Skip to content
Integra Protocol

Buyer

Read the challenge, compare the served bytes with H, build and sign, and finish.

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

The buyer's side of the binding is the buyer gate: compare, then build and sign, then finish. This guide writes it with this package's pieces on x402 with x402/exact/eip155/eip3009; at the end you have a program that reads a seller's 402, compares the served bytes with H, and signs a payment that carries it. For a ready-made gate with the fetch bounds and declines already in place, use the buyer gate packages.

1. Compare

Read the challenge from the 402 answer's PAYMENT-REQUIRED header with decodePaymentRequired(header). Then read(doc) gives H, the link, and the options the pairing can pay. Fetch the link with bounds, keep the bytes exactly as received, and compare their hash with H. On any failure, stop before anything is signed.

The fetch below is the one the shared vectors fix: one GET asking for the identity coding (Accept-Encoding: identity), no redirects, a 10-second deadline over headers and body, at most 1 MiB, counted as the body streams, and an answer in any other content coding declined. It asks with redirect: "manual" and reads a 3xx answer, or the opaqueredirect answer with status 0 that browsers give, as a failure. Cloudflare Workers refuse redirect: "error" with a TypeError, and under "manual" a Worker's fetch answers a redirect with the 3xx itself (measured on Cloudflare's runtime with wrangler 4.141.0). In a browser, Accept-Encoding is a forbidden request header and a cross-origin answer's Content-Encoding is hidden unless the seller exposes it, so the coding check cannot be made there.

2. Build and sign

build(choice, h) returns what the signer signs with H in its place. On x402/exact/eip155/eip3009 that is EIP-712 typed data for TransferWithAuthorization whose nonce is H, valid until now plus the option's maxTimeoutSeconds. Your signer signs it; this package never holds a key.

Pass the H you compared. Never read H from the document again between the comparison and build.

3. Finish

complete(signature) gives the x402 payment, echoing the challenge's resource and extensions unchanged. Before sending it, read H back with bound(payment) and check that it equals the H you compared: the signer signed what you asked it to sign.

The whole flow

The seller's challenge below was advertised for an ATR the buyer can fetch. A stand-in fetch serves the bytes, so no network is used.

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

const  = 1_048_576;

/**
 * One GET asking for the identity coding, no redirects, a 10-second deadline, and at most 1 MiB. The bytes as
 * received, or why not.
 */
async function (: string, : typeof  = ): < | string> {
  const  = new ();
  const  = (() => .(), 10_000);
  try {
    const  = await (, {
      : "manual",
      : .,
      : { "accept-encoding": "identity" },
    });
    const  = . === "opaqueredirect" || (. >= 300 && . <= 399);
    if ( || . !== 200 || . === null) return "atr-unfetchable";
    const  = (..("content-encoding") ?? "").().();
    if ( !== "" &&  !== "identity") return "atr-unfetchable";
    const : [] = [];
    let  = 0;
    for await (const  of .) {
       += .;
      if ( > ) {
        .();
        return "atr-too-large";
      }
      .();
    }
    const  = new ();
    let  = 0;
    for (const  of ) {
      .(, );
       += .;
    }
    return ;
  } catch {
    return "atr-unfetchable";
  } finally {
    ();
  }
}

// What the seller served: the ATR's bytes at the link, and the 402 challenge that advertises their hash.
const  = new ().('{"atrVersion":"1","id":"0f8fad5b-d9cb-469f-a165-70867728950e","terms":"10000 units"}');
const  = "https://atr.seller.example/quote-0001";
const  = await ();
const :  = {
  : 2,
  : { : "https://api.seller.example/v1/quote" },
  : [
    {
      : "exact",
      : "eip155:84532",
      : "10000",
      : "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
      : "0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
      : 60,
      : { : "USDC", : "2" },
    },
  ],
  : {
    : {
      : { : "sha256", : , :  },
      : {},
    },
  },
};
const : typeof  = async () => new ();
const  = (); // the 402's PAYMENT-REQUIRED header
if (()) throw new (.);

// 1. Compare.
const  = ();
if (()) throw new (`decline: ${.}`);
const  = .();
if (()) throw new (`decline: ${.}`);
const  = await (., );
if (typeof  === "string") throw new (`decline: ${}`);
if (!(await (), .)) throw new ("decline: hash-mismatch");
.("compared:", . === );

// 2. Build and sign.
const  = (());
const  = ..[0]!;
const  = await .(
  { : , , : ., : .(.() / 1000) },
  .,
);
if (()) throw new (`decline: ${.}`);
.("signing:", .., "with nonce H:", ... === .);
const  = await .(. as );

// 3. Finish.
const  = .();
if (()) throw new (`decline: ${.}`);
const  = await .();
if (typeof  !== "string" || !(, .)) throw new ("decline: signed-not-bound");
const  = (); // the retried request's PAYMENT-SIGNATURE header
if (()) throw new (.);
.("finished: the payment carries H");
compared: true
signing: TransferWithAuthorization with nonce H: true
finished: the payment carries H

Send encodeHeader(payment) to the seller as the retried request's PAYMENT-SIGNATURE header (PAYMENT_SIGNATURE; The headers), and keep served: it is your copy of what you agreed to.

Choosing among options

A challenge may offer several options on several rails. pairingOf(option) names the pairing that serves each one, and each pairing's read returns only the options it can pay. Choose an option your accounts can pay, then use that pairing's build. The same H rides in whichever you choose.

When the challenge carries an agreement URL

Some pairings' payments carry H in nothing public: their data.coverage is none. read returns agreement, an https URL, whenever the challenge carries one. Pay it only when the chosen pairing's data.coverage is none, and pay it first, with a payment that carries H publicly. The agreement payment is approved like any other: hand the agent its amount, token, payee and network, and sign it only once the agent approves. Pay the full payment only after the agreement's 200 receipt names the same H. Where the agreement URL answers the unpaid request 202, an agreement payment for this ATR is settling: sign nothing, and call again later without approval. See the agreement URL.

Pay the agreement through a pairing whose data.agreement is present, one whose payment can itself be an agreement, and build it as one: build(choice, h, "agreement"). On a pairing whose single-use value is H itself, such as x402/exact/eip155/eip3009, the agreement then carries the agreement's own value, agreementValue(h), where a payment carries H, so the agreement and the charge under one H never share a nonce. bound(agreement, { act: "agreement", h }) reads H back from it.

Returning after the agreement

Where the sale's charge is offered only once its agreement is recorded, the buyer's agent repeats its request after it pays the agreement, with the sale's H in the Legal-Context request header (profile legal-context-return). Over MCP, the agent sends the same value in params._meta under LEGAL_CONTEXT_META, com.integraledger.lcp/legal-context, on each later tool call of the sale. toLegalContextHeader(h, returnValue?) writes it, an RFC 9651 Item whose token is H's LCP string, with the sale's 32-byte return value as the parameter rv where the first response gave one; fromLegalContextHeader(value) reads it as RFC 9651 parses an Item, an rv given twice counting as the last and its base64 read with or without its padding. Send a return value only to the resource server that gave it, on the return and on every later request of the sale. servesOf(option, atr?) names the charge options an agreement option serves, each <slot>/<i> (x402/<i>, mpp/<i>, card/<i> and the other slots the profile lists), the option at that index of the charge options the ATR's binding slot of that name holds, so the buyer pays an agreement that serves the charge it means to pay. Given the ATR's bytes, it also refuses a name whose slot is not the ATR's binding slot or whose index is past that slot's options.

Channels and sessions

In a channel, the buyer compares once, at the opening: one ATR covers the whole channel. See Channels, sessions and subscriptions.

Edit on GitHub

Last updated on

On this page