Files
skills/public/hip-0018.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
hanzoskills.com/llms.txt now opens with the install line, the API
reference index and the company index, so an agent that lands on any
one of the three can find the rest.

robots.txt claimed 537 documents while llms.txt counts 920. The number
is gone from robots.txt; llms.txt derives it.

public/ is regenerated from scripts/site.py, which it had fallen
behind: the copy-prompt menu and agent bar were in the generator and
not in the committed pages. tests/site.mjs passes against the result.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-11 00:27:59 -07:00

583 lines
54 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>hip-0018</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/hip-0018.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/hip-0018">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/hip-0018.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>hip-0018</h1><p class="lede">HIP-18: Payment Processing Standard. Status Draft. Hanzo architectural specification.</p><h1>HIP-0018: Payment Processing Standard</h1>
<h2>Abstract</h2>
<p>This proposal defines the payment processing standard for the Hanzo ecosystem. Hanzo Commerce is the billing, subscription, and payment service that bridges the <strong>native Hanzo PSP (Hanzo Pay — the same payment engine white-labeled as <code>lux-pay</code> on Lux and per-brand elsewhere)</strong> with the internal credit system managed by Hanzo IAM (HIP-26). Card data is tokenized inside the Hanzo Vault PCI CDE; on-chain rails settle $AI directly. Every dollar a user pays is converted into credits. Every AI inference, API call, or compute job consumes credits. Commerce handles the money side; IAM holds the balance; the LLM Gateway (HIP-4) and Cloud services meter usage.</p>
<blockquote><p><strong>No external-processor dependency.</strong> First-party Hanzo/Lux/Zoo/Zen surfaces process payments through the native PSP, never through a third-party processor that can deplatform us. Commerce keeps a <em>pluggable</em> provider-adapter interface so a brand MAY add a regional rail, but no first-party flow depends on one.</p></blockquote>
<p>The system is designed around a single invariant: <strong>IAM is the source of truth for user balances</strong>. Commerce writes credits in; Cloud and Gateway write credits out. No service other than IAM may directly mutate a user&#x27;s balance. All mutations flow through IAM&#x27;s transaction API.</p>
<p><strong>Repository</strong>: <a href="https://github.com/hanzoai/commerce">github.com/hanzoai/commerce</a> <strong>Port</strong>: 8090 (<code>COMMERCE_HTTP</code>) <strong>Docker</strong>: <code>ghcr.io/hanzoai/commerce:latest</code></p>
<h2>Motivation</h2>
<h3>The Problem</h3>
<p>AI usage billing is fundamentally different from SaaS billing. A typical SaaS charges a flat monthly fee for feature access. AI platforms charge per token, per image, per minute of audio, per GPU-second of fine-tuning. The unit costs span four orders of magnitude -- a GPT-3.5 completion might cost $0.0002 while a GPT-4 Vision request with a large image costs $0.30. Presenting these raw costs to users is confusing and creates billing anxiety.</p>
<p>Meanwhile, the Hanzo ecosystem has multiple services that incur costs:</p>
<ol><li><strong>LLM Gateway</strong> (HIP-4): Chat completions, embeddings, image generation across 100+ providers</li><li><strong>Cloud</strong>: Hosted model inference, fine-tuning jobs, compute clusters</li><li><strong>MCP Tools</strong>: Computer use, browser automation, search -- each with different cost profiles</li><li><strong>Agent SDK</strong>: Multi-agent orchestration where a single user request may trigger dozens of LLM calls</li></ol>
<p>Without a unified billing system, each service would need its own payment integration, balance tracking, and invoice generation. Users would face multiple bills, multiple balances, and no single view of their spend.</p>
<h3>Why This Matters</h3>
<ol><li><strong>User trust</strong>: Users must understand what they are paying for. Opaque per-token billing erodes trust. Credits provide a simple, predictable unit.</li><li><strong>Service isolation</strong>: LLM Gateway should not need payment-processor credentials. It should check a balance, do the work, and report usage. Payment processing is not its job.</li><li><strong>Fraud prevention</strong>: A single source of truth for balances prevents double-spending. If Cloud and Gateway each maintained independent balances, a race condition could allow a user to spend more than they have.</li><li><strong>Regulatory compliance</strong>: Financial transactions require audit trails, PCI compliance, and dispute resolution. Centralizing this in Commerce means one team handles compliance, not five.</li></ol>
<h2>Design Philosophy</h2>
<p>This section explains the <em>why</em> behind each major design decision. Payment systems are among the most consequential infrastructure choices a company makes. Mistakes are expensive -- literally.</p>
<h3>Why Credits-Based Billing</h3>
<p>AI usage is unpredictable. A user might send one message that triggers a 4-token response or one that triggers a 4,000-token response with tool calls, image generation, and web search. Showing users a per-request cost breakdown like &quot;$0.000847 for 423 input tokens at $0.002/1K + $0.000612 for 204 output tokens at $0.003/1K&quot; is hostile UX.</p>
<p>Credits provide a simple mental model: you buy credits, you spend credits. 1 credit = $0.001 USD. A $20 top-up gives you 20,000 credits. A typical GPT-4 conversation costs 50-200 credits. Users can reason about their spending without understanding tokenization, provider pricing tiers, or markup calculations.</p>
<p>Credits also decouple the billing unit from provider pricing. When OpenAI changes their per-token rates (which happens quarterly), we adjust the internal credit-to-token conversion without changing the user-facing credit price. The user&#x27;s mental model remains stable.</p>
<p>The alternative -- real-time per-token billing in USD -- requires sub-cent transaction tracking, creates rounding errors that accumulate, and produces invoices with thousands of line items. Credits eliminate all three problems.</p>
<h3>Why a Native PSP (Hanzo Pay)</h3>
<p>Hanzo originally bridged an external processor. That dependency proved fatal: a third-party processor can <strong>deplatform an entire ecosystem at will</strong> — freezing funds, disabling checkout, and cutting off every brand that rides on it, with no recourse and no portability. This is not hypothetical; it is exactly what happened, and it is why this standard now mandates a <strong>native PSP</strong>. Payment sovereignty — owning the rail end-to-end — is a first-class requirement, not an optimization.</p>
<p>The native PSP (<strong>Hanzo Pay</strong>, the same engine white-labeled as <code>lux-pay</code> / per-brand) provides:</p>
<ul><li><strong>Sovereignty</strong>: No external party can disable, freeze, or deplatform a first-party flow. The rail is ours; outages and policy changes are ours to manage.</li><li><strong>PCI offload, in-house</strong>: Card data never touches Commerce or any app server. The <strong>Hanzo Vault</strong> CDE (a dedicated PCI-DSS-scoped tokenization service) holds the card-handling surface; everything else operates on opaque tokens, keeping the broad system out of PCI scope exactly as an external processor would — but under our control.</li><li><strong>Hosted checkout</strong>: A native hosted payment page (served from the Vault/PSP boundary) so app servers only ever receive a signed completion webhook.</li><li><strong>Subscription management</strong>: Recurring billing, proration, dunning (failed-payment retry), and lifecycle hooks.</li><li><strong>Invoicing</strong>: Invoice generation, PDF rendering, and email delivery.</li><li><strong>Fraud detection</strong>: Risk scoring on the native rail; on-chain rails are inherently irreversible (no chargeback exposure).</li><li><strong>Marketplace payouts</strong>: Connect-style transfers for agent revenue (HIP-25) settle natively, including on-chain $AI to any wallet.</li></ul>
<p>The compliance burden the standard once cited as a reason to outsource (PCI DSS: 300+ controls across 12 categories) is met by scoping the CDE to <strong>Hanzo Vault</strong> alone, not by handing the customer relationship to a party that can revoke it.</p>
<h3>Pluggable Provider Adapters (Optional, Per-Brand)</h3>
<p>Commerce keeps a provider-adapter interface so a brand MAY plug an additional rail (regional cards, bank transfer, a Merchant-of-Record for EU VAT, etc.). These are <strong>optional, per-brand, and never on a first-party critical path</strong> — the native PSP is always the default and the only rail a first-party surface is required to support. Adapters are registered explicitly; none is implicit or default. (Notably, no first-party surface registers an external processor that can deplatform the ecosystem.)</p>
<h3>Why Not Blockchain-Only Payments</h3>
<p>The Hanzo ecosystem includes $AI token (HIP-1) and on-chain settlement (HIP-25). Why not use blockchain for all payments?</p>
<ol><li><strong>Friction</strong>: Most developers do not have crypto wallets. Requiring wallet setup, token purchase, and gas fees for a $20 credit top-up would eliminate 90%+ of potential users.</li><li><strong>Volatility</strong>: Token prices fluctuate. If a user buys credits with $AI at $0.50 and the price drops to $0.30 before they use the credits, who absorbs the loss?</li><li><strong>Speed</strong>: The native PSP processes a card payment in 2-3 seconds. On-chain settlement takes 2-15 seconds depending on the chain and requires block confirmations for finality.</li><li><strong>Chargebacks</strong>: Card users have dispute rights. Blockchain transactions are irreversible. Offering only crypto payments forfeits consumer protection, which is a regulatory risk.</li></ol>
<p>The correct approach is <strong>both</strong>: the native PSP for fiat, blockchain for crypto. Commerce accepts both and normalizes them into credits. The user does not need to know or care which payment rail was used.</p>
<h3>Why IAM Holds Balances</h3>
<p>Every authenticated API call already hits IAM to validate the JWT. The LLM Gateway (HIP-4) receives a request, extracts the bearer token, and validates it against IAM&#x27;s public key or calls <code>/v1/iam/get-account</code>. This round-trip is unavoidable -- you must authenticate before executing.</p>
<p>If balance lived in Commerce, every LLM call would require two round-trips:</p>
<pre><code>Request -&gt; Gateway -&gt; IAM (auth: 3ms) -&gt; Commerce (balance: 5ms) -&gt; Upstream (inference: 200ms)</code></pre>
<p>By storing balance in IAM, the auth check and balance check collapse into one operation:</p>
<pre><code>Request -&gt; Gateway -&gt; IAM (auth + balance: 3ms) -&gt; Upstream (inference: 200ms)</code></pre>
<p>At 1,000 requests/second, eliminating the Commerce round-trip saves 5,000ms of cumulative latency per second and removes Commerce as a critical-path dependency. If Commerce goes down, users cannot <em>buy</em> credits, but they can still <em>use</em> existing credits because IAM is independent.</p>
<p>The tradeoff: balance is denormalized. Commerce is the authoritative ledger (&quot;what transactions occurred&quot;), and IAM is the balance cache (&quot;what is the current balance&quot;). A reconciliation job detects and corrects drift between the two. This is covered in detail in HIP-26 Section &quot;Why Credit Balances Live in IAM.&quot;</p>
<h3>Why Webhook-Driven Architecture</h3>
<p>Payment processing is inherently asynchronous. A user clicks &quot;Pay&quot; on the native hosted checkout page, enters their card, waits for 3D Secure, and the PSP processes the charge. This takes 5-30 seconds. Holding a synchronous HTTP connection open for this duration is fragile.</p>
<p>Instead, Commerce uses webhooks:</p>
<ol><li>Commerce creates a native PSP checkout session and returns the URL to the client.</li><li>Client redirects to the native hosted checkout page (served from the Vault/PSP boundary; card data never reaches Commerce).</li><li>User completes payment on the PCI-scoped CDE.</li><li>The PSP sends a signed <code>checkout.session.completed</code> webhook to Commerce.</li><li>Commerce verifies the webhook signature, records the transaction, then calls IAM to add credits.</li></ol>
<p>This decouples payment processing from service delivery. If Commerce is briefly unavailable when the webhook fires, the PSP retries with exponential backoff for up to 72 hours. Eventual consistency is acceptable for billing -- a 30-second delay between payment and credit delivery is imperceptible to users.</p>
<h2>Specification</h2>
<h3>Architecture</h3>
<pre><code> +------------------------+
| Hanzo Pay (native PSP)|
| + Hanzo Vault (PCI |
| CDE: card tokens) |
| Checkout/Billing/Hooks|
+------+------+----------+
| |
webhooks | | checkout sessions
| |
+------v------v----------+
| Hanzo Commerce |
| (payment logic) |
| :4242 |
+------+--------+--------+
| |
+--------------+--------+-------------+
| | |
add-balance add-transaction get-account
| | |
v v v
+----------------------------------------------+
| Hanzo IAM (HIP-26) |
| (user balances, transactions) |
| hanzo.id :8000 |
+----------------------------------------------+
^ ^
| |
token validation debit transactions
| |
+------------+-+ +------+----------+
| LLM Gateway | | Hanzo Cloud |
| (HIP-4) | | (compute jobs) |
| :4000 | | |
+--------------+ +-----------------+</code></pre>
<h3>Credit System</h3>
<h4>Credit Definition</h4>
<p>| Property | Value | |----------|-------| | Unit name | credit | | USD value | 1 credit = $0.001 USD | | Minimum purchase | 1,000 credits ($1.00) | | Maximum single purchase | 10,000,000 credits ($10,000) | | Precision | Integer (no fractional credits) | | Storage | <code>float64</code> in IAM user <code>balance</code> field (USD-denominated) |</p>
<p>Credits are stored as a USD-denominated float in IAM (1,000 credits = $1.00 balance). The &quot;credit&quot; is a user-facing abstraction; the IAM balance field stores the dollar equivalent. This means 20,000 credits = $20.00 balance.</p>
<h4>Credit Pricing Tiers</h4>
<p>Bulk purchases receive volume discounts:</p>
<p>| Purchase Amount | Credits | Bonus | Effective Rate | |----------------|---------|-------|----------------| | $5 | 5,000 | 0% | $0.001/credit | | $20 | 21,000 | 5% | $0.000952/credit | | $50 | 55,000 | 10% | $0.000909/credit | | $100 | 115,000 | 15% | $0.000870/credit | | $500 | 600,000 | 20% | $0.000833/credit | | $1,000+ | Custom | 25%+ | Negotiated |</p>
<h4>AI Usage Credit Costs</h4>
<p>Credit costs are derived from provider pricing plus a margin. The LLM Gateway publishes a rate card:</p>
<p>| Operation | Model Tier | Credits | Approx. USD | |-----------|-----------|---------|-------------| | Chat completion (1K input tokens) | Economy (Mixtral, Llama) | 1 | $0.001 | | Chat completion (1K input tokens) | Standard (GPT-4-Turbo, Claude Sonnet) | 10 | $0.01 | | Chat completion (1K input tokens) | Premium (GPT-4, Claude Opus) | 30 | $0.03 | | Chat completion (1K output tokens) | Economy | 2 | $0.002 | | Chat completion (1K output tokens) | Standard | 15 | $0.015 | | Chat completion (1K output tokens) | Premium | 60 | $0.06 | | Image generation (1024x1024) | DALL-E 3 | 40 | $0.04 | | Embedding (1K tokens) | text-embedding-3-small | 0.1 | $0.0001 | | Audio transcription (1 minute) | Whisper | 6 | $0.006 | | Computer use (1 action) | Operative | 5 | $0.005 |</p>
<p>These rates are stored in the LLM Gateway configuration and updated when provider pricing changes. Commerce does not need to know the rates; it only processes the debit transactions that Gateway and Cloud submit to IAM.</p>
<h3>Subscription Tiers</h3>
<pre><code class="lang-yaml">tiers:
free:
name: &quot;Free&quot;
price_monthly: 0
credits_monthly: 1000
psp_price_id: null
overage: blocked
features:
- &quot;1,000 credits/month (~100 GPT-4 messages)&quot;
- &quot;Community support&quot;
- &quot;3 requests/minute rate limit&quot;
- &quot;Standard models only&quot;
pro:
name: &quot;Pro&quot;
price_monthly: 20
credits_monthly: 50000
psp_price_id: &quot;price_pro_monthly&quot;
overage: pay_as_you_go
features:
- &quot;50,000 credits/month (~5,000 GPT-4 messages)&quot;
- &quot;Priority support&quot;
- &quot;60 requests/minute rate limit&quot;
- &quot;All models including Premium tier&quot;
- &quot;MCP tool access&quot;
- &quot;Usage analytics dashboard&quot;
team:
name: &quot;Team&quot;
price_monthly: 100
credits_monthly: 150000
psp_price_id: &quot;price_team_monthly&quot;
overage: pay_as_you_go
features:
- &quot;150,000 credits/month&quot;
- &quot;5 team members included ($15/additional)&quot;
- &quot;Shared org billing&quot;
- &quot;120 requests/minute rate limit&quot;
- &quot;Admin dashboard&quot;
- &quot;SSO via IAM (HIP-26)&quot;
enterprise:
name: &quot;Enterprise&quot;
price_monthly: custom
credits_monthly: custom
psp_price_id: &quot;price_enterprise_custom&quot;
overage: invoice
features:
- &quot;Custom credit allocation&quot;
- &quot;Unlimited team members&quot;
- &quot;Dedicated support and SLA&quot;
- &quot;Custom rate limits&quot;
- &quot;Volume discounts (25%+)&quot;
- &quot;Invoice billing (NET 30)&quot;
- &quot;SOC 2 compliance reports&quot;</code></pre>
<p>Free-tier credits reset monthly and do not accumulate. Paid-tier included credits roll over for 90 days. Purchased credits (one-time top-ups) never expire.</p>
<h4>Subscription Lifecycle</h4>
<ul><li><strong>Upgrade</strong>: Commerce creates a PSP subscription -&gt; the PSP charges monthly -&gt; webhook <code>invoice.paid</code> -&gt; Commerce credits IAM with included credits.</li><li><strong>Renewal</strong>: the PSP auto-charges -&gt; webhook <code>invoice.paid</code> -&gt; Commerce adds monthly credits. Unused credits from previous months roll over for 90 days.</li><li><strong>Overage</strong>: When a Pro/Team user exceeds included credits, usage continues at the standard rate. Overage is metered via PSP usage records and billed at period end alongside the subscription fee.</li><li><strong>Downgrade</strong>: Commerce cancels the PSP subscription at period end. Remaining credits are usable until expiry. After the period ends, the user reverts to Free tier (1,000 credits/month, hard cap).</li><li><strong>Payment failure</strong>: the PSP retries 3 times over 7 days using smart retries. After 3 failures the subscription enters <code>past_due</code>. After 14 days <code>past_due</code>, the subscription is canceled and the user is downgraded to Free.</li></ul>
<h3>Payment Flow</h3>
<h4>One-Time Credit Purchase (Fiat)</h4>
<pre><code>1. Client: POST /v1/billing/checkout { amount: 2000, currency: &quot;usd&quot;, credits: 21000 }
2. Commerce creates a PSP checkout session with metadata (user_id, org_id, credits, idempotency_key)
3. Commerce returns checkout URL -&gt; client redirects user to the native hosted checkout
4. User completes payment on the native hosted checkout page (Hanzo Vault CDE)
5. PSP fires webhook: checkout.session.completed
6. Commerce verifies webhook signature (HMAC-SHA256)
7. Commerce checks the idempotency key in the shared KV (prevent double-processing)
8. Commerce records the transaction in its OWN ledger — it does not write a
balance into IAM. IAM&#x27;s balance fields are read-only mirrors of this ledger
(HIP-0026 §The balance mirror); the `add-balance` and `add-transaction` verbs
an earlier revision called here do not exist and would be forbidden if they
did (HIP-0111 §4.8).
9. The mirror follows from the ledger. A surface that gates spend reads the
authoritative position, never the mirror.
10. User&#x27;s IAM balance updated. Credits available immediately.</code></pre>
<h4>Crypto Payment Flow ($AI Token)</h4>
<p>Commerce also accepts $AI token (HIP-1) payments on Hanzo Network (chain ID 36963). The user sends tokens to a per-user deposit address. Commerce&#x27;s on-chain listener detects the Transfer event (1 block confirmation for &lt;$1K, 6 for &gt;=$1K), converts $AI to USD at the 10-minute TWAP oracle rate via HMM (HIP-8), and credits the user&#x27;s IAM balance through the same add-balance/add-transaction flow as fiat.</p>
<h3>Billing API Endpoints</h3>
<p>| Method | Endpoint | Description | Auth | |--------|----------|-------------|------| | GET | <code>/v1/billing/balance</code> | Current credit balance | Bearer token | | GET | <code>/v1/billing/transactions</code> | Transaction history with pagination | Bearer token | | POST | <code>/v1/billing/checkout</code> | Create PSP checkout session | Bearer token | | POST | <code>/v1/billing/checkout/crypto</code> | Create crypto payment intent | Bearer token | | POST | <code>/v1/billing/subscribe</code> | Create or change subscription | Bearer token | | DELETE | <code>/v1/billing/subscribe</code> | Cancel subscription | Bearer token | | GET | <code>/v1/billing/subscription</code> | Current subscription details | Bearer token | | GET | <code>/v1/billing/invoices</code> | List invoices | Bearer token | | GET | <code>/v1/billing/invoices/:id</code> | Download invoice PDF | Bearer token | | GET | <code>/v1/billing/usage</code> | Usage breakdown by period | Bearer token | | POST | <code>/v1/billing/portal</code> | Create PSP customer portal session | Bearer token | | POST | <code>/webhooks/psp</code> | PSP webhook receiver | PSP signature |</p>
<h4>Response Examples</h4>
<p><strong>GET /v1/billing/balance</strong> returns the user&#x27;s current credit state:</p>
<pre><code class="lang-json">{
&quot;balance&quot;: 15420, &quot;balance_usd&quot;: 15.42, &quot;tier&quot;: &quot;pro&quot;,
&quot;credits_included&quot;: 50000, &quot;credits_used&quot;: 34580, &quot;credits_remaining&quot;: 15420,
&quot;period_start&quot;: &quot;2026-02-01T00:00:00Z&quot;, &quot;period_end&quot;: &quot;2026-03-01T00:00:00Z&quot;,
&quot;auto_recharge&quot;: { &quot;enabled&quot;: true, &quot;threshold&quot;: 1000, &quot;amount&quot;: 20000 }
}</code></pre>
<p><strong>GET /v1/billing/transactions</strong> returns paginated transaction history. Each transaction includes <code>id</code>, <code>timestamp</code>, <code>category</code> (Purchase/Recharge), <code>credits</code> (negative for debits), <code>balance_after</code>, and <code>metadata</code> with model/token/provider details.</p>
<p><strong>GET /v1/billing/usage?period=2026-02</strong> returns usage aggregated by model (<code>gpt-4-turbo</code>, <code>claude-3-sonnet</code>, etc.), by service (<code>llm-gateway</code>, <code>cloud</code>, <code>mcp</code>), and optionally by day when <code>granularity=daily</code> is specified.</p>
<h3>Webhook Handling</h3>
<p>Commerce receives webhooks from the native PSP for all payment-related events. The webhook handler follows a strict pipeline:</p>
<pre><code class="lang-python">async def handle_psp_webhook(request):
# 1. Verify signature (CRITICAL - prevents forgery)
payload = request.body
signature = request.headers[&quot;X-Webhook-Signature&quot;]
try:
event = psp.verify_event(
payload, signature, psp_webhook_secret
)
except psp.SignatureError:
return Response(status=400, body=&quot;Invalid signature&quot;)
# 2. Check idempotency (prevent double-processing)
event_id = event[&quot;id&quot;]
if await kv.exists(f&quot;webhook:processed:{event_id}&quot;):
return Response(status=200, body=&quot;Already processed&quot;)
# 3. Route by event type
handlers = {
&quot;checkout.session.completed&quot;: handle_checkout_completed,
&quot;invoice.paid&quot;: handle_invoice_paid,
&quot;invoice.payment_failed&quot;: handle_payment_failed,
&quot;customer.subscription.updated&quot;: handle_subscription_updated,
&quot;customer.subscription.deleted&quot;: handle_subscription_deleted,
&quot;charge.dispute.created&quot;: handle_dispute_created,
&quot;charge.refunded&quot;: handle_refund,
}
handler = handlers.get(event[&quot;type&quot;])
if handler:
await handler(event)
# 4. Mark as processed (72h TTL matching the PSP retry window)
await kv.set(f&quot;webhook:processed:{event_id}&quot;, &quot;1&quot;, ex=259200)
return Response(status=200)</code></pre>
<h4>Handled Webhook Events</h4>
<p>| Event | Action | |-------|--------| | <code>checkout.session.completed</code> | Add credits to user&#x27;s IAM balance | | <code>invoice.paid</code> | Add subscription credits; record payment | | <code>invoice.payment_failed</code> | Send warning email; flag account | | <code>customer.subscription.updated</code> | Update tier in IAM user properties | | <code>customer.subscription.deleted</code> | Downgrade to Free tier | | <code>charge.dispute.created</code> | Freeze account; debit disputed amount; create support ticket | | <code>charge.dispute.closed</code> | Unfreeze if won; maintain debit if lost | | <code>charge.refunded</code> | Debit refunded credits from IAM balance |</p>
<h3>Usage Metering</h3>
<p>The LLM Gateway and Cloud services do not interact with Commerce directly for debits. They submit usage to IAM via the transaction API:</p>
<pre><code>LLM Gateway receives request
|
+-- 1. Validate JWT (IAM)
+-- 2. Check balance from JWT claims or /v1/iam/get-account
+-- 3. If insufficient balance: return 402 Payment Required
+-- 4. Execute LLM request (provider API)
+-- 5. Calculate cost:
| input_tokens * input_rate + output_tokens * output_rate
| -&gt; convert to USD -&gt; round to credits
+-- 6. Submit debit transaction to IAM:
| POST /v1/iam/add-transaction
| {
| &quot;category&quot;: &quot;Purchase&quot;,
| &quot;user&quot;: &quot;&lt;user&gt;&quot;,
| &quot;amount&quot;: -0.012, // negative = debit
| &quot;detail&quot;: &quot;gpt-4-turbo: 847 in + 400 out tokens&quot;
| }
+-- 7. Return response to user</code></pre>
<p>The Gateway batches transaction submissions. Rather than calling IAM for every request, it accumulates usage per user over a 10-second window and submits a single aggregated transaction. This reduces IAM load by ~90% during high-throughput periods.</p>
<pre><code class="lang-yaml">metering:
batch_interval: 10s
batch_max_size: 100
minimum_charge: 0.001 # 1 credit minimum debit
balance_check: jwt_claims # or &quot;api_call&quot;
insufficient_balance_code: 402
retry_on_iam_failure: true
retry_max_attempts: 3
retry_backoff: exponential</code></pre>
<h3>Multi-Organization Billing</h3>
<p>Each organization in IAM has independent billing. A user who belongs to multiple organizations (e.g., <code>[email protected]</code> is a member of both <code>hanzo</code> and <code>zoo</code>) has a separate balance in each organization context.</p>
<pre><code>Organization: hanzo
User: z
Balance: $150.00
Tier: Enterprise
Transactions: [org-scoped]
Organization: zoo
User: z
Balance: $25.00
Tier: Pro
Transactions: [org-scoped]</code></pre>
<p>When the LLM Gateway processes a request, the organization context is determined by the OAuth application that issued the token. A token from <code>app-cloud</code> (organization: <code>hanzo</code>) bills against the <code>hanzo</code> org balance. A token from <code>app-zoo</code> bills against the <code>zoo</code> org balance.</p>
<p>Organizations can choose between two billing modes:</p>
<ul><li><strong>Shared pool</strong> (default for Team/Enterprise): One org-level balance. All members draw from the shared pool. The org owner manages top-ups and subscriptions.</li><li><strong>Individual allocation</strong>: Org admin allocates credits to each member. Members cannot exceed their allocation without admin approval.</li></ul>
<h3>Refund and Dispute Handling</h3>
<h4>Refund Policy</h4>
<ul><li><strong>Unused credits</strong>: Full refund within 14 days of purchase.</li><li><strong>Partially used credits</strong>: Pro-rated refund for unused portion within 14 days.</li><li><strong>After 14 days</strong>: No refund for credit purchases.</li><li><strong>Subscriptions</strong>: Cancel anytime; no refund for current period; access continues until period end.</li></ul>
<h4>Refund Flow</h4>
<ol><li>User requests refund via support or <code>/v1/billing/refund</code>.</li><li>Commerce validates eligibility (14-day window, sufficient credit balance).</li><li>Commerce creates a refund via the PSP (<code>psp.refunds.create</code>) for the original payment intent.</li><li>The PSP processes the refund (3-5 business days to card).</li><li>On webhook <code>charge.refunded</code>, Commerce debits the refunded credits from IAM via <code>add-transaction</code> with negative amount.</li><li>If the user&#x27;s balance goes negative after the debit, the account is flagged and usage is suspended until the balance is positive.</li></ol>
<h4>Dispute (Chargeback) Flow</h4>
<ol><li>The PSP receives a chargeback from the card issuer -&gt; webhook <code>charge.dispute.created</code>.</li><li>Commerce immediately freezes the user account (<code>suspended=true</code> in IAM), debits the disputed amount, creates a support ticket, and notifies the admin team.</li><li>Commerce submits evidence to the PSP: usage logs, IP addresses, login timestamps, and ToS acceptance.</li><li>The card network arbitrates (60-90 days). On <code>charge.dispute.closed</code>: if won, Commerce unfreezes the account and restores the debited amount; if lost, the account remains suspended until the balance is positive.</li></ol>
<h3>Invoice Generation</h3>
<p>Commerce generates monthly invoices for all users with non-zero activity. Each invoice includes:</p>
<ul><li><strong>Header</strong>: Hanzo AI Inc., 548 Market St, Suite 45000, San Francisco, CA 94104</li><li><strong>Line items</strong>: Subscription fee, credit purchases, overage charges</li><li><strong>Usage summary</strong>: Credits consumed by service (LLM Gateway, Cloud, MCP) with request counts</li><li><strong>Balance</strong>: Opening balance, credits added, usage consumed, closing balance</li><li><strong>Payment</strong>: Method used (card ending, wire reference, or $AI tx hash)</li></ul>
<p>Invoices are stored as PDFs in MinIO (HIP-32) and emailed to the user. Enterprise customers on Net-30 receive invoices with payment instructions instead of automatic billing.</p>
<h3>Auto-Recharge</h3>
<p>Users can configure automatic credit purchases when their balance drops below a threshold:</p>
<pre><code class="lang-json">POST /v1/billing/auto-recharge
Authorization: Bearer &lt;access_token&gt;
{
&quot;enabled&quot;: true,
&quot;threshold&quot;: 1000,
&quot;amount&quot;: 20000,
&quot;max_monthly&quot;: 5,
&quot;payment_method&quot;: &quot;pm_...&quot;
}</code></pre>
<p>When the metering pipeline detects a balance crossing below the threshold, it enqueues an auto-recharge job. The job creates a PSP payment intent using the stored (tokenized) payment method, processes the charge, and credits the balance without user interaction. Auto-recharge is rate-limited (max 5/month by default) to prevent runaway charges from buggy clients or compromised API keys.</p>
<h2>Implementation Roadmap</h2>
<h3>Phase 1: Core Billing (Completed)</h3>
<ul><li>[x] Native PSP checkout integration for one-time credit purchases</li><li>[x] Webhook handler for <code>checkout.session.completed</code></li><li>[x] IAM balance update via <code>/v1/iam/add-balance</code></li><li>[x] Transaction recording via <code>/v1/iam/add-transaction</code></li><li>[x] Balance and transaction query endpoints</li><li>[x] Idempotency key tracking in the shared KV</li></ul>
<h3>Phase 2: Subscriptions (Completed)</h3>
<ul><li>[x] Native PSP subscription creation for Pro/Team tiers</li><li>[x] Monthly credit allocation on <code>invoice.paid</code></li><li>[x] Subscription upgrade/downgrade with proration</li><li>[x] Dunning (failed payment) handling</li><li>[x] Subscription cancellation flow</li></ul>
<h3>Phase 3: Usage Metering (In Progress)</h3>
<ul><li>[ ] LLM Gateway batched transaction submission</li><li>[ ] Per-model credit cost configuration</li><li>[ ] Real-time usage dashboard</li><li>[ ] Usage breakdown by model, service, and time period</li><li>[ ] Overage billing via PSP metered usage</li></ul>
<h3>Phase 4: Multi-Org and Enterprise (Planned)</h3>
<ul><li>[ ] Org-level billing with shared pool mode</li><li>[ ] Individual credit allocation per member</li><li>[ ] Enterprise invoice billing (NET 30)</li><li>[ ] Custom rate cards for enterprise customers</li><li>[ ] SOC 2 Type II audit trail exports</li></ul>
<h3>Phase 5: Crypto Payments (Planned)</h3>
<ul><li>[ ] $AI token payment acceptance on Hanzo Network</li><li>[ ] USDC/USDT acceptance via Lux Bridge (HIP-101)</li><li>[ ] On-chain settlement receipts</li><li>[ ] Token-to-credit conversion via HMM oracle (HIP-8)</li></ul>
<h2>Security Considerations</h2>
<h3>PCI DSS Compliance</h3>
<p>Commerce achieves PCI compliance by <strong>never handling cardholder data</strong>. Cardholder data is confined to the <strong>Hanzo Vault</strong> CDE — the only PCI-DSS-scoped component — which hosts the payment form (native hosted checkout) and issues opaque tokens. Commerce and every app server operate on tokens only; they never see, store, process, or transmit card numbers, CVVs, or expiration dates. Commerce qualifies as a <strong>SAQ A</strong> surface; the Vault carries the full SAQ D / RoC scope, isolated from the rest of the ecosystem.</p>
<h3>Webhook Signature Verification</h3>
<p>Every native-PSP webhook is verified using HMAC-SHA256:</p>
<pre><code class="lang-python"># The PSP signs webhooks with the webhook signing secret (held in KMS).
# The signature includes a timestamp to prevent replay attacks.
signature = request.headers[&quot;X-Webhook-Signature&quot;]
# Format: t=&lt;timestamp&gt;,v1=&lt;signature&gt;
expected = hmac_sha256(
key=psp_webhook_secret, # from KMS, never plaintext
message=f&quot;{timestamp}.{payload}&quot;
)
# Reject if:
# 1. Signature does not match (forged webhook)
# 2. Timestamp is &gt; 300 seconds old (replay attack)
# 3. Event ID already processed (duplicate delivery)</code></pre>
<h3>Idempotency</h3>
<p>Every payment operation uses idempotency keys to prevent double-charging:</p>
<ol><li><strong>PSP Checkout</strong>: The <code>idempotency_key</code> in session metadata ensures retried webhooks do not create duplicate credits.</li><li><strong>IAM Transactions</strong>: The transaction <code>name</code> field (<code>txn_psp_{event_id}</code>) acts as a unique constraint. IAM rejects duplicate transaction names.</li><li><strong>Deduplication store</strong>: Processed webhook event IDs are persisted with a 72-hour TTL matching the PSP&#x27;s retry window.</li></ol>
<p>These three layers provide defense-in-depth against double-processing.</p>
<h3>Rate Limiting</h3>
<p>| Endpoint | Limit | Window | |----------|-------|--------| | <code>/v1/billing/checkout</code> | 10 | per minute per user | | <code>/v1/billing/subscribe</code> | 5 | per minute per user | | <code>/v1/billing/balance</code> | 60 | per minute per user | | <code>/v1/billing/transactions</code> | 30 | per minute per user | | <code>/v1/billing/usage</code> | 10 | per minute per user | | <code>/webhooks/psp</code> | 1000 | per minute (global) |</p>
<p>Rate limiting is enforced with sliding-window counters in the shared KV (HIP-0144). Exceeding the limit returns <code>429 Too Many Requests</code> with a <code>Retry-After</code> header.</p>
<h3>Audit Trail</h3>
<p>Every financial event produces an immutable audit record:</p>
<pre><code class="lang-json">{
&quot;event_id&quot;: &quot;evt_audit_001&quot;,
&quot;timestamp&quot;: &quot;2026-02-23T10:30:15.123Z&quot;,
&quot;action&quot;: &quot;credit_purchase&quot;,
&quot;actor&quot;: {
&quot;user_id&quot;: &quot;hanzo/z&quot;,
&quot;ip&quot;: &quot;203.0.113.42&quot;,
&quot;user_agent&quot;: &quot;Mozilla/5.0...&quot;
},
&quot;details&quot;: {
&quot;psp_event_id&quot;: &quot;evt_...&quot;,
&quot;psp_session_id&quot;: &quot;cs_...&quot;,
&quot;amount_usd&quot;: 20.00,
&quot;credits_added&quot;: 21000,
&quot;balance_before&quot;: 5000,
&quot;balance_after&quot;: 26000,
&quot;idempotency_key&quot;: &quot;ik_abc123&quot;
},
&quot;integrity&quot;: &quot;sha256:ab3f...&quot;
}</code></pre>
<p>Audit records are append-only (never updated or deleted), integrity-protected with SHA-256 hash chains, retained for 7 years (financial regulatory minimum), and exportable for SOC 2 and compliance audits.</p>
<h3>Fraud Prevention</h3>
<ul><li><strong>Velocity checks</strong>: Commerce flags users who make &gt;5 purchases in 1 hour or &gt;$500 in 24 hours for manual review.</li><li><strong>Chargeback response</strong>: Disputes trigger immediate account freeze and balance debit. Evidence is automatically compiled from usage logs.</li><li><strong>Free-tier abuse</strong>: Free-tier credit resets are tied to verified email addresses. Multiple accounts with the same email or phone are detected and consolidated.</li></ul>
<h3>Insufficient Balance Handling</h3>
<p>When a user&#x27;s balance reaches zero during an API request:</p>
<ol><li>The LLM Gateway returns <code>402 Payment Required</code> with a link to the billing page.</li><li>Streaming responses are terminated gracefully -- partial completions are delivered with a final chunk indicating billing exhaustion.</li><li>If auto-recharge is enabled, it triggers immediately, and the request can be retried.</li></ol>
<h2>References</h2>
<ol><li><a href="./hip-0001-ai-coin-hanzos-native-currency.md">HIP-1: $AI Token</a> - Native currency for crypto payments</li><li><a href="./hip-0004-llm-gateway-unified-ai-provider-interface.md">HIP-4: LLM Gateway</a> - Primary usage metering source</li><li><a href="./hip-0008-hmm-hanzo-market-maker-native-dex-for-ai-compute-resources.md">HIP-8: HMM (Hanzo Market Maker)</a> - Token price oracle for crypto-to-credit conversion</li><li><a href="./hip-0025-bot-agent-wallet-rpc-billing-protocol.md">HIP-25: Bot Agent Wallet &amp; RPC Billing Protocol</a> - Agent-level billing built on Commerce</li><li><a href="./hip-0026-identity-access-management-standard.md">HIP-26: Identity &amp; Access Management Standard</a> - Balance storage and transaction ledger</li><li><a href="./hip-0027-secrets-management-standard.md">HIP-27: Secrets Management Standard</a> - KMS for PSP keys and secrets</li><li><a href="./hip-1060-pubsub-the-tenant-door-on-the-bus.md">HIP-1060: Pubsub — The Tenant Endpoint on the Bus</a> - billing event distribution</li><li><a href="./hip-1165-s3-buckets-and-objects.md">HIP-1165: S3 — Buckets and Objects</a> - invoice PDF storage</li><li><a href="./hip-0101-hanzo-lux-bridge-protocol-integration.md">HIP-101: Hanzo-Lux Bridge Protocol</a> - Cross-chain payment acceptance</li><li><a href="https://github.com/lux-pay">Hanzo Pay (native PSP) — <code>github.com/lux-pay</code></a> (white-labeled <code>lux-pay</code> on Lux)</li><li><a href="https://github.com/hanzoai/vault">Hanzo Vault — PCI CDE / card tokenization</a></li><li><a href="https://www.pcisecuritystandards.org/">PCI DSS v4.0 — SAQ A / SAQ D scoping</a></li><li><a href="https://www.pcisecuritystandards.org/document_library">PCI DSS Quick Reference Guide</a></li><li><a href="https://github.com/hanzoai/commerce">Hanzo Commerce Repository</a></li></ol>
<h2>Copyright</h2>
<p>Copyright and related rights waived via <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0</a>.</p>
<h2>Conformance status</h2>
<p>Measured against <code>hanzoai/commerce</code> at <code>c17a4f786</code> on 2026-09-09. The credit model ships; the payment-sovereignty claim in the abstract does not.</p>
<p><strong>The native PSP does not exist as a rail.</strong> <code>payment/processor</code> defines sixteen <code>ProcessorType</code> values. The fiat ones are <code>stripe</code>, <code>square</code>, <code>paypal</code>, <code>adyen</code>, <code>braintree</code>, <code>recurly</code>, <code>lemonsqueezy</code> — every one a third-party processor. The first-party ones are crypto (<code>mpc</code>, <code>bitcoin</code>, <code>ethereum</code>, <code>solanapay</code>, <code>circle</code>) plus <code>wire</code>. There is no <code>hanzopay</code> or <code>lux-pay</code> type, so &quot;the native PSP is always the default and the only rail a first-party surface is required to support&quot; describes a rail that is not implemented.</p>
<p><strong>A first-party surface&#x27;s fiat default is Square.</strong> <code>DefaultConfig()</code> sets <code>ProcessorPriority</code> to <code>Square</code> first, annotated in the source as <code>// fiat default — pay.hanzo.ai (Square + crypto)</code>. Stripe is registered but held un-selectable for new charges through <code>DisabledProcessors</code>, which is a deliberate and well-built deny policy — but it is a policy about <em>which</em> third-party processor is used, not evidence of a native one. The abstract&#x27;s &quot;no first-party surface registers an external processor that can deplatform the ecosystem&quot; is contradicted by the shipped default.</p>
<p>This is the gap that keeps this HIP a Draft, and it is a substantive one: the document mandates payment sovereignty as a first-class requirement and gives the deplatforming history as the reason. Either the native PSP lands and the default moves to it, or this HIP is rewritten to describe Square-first fiat with crypto as the sovereign rail. It should not be marked Final while it reads as though the first has already happened.</p>
<p>The crypto half is sound: <code>DefaultCryptoProcessor</code> defaults to <code>MPC</code>, a first-party rail, and crypto routing is by currency rather than preference order.</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/hip-0018.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>