CHAPTER 04 // X402 HTTP 402, AP2 MANDATES & MINOR-UNIT MATH

x402 HTTP 402 & AP2 Agent Payments Wiki: Base USDC EIP-3009, Stacks sBTC & Integer Minor-Unit Caps

Complete architecture reference for machine-to-machine A2A & MCP settlement combining HTTP 402 x402 v2 (Base Mainnet USDC EIP-3009 & Stacks sBTC) with Google AP2 cryptographic mandates, zero-float atomic integer math, and 4-tuple WAL idempotency locks.

EIP155:8453 USDC · STACKS SBTC · AP2 MANDATES
4-Tuple WAL Deep Dive →

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 ChainSigned CartMandate + PaymentMandateInteger minor units (int only)mandate_id + allowed_payees + hop expires_at
Base x402 v2PAYMENT-REQUIRED / PAYMENT-SIGNATUREUSDC 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 (6 dec)EIP-712 EIP-3009 32-byte nonce + validBefore
Stacks x402 sBTCX402_RELAY Durable Object RPCsBTC SIP-010 (8 dec sats, 128-bit Clarity uint)HTTP 409 PAYER_NONCE_UNVERIFIED + is_terminal=1
Server LedgerSQLite WAL / Postgres ON CONFLICTargs_sha256 canonical payload digest4-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 Decimal scaling and compute fees strictly in integer basis points: (gross_atomic * (10_000 - fee_bps)) // 10_000.
  • Non-negative bounded slippage: Reject slippage_bps < 0 or > 5000 (A2A_INVALID_SLIPPAGE_BPS).
  • Payee allowlist binding: Enforce mandate.pay_to in leaf_grant.allowed_payees to block MITM payee substitution on untrusted 402 challenges.
  • 4-tuple WAL idempotency: Bind retries to (tenant_id, token_id, tool_name, client_key) + args_sha256 so socket retries replay the settled receipt with zero duplicate charges.

3. Copy-Paste Reference: Atomic USDC Math & x402/AP2 Mandate Verifier

python // x402_ap2_mandate_guard.py
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}
1-CLICK .MCPB BUNDLES • MANIFEST V0.3 • ZERO RUNTIME DEPS

Install Companion A2A & MCP Verification Bundles in 1 Click

Full 9-Server .mcpb Hub →
a2a-wiki.mcpb .mcpb v0.3

Offline A2A v1.0.1 + MCP encyclopedia search & wire-diff reference server

a2a-iq-mcp.mcpb .mcpb v0.3

8-Dimension A2A v1.0.1 & MCP Model IQ Benchmark (IQ 60-160 + SVG radar)

mcp-tool-guard.mcpb .mcpb v0.3

7-tool A2A v1.0.1 JCS/JWKS verifier, 11-CVE SCA & 5-layer MCP guard

a2a-registry-bridge-mcp.mcpb .mcpb v0.3

Bidirectional A2A v1.0.1 <-> MCP converter & RFC 8032 Ed25519 card signer

a2a-x402-guard-mcp.mcpb PRIMARY

HTTP 402 x402 v2 Base USDC EIP-3009, Stacks sBTC & AP2 mandate guard

a2a-task-orchestrator-mcp.mcpb .mcpb v0.3

CAS atomic A2A TaskState FSM, 4-tuple WAL idempotency & BFT quorum

FIXED-SCOPE A2A & MCP ENGINEERING • 100% WRITTEN WORKFLOW

Need Production A2A v1.0.1 / MCP Bridging ($145–$290) or a 72h Security Hardening Audit ($450)?

I operate a transparent A2A engineering practice strictly via written channels (Email, GitHub Specs/PRs — zero live meetings), leading with Code-First PoCs, deterministic pytest/vitest suites, and $0 upfront Pay-on-Green-PR-Pass first-time trials ($145–$250).

Scope Fixed-Price A2A / MCP Sprint → 72h A2A & MCP Hardening ($450) → Test Agent IQ (60–160) →
A2A AGENT CARDv1.1.0 · VERIFIED_EDDSA
UPSTREAM TRACK33+ Merged Pull Requests
SECURITY SUITEmcp-tool-guard v0.7.0 (0 Deps)
WRITTEN SLA< 2–4h Initial Async Reply