1. Composing Google AP2 Authorization with x402 v2 Settlement
In autonomous agent commerce, Google AP2 proves cryptographic intent and budget boundaries (IntentMandate → CartMandate → PaymentMandate), while x402 v2 executes per-call HTTP 402 settlement over Base Mainnet USDC or Stacks sBTC:
| Layer / Rail | Wire Envelope | Asset & Atomic Precision | Replay & Safety Invariant |
|---|---|---|---|
| AP2 Mandate Chain | Signed CartMandate + PaymentMandate | Integer minor units (int only) | mandate_id + allowed_payees + hop expires_at |
Base x402 v2 | PAYMENT-REQUIRED / PAYMENT-SIGNATURE | USDC 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 (6 dec) | EIP-712 EIP-3009 32-byte nonce + validBefore |
Stacks x402 sBTC | X402_RELAY Durable Object RPC | sBTC SIP-010 (8 dec sats, 128-bit Clarity uint) | HTTP 409 PAYER_NONCE_UNVERIFIED + is_terminal=1 |
| Server Ledger | SQLite WAL / Postgres ON CONFLICT | args_sha256 canonical payload digest | 4-tuple (tenant_id, token_id, tool_name, client_key) |
2. Four Non-Negotiable Settlement Invariants (SPEC_CLASS_09 & A2A-06)
- Zero IEEE-754 binary floats: Convert decimal strings via exact
Decimalscaling and compute fees strictly in integer basis points:(gross_atomic * (10_000 - fee_bps)) // 10_000. - Non-negative bounded slippage: Reject
slippage_bps < 0or> 5000(A2A_INVALID_SLIPPAGE_BPS). - Payee allowlist binding: Enforce
mandate.pay_to in leaf_grant.allowed_payeesto block MITM payee substitution on untrusted 402 challenges. - 4-tuple WAL idempotency: Bind retries to
(tenant_id, token_id, tool_name, client_key)+args_sha256so socket retries replay the settled receipt with zero duplicate charges.
3. Copy-Paste Reference: Atomic USDC Math & x402/AP2 Mandate Verifier
from decimal import Decimal, InvalidOperation
import re
import time
from typing import Any
BASE_MAINNET_NETWORK = "eip155:8453"
BASE_USDC_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
USDC_DECIMALS = 6
EVM_ADDR_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
def usdc_str_to_atomic_int(amount_usdc: str) -> int:
try:
dec = Decimal(amount_usdc.strip())
except (InvalidOperation, AttributeError) as exc:
raise ValueError(f"Invalid USDC decimal string: {amount_usdc!r}") from exc
if not dec.is_finite() or dec <= 0:
raise ValueError("USDC amount must be positive and finite")
scaled = dec * (Decimal(10) ** USDC_DECIMALS)
if scaled != int(scaled):
raise ValueError(f"Exceeds {USDC_DECIMALS} decimal places: {amount_usdc!r}")
return int(scaled)
def compute_net_settlement_atomic(gross_atomic: int, fee_bps: int) -> int:
if isinstance(gross_atomic, bool) or not isinstance(gross_atomic, int) or gross_atomic <= 0:
raise ValueError("gross_atomic must be a positive int")
if isinstance(fee_bps, bool) or not isinstance(fee_bps, int) or not (0 <= fee_bps <= 10_000):
raise ValueError("fee_bps must be an int in [0, 10000]")
return (gross_atomic * (10_000 - fee_bps)) // 10_000
def verify_x402_ap2_mandate(
mandate: dict[str, Any],
*,
allowed_payees: set[str],
max_spend_atomic: int,
delegation_expires_at: int,
now_epoch: int | None = None,
) -> dict[str, Any]:
now = int(time.time()) if now_epoch is None else now_epoch
amt = mandate.get("amount_minor_units")
if isinstance(amt, bool) or not isinstance(amt, int) or amt <= 0:
raise ValueError("A2A_FLOAT_OR_NONPOSITIVE_AMOUNT")
if amt > max_spend_atomic:
raise PermissionError(f"A2A_SPEND_CAP_EXCEEDED: {amt} > {max_spend_atomic}")
pay_to = str(mandate.get("pay_to") or "")
if not EVM_ADDR_RE.match(pay_to) or pay_to not in allowed_payees:
raise PermissionError(f"A2A_UNAUTHORIZED_PAYEE: {pay_to!r}")
slip = mandate.get("slippage_bps", 0)
if isinstance(slip, bool) or not isinstance(slip, int) or not (0 <= slip <= 5000):
raise ValueError(f"A2A_INVALID_SLIPPAGE_BPS: {slip!r}")
exp = mandate.get("expires_at")
if isinstance(exp, bool) or not isinstance(exp, int) or now > exp or exp > delegation_expires_at:
raise PermissionError("A2A_PAYMENT_MANDATE_EXPIRED_OR_EXCEEDS_HOP")
if not str(mandate.get("mandate_id") or "").strip() or not str(mandate.get("idempotency_key") or "").strip():
raise ValueError("A2A_MISSING_MANDATE_OR_IDEMPOTENCY_KEY")
return {"approved": True, "network": BASE_MAINNET_NETWORK, "asset": BASE_USDC_CONTRACT, "amount_atomic": amt}