A2A x402 Extension

repository·main·Indexed 19 days ago

https://github.com/google-agentic-commerce/a2a-x402

Official x402 payment protocol extension for Agent-to-Agent (A2A) commerce (v0.1.0). It enables cryptocurrency-based monetization for AI services, such as inference or data processing, by implementing a standardized 'Payment Required' flow on-chain. The library provides a functional core for protocol data structures and executors for client and server integration, supporting dynamic pricing via the x402PaymentRequiredException and a pluggable Wallet interface for transaction signing.

Tokens
35.4K
Snippets
77
Records
109
Agent score
68%

What's inside x402-a2a

  1. Explore the x402 repository structure

    main

    The repository is organized into specifications, experimental schemes, and language-specific implementations:

    • x402-a2a/spec/v0.1/spec.md: The official technical specification.
    • x402-a2a/schemes/: Experimental payment schemes drafted by contributors.
    • {language}/x402_a2a/: The core library implementation for a specific language.
    • {language}/examples/{demo}/: Demonstration applications for the core library.
  2. Manage x402 payment state via Message metadata

    main

    The x402 extension tracks payment progress using the metadata field on Message objects. Developers must use specific keys depending on whether they are implementing a Standalone Flow or an Embedded Flow.

    Required Keys

    • x402.payment.status: (Required) The current stage of the payment flow. This MUST be present in all x402-related messages.
    • x402.payment.receipts: (Required) A persistent array containing the complete history of all x402SettleResponse objects for the task. This MUST be present in the final task message.

    Flow-Specific Keys

    • Standalone Flow Only:
      • x402.payment.required: The default metadata key for the x402PaymentRequiredResponse object.
      • x402.payment.payload: The default metadata key for the PaymentPayload object.
      • Note: These MUST NOT be used if an Embedded Flow is active.

    Status Values for x402.payment.status

    • payment-required: Payment requirements have been sent.
    • payment-submitted: Payment payload has been received.
    • payment-rejected: Payment requirements have been rejected.
    • payment-verified: Payment payload has been verified.
    • payment-completed: Payment transaction has been settled.
    • payment-failed: Payment failed.
  3. Implement Flow Detection Logic for x402

    main

    A Client Agent must distinguish between Standalone and Embedded flows when it receives a Task where task.status.message.metadata contains x402.payment.status: "payment-required".

    Follow this decision path:

    1. Inspect task.status.message.metadata.
    2. Check for Standalone Flow: If the metadata contains the x402.payment.required key, it is a Standalone Flow. Retrieve the x402PaymentRequiredResponse from the value of the x402.payment.required key.
    3. Otherwise (Embedded Flow): If the key is missing, it is an Embedded Flow. Scan the task.artifacts array to find a supported higher-level artifact (e.g., an AP2 CartMandate) and extract the x402PaymentRequiredResponse from within it.
  4. Understand the `exact` payment scheme for UMA

    main

    The exact scheme is a specific implementation of the x402 protocol designed for UMA. It allows for payments of a specific amount over Bitcoin using UMA, either by sending payments directly to a UMA address or by using a provided UMA invoice.

    Protocol Flow:

    1. Request: Client requests a resource from a Resource Server.
    2. Challenge: Resource Server returns 402 Payment Required with paymentRequirements (using the exact scheme).
    3. Payment: Client either sends an LNURLp request to the payTo address OR decodes the umaInvoice found in the extra field to send a pay request to the specified URL.
    4. Settlement: Client completes the UMA handshake and makes the payment.
    5. Verification: Client retries the original request, including an X-PAYMENT header containing the payment proof.
    6. Access: Resource Server verifies the proof and returns the resource with a 200 OK and an X-PAYMENT-RESPONSE header.
  5. How the x402 Payment Protocol Flow works

    main

    The x402 extension manages the lifecycle of a payment through three main steps involving a Client Agent and a Merchant Agent:

    1. Payment Request (Merchant → Client): The Merchant Agent identifies a service requires payment. It responds with a Task in the input-required state. The task's message metadata contains x402.payment.status: "payment-required" and an x402.payment.required object listing accepted payment terms.
    2. Payment Authorization (Client → Wallet → Client): The Client Agent evaluates the requirements. If accepting, it selects a requirement and uses a signing service/wallet to create a signed PaymentPayload. If rejecting, it responds with x402.payment.status: "payment-rejected".
    3. Fulfill and Settle (Client → Merchant → Client): The Client Agent sends a new message to the Merchant containing the PaymentPayload and the original taskId. The Merchant verifies and settles the payment on-chain, then updates the task status (e.g., to payment-verified or payment-completed) and includes x402.payment.receipts in the metadata.
    sequenceDiagram
        participant Client Agent
        participant Merchant Agent
        Client Agent->>Merchant Agent: 1. Request service (Message)
        Merchant Agent-->>Client Agent: 2. Respond with Task (state: 'input-required', message: { metadata: x402PaymentRequiredResponse })
        Client Agent->>Client Agent: 3. Create signed PaymentPayload (Typically signed by a wallet or separate service)
        Client Agent->>Merchant Agent: 4. Fulfill request (Message with metadata containing PaymentPayload & taskId)
        Merchant Agent->>Merchant Agent: 5. Verifies and settles the PaymentPayload (Typically verified by an x402 Facilitator) and begins processing the task*.
        Merchant Agent-->>Client Agent: 6. Respond with updated Task (state: e.g., 'working', message: { metadata: { x402.payment.receipts: [...] }, payment-status: payment-verified | payment-complete })
  6. Roles and Responsibilities in x402

    main

    The protocol defines four logical roles:

    • Client Agent: Acts on behalf of the user. It initiates requests, processes x402PaymentRequiredResponse, manages signing via a wallet/service to create a PaymentPayload, and submits the payload back to the Merchant.
    • Merchant Agent: Provides the monetized service. It determines when payment is needed, manages the taskId state, communicates with facilitators to verify/settle payments, and returns the final service Artifact and payment receipt.
    • Signing Service/Wallet (Implicit): A service used by the Client Agent to securely sign the payment requirements to create a valid PaymentPayload.
    • Facilitator (Implicit): A service used by the Merchant Agent to verify the signature and settle the transaction on-chain.
  7. Implement a custom Wallet for the Client Agent

    main

    The ClientAgent uses a pluggable Wallet interface (wallet.py) to handle transaction signing. This allows you to decouple orchestration logic from the specific signing mechanism.

    In the demo, MockLocalWallet is used (signing with a hardcoded private key). To use this in production, you can implement the Wallet interface to connect to:

    • Browser extensions (e.g., MetaMask)
    • Secure MPC (Multi-Party Computation) services
    • Hardware signing devices
  8. Understand the `exact` payment scheme for Lightning Network

    main

    The exact scheme is a specialized x402 protocol implementation for Bitcoin's Lightning Network. It uses the BOLT11 invoice standard to facilitate instant, low-fee micropayments.

    Key characteristics:

    • Instant Settlement: Sub-second confirmation.
    • Micropayment Friendly: Supports sub-cent transactions.
    • Security: Uses preimage verification and protects against invoice reuse and routing attacks.

    Protocol Flow:

    1. Client requests a resource from the Resource Server.
    2. Resource Server requests a BOLT11 invoice from a Lightning Facilitator.
    3. Resource Server returns a 402 Payment Required response containing PaymentRequirements (including the invoice in the extra field).
    4. Client signs an authorization for that specific invoice.
    5. Client submits a PaymentPayload containing the signed authorization.
    6. Resource Server asks the Facilitator to verify the signature.
    7. Resource Server asks the Facilitator to settle the payment (the facilitator pays the invoice on the Lightning Network).
    8. Resource Server grants access upon successful settlement.
  9. Architectural patterns for Signing Service roles

    main

    The Signing Service is a recommended architectural pattern for security and domain separation. While the x402 spec does not mandate a specific implementation, separating signing logic from the Client Agent allows for the use of secure environments like HSMs, MPC, or hardware wallets.

    Implementation Options:

    1. Separate Signing Service (Recommended): The Client Agent communicates with an independent service. This creates a clear security boundary.
    2. Integrated Signing: The Client Agent handles signing directly. This is spec-compliant but offers less domain separation.

    Core Responsibility: Receive an x402PaymentRequiredResponse, select an appropriate PaymentRequirements option from the accepts list, sign it using a private key/account, and return a PaymentPayload.

    # Example pattern for a Signing Service
    class SigningServiceOperations:
        def __init__(self, account: Account):
            self._account = account
            
        async def process_payment_required(
            self, 
            payment_required: x402PaymentRequiredResponse, 
            max_value: Optional[int] = None
        ) -> PaymentPayload:
            # 1. Select requirement
            selected_requirement = self._select_payment_requirement(payment_required.accepts)
            # 2. Sign requirement
            payment_payload = await process_payment(selected_requirement, self._account, max_value)
            return payment_payload
    
        def _select_payment_requirement(
            self, 
            accepts: list[PaymentRequirements]
        ) -> PaymentRequirements:
            return accepts[0]  # Implementation specific selection logic
  10. How the x402 library architecture works

    main

    The x402_a2a libraries are designed using a functional core, imperative shell architecture to balance control and ease of use:

    • Core Protocol: Provides the fundamental data structures and pure functions required to create, sign, and verify payments. Use this if you need to implement highly customized payment logic.
    • Executors: These are middleware components that automate the entire payment flow. Use these to quickly add payment capabilities to an existing agent with minimal boilerplate.
  11. Manage Signing Models in Embedded Flows

    main

    In an Embedded Flow, an order authorization (e.g., AP2 PaymentMandate) envelops the x402PaymentPayload. Because x402 is a "push" payment method, the payload itself is the cryptographic authorization. The specification supports three patterns to handle this without excessive user friction:

    1. Atomic Signing (Human-Present Flow)

    Recommended for direct, human-present transactions.

    • The Client Agent assembles both the unsigned order authorization and the unsigned x402PaymentPayload.
    • A compatible wallet presents a single, unified confirmation to the user.
    • The wallet performs two signatures: first the x402PaymentPayload, then the complete order authorization containing the signed payload.

    2. Delegated Signing (Human-Not-Present Flow)

    Ideal for asynchronous agentic commerce.

    • The user provides a pre-authorization signature at an earlier time, granting the Client Agent authority within specific constraints.
    • The Client Agent uses its own or a delegated key to sign both the x402PaymentPayload and the order authorization at the time of execution.

    3. Smart Contract Escrow (Decoupled Flow)

    Ideal for pre-funded users.

    • Setup: User moves funds into a smart contract (one-time on-chain "push").
    • Checkout: The Client Agent constructs only the order authorization. The user signs this single off-chain message.
    • Settlement: The Merchant Agent presents the signed order to the smart contract, which verifies the signature and rules, then releases the pre-deposited funds to the merchant.
  12. How the x402 Payment Flow works

    main

    The x402 protocol separates business logic from payment protocol logic using an interceptor pattern.

    Merchant-Side Flow

    1. The AdkMerchantAgent handles business logic (e.g., product details).
    2. When a payment is needed, the agent raises a x402PaymentRequiredException.
    3. The x402ServerExecutor (injected in routes.py) intercepts this exception to handle the protocol: creating the payment-required response, receiving the client's signed payload, verifying it, and settling the transaction.

    Client-Side Flow

    1. The ClientAgent receives a payment-required response from the merchant.
    2. The agent prompts the user for confirmation.
    3. Upon confirmation, the agent calls its injected Wallet to sign the payment details.
    4. The agent uses x402Utils from the core library to construct a payment-submitted message and sends it to the merchant to finalize the purchase.