Reference

Seller middleware

The Hono and Express middleware, verifyAndSettle and paymentRequirements, with every option.

The seller middleware puts a price on a route. A request without payment gets a 402 with the route's requirements, and a request with payment reaches the handler only after the facilitator has settled it. It ships in @alba/sdk for Hono and Express, with two plain functions for any other framework.

ts
import { honoMiddleware, expressMiddleware, verifyAndSettle, paymentRequirements } from '@alba/sdk/seller'

Prices are decimal strings in the mint's raw units: 10000 of a 6-decimal mint is 0.01.

On a route#

ts
import { Hono } from 'hono'
import { honoMiddleware } from '@alba/sdk/seller'

const app = new Hono()

app.get(
  '/papers/search',
  honoMiddleware({ price: '10000', asset: mint, payTo, network, facilitatorUrl }),
  (ctx) => ctx.json({ query: ctx.req.query('q') }),
)

honoMiddleware(options) returns a Hono MiddlewareHandler and expressMiddleware(options) an Express RequestHandler. Both take the same options. Each call makes its own gate, so give every priced route its own middleware.

SellerOptions#

OptionTypeMeaning
pricerequiredstringThe price of one request, a positive u64 in raw units.
assetrequiredstringThe mint the price is in. It names the pool the payment comes from.
payTorequiredstringWhere the price goes: a wallet address, or an Alba address to receive into a private balance.
networkrequiredstringThe x402 network identifier, solana: and the first 32 characters of the genesis hash. GET /v1/config reports the facilitator's.
facilitatorUrlstringThe facilitator's base URL. It goes into the requirements as extra.facilitator and is where the middleware settles. Left out, it is read from the ALBA_FACILITATOR_URL environment variable, and a request throws INVALID_ARGUMENT when neither is set.
maxTimeoutSecondsnumberHow long the requirements stay open. Defaults to 120.
descriptionstringWhat the resource is, sent in the 402. Defaults to Paid resource.
nonceSecretstringThe secret that signs the nonces of an Alba address pay-to. Give every instance of the server the same one. Defaults to a random secret per process.
receiptStoreSellerReceiptStoreWhere served settlements are recorded. See Receipts.
privateOwnerOwnerThe opened balance that receives, when payTo is an Alba address. See An Alba address as pay-to.
fetchtypeof fetchThe transport for the call to the facilitator. Defaults to the global fetch.

What the middleware does#

A request without payment#

The middleware answers 402. The requirements go out twice: base64-encoded JSON in the PAYMENT-REQUIRED header, and the same object as the JSON body.

FieldTypeMeaning
x402Version2The protocol version.
resourceobjecturl, the request's full URL. description, from the options. mimeType, application/json.
acceptsPaymentRequirements[]One alba entry built from the options: scheme, network, amount, asset, payTo, maxTimeoutSeconds, and extra with facilitator, assetTransferMethod: "groth16" and paymentFlow: "upfront".
errorstringPresent when this 402 answers a payment that was refused: the reason.

The alba x402 scheme defines each field.

A request with payment#

  1. The payment is decoded and matched

    The middleware decodes the PAYMENT-SIGNATURE header and compares the requirements the agent accepted with the route's own. They have to be equal field for field. A payment made for another price, another address or another route's requirements is answered with a fresh 402.

  2. The facilitator settles

    The payment and the route's requirements go to the facilitator's POST /settle. The handler has not run yet.

  3. The receipt is claimed

    A settled transaction is claimed once, by its signature. A signature that was already claimed does not buy a second response.

  4. The handler runs

    The middleware sets the PAYMENT-RESPONSE header to the base64-encoded settle response and calls the handler.

A refused payment#

When the accepted requirements do not match, the facilitator refuses the payment, or the receipt was already claimed, the middleware answers a new 402. When the facilitator gave a reason, the body carries it as error, one of the scheme's reason strings. The handler does not run.

Receipts#

One settlement buys one response. The middleware enforces that through a receipt store:

ts
import type { SellerReceiptStore } from '@alba/sdk/seller'

const receiptStore: SellerReceiptStore = {
  async claim(signature, resource) {
    return insertOnce(signature, resource)
  },
}

claim(signature, resource) receives the settled transaction's signature and the request's URL. It returns true the first time it sees a signature and false every time after, and it has to decide that atomically: a unique key on the signature in the seller's database does it.

Without receiptStore the middleware remembers claimed signatures in memory, which holds for one process. A seller that restarts or runs more than one instance supplies a store backed by its database, so a settlement stays claimed across all of them.

An Alba address as pay-to#

With an Alba address as payTo, the price arrives as a note in the seller's private balance and no token account is involved. The middleware needs that balance opened, to check that each payment's note is really there before the handler runs.

ts
import { connectBalance } from '@alba/sdk'
import { honoMiddleware } from '@alba/sdk/seller'

const seller = await connectBalance(signMessage, { facilitatorUrl })

const paid = honoMiddleware({
  price: '10000',
  asset: mint,
  payTo: seller.address,
  network,
  facilitatorUrl,
  privateOwner: seller,
  nonceSecret,
})

privateOwner is required for an Alba address, and its address has to equal payTo. The middleware throws when it is created otherwise.

Two things differ from a wallet pay-to:

  • Each 402 carries a signed nonce. The middleware makes a fresh one for every 402 and puts it in extra.nonce. A nonce is one field element holding an expiry maxTimeoutSeconds ahead, 10 random bytes and an HMAC-SHA256 over them and the pay-to address under nonceSecret. A payment is accepted only when its nonce carries a valid signature and has not expired, and when the requirements it accepted equal the route's own with that nonce.
  • The note is checked after settlement. The middleware scans the seller's balance for the payment's note at the route's price. When it is not there, the response is treated as refused with the reason private_note_unavailable, and the handler does not run.

The middleware keeps no list of the nonces it issued, so any instance holding the same nonceSecret accepts a retry. A seller running several instances gives them all one secret.

Any other framework#

The two functions the middleware is built from.

paymentRequirements(options, nonce?)#

Takes a SellerOptions and returns one PaymentRequirements object for a 402. When payTo is an Alba address it carries extra.nonce: a fresh signed nonce, or the nonce passed as the second argument. On a retry, pass the nonce the payment accepted to rebuild the requirements that payment answers, then settle against them.

verifyAndSettle(paymentHeader, requirements, options?)#

ParameterTypeMeaning
paymentHeaderrequiredstringThe value of the request's PAYMENT-SIGNATURE header.
requirementsrequiredPaymentRequirementsThe requirements this seller issued for the request.
optionsobjectfacilitatorUrl (defaults to requirements.extra.facilitator), fetch, signal, and privateOwner for an Alba address pay-to.

It decodes the header, sends the payment and the requirements to the facilitator's /settle, and returns the settle response. For an Alba address it also scans for the note, and returns success: false with errorReason: "private_note_unavailable" when the note is absent. It throws when the header is not a valid payment payload, and when the facilitator cannot be reached.

verifyAndSettle does not compare the accepted requirements with yours and does not claim the receipt. A handler built on it does both:

ts
import { paymentRequirements, verifyAndSettle } from '@alba/sdk/seller'

const requirements = paymentRequirements({ price: '10000', asset: mint, payTo, network, facilitatorUrl })

async function handle(request: Request): Promise<Response> {
  const header = request.headers.get('PAYMENT-SIGNATURE')
  if (header) {
    const receipt = await verifyAndSettle(header, requirements)
    if (receipt.success && (await receiptStore.claim(receipt.transaction, request.url))) {
      return Response.json({ ok: true }, { headers: { 'PAYMENT-RESPONSE': btoa(JSON.stringify(receipt)) } })
    }
  }
  const required = { x402Version: 2, resource: { url: request.url }, accepts: [requirements] }
  return Response.json(required, { status: 402, headers: { 'PAYMENT-REQUIRED': btoa(JSON.stringify(required)) } })
}

The facilitator checks that the payment's accepted requirements equal the ones passed in, so a payment made for other requirements comes back with success: false.