AgentSmithx402
Facilitator / Overview

AgentSmith Facilitator

The AgentSmith Facilitator implements the open-source x402 v2 protocol for fee-sponsored payments on Stellar Testnet. 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 and is identified separately below.

Testnet only. The current AgentSmith service supports stellar:testnet. Do not configure it for Stellar Mainnet or use it to receive production funds.

Supported capabilities

CapabilityCurrent support
Protocolx402 v2; official Stellar exact scheme
Networkstellar:testnet only
AssetsStellar Testnet USDC only
Schemesexact; optional experimental upto
Network feeSponsored in XLM by the Facilitator, subject to its configured fee cap

Endpoints

EndpointPurpose
GET /healthReturns service health, version and network.
GET /supportedLists the registered x402 version, network, schemes, signing addresses and fee-sponsorship metadata.
POST /verifyValidates a payment without submitting it on-chain.
POST /settleSubmits a valid payment to Stellar Testnet and returns the settlement result.

Both POST endpoints accept an x402 v2 body containing x402Version, paymentPayload and paymentRequirements. The resource server calls these endpoints; the buyer does not call the Facilitator directly.

Exact and upto

exact is the default path. The buyer authorizes one SEP-41 transfer(from, to, amount), and the Facilitator cannot change its asset, recipient or amount without invalidating the authorization.

upto is an experimental AgentSmith scheme backed by a Soroban settlement Kernel. The buyer authorizes a maximum and the resource server settles an actual amount at or below that cap, including zero. It is advertised only when the Facilitator is configured with the current Kernel contract and is not yet an upstream x402 scheme.

Current service behavior

These are the defaults enforced by the AgentSmith-operated Facilitator. Sellers should build payment requirements around them, and buyers should use the requirements exactly as returned in the 402 response.

BehaviorCurrent serviceIntegration guidance
Facilitator URLhttps://agentsmith.xyz/facilitatorUse this as X402_FACILITATOR_URL. The Resource Server calls it; the Buyer does not.
Network and assetstellar:testnet and Testnet USDC onlySellers must advertise this exact network and USDC contract. The buyer needs sufficient Testnet USDC; the seller's receiving account must be able to hold it.
Strict verificationNetwork, scheme, asset, recipient, amount, signature, expiration and simulated transfer must match.Do not alter payment requirements between the 402 response and the paid retry. A mismatch is rejected before settlement.
Authorization lifetimeThe Facilitator enforces the Seller's maxTimeoutSeconds; the x402 server default is 300 seconds when omitted.Buyers should sign and retry promptly. If an authorization expires, request a new 402 challenge and sign again.
Fee sponsorshipThe Facilitator pays the XLM network fee, capped at 50000 stroops (0.005 XLM) per settlement.The buyer does not need XLM for the transaction fee. A simulation above the cap is rejected with invalid_exact_stellar_payload_fee_exceeds_maximum.
Settlement result/verify never moves funds. /settle re-verifies, submits and waits for confirmation.Return the protected resource only after settlement succeeds. Persist the returned transaction hash for reconciliation.

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 Stellar Testnet, 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 Stellar Testnet, and returns the resource to the buyer. Buyer Resource Server Facilitator Stellar Testnet 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.
Facilitator / Seller integration

Integrate the Facilitator

This guide is for a Seller connecting its Resource Server to an already deployed instance of the AgentSmith Facilitator from this repository. It follows the same integration pattern as the AgentSmith Weather service and end-to-end tests: keep the Facilitator behind the Resource Server, pass its URL through an environment variable, and let the x402 middleware call it. Buyers call only the Seller's paid endpoint; they never call the Facilitator directly. The complete Seller and Buyer reference implementation is available in weather-x402 on GitHub.

Use the official Stellar exact scheme for fixed-price payments. The deployed Facilitator can also advertise AgentSmith's experimental upto scheme for usage-based settlement through /supported. upto has not been adopted by the upstream x402 specification; see Exact and upto. The example below uses the standard exact path.

1. Install the server packages

Install the official server packages from the x402 GitHub repository.

resource serverbash
pnpm add @x402/core @x402/express @x402/stellar

2. Configure the integration

The only Facilitator-specific environment variable the Resource Server needs is X402_FACILITATOR_URL. Use the public AgentSmith Facilitator base URL below. The x402 client appends /supported, /verify and /settle as needed.

resource serverdotenv
X402_FACILITATOR_URL=https://agentsmith.xyz/facilitator
Payment terms remain Seller configuration. Keep the receiving address, resource URL and route price in your application's existing configuration. They are passed to the x402 middleware, not used to connect to the Facilitator. For the current Testnet deployment, the receiving account must be able to hold Testnet USDC.

3. Connect the protected route

Create an x402 Resource Server with the configured Facilitator URL, register the Stellar scheme, and pass that Resource Server to the payment middleware. Keep the route definitions and payment terms in your existing Seller configuration. Initialize the Resource Server during startup so an unreachable or incompatible Facilitator fails before the app serves traffic.

payment.tstypescript
import { paymentMiddleware } from '@x402/express';
import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';
import { ExactStellarScheme } from '@x402/stellar/exact/server';

const facilitatorUrl = process.env.X402_FACILITATOR_URL;
if (!facilitatorUrl) throw new Error('X402_FACILITATOR_URL is required');

const facilitator = new HTTPFacilitatorClient({ url: facilitatorUrl });
const resourceServer = new x402ResourceServer(facilitator)
  .register('stellar:testnet', new ExactStellarScheme());

// Check /supported once during startup.
await resourceServer.initialize();

// sellerRoutes contains your payTo, price and resource URL.
app.use(paymentMiddleware(sellerRoutes, resourceServer));

Compare this with the runnable demo's minimal Seller example and complete payment configuration.

Add upto settlement (experimental)

Use upto only when the Facilitator advertises it through /supported. Unlike exact, the server adapter is not exported by an official x402 package. Add the AgentSmith UptoStellarServer implementation to your project:

src/upto.ts (server excerpt)typescript
import type {
  Network,
  PaymentRequirements,
  SchemeNetworkServer,
  SupportedKind,
} from '@x402/core/types';
import { ExactStellarScheme as ExactServerScheme } from '@x402/stellar/exact/server';

/** Resource Server adapter for AgentSmith's experimental Stellar upto scheme. */
export class UptoStellarServer implements SchemeNetworkServer {
  readonly scheme = 'upto';
  readonly defaultAssetTransferMethod = 'default';
  readonly paymentFlows = {
    default: { supported: ['authorization'] as const, default: 'authorization' as const },
  };
  private readonly delegate = new ExactServerScheme();

  parsePrice = this.delegate.parsePrice.bind(this.delegate);
  getAssetDecimals = this.delegate.getAssetDecimals.bind(this.delegate);
  enhancePaymentRequirements = async (
    requirements: PaymentRequirements,
    supported: SupportedKind,
    extensions: string[],
  ) => this.delegate.enhancePaymentRequirements(requirements, supported, extensions);
  getExtra = (_network: Network) => ({ areFeesSponsored: true });
}

Register that adapter on the same Resource Server before calling initialize() or mounting the middleware. Use the Kernel contract and Facilitator signing address published for that deployment. The adapter is an AgentSmith extension and is not part of the official x402 packages or specification.

payment.tstypescript
import { setSettlementOverrides } from '@x402/express';
import { UptoStellarServer } from './upto.js';

// Run this before resourceServer.initialize().
resourceServer.register('stellar:testnet', new UptoStellarServer());

const uptoPaymentOption = {
  scheme: 'upto',
  network: 'stellar:testnet',
  price: { asset: usdc, amount: maximumAmountAtomic },
  payTo,
  extra: {
    settlementContract: uptoTerms.settlementContract,
    facilitator: uptoTerms.facilitator,
  },
};

// Add this option to sellerRoutes before mounting paymentMiddleware.
sellerRoutes['POST /v1/resource'].accepts.push(uptoPaymentOption);

// After the protected resource succeeds, charge its actual cost.
// selectedPaymentScheme reads the option chosen in the signed payment payload.
if (selectedPaymentScheme(req) === 'upto') {
  const actualAmountAtomic = calculateActualAmount(result);
  setSettlementOverrides(res, { amount: actualAmountAtomic });
}
Maximum versus actual amount. The amount in the 402 payment option is the maximum the Buyer authorizes. The settlement override is the actual amount charged after the resource completes; it may be zero but must not exceed that maximum. If the same route offers both schemes, set the override only when the paid request selected upto.

Mount the middleware before the protected route. It returns the initial 402, forwards the paid retry to the Facilitator for verification and settlement, and attaches the x402 payment response after a successful settlement.

Next: integrate the Buyer. The Buyer integration shows how to receive the payment requirements, sign locally and retry the protected request.
Facilitator / Buyer integration

Complete a payment as a Buyer

A Buyer interacts only with the Seller's protected endpoint. It makes the initial request, reads the payment requirements from the 402 response, signs the selected requirement locally and retries the same request with the signed x402 payload. The Seller's Resource Server handles verification and settlement through the Facilitator.

The Browser does not call the Facilitator. Browser JavaScript requests the Seller's protected endpoint and signs the Buyer authorization locally. The Seller's Resource Server is the component that calls the Facilitator's /verify and /settle endpoints.

1. Connect the wallet

Connect Freighter, confirm that it is on Stellar Testnet, construct the official Stellar exact client, sign the Soroban authorization entry locally, and retry the same request. The private key never leaves Freighter.

Create the exact client

buyer.js — connect and exactjavascript
import {
  requestAccess,
  getNetwork,
  signAuthEntry,
  signTransaction,
} from '@stellar/freighter-api';
import { ExactStellarScheme } from '@x402/stellar/exact/client';

const access = await requestAccess();
if (access.error || !access.address) {
  throw new Error('Freighter access was not granted');
}

const network = await getNetwork();
if (network.error || !/TESTNET/i.test(network.network || '')) {
  throw new Error('Switch Freighter to Stellar Testnet');
}

const signer = {
  address: access.address,
  signAuthEntry,
  signTransaction,
};
const exact = new ExactStellarScheme(signer, { url: rpcUrl });

2. Handle 402, sign and retry

The initial request returns payment requirements. The official exact client builds and simulates the SEP-41 transfer, invokes Freighter's signAuthEntry, and produces the payload sent in PAYMENT-SIGNATURE.

buyer.js — paid retryjavascript
let response = await fetch(url, request);
if (response.status !== 402) return response;

const paymentRequired = fromBase64(
  response.headers.get('payment-required'),
);
const requirements = paymentRequired.accepts.find(
  option => option.scheme === 'exact',
);

const { x402Version, payload } =
  await exact.createPaymentPayload(2, requirements);

response = await fetch(url, {
  ...request,
  headers: {
    ...request.headers,
    'payment-signature': toBase64({
      x402Version,
      resource: paymentRequired.resource,
      accepted: requirements,
      payload,
    }),
  },
});
Complete reference implementation. See weather-x402 on GitHub for the full Seller and Buyer flow, including exact and experimental upto payments.
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.