Guides

Pay x402 from an agent

The one call an agent makes: what it does, its options, and each way it can end.

An agent that holds a grant credential pays any Alba seller with one call. This guide covers that call: what it does, how to configure it, and each way it can end.

Install and configure#

bash
npm install @alba/sdk

The SDK needs Node 22 or later. It reads the grant credential from the ALBA_GRANT environment variable:

bash
ALBA_GRANT=alba_grant_…

Make a paid request#

alba.fetch takes what fetch takes and returns a Response.

ts
import { alba } from '@alba/sdk'

const res = await alba.fetch('https://api.example/v1/search?q=lithium')

if (res.ok) {
  const data = await res.json()
}

A request with a method, headers and a body works the same way:

ts
const res = await alba.fetch('https://api.example/v1/chat', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ prompt: 'Summarize the attached filing.' }),
})

What the call does#

  1. It sends the request as it is. Any answer other than 402 is returned untouched, so alba.fetch is safe to use for every request the agent makes.
  2. On a 402 it reads the PAYMENT-REQUIRED header and looks for an entry with the scheme alba, the grant's mint and the grant's facilitator. With no such entry it returns the 402 as it came.
  3. It checks the price against the grant: the cap, the expiry, the seller list and what the grant has left after fees. A payment the grant does not allow throws before anything is proved.
  4. It proves the payment and encrypts a memo for the owner with the request's method and URL. A URL too long for the memo is stored cut short, ending in an ellipsis, and the payment goes ahead.
  5. It sends the request once more with the proof in the PAYMENT-SIGNATURE header, and returns the seller's answer.

The payment's deadline is the seller's maxTimeoutSeconds, at most 120 seconds from the moment of proving and never later than the grant's expiry. Proving takes about two seconds in Node.

Several grants in one process#

Bind a credential in code when the agent holds more than one, or when it does not come from the environment:

ts
import { alba } from '@alba/sdk'

const research = alba.with(researchCredential)
const res = await research.fetch('https://api.example/v1/search?q=lithium')

alba.with also takes transport options as a second argument: facilitatorUrl to use another address for the facilitator named in the credential, fetch to supply the HTTP client, and artifactBaseUrl to load the proving files from your own host.

Within one process the SDK sends a grant's payments one after another, so concurrent calls on the same grant are queued and all of them complete. Two processes should not share a credential: give each its own grant.

Check what the grant has left#

ts
const grant = await alba.grantStatus()

grant.remaining // raw units, as a string
grant.state // 'active', 'expired', 'spent' or 'revoked'

grantStatus reads the chain and spends nothing.

Follow progress and cancel#

The third argument takes an AbortSignal and a progress callback:

ts
const res = await alba.fetch(url, undefined, {
  signal: AbortSignal.timeout(30_000),
  onProgress: (p) => console.log(p.stage, p.progress, p.message),
})

The receipt#

A paid response carries a PAYMENT-RESPONSE header, the settlement as base64 JSON:

ts
const header = res.headers.get('PAYMENT-RESPONSE')

if (header) {
  const receipt = JSON.parse(atob(header))
  receipt.transaction // the transaction signature
}

When the payment is not made#

alba.fetch throws an AlbaSdkError when the grant does not allow the payment. Nothing has been spent in any of these cases.

error.codeCauseWhat to do
INVALID_CREDENTIALALBA_GRANT is not set, or the string is not a grant credential.Set the credential.
AMOUNT_OVER_CAPThe seller's price is above the grant's cap per payment.Ask the owner for a grant with a higher cap.
SELLER_NOT_ALLOWEDThe seller's pay-to address is not on the grant's seller list.Ask the owner to grant this seller.
GRANT_EXPIREDThe grant's expiry has passed.Ask the owner for a new grant.
GRANT_REVOKEDThe owner revoked the grant.Stop paying from it.
INSUFFICIENT_GRANT_BALANCEThe grant cannot cover the price and the fees.Ask the owner to top it up.
INVALID_ARGUMENTThe seller is on a different network from the grant.Use a grant on the seller's network.
ts
import { alba, AlbaSdkError } from '@alba/sdk'

try {
  const res = await alba.fetch(url)
} catch (e) {
  if (e instanceof AlbaSdkError && e.code === 'INSUFFICIENT_GRANT_BALANCE') {
    // tell the owner the grant needs a top-up
  }
}

When the seller refuses the payment#

If the facilitator refuses the proof at settlement, the seller answers the retry with another 402, and alba.fetch returns it. Its JSON body has an error field with the reason, such as spent_tag when the owner revoked or topped up the grant in the same moment. The grant is unchanged, and calling alba.fetch again makes a fresh payment against the grant's current state.

Two reasons mean the payment did go out, so the agent does not pay again: settlement_pending, where the transaction is sent and the facilitator is still following it, and private_note_unavailable, where the payment settled and the seller could not find its note. Both responses carry the transaction signature.

Private payments lists every reason.

What a payment costs#

The grant pays the seller's price, the protocol fee and the relay fee. Fees and the ALBA token has the formula and where to read the current rates.