Skip to main content
A complete example of a REST API that charges per request using x402 micropayments.

Server

server.ts
import express from "express"
import { createMiddleware } from "@faremeter/middleware/express"
import { xSolanaSettlement } from "@faremeter/info/solana"

const app = express()

const microPayment = await createMiddleware({
  facilitatorURL: "https://facilitator.corbits.dev",
  accepts: [
    xSolanaSettlement({
      network: "devnet",
      payTo: process.env.MERCHANT_ADDRESS,
      asset: "USDC",
      amount: "100",
    }),
  ],
})

app.get("/api/weather/:city", microPayment, (req, res) => {
  res.json({
    city: req.params.city,
    temperature: 72,
    conditions: "sunny",
  })
})

app.get("/api/quote", microPayment, (req, res) => {
  res.json({
    quote: "The best way to predict the future is to invent it.",
    author: "Alan Kay",
  })
})

app.listen(3000)

Client

client.ts
import "dotenv/config"
import { payer } from "@faremeter/rides"
import { getLogger } from "@faremeter/logs"

const logger = await getLogger(["client"])

await payer.addLocalWallet(process.env.PAYER_KEYPAIR_PATH)

const weather = await payer.fetch("http://localhost:3000/api/weather/seattle")
logger.info(JSON.stringify(await weather.json()))

const quote = await payer.fetch("http://localhost:3000/api/quote")
logger.info(JSON.stringify(await quote.json()))

Running the example

# Terminal 1
MERCHANT_ADDRESS=7xKXwxRPMo2sUAT5... pnpm tsx server.ts

# Terminal 2
PAYER_KEYPAIR_PATH=~/.config/solana/id.json pnpm tsx client.ts
Each request triggers a separate micropayment. The client pays 100 units (0.0001 USDC) per API call.