BlogTangle Network Protocolpart 7 of 10

x402 Payments for AI Agents: v2 Safety Guide

How an agent reads an x402 price, avoids duplicate charges, and reconciles settlement with the work it paid for.

This post is about the Tangle Network protocol, a separate project from Tangle's infrastructure for AI agents. Introduction to Tangle covers the agent infrastructure.

An agent reaches a paid endpoint while processing a customer request. The server returns HTTP 402 and asks for a small stablecoin payment. The dangerous implementation signs whatever amount appears in the response and retries automatically. The safe implementation treats the 402 response as a policy decision.

The x402 protocol is an HTTP payment flow for AI agents. The server states what payment it accepts. The agent checks the amount, asset, network, recipient, expiry, and requested capability. A wallet signs a payment payload. The agent retries the request. The server verifies and settles the payment, then returns the resource or accepts the job.

That payment step does not prove the service did useful work. A receipt can show that payment conditions were met. It cannot show that a browser task reached the right page, a sandbox fixed the right file, or a model returned a correct answer.

The Tangle surface this post depends on is the x402 job route on a Blueprint operator’s gateway, POST /x402/jobs/{service_id}/{job_index}. An unpaid POST returns 402 with the payment requirements. A paid POST returns 202 Accepted once the job is enqueued, which means accepted, not finished. The price route, GET /x402/jobs/{service_id}/{job_index}/price, needs no payment, so a buyer can read the price before signing.

Define the pieces before spending

x402 uses the HTTP 402 Payment Required status to communicate payment requirements for a resource. It is designed for programmatic clients, including AI agents, that can inspect requirements, sign with a wallet, and retry without first creating a conventional account. The Coinbase x402 overview and protocol flow document that sequence.

A wallet is the software or service that controls a payment key and signs a payment payload. The agent should be able to ask the wallet to sign within a spending policy. The agent should not receive a raw seed phrase as a tool input.

A facilitator is a service that helps a resource server, the endpoint selling the resource, verify and settle a payment on a supported network. The purchased AI service performs the work after the payment path accepts the request.

A Blueprint is a reusable Tangle service definition. It declares jobs, inputs, outputs, artifacts, and execution requirements. A job is one callable unit of work inside a live service. An operator is the infrastructure provider that runs the service instance created from the Blueprint. The Tangle Blueprint introduction defines those terms.

A trace is the structured record of the request, payment state, tool calls, outputs, timing, and failures. An evaluation is the repeatable check of the result, cost, and policy behavior. Payment is one event in the trace, not the evaluation. The Blueprint SDK x402 guide shows the adjacent Tangle job path. The x402 Blueprint deployment checklist covers the operator decisions that need to be settled before exposure.

An agent profile sets the model, tools, permissions, budget, and spending rules for one agent. It should name the services and recipients the agent may pay and the maximum amount it may authorize.

The x402 v2 request flow

The protocol flow is a conversation between a buyer and a resource server:

Step Direction What happens
1 Agent to server The agent requests a resource or job without a payment signature
2 Server to agent The server returns 402 and payment requirements
3 Agent The agent checks the requirements against its policy
4 Wallet to agent The wallet signs a payment payload
5 Agent to server The agent retries the same request with the payment signature
6 Server and facilitator The server verifies and settles the payment
7 Server to agent The server returns the resource and settlement response

The Coinbase v2 documentation names three headers:

Header Direction Purpose
PAYMENT-REQUIRED Server to client Encodes accepted payment requirements in the 402 response
PAYMENT-SIGNATURE Client to server Carries the signed payment payload on the retry
PAYMENT-RESPONSE Server to client Returns settlement information with the resource

A generic request shape looks like this:

POST /paid-task HTTP/1.1
Content-Type: application/json
Idempotency-Key: task-2026-08-03-001

{"task":"summarize the attached report"}

HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: <base64-encoded-payment-requirements>

POST /paid-task HTTP/1.1
Content-Type: application/json
Idempotency-Key: task-2026-08-03-001
PAYMENT-SIGNATURE: <base64-encoded-signed-payment-payload>

{"task":"summarize the attached report"}

HTTP/1.1 202 Accepted
PAYMENT-RESPONSE: <base64-encoded-settlement-response>
Content-Type: application/json

{"jobId":"job-17","status":"accepted"}

The payload is not arbitrary JSON. Its exact fields depend on the x402 version, payment scheme, network, asset, and implementation. The x402 migration guide documents the v1 and v2 header and network differences. The v2 documentation uses CAIP-2 network identifiers, such as eip155:84532, rather than human chain names.

The Idempotency-Key here is an application-level header, not a guarantee that the service deduplicates work. The server must define what the key means and retain enough state to answer a retry.

A 402 response is not permission to pay

The agent should decode the payment requirements and compare them with a local policy before asking a wallet to sign.

Check Question
Capability Is this endpoint the service the agent intended to buy?
Amount Is the amount within the per-request and daily budget?
Asset Is the token an approved asset with a known decimal format?
Network Does the wallet support the requested chain identifier?
Recipient Does the destination match the service or an approved recipient?
Expiry Does the signature remain valid only for the necessary window?
Scheme Does the wallet support the requested payment scheme?
Request binding Does the signed request cover the method, URL, and required body fields?
Output Does the agent know what resource, job ID, receipt, or evidence it will receive?

A small policy function makes the decision testable:

type PaymentRequest = {
  resource: string
  amount: string
  asset: string
  network: string
  payTo: string
  validBefore: number
}

type SpendPolicy = {
  allowedResources: string[]
  allowedAssets: string[]
  allowedNetworks: string[]
  allowedRecipients: string[]
  maxAmount: bigint
  now: number
}

function approvePayment(request: PaymentRequest, policy: SpendPolicy) {
  const reject = (reason: string) => ({ approved: false, reason })
  if (!policy.allowedResources.includes(request.resource)) return reject('resource is not allowed')
  if (!policy.allowedAssets.includes(request.asset)) return reject('asset is not allowed')
  if (!policy.allowedNetworks.includes(request.network)) return reject('network is not allowed')
  if (!policy.allowedRecipients.includes(request.payTo)) return reject('recipient is not allowed')
  if (BigInt(request.amount) > policy.maxAmount) return reject('amount exceeds policy')
  if (request.validBefore <= policy.now) return reject('payment window is expired')
  return { approved: true, reason: 'payment matches policy' }
}

This policy is illustrative, not an SDK parser. The agent should use the payment requirements supplied by the server rather than inventing a payload. The wallet or x402 client library should perform the actual signing.

Fail closed when a required field is missing or ambiguous. A cheap request is still unauthorized when it points to the wrong recipient. A valid signature is still unsafe when the agent did not understand what it buys.

The version boundary around Tangle Blueprint jobs

The public x402 protocol documentation recommends v2 for new integrations. A particular service can still expose a different wire version or compatibility path.

The current public Tangle Blueprint x402 documentation describes an optional off-chain, or non-blockchain, payment ingress for jobs. It says the gateway verifies and settles payment, meaning records the transfer as accepted, then injects a JobCall, a job invocation record, into the Blueprint runtime. It documents job routes as:

POST /x402/jobs/{service_id}/{job_index}

The same docs describe invocation modes:

Mode Meaning
disabled The job cannot be called through x402
public_paid A valid payment can invoke the job
restricted_paid Payment is required and a caller policy must also pass

The current public Blueprint x402 crate README documents the x402 ingress with legacy X-PAYMENT and X-Payment-Response headers. The Coinbase v2 docs use PAYMENT-SIGNATURE and PAYMENT-RESPONSE. Those are not interchangeable examples.

This is the integration rule:

  1. Identify the exact server endpoint and released package.
  2. Read that endpoint’s payment-version and header contract.
  3. Use a client and facilitator that support the same version and network.
  4. Test an unpaid request, a valid payment, a rejected payment, and a repeated request.
  5. Record the release or API version in the integration configuration.

Step 4 starts with the two unpaid calls. This fence reads the price route, then sends an unpaid POST to the job route, using the operator origin, service ID, and job index from the environment.

// Read a Tangle x402 job's price, then probe its paid route unpaid.
const base = process.env.TANGLE_X402_OPERATOR_URL! // the operator's origin
const job = `${base}/x402/jobs/${process.env.TANGLE_SERVICE_ID!}/${process.env.TANGLE_JOB_INDEX!}`

// The price route needs no payment.
const price = await fetch(`${job}/price`)
console.log(price.status, await price.text())

// With no payment, the x402 middleware answers before the job is enqueued.
const unpaid = await fetch(job, {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: '{}', // a placeholder for the job's real input
})
console.log(unpaid.status, unpaid.headers.get('content-type'))
console.log(await unpaid.text()) // the payment requirements, in the form this endpoint's x402 version defines

On an enabled job, expect 402 from the POST. Read the requirements it returns before signing anything; the header or body that carries them is set by the x402 version the endpoint speaks, so print both. A 403 with x402_disabled from the price route means the job is not enabled for x402. The 402 shows that the route is gated, not which version it speaks, so check what it returned against that endpoint’s documented contract.

Do not copy a v2 header example into a Tangle endpoint that currently documents the legacy header. Do not assume a route called x402 has one universal payload shape.

Tangle’s public docs also expose an authorization dry run for restricted jobs. It checks caller policy without enqueuing work or settling payment. Use it when the job has access restrictions, but do not treat a dry run as proof that the paid job will complete.

Payment acceptance is not job completion

The Tangle x402 docs define a successful paid request as 202 Accepted after the job is accepted and enqueued. That means the server accepted the work, not that the job finished.

A paid request needs a state model:

State Meaning Safe next action
Not paid No valid payment was accepted Do not claim access or retry without policy
Payment state unknown The facilitator or network result is uncertain Query the payment or job before signing again
Paid and enqueued Payment settled and work entered the runtime Poll or follow the documented result path
Paid but failed Payment settled and execution failed Apply refund, retry, or support policy
Completed but response lost Work may have finished even though the client timed out Query by job ID before retrying
Completed and reviewed Output and task checks passed Release the result to the next workflow

If the server returns only a Boolean “paid,” the buyer cannot safely recover from a lost response. The payment receipt and job ID should be correlated. The service should document whether a retry with the same request identifier returns the existing result or starts a new job.

Idempotency is a job property

The endpoint must define whether two identical requests produce one job or two.

For an idempotent job, the server can store:

{
  "requestKey": "task-2026-08-03-001",
  "requestDigest": "sha256:request-body",
  "paymentState": "settled",
  "jobId": "job-17",
  "executionState": "running",
  "result": null
}

On a repeated request, the server compares the digest and returns the existing job when the key matches. If the same key is used with a different body, the server should reject it. A server that ignores the body can accidentally return one customer’s result for another customer’s request.

The x402 FAQ documents a Payment Identifier extension for handling duplicate calls. Use that extension or an application-level key that matches your client and server versions. Do not invent idempotency semantics at the agent layer after payment has already moved.

Tangle’s restricted delegated-caller path adds a one-use nonce and a replay check. The public Tangle docs say a reused nonce in the same caller and job scope is rejected in the paid flow. It is an authorization control, not request deduplication for public paid jobs.

Payment and result evidence answer different questions

Return evidence matched to the purchased work:

Purchased work Payment evidence Result evidence
Browser task Settlement response and job ID Final URL, screenshots, DOM state, and action record
Sandbox repair Settlement response and job ID Exit status, changed files, logs, and artifact hashes
Model call Settlement response and model route Model ID, usage, structured-output validation, and policy checks
Code audit Settlement response and job ID Reproduction, affected files, regression test, and findings
On-chain action Settlement response and transaction reference Chain, transaction receipt, contract, and decoded event

A trace connects these records over time. An evaluation checks whether the work met the task contract. Neither one is created automatically by a successful payment.

Many agent products show a payment receipt next to a fluent answer and call the pair “verified.” The receipt proves a payment event. The answer needs its own evidence.

Failure cases to test before launch

Test a signature for the wrong recipient. Test a signature with the wrong amount or asset. Test a network identifier that the wallet does not support. Test an expired payment window. Test a malformed payload. Test a facilitator timeout before settlement is known. Test settlement success followed by a job failure. Test job success followed by a lost HTTP response. Test two calls with the same request key. Test two calls with the same key but different bodies. Test a restricted job with a valid payer and an unauthorized caller. Test a client that speaks v1 against a server that requires v2. Test a v2 client against a service that documents legacy headers.

For each case, record:

{
  "payment": "not-paid | unknown | settled",
  "execution": "not-started | queued | running | failed | completed",
  "response": "received | lost",
  "retry": "safe | query-first | forbidden",
  "customerAction": "retry | poll | refund | human-review"
}

The categories are separate on purpose: a retry can be safe in one state and harmful in another.

x402 or a subscription?

x402 is a good fit when the commercial unit is one request and the buyer is software. A subscription or prepaid account is often a better fit when a team needs invoices, tax records, shared budgets, refunds, procurement, or predictable monthly administration.

Prefer x402 when Prefer subscription or prepaid billing when
One request maps to one price Many users share one account
Wallet signing is acceptable Card, invoice, tax, or refund workflows are required
Stateless access is useful Account history and team administration matter
The agent can inspect payment terms A human approves purchases in a dashboard
Settlement latency fits the job The request path needs a stable pre-funded balance
The service can expose a clear result contract Usage is pooled across many kinds of work

A service can support both paths if both converge on the same authorization, job-dispatch, evidence, and refund rules after payment.

What are x402 payments for AI agents?

They are HTTP-native machine payments in which a server returns 402 payment requirements, an agent signs a payment payload with a wallet, and the agent retries to receive a resource or job result.

Does x402 replace API keys?

It can provide a paid access path without an API key for public jobs. A restricted job may still require identity, caller authorization, or another access policy in addition to payment.

What headers does x402 v2 use?

The documented v2 flow uses PAYMENT-REQUIRED, PAYMENT-SIGNATURE, and PAYMENT-RESPONSE. Legacy implementations use different X-PAYMENT names, so the server and client versions must match.

Does a successful payment prove the service result is correct?

No. Payment proves a payment condition was met. The service must return task-specific evidence, and the buyer must evaluate that evidence.

What does 202 Accepted mean for a Tangle x402 job?

The current Tangle docs mean that payment was accepted and the job enqueued, not completed.

How should an agent avoid duplicate charges?

Check the request key, payment state, and job state before retrying. Use the idempotency or payment-identifier feature supported by the exact client and server pair.

The decision

Treat every 402 response as an authorization request with a budget, recipient, network, and capability. Keep protocol version, payment state, job state, and result quality visible in the same record. Use x402 when per-request machine payment is the simplest commercial boundary, and choose a subscription when account administration and refunds are the real product requirement. For a browser workflow that must carry a payment or wallet decision safely, see natural-language end-to-end testing for wallet apps.

Next in Tangle Network Protocol: Deploy a Paid AI Agent Service: One Traceable Job