AgentSmithx402
Facilitator / Overview

AgentSmith Facilitator

The AgentSmith Facilitator implements the open-source x402 v2 protocol for fee-sponsored payments on Stellar Testnet and Mainnet. It verifies buyer-signed Soroban authorization entries, builds and submits the transaction, waits for confirmation, and returns the settlement result to the resource server. It never holds the buyer's payment funds.

The default exact payment path is built with the official @x402/core and @x402/stellar packages and follows the normative requirements of the x402 v2 protocol and the official Stellar exact scheme. The optional upto path is an experimental AgentSmith extension, covered under Schemes below.

Non-custodial by design The Facilitator never holds or sources the buyer's funds. The buyer's signature binds the asset, recipient and amount, so the Facilitator can build and submit the transaction and sponsor the XLM network fee, but it cannot redirect a payment or change what was authorized. For metered upto, the on-chain settlement Kernel moves the token directly from buyer to recipient and enforces the buyer's signed ceiling and validity window. The Kernel is intentionally minimal — no owner, upgrade, pause, withdrawal, or arbitrary-call interface — so it can neither divert nor custody funds.

Payment flow

The buyer first requests the protected resource and receives a 402 Payment Required response with the payment terms. After the buyer signs and retries, the resource server asks the Facilitator to verify the authorization without moving funds. If verification succeeds, the server runs the protected resource and then asks the Facilitator to settle the payment. The Facilitator sponsors the XLM network fee, submits the transaction to the selected Stellar network, waits for confirmation, and returns the settlement result to the resource server.

AgentSmith x402 payment sequence The buyer requests a resource, receives payment requirements, signs and retries. The resource server verifies through the Facilitator, runs the protected resource, settles through the Facilitator on the selected Stellar network, and returns the resource to the buyer. Buyer Resource Server Facilitator Stellar network Request protected resource 402 + payment requirements Retry + signed payment payload POST /verify Simulate transaction Simulation result Verified POST /settle Submit fee-sponsored transaction Confirmed + transaction hash Settlement result 200 + resource + payment response Sign Soroban authorization entry Run protected resource then determine success
Verification does not move funds. Settlement happens only after the protected resource succeeds.

For a complete end-to-end example, see the weather-x402 reference — an x402-gated weather service settled through the Facilitator, including a browser wallet flow.

Facilitator environments

Choose the same network in the Seller, Buyer and token configuration. The Resource Server calls the Facilitator; Buyers call the Seller only.

Environment Facilitator base URL Network API key
Testnet https://testnet.agentsmith.xyz/facilitator stellar:testnet Not required
Mainnet https://mainnet.agentsmith.xyz/facilitator stellar:pubnet Required

On mainnet, every request carries Authorization: Bearer <API_KEY>. The key authenticates the Seller to the Facilitator; never expose it in browser code.

Schemes

The Facilitator accepts a fixed-price exact payment and an experimental metered upto payment. Pick the one that matches how the price is known.

exact is the default path and the only upstream-standard scheme. The buyer authorizes one SEP-41 transfer(from, to, amount) for a fixed amount; the Facilitator cannot change its asset, recipient or amount without invalidating the authorization. Use it whenever the price is known before the request runs. It is available on both stellar:testnet and stellar:pubnet.

Getting an API key

Register a Resource Server through POST /credentials/register with a name, domain and email. The domain must be unique; a second registration for the same domain is rejected. The response returns a resourceServerId and the API key. The key is shown only once, so store it in backend secret storage immediately.

Rotate on a schedule or when a key may be compromised, and revoke a key you no longer use; rotation and revocation authenticate with the current key. Keys are per environment — a testnet deployment does not require one, so these routes apply to mainnet. The full request and response shapes are in the Credentials endpoints below.

Use GET /supported to check the selected deployment's advertised capabilities. Each environment has a separate deployment; an endpoint error does not establish supported payment capabilities.

Supported capabilities

CapabilityCurrent support
Protocolx402 v2; official Stellar exact scheme
Networkstellar:testnet and stellar:pubnet (separate deployments)
AssetsSEP-41 token contracts; quote an explicit contract and atomic amount
Schemesexact; optional experimental upto
Network feeSponsored in XLM by the Facilitator, subject to its configured fee cap

Endpoints

The resource server calls these endpoints; the buyer never calls the Facilitator directly. On mainnet every request carries Authorization: Bearer <API_KEY>. Bodies follow the x402 v2 specification.

Service

Status and advertised capabilities.

GET/healthLiveness and build info
Request
No parameters.
Response 200
okboolean
True while the service is serving.
servicestring
Service identifier, agentsmith-stellar-facilitator.
versionstring
Deployed build version.
networkstring
CAIP-2 network the deployment serves, stellar:testnet or stellar:pubnet.
GET/supportedAdvertised payment capabilities
Request
No parameters.
Response 200
kindsarray
The payment kinds this deployment accepts.
x402Versioninteger
Protocol version. 2.
schemestring
exact, or upto when a Kernel is configured.
networkstring
CAIP-2 network the kind applies to.
extraobjectoptional
Scheme metadata, including areFeesSponsored.
extensionsstring[]
Enabled protocol extensions.
signersobject
CAIP-2 network pattern mapped to the deployment's public signer addresses.
Payments

Verify and settle a buyer's signed payment. Both take the same x402 v2 body.

POST/verifyValidate a payment, no funds moved
Request body
x402Versionintegerrequired
Protocol version. 2.
paymentPayloadobjectrequired
The buyer's signed payment.
x402Versioninteger
2; must match the top-level version.
acceptedobject
The payment requirements the buyer accepted (same shape as below).
payloadobject
Scheme-specific signed authorization.
resourceobjectoptional
Resource metadata passed through from the challenge.
extensionsobjectoptional
x402 extension data.
paymentRequirementsobjectrequired
The terms the payment is validated against.
schemestring
exact or upto.
networkstring
CAIP-2 network, e.g. stellar:testnet.
amountstring
Atomic units as a digit string.
assetstring
SEP-41 token contract.
payTostring
Recipient Stellar address.
maxTimeoutSecondsinteger
Authorization lifetime, 1–300.
extraobjectoptional
Scheme metadata, e.g. the upto settlement contract.
Response 200
isValidboolean
Whether the payment would settle.
payerstringoptional
Buyer address recovered from the signature.
invalidReasonstringoptional
Machine-readable code when isValid is false.
invalidMessagestringoptional
Human-readable detail for the failure.
POST/settleSubmit and confirm a payment
Request body
Same body as POST /verify: x402Version, paymentPayload and paymentRequirements.
Response 200
successboolean
Whether settlement is confirmed.
transactionstring
Stellar transaction hash; empty when nothing was submitted.
networkstring
CAIP-2 network the payment settled on.
payerstringoptional
Buyer address.
amountstringoptional
Settled amount in atomic units.
errorReasonstringoptional
Machine-readable code when settlement did not succeed.
errorMessagestringoptional
Human-readable detail for the failure.
Credentials / API keys

Mainnet only. Register a Resource Server, then rotate or revoke its key.

POST/credentials/registerPublicRegister and issue the first key
Request body
namestringrequired
Display name for the Resource Server, 1–100 characters.
domainstringrequired
Bare host name, stored lower-case. Must be unique; a repeat is rejected with DOMAIN_TAKEN.
emailstringrequired
Contact email, up to 254 characters.
Response 201
resourceServerIdstring
UUID identifying the registered Resource Server.
apiKeystring
The API key. Shown only once — store it immediately.
POST/credentials/keys/rotateBearerIssue a new key
Request
No body. Authenticate with the current key as Authorization: Bearer <API_KEY>.
Response 201
apiKeystring
The new key. The previous key keeps working for ten minutes to allow a rollover.
DELETE/credentials/keys/currentBearerRevoke the current key
Request
No body. Authenticate with the key to revoke as Authorization: Bearer <API_KEY>.
Response 204
No content. The presented key is revoked immediately.
SDK / Overview

AgentSmith payment SDK

Install agentsmith-x402-sdk for Seller payment middleware and Node Buyer paid fetch. Requires Node.js 24+ and ES modules ("type": "module"). Reuses official x402 packages for exact payments and includes local experimental upto adapters; no copied adapter or dependency patch is required.

Install the SDK
npm install agentsmith-x402-sdk
# Sellers using Express (including NestJS with the Express adapter):
npm install express @x402/express@2.23.0
Entry Use
agentsmith-x402-sdk/seller/express createPaymentMiddleware, setSettlementOverrides — Express and NestJS with the Express adapter
agentsmith-x402-sdk/seller createResourceServer — compose native x402 server integrations
agentsmith-x402-sdk/buyer createBuyerFetch — Node signing and paid fetch

Seller: protect an API route

Set the recipient and SEP-41 token contract for your selected network in backend configuration. Prices are atomic integer strings: a seven-decimal token uses 10000000 units per token. The SDK does not infer arbitrary token precision or convert USD prices for explicit asset/amount quotes.

Seller — Express · TypeScript
import express, { type Request, type Response } from 'express';
import { createPaymentMiddleware } from 'agentsmith-x402-sdk/seller/express';

const asset = process.env.TOKEN_CONTRACT;
const payTo = process.env.SELLER_ADDRESS;
if (!asset || !payTo) throw new Error('Set TOKEN_CONTRACT and SELLER_ADDRESS');

const app = express();
app.use(await createPaymentMiddleware({
  network: 'stellar:testnet',
  facilitator: { url: 'https://testnet.agentsmith.xyz/facilitator' },
  routes: {
    'GET /price': {
      accepts: {
        scheme: 'exact',
        payTo,
        price: { asset, amount: '40000' },
      },
    },
  },
}));
app.get('/price', (_req: Request, res: Response) => res.json({ result: 'data' }));
app.listen(3000);

The helper fetches Facilitator capabilities at initialization, registers the selected schemes and returns native payment middleware. Unpaid requests receive 402 before the handler runs. The framework verifies authorization, runs the handler and then settles; application handlers do not call /verify or /settle manually. NestJS applications using Express can mount this middleware in bootstrap; route patterns must include any global prefix.

Connect the Seller to mainnet

Replace the testnet network and Facilitator configuration with the following fields in createPaymentMiddleware. Configure a mainnet recipient and token contract. The SDK sends the API key as a Bearer token; keep it in backend secret storage.

Mainnet configuration fields · TypeScript
network: 'stellar:pubnet',
facilitator: {
  url: 'https://mainnet.agentsmith.xyz/facilitator',
  apiKey: process.env.FACILITATOR_API_KEY,
},

Metered payments with upto

Choose scheme: 'upto' in the route accepts configuration and quote the maximum authorized amount. The built-in adapter reads the advertised Kernel and authorization signer from the selected Facilitator. In every successful metered handler, set the actual atomic usage before responding:

Seller — actual usage · TypeScript
import { setSettlementOverrides } from 'agentsmith-x402-sdk/seller/express';
import type { Request, Response } from 'express';

// Configure the metered route with scheme: 'upto' and its maximum price.
app.get('/metered', (_req: Request, res: Response) => {
  setSettlementOverrides(res, { amount: '20000' });
  res.json({ result: 'data' });
});

Actual usage must be positive and no greater than the Buyer-authorized maximum. Missing, zero, malformed or over-cap amounts reject settlement. The SDK never substitutes the ceiling. upto remains experimental and requires a compatible deployed Kernel.

Business side effects cannot be rolled back by failed or uncertain settlement. Applications own idempotency, handler deadlines, CORS and recovery.

Buyer: Node paid fetch

The Buyer calls the Seller, receives a 402 challenge, signs locally and resends through the native x402 fetch flow. It does not need the Seller's Facilitator API key. Keep the signing seed in application-owned secret storage; never embed it in browser JavaScript.

Buyer — Node · TypeScript
import { createBuyerFetch } from 'agentsmith-x402-sdk/buyer';

const secret = process.env.STELLAR_SECRET;
if (!secret) throw new Error('Set STELLAR_SECRET');

const paidFetch = createBuyerFetch({
  secret,
  network: 'stellar:testnet',
  schemes: ['exact'],
});
const response = await paidFetch('http://localhost:3000/price');
if (!response.ok) throw new Error(`Paid request failed: ${response.status}`);
const data = await response.json();

Approve a payment before signing

Add the following hook to createBuyerFetch to apply your own approval policy. Omit the hook for automatic agent signing. The approval function is supplied by your application.

Buyer — application approval · TypeScript
onBeforePaymentCreation: async ({ selectedRequirements }) => {
  const approved: boolean = await approvePayment(selectedRequirements); // your application policy/UI
  if (!approved) return { abort: true, reason: 'Payment declined' };
},
Roadmap / Bazaar

Bazaar Coming soon

Bazaar discovery and registration are still under active development and are not part of the current supported Facilitator integration. Do not build a production dependency on Bazaar endpoints yet. This documentation will publish the supported discovery workflow when it is ready.

Available now: integrate the AgentSmith Facilitator from your Resource Server and complete the paid request with the Buyer integration above.