Skip to content
Integra Protocol

x402

The legalContext extension, the request commitment, and the x402 pairings.

For AI agents: this page as Markdown, and llms.txt, the index of every page.

x402 is HTTP 402 payment: the seller answers a request with a PaymentRequired document listing the options it accepts, and the buyer retries with a payment for one of them. This package reads and writes x402 version 2 documents. Import the x402 pieces from @integraledger/lcp/x402. This page is for a seller or a buyer on x402: it gives where H rides in the document and the payment, every x402 pairing, and how to read a payment's settlement.

The legalContext extension

Every x402 pairing advertises H in the same place: the document's extensions.legalContext, as x402's extension mechanism defines it (an info object and a JSON Schema for it).

{
  "extensions": {
    "legalContext": {
      "info": {
        "type": "sha256",
        "value": "0xba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        "legalContextUrl": "https://atr.seller.example/b3195b1f-4115-46b2-95a3-c9d61d7bfb01"
      },
      "schema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object" }
    }
  }
}

LEGAL_CONTEXT is the extension's key and LEGAL_CONTEXT_SCHEMA the full schema every pairing writes. The buyer echoes extensions unchanged in its payment; x402 requires it to keep at least the info it received. When the seller passes an agreement URL, info also carries legalContextAgreementUrl (the agreement URL).

x402's cloudflare:402 network omits schema from the extensions it carries, to keep each header under 2 KB. On x402/batch-settlement/cloudflare the legalContext entry carries LEGAL_CONTEXT_SCHEMA as on every pairing, in PAYMENT-REQUIRED and again in the PAYMENT-SIGNATURE that echoes it.

One document has one legal context. Each pairing that advertises into the same document with the same H, link and agreement URL leaves info as it is and writes LEGAL_CONTEXT_SCHEMA as its schema; a different H, link or agreement URL (one given and the other absent included) is refused as x402/legal-context-conflict. The comparison is of the JSON values, so a legal context naming the same H in upper case, or the link as legal_context_url, is refused as x402/legal-context-conflict too. A challenge offering options on several rails therefore carries one H, and the buyer's payment on any of them is bound to the same ATR.

The headers

encodeHeader(value) writes PAYMENT-REQUIRED, PAYMENT-SIGNATURE or PAYMENT-RESPONSE as x402's HTTP transport and its stock clients write them: padded standard base64 of the UTF-8 of JSON.stringify(value), the object's members in their own order. As @x402/core 2.30.0 writes them, a member whose value is undefined is left out, at any depth, and so is a top-level extensionResponses, which its PAYMENT-RESPONSE encoder deletes. decodePaymentRequired, decodePaymentSignature and decodePaymentResponse read a header's value back: canonical padded base64 of well-formed UTF-8 that is a JSON object, at most MAX_HEADER_BYTES bytes, else x402/header-malformed, with x402Version 2 on the first two, else x402/not-v2. Every member is kept as it is, so an extension the package does not declare passes through untouched beside the legalContext extension advertise composes. The vectors are x402-headers.json.

The request commitment

requestCommitment({ method, target, body }) commits to the request the challenge answers: the method as received, the request-target split at its first ? into path and query, and bodyDigest, SHA-256 over the body bytes exactly as received. The target is at most 8 KiB of visible ASCII starting with /, and the body at most 1 MiB. requestCommitment({ method, target, body, headers }, fields) also commits to the request header fields a resource server names in fields, those its price or its answer rests on: for each, in the order named, its lower-cased name and SHA-256 of its value as received, never the value, a field given on several lines joined by , (cookie by ; ), and null for a field the request lacks; headers is required where fields names any. With no field named there is no headers member. A digest of a short or common value is guessed by hashing the candidates, so name only fields whose values that does not expose, and none a proxy writes (x402-request-commitment, rule 3).

Over MCP, toolCallCommitment({ name, arguments }) commits to the tools/call request the challenge answers: the tool's name as received and argumentsDigest, SHA-256 over the RFC 8785 form of its arguments, absent read as {}; arguments that are present and not an object, null among them, are refused x402/tool-call-malformed. _meta, where the payment rides on the retry, is not committed, so the paid retry has the commitment of the first call (x402-request-commitment).

tie(accepts, request) is the ATR's binding slot for every x402 pairing: ["x402", { accepts, request }], with every option exactly as issued. issuedDigest is SHA-256 over the RFC 8785 form of one option or one commitment, for a seller that keeps a digest of what it issued.

Advertising several options

This example advertises one H into a challenge with two EVM options, one for EIP-3009 and one for Permit2, and shows which pairing serves each option:

import { , ,  } from "@integraledger/lcp";
import {
  ,
  ,
  ,
  type ,
  type ,
} from "@integraledger/lcp/x402";

const :  = {
  : "exact",
  : "eip155:84532",
  : "10000",
  : "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
  : "0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
  : 60,
  : { : "USDC", : "2" },
};
const :  = { ..., : { ...., : "permit2" } };
const :  = {
  : 2,
  : { : "https://api.seller.example/v1/quote" },
  : [, ],
};

const  = await (new ().("the ATR's bytes"));
const  = `https://atr.seller.example/${.()}`;

const  = .(, , , );
if (()) throw new (.);
const  = .(, , , );
if (()) throw new (.);

.((), ());
const  = .();
.(() ? . : `${...} option, H ${. ===  ? "matches" : "differs"}`);

const  = await (new ().("another ATR"));
const  = .(, , , );
.(() ? . : "placed");

.(await ({ : "POST", : "/v1/quote?tier=1", : new ().("{}") }));
x402/exact/eip155/eip3009 x402/exact/eip155/permit2
1 option, H matches
x402/legal-context-conflict
{
  method: 'POST',
  path: '/v1/quote',
  query: 'tier=1',
  bodyDigest: '0x44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a'
}

A Worker that serves one pairing

pairingOf, from the package root, names the first x402 pairing in BINDINGS whose read offers an option, so a bundle that calls it holds every pairing. A Worker that serves one pairing need not import the root. It imports that pairing's entry point, such as @integraledger/lcp/x402-exact-solana, and asks the pairing itself: its read, on a PaymentRequired document holding the option and the legalContext extension, offers the option only if the pairing serves it, and its bound, on a presented payment, refuses a payment whose accepted the pairing's read does not offer. Each x402 pairing has one option filter, which its advertise, read, build, bound and reference apply, and which holds every check those make on the option alone: the option's own members and the widths build writes them into. So a pairing's read offers no option its build or bound then refuses for what the option says, and every refusal of a payment under an option read offers compares what the payer signed with the option: a carrier, a channel id, a nonce or a salt. Every x402 pairing's bound holds accepted to that filter: an option of another pairing, or of none, is x402/option-not-this-pairing, and an option of the pairing that its read does not offer is refused with the code its advertise gives that option.

No two x402 pairings' read offers one option, with one case to know:

  • The two ERC-7710 levels share the erc7710 option, and both offer it. pairingOf names x402/exact/eip155/erc7710; pairingOfPayment, from @integraledger/lcp/x402, names the level from the payment.

The x402 pairings

Every x402 pairing in the registry. The pairings reference states what each one proves, and Rails gives the field on each chain. Coverage is none where no public ledger shows a payer-signed act carrying H: there the seller also advertises an agreement URL. Confirmed is yes where something outside this package has shown the form as its profile defines it, and no where nothing has yet.

PairingWhere H ridesCoverageConfirmed
x402/exact/eip155/eip3009The EIP-3009 authorization's nonce, which is H.fullyes
x402/exact/eip155/permit2The Permit2 nonce, which is H.fullyes
x402/exact/eip155/erc7710-saltThe salt of the redeemed leaf delegation, which is H, through MetaMask's DelegationManager.fullyes
x402/exact/eip155/erc7710Nothing the delegator signs: H rides only in the echoed legalContext extension.noneyes
x402/exact/eip155/gateway-batchedThe nonce of the TransferWithAuthorization signed in Circle Gateway's GatewayWalletBatched domain, which is H; no public ledger shows it.noneyes
x402/upto/eip155/permit2The Permit2 nonce, which is H, for a signed maximum.fullyes
x402/auth-capture/eip155/eip3009, x402/auth-capture/eip155/permit2The escrow payment's PaymentInfo.salt: H, or, where the option binds a receiver authorizer or a policy, a digest over them and H, which travels with saltNonce, H.fullyes
x402/batch-settlement/eip155The channel configuration's salt, or in the scheme's refund-authorizer mode the deposit authorization's salt or Permit2 nonce. See Channels, sessions and subscriptions.fullyes
x402/batch-settlement/solanaThe seller's Memo instruction in the channel's opening, H's LCP string (extra.memo).fullno
x402/batch-settlement/cloudflareNothing: Cloudflare writes the 402, so the payment carries no H the seller issued; its echoed legalContext extension only locates the sale.noneno
x402/exact/solanaOne Memo instruction, H's LCP string (extra.memo).fullyes
x402/upto/solanaThe Memo instruction of the transaction that opens a one-request payment channel (extra.memo).fullno
x402/exact/xrplThe Payment's InvoiceID, the SHA-256 of H's LCP string (extra.invoiceId).fullyes
x402/upto/xrplNothing: the payer opens the payment channel itself, so the payment follows an agreement on the same network.noneyes
x402/exact/hederaThe memo of the transfer body the buyer signs, H's LCP string.fullyes
x402/exact/hedera/transfer-executorNothing the payer signs: H reaches the payer only in the extension.noneno
x402/exact/algorandThe asset transfer's note, H's LCP string.fullyes
x402/exact/aptosNothing the payer signs.noneyes
x402/exact/cardanoCIP-20 metadata, label 674, holding H's LCP string, to which the signed body commits.fullyes
x402/exact/cardano/lockAs on x402/exact/cardano.fullyes
x402/exact/casperThe CEP-3009 authorization's nonce, which is H.fullno
x402/exact/ccdThe transfer's memo, H's LCP string, in the account transaction the sender signs.fullno
x402/exact/nearThe memo of the one ft_transfer, H's LCP string, in the NEP-366 delegate action the payer signs.fullyes
x402/exact/polkadot/lcp-assets-remarksystem.remark_with_event of H's LCP string, batched with the transfer in the extrinsic the payer signs.fullyes
x402/exact/starknetThe SNIP-9 outside execution's Nonce: H's low 250 bits.fullyes
x402/exact/stellar/preconditionThe transaction's PRECOND_V2 extra signer: a signed payload of H and the nonce of the buyer's Soroban authorization.fullyes
x402/exact/suiOne Pure input, H's 32 bytes, that no command uses.fullyes
x402/exact/tron/lcp-trc20-memoraw_data.data, H's LCP string, signed with the one TriggerSmartContract.fullyes
x402/exact/tvmThe forward payload's comment cell in the Jetton transfer the payer's wallet signs (extra.forwardPayload).fullyes
x402/exact/lnbtc/payment-hashNothing the payer signs: the ATR commits the invoice's payment hash (extra.paymentHash).noneyes

Where the payment carries H, the payer's client writes it. The stock x402 client does so only where it copies an option member that advertise sets: extra.memo on the three Solana pairings, extra.invoiceId on x402/exact/xrpl and extra.forwardPayload on x402/exact/tvm. On every other pairing whose payment carries H, the payer uses this package's build, or a client of its own written to the pairing's profile. x402/exact/casper and x402/exact/ccd are not confirmed, and no stock client pays them: the stock @x402/casper client draws a random nonce, and the stock @x402/concordium client writes no memo.

Building on x402

build(choice, h) takes the document, the chosen option, the payer's account and the time in Unix seconds:

interface X402Choice {
  required: PaymentRequired;
  accepted: PaymentRequirements;
  from: Hex;
  now: number;
}

It returns what the buyer's signer signs, in the rail's own form, and complete, which turns the signer's answer into the x402 payment. On x402/exact/eip155/eip3009 that is EIP-712 typed data; on the other EVM pairings a request whose kind names the form ("eip712", or "erc7710" for a delegation); on other rails a transaction or message to sign.

build checks H first, before it reads the choice or its document. H is your own argument, so an H that is not a valid ATR hash gets one code on every rail, whatever else the choice holds and whether or not the rail's optional peer is installed: x402/payload-malformed, or the code a pairing documents for it (refusals).

Then it checks the form of each member of the choice that you pass besides the document and the option: a payer address, a clock, a ledger or block, a fee or nonce, a wallet's parameters. These are your arguments too, so a malformed one gets its own code on every rail, again whatever the document holds and with or without the peer. Only then does build read the document and the chosen option, and last it checks what compares a member with the option, such as now plus the option's timeout, or a token program the option names.

Reading the payment

bound(payment) reads H from the payment. reference(payment, option) gives the keys to find its settlement, with the payee of option, the issued option the payment answers; on x402/exact/eip155/eip3009 they are the network, the token (asset), the payer, validBefore, H (h) and presented, the authorization's members as presented. pairingOfPayment(payment) names the pairing that serves a presented EVM payment.

status(ref, reader, query) reads the act query.act names, "payment" or "agreement", at the finality query.finality asks for, "latest", "safe" or "finalized". query also takes, where you have them, a final position the transaction must come after (after), the search position an earlier pending answer returned (search), and other acts under the same H (others). The read goes through an EvmReader you supply: network, the network it reads; receipt (eth_getTransactionReceipt); blockNumber for the safe and finalized marks; transaction (eth_getTransactionByHash); call (eth_call at a block number); and, where you give them, logs (eth_getLogs) and block (eth_getBlockByNumber). The read searches for the act only through logs, and knows the latest head and each head's time only through block: without them it gives no failed answer that rests on a search or a lapse, and no instrument-live. Where the facilitator's settle answer names the transaction, add it to the reference as transaction. It is read beside the search, and is never required.

status answers settled, pending, failed or unreadable, with one reason of the closed list the read-status profile states:

StateReasons
settledNone: the answer names the transaction, the finality it reached, and presented.
pendingbelow-mark, instrument-live, search-incomplete, not-found
failedinstrument-unused, instrument-consumed, transaction-failed, before-position
unreadablehistory-gap, transport, unparseable, too-large, chain-mismatch

Every answer also lists the foreign items the read met: transactions that carry H and are not the act, each with its reason. A pending answer can carry search, the position to pass back as query.search.

It settles on a transaction that carries H, was signed by the reference's payer and, for a payment, pays the option's payee, read at the finality asked for or above it; below it, the answer is pending below-mark. The amount is not compared: presented on a settled answer says whether the landed act is the payment presented. failed, for any reason but before-position, comes only from a read at the finalized mark and, at coverage full, only once the search for H is read whole. A reader call that rejects makes the answer unreadable, never failed, and so does a reader that declares another network (chain-mismatch). A missing or malformed query or reference is unreadable, unparseable, with nothing read. Reading settlement gives the rules rail by rail.

What counts as the act

PairingThe act status settles on
x402/exact/eip155/eip3009The token's AuthorizationUsed whose nonce is H, from the reference's payer, paired with its Transfer: by the token's two logs where the transaction holds one use and at most one transfer of that authorizer on that contract, and otherwise by the one call that consumed it, decoded. The transfer pays the option's payee.
x402/exact/eip155/permit2, x402/upto/eip155/permit2A call to the scheme's Permit2 proxy whose nonce is H, found at any byte offset of the transaction's input, with that proxy's Transfer of the call's token from its owner to its witness's to, and the owner's Permit2 bit for the nonce set at the receipt's block and unset at the block before.
x402/exact/eip155/erc7710-saltA RedeemedDelegation from the DelegationManager for a leaf delegation, one whose delegate is the redeemer or the wildcard delegate, with salt H, and a Transfer from its root delegator, the reference's payer, to the option's payee.
x402/exact/eip155/erc7710The transaction the reference names, holding a Transfer from the payment's delegator to the option's payee. Nothing in it ties it to this payment, so give query.after, the position of the agreement's own settlement, which the transaction must come after.
x402/auth-capture/eip155/eip3009, x402/auth-capture/eip155/permit2The escrow's PaymentAuthorized or PaymentCharged event, the option's flow's, through the deployment's collector for the pairing's scheme, whose PaymentInfo.salt is the reference's and whose receiver is the option's payee.
x402/batch-settlement/eip155The deposit into the reference's channel; see Channels, sessions and subscriptions.

Before a transaction is named

On the pull pairings, where the payer signs an authorization that someone else executes later (x402/exact/eip155/eip3009, x402/exact/eip155/permit2, x402/upto/eip155/permit2, x402/auth-capture/eip155/eip3009 and x402/auth-capture/eip155/permit2), status reads the authorization's single-use value at the final mark and, through a reader that has block, at the latest head. It answers pending instrument-live while the authorization reads unused at both and is still valid. Once it has lapsed unused, the answer is failed instrument-unused where the search is whole, and pending search-incomplete otherwise. On the auth-capture pairings the signed nonce is a digest over more than H, so the search is never whole.

authorizer(payment) gives the account whose signature authorises the pull, as lowercase hex. authorizationUsed({ network, authorization }, authorizer, block, reader), from @integraledger/lcp/evm, asks the contract that records the use whether the authorization had executed by a given block. The x402 references carry no authorization, so build it from the reference:

MemberValue
scheme"eip3009" or "permit2", the authorization's kind (ref.scheme on auth-capture).
atThe contract that records the use: the token, ref.asset, for EIP-3009; PERMIT2, from @integraledger/lcp/evm, for Permit2.
nonceThe nonce the payer signed: ref.h on the exact and upto pairings, ref.signatureNonce on auth-capture.
deadlineThe signed bound: ref.validBefore on EIP-3009, ref.deadline on Permit2, ref.expiry on auth-capture.
assetref.asset.

The seller guide builds it for EIP-3009. An EIP-3009 authorization executes only while the block's timestamp is below deadline, and a Permit2 permit only while it is at most deadline. x402/exact/eip155/erc7710-salt gives authorizer, the delegator of the permission context's root delegation, and no single-use value: a delegation records no nonce and names no deadline.

Edit on GitHub

Last updated on

On this page