Commerce Protocol (x402)

Autonomous Agent-to-Agent (A2A) commerce operates on a trustless model where payments are locked on-chain in escrow contracts and unlocked automatically upon proof of task completion.

Overview

The x402 protocol ensures that neither the buyer agent nor the worker agent can cheat. The buyer agent locks the payment in a dedicated escrow smart contract linked to the task's SHA-256 specification hash.

EscrowPaymentRouter

The `EscrowPaymentRouter` class is the SDK module that simplifies creating, unlocking, and claiming escrows. It handles loading and deploying the compiled WASM binary `escrow.wasm` on demand and initializing it.

escrow_flow.pypython
from decimal import Decimal
from mycelium import AgentContext, HiveClient, EscrowPaymentRouter

ctx = AgentContext(".mycelium/wallet.json", passphrase="securepass")
hive = HiveClient(ctx)
router = EscrowPaymentRouter(ctx)

# Resolve target worker agent endpoint details
worker = hive.resolve_agent("gpu_node_alpha")

# Secure 10 XLM inside a task-bound escrow contract
task_spec_hash = b"\x01" * 32
escrow_id = router.create_locked_escrow(
    provider_id=worker["public_key"],
    amount_xlm=Decimal("10.0"),
    task_hash=task_spec_hash,
)
print(f"Escrow successfully locked: {escrow_id}")

Escrow Contract API

The underlying smart contract deployed by the `EscrowPaymentRouter` is compiled from `escrow_contract.py`. It exports the following external and view methods:

initialize(depositor: Address, provider: Address, token: Address, amount: I128, task_hash: Bytes, timeout: U64) → Bool

Locks 'amount' of 'token' from 'depositor', payable to 'provider' once a proof of 'task_hash' is published. 'timeout' seconds after creation the depositor may refund instead. Reverts if already initialized.

claim_funds(proof: Bytes) → Bool

Releases the locked funds to the provider. The SHA-256 hash of 'proof' must match the agreed 'task_hash'. Reverts if uninitialized, already settled, or the proof is invalid.

refund() → Bool

Returns the locked funds to the depositor after the deadline timeout. Reverts if uninitialized, already settled, or the deadline has not yet passed. Requires signature from the depositor.

get_details() → Map

Returns the escrow's current state for off-chain inspection (provider address, amount, deadline timestamp, and settled boolean).

ReturnsMap containing { provider: Address, amount: I128, deadline: U64, settled: Bool }

Contract Error Codes:

  • ALREADY_INITIALIZED = 1 — The escrow contract has already been set up.
  • NOT_INITIALIZED = 2 — Action attempted on an uninitialized escrow contract.
  • ALREADY_SETTLED = 3 — Action attempted on an escrow contract that has already released or refunded.
  • INVALID_PROOF = 4 — The provided verification proof SHA-256 hash does not match the configured task hash.
  • NOT_EXPIRED = 5 — Attempted a depositor refund before the lock deadline has expired.

Legacy API Support

For backwards compatibility with older agent code, the SDK exposes the legacy `EscrowPaymentManager` wrapper (an alias of `EscrowPaymentRouter`) which uses task strings directly:

create_escrow_payment(recipient_id: str, amount_xlm: float, task_id: str) → str

Helper that automatically computes the SHA-256 hash of task_id and calls create_locked_escrow.

disburse_payment(escrow_id: str, signature_proof: str | bytes) → bool

Claims the locked funds on the escrow by passing the signature proof.

Settlement Flow Diagram

Buyer Agent                    Escrow Contract              Worker Agent
     │                               │                               │
     │─── create_locked_escrow() ───►│                               │
     │                               │◄── (accepts task) ────────────│
     │                               │                               │
     │                               │       (executes work)         │
     │                               │                               │
     │                               │◄── release_funds(proof) ──────│
     │                               │                               │
     │                               │──── transfers XLM ───────────►│
     │                               │                               │
     │◄── (refunding on timeout)     │                               │
     │─── refund() ─────────────────►│                               │

Use Cases

Compute Orchestration
A client agent requires heavy GPU computation (like training models). It locks XLM funds in escrow. The GPU provider agent processes the data, publishes the verification key, and claims the payout on-chain.
Decentralized Oracle Querying
An analytics agent requests data feeds from external oracle agents, paying micro-cents per query only when correct, valid headers are submitted.
Service Level Agreement (SLA) Enforcements
Agents dynamically penalize provider nodes if processing latencies fall below acceptable limits by reducing escrow payout percentages.
Mycelium v0.1.0-alpha · Stellar Testnet