> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Add it to your server

> Pay for your endpoint from a client with a spending cap, run the server and client on a local test network, and move the handler into your own app.

<div className="sol-stepper not-prose" data-path="paywall-api">
<div className="sol-stepper-nav" role="navigation" aria-label="Paywall an endpoint · ~30 min">
<ol>
<li data-state="done"><a href="/developers/docs/payments/paywall-api/try-it"><span className="sol-stepper-n">Step 1<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Call a paid API</span></a></li>
<li data-state="done"><a href="/developers/docs/payments/paywall-api/browser"><span className="sol-stepper-n">Step 2<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Read the code</span></a></li>
<li data-state="current"><a href="/developers/docs/payments/paywall-api/server" aria-current="step"><span className="sol-stepper-n">Step 3<span className="sol-vh">: </span></span><span className="sol-stepper-t">Add it to your server</span></a></li>
<li data-state="todo"><a href="/developers/docs/payments/paywall-api/go-live"><span className="sol-stepper-n">Step 4<span className="sol-vh">: </span></span><span className="sol-stepper-t">Go live</span></a></li>
</ol>
</div>
</div>

This step puts the server in a project on your machine, adds the client that
pays it, and runs both against a local test network or devnet.

## 1. Create the project

You need Node.js 20.18 or later. The paywall shares the `solana-payments`
project with the Build a checkout tutorial: its files go in `paywall-api/`,
next to the `checkout/` folder it reuses two files from. Run every command from
`solana-payments`. If you did the checkout tutorial, skip to
[step 2](#2-save-the-server). Otherwise create the project:

```bash Terminal
mkdir -p solana-payments/checkout solana-payments/paywall-api && cd solana-payments
npm init -y && npm pkg set type=module
npm install @solana/kit @solana-program/token
npm install --save-dev tsx
```

`"type": "module"` lets the scripts use top-level `await`. `tsx` runs the
TypeScript files directly. The examples are tested with `@solana/kit` 8.4 and
`@solana-program/token` 0.17.

The server and client read their network settings from environment variables
and default to devnet. Save this as `checkout/config.ts`:

```ts checkout/config.ts
import {
  address,
  createSolanaRpc,
  createSolanaRpcSubscriptions,
} from "@solana/kit";

// Devnet by default. Point RPC_URL at mainnet (and USDC_MINT at mainnet USDC,
// EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v) when you go live.
export const RPC_URL = process.env.RPC_URL ?? "https://api.devnet.solana.com";
export const RPC_SUBSCRIPTIONS_URL =
  process.env.RPC_SUBSCRIPTIONS_URL ?? "wss://api.devnet.solana.com";
export const USDC_MINT = address(
  process.env.USDC_MINT ?? "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
);
export const USDC_DECIMALS = 6;

export const rpc = createSolanaRpc(RPC_URL);
export const rpcSubscriptions = createSolanaRpcSubscriptions(
  RPC_SUBSCRIPTIONS_URL,
);
```

<div className="sol-concept not-prose">
[<span className="sol-concept-name">RPC</span> <span className="sol-concept-def">RPC is the HTTP/JSON API your code uses to read from and send to the network.</span>](/developers/docs/rpc)
</div>

The server checks each settled payment with the checkout tutorial's
`verifyPayment`. Save it as `checkout/verify-payment.ts`:

```ts checkout/verify-payment.ts
import type { Address, Signature } from "@solana/kit";
import { rpc } from "./config";

export type PaymentCheck = { paid: true } | { paid: false; reason: string };

/**
 * Confirm on your server that `signature` paid this order: the transaction
 * succeeded, it carries the order's reference, and the store's token account
 * for `mint` received exactly `amount` base units. Never trust the browser's
 * word for it.
 */
export async function verifyPayment(order: {
  signature: Signature;
  storeOwner: Address;
  mint: Address;
  amount: bigint;
  reference?: Address;
}): Promise<PaymentCheck> {
  const tx = await rpc
    .getTransaction(order.signature, {
      commitment: "confirmed",
      encoding: "jsonParsed",
      maxSupportedTransactionVersion: 0,
    })
    .send();
  if (!tx) return { paid: false, reason: "transaction not found" };
  if (tx.meta?.err) return { paid: false, reason: "transaction failed" };

  const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey);
  if (order.reference && !keys.includes(order.reference)) {
    return { paid: false, reason: "reference not found" };
  }

  // What the store's token account for this mint held before and after.
  type TokenBalances = NonNullable<typeof tx.meta>["preTokenBalances"];
  const balance = (list: TokenBalances) =>
    BigInt(
      list?.find((b) => b.owner === order.storeOwner && b.mint === order.mint)
        ?.uiTokenAmount.amount ?? "0",
    );
  const received =
    balance(tx.meta?.postTokenBalances) - balance(tx.meta?.preTokenBalances);
  if (received !== order.amount) {
    return {
      paid: false,
      reason: `amount mismatch: expected ${order.amount}, received ${received}`,
    };
  }
  return { paid: true };
}
```

<div className="sol-term not-prose" data-term="paths/payments/checkout/verify" data-tab="checkout/verify-payment.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of verifyPayment() with the right and a wrong amount</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of verifyPayment() with the right and a wrong amount: Output">
<div className="sol-term-step" data-step="1" data-pending="call">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> `await verifyPayment({ ...order, signature, mint: USDC_MINT })`</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">\{ paid\: true \}</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> `await verifyPayment({ ...order, amount: 2_000_000n, signature, mint: USDC_MINT })`</div>
<div className="sol-term-row sol-term-ln">\{</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">paid\:</span> false,</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">reason\:</span> `'amount mismatch: expected 2000000, received 1000000'`</div>
<div className="sol-term-row sol-term-ln">\}</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">Right amount\: paid</span><span className="sol-term-badge" data-tone="error">Wrong amount\: refused</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

## 2. Save the server

Save the two files from the previous step as `paywall-api/x402.ts` and
`paywall-api/server.ts`:

```ts paywall-api/x402.ts
// The x402 "exact" scheme messages, as plain types. The server answers an
// unpaid request with 402 and a list of accepted payments; the client retries
// with an X-PAYMENT header holding a signed USDC transfer; the server answers
// with X-PAYMENT-RESPONSE holding the settled transaction signature.
export const X402_VERSION = 1;

/** CAIP-2 id of Solana devnet (genesis hash prefix). */
export const NETWORK =
  process.env.X402_NETWORK ?? "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";

export interface PaymentRequirements {
  scheme: "exact";
  network: string;
  /** Price in the asset's base units (USDC: 1_000_000 = 1 USDC). */
  maxAmountRequired: string;
  /** Token mint. */
  asset: string;
  /** Wallet that receives the payment (its USDC token account is credited). */
  payTo: string;
  resource: string;
  description: string;
  mimeType: string;
  maxTimeoutSeconds: number;
}

export interface PaymentRequired {
  x402Version: number;
  error: string;
  accepts: PaymentRequirements[];
}

export interface PaymentPayload {
  x402Version: number;
  scheme: "exact";
  network: string;
  /** Base64 wire transaction, fully signed by the payer. */
  payload: { transaction: string };
}

export interface SettlementResponse {
  success: boolean;
  transaction: string;
  network: string;
}

export const encodeHeader = (value: unknown) =>
  Buffer.from(JSON.stringify(value)).toString("base64");
export const decodeHeader = <T>(value: string): T =>
  JSON.parse(Buffer.from(value, "base64").toString("utf8")) as T;
```

`x402.ts` reads `X402_NETWORK` the same way as `config.ts`, with the devnet
CAIP-2 identifier as the default.

```ts paywall-api/server.ts
import { createServer } from "node:http";
import {
  address,
  getBase64Encoder,
  getCompiledTransactionMessageDecoder,
  getSignatureFromTransaction,
  getTransactionDecoder,
  type Address,
  type Base64EncodedWireTransaction,
} from "@solana/kit";
import {
  findAssociatedTokenPda,
  parseTransferCheckedInstruction,
  TOKEN_PROGRAM_ADDRESS,
  TokenInstruction,
} from "@solana-program/token";
import { rpc, USDC_MINT } from "../checkout/config";
import { verifyPayment } from "../checkout/verify-payment";
import {
  decodeHeader,
  encodeHeader,
  NETWORK,
  X402_VERSION,
  type PaymentPayload,
  type PaymentRequirements,
} from "./x402";

export function createPaywallServer(options: {
  payTo: Address;
  price: bigint;
}) {
  const usedSignatures = new Set<string>();
  const requirements: PaymentRequirements = {
    scheme: "exact",
    network: NETWORK,
    maxAmountRequired: options.price.toString(),
    asset: USDC_MINT,
    payTo: options.payTo,
    resource: "/api/forecast",
    description: "Tomorrow's forecast for one city",
    mimeType: "application/json",
    maxTimeoutSeconds: 60,
  };

  return createServer(async (req, res) => {
    const send = (status: number, body: unknown, headers = {}) => {
      res.writeHead(status, { "content-type": "application/json", ...headers });
      res.end(JSON.stringify(body));
    };
    const paymentRequired = (error: string) =>
      send(402, { x402Version: X402_VERSION, error, accepts: [requirements] });

    if (req.method !== "GET" || req.url !== "/api/forecast") {
      return send(404, { error: "not found" });
    }
    const header = req.headers["x-payment"];
    if (typeof header !== "string")
      return paymentRequired("X-PAYMENT header is required");

    let result: Awaited<ReturnType<typeof settle>>;
    try {
      result = await settle(header);
    } catch (err) {
      // RPC outage or similar: never let one request take the process down.
      console.error("settlement error", err);
      return send(500, { error: "payment could not be settled, try again" });
    }
    if (!result.ok) return paymentRequired(result.reason);
    send(
      200,
      { city: "Lisbon", tomorrow: "Sunny, 24°C" },
      {
        "X-PAYMENT-RESPONSE": encodeHeader({
          success: true,
          transaction: result.signature,
          network: NETWORK,
        }),
      },
    );
  });

  /** Check the signed transfer pays the price, then send it and confirm it. */
  async function settle(
    header: string,
  ): Promise<{ ok: true; signature: string } | { ok: false; reason: string }> {
    // Everything in the header is untrusted input: any decoding failure is a
    // 402 "malformed", never an exception.
    let payment: PaymentPayload;
    let wire: Base64EncodedWireTransaction;
    let transaction: ReturnType<
      ReturnType<typeof getTransactionDecoder>["decode"]
    >;
    let message: ReturnType<
      ReturnType<typeof getCompiledTransactionMessageDecoder>["decode"]
    >;
    try {
      payment = decodeHeader<PaymentPayload>(header);
      if (payment?.scheme !== "exact" || payment.network !== NETWORK) {
        return { ok: false, reason: "unsupported scheme or network" };
      }
      if (typeof payment.payload?.transaction !== "string") {
        return { ok: false, reason: "malformed X-PAYMENT header" };
      }
      wire = payment.payload.transaction as Base64EncodedWireTransaction;
      transaction = getTransactionDecoder().decode(
        getBase64Encoder().encode(wire),
      );
      message = getCompiledTransactionMessageDecoder().decode(
        transaction.messageBytes,
      );
    } catch {
      return { ok: false, reason: "malformed X-PAYMENT header" };
    }
    // Only accounts listed in the message itself are checked, so refuse
    // address lookup tables rather than resolving them.
    if (
      !("instructions" in message) ||
      ("addressTableLookups" in message &&
        (message.addressTableLookups?.length ?? 0) > 0)
    ) {
      return { ok: false, reason: "unsupported transaction version" };
    }
    const keys = message.staticAccounts;
    const inRange = (i: number) => i >= 0 && i < keys.length;

    const [payToTokenAccount] = await findAssociatedTokenPda({
      owner: options.payTo,
      mint: USDC_MINT,
      tokenProgram: TOKEN_PROGRAM_ADDRESS,
    });
    const transfer = message.instructions
      .filter(
        (ix) =>
          keys[ix.programAddressIndex] === TOKEN_PROGRAM_ADDRESS &&
          ix.data?.[0] === TokenInstruction.TransferChecked &&
          (ix.accountIndices ?? []).length >= 4 &&
          (ix.accountIndices ?? []).every(inRange),
      )
      .map((ix) =>
        parseTransferCheckedInstruction({
          programAddress: TOKEN_PROGRAM_ADDRESS,
          accounts: (ix.accountIndices ?? []).map((i) => ({
            address: address(keys[i]!),
            role: 0,
          })),
          data: ix.data!,
        }),
      )
      .find(
        (t) =>
          t.accounts.mint.address === USDC_MINT &&
          t.accounts.destination.address === payToTokenAccount &&
          t.data.amount >= options.price,
      );
    if (!transfer)
      return { ok: false, reason: "transaction does not pay the price" };

    const signature = getSignatureFromTransaction(transaction);
    if (usedSignatures.has(signature))
      return { ok: false, reason: "payment already used" };
    usedSignatures.add(signature);

    try {
      await rpc
        .sendTransaction(wire, {
          encoding: "base64",
          preflightCommitment: "confirmed",
        })
        .send();
    } catch (err) {
      return {
        ok: false,
        reason: `transaction rejected: ${(err as Error).message}`,
      };
    }
    for (let i = 0; i < 60; i++) {
      const { value } = await rpc.getSignatureStatuses([signature]).send();
      const status = value[0];
      if (status?.err) return { ok: false, reason: "transaction failed" };
      if (
        status?.confirmationStatus === "confirmed" ||
        status?.confirmationStatus === "finalized"
      )
        break;
      await new Promise((r) => setTimeout(r, 500));
    }

    // Same server-side check as the checkout tutorial: read the settled
    // transaction back and confirm the payTo account received the amount.
    const check = await verifyPayment({
      signature,
      storeOwner: options.payTo,
      mint: USDC_MINT,
      amount: transfer.data.amount,
    });
    return check.paid
      ? { ok: true, signature }
      : { ok: false, reason: check.reason };
  }
}
```

<div className="sol-term not-prose" data-term="paths/payments/paywall-api/server" data-tab="paywall-api/server.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">An unpaid request, printed by paywall-api/run.ts</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="An unpaid request, printed by paywall-api/run.ts: Output">
<div className="sol-term-step" data-step="1" data-pending="http">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await fetch(url)</div>
<div className="sol-term-row sol-term-ln" data-tone="warn">GET /api/forecast -\> <span className="sol-term-code" data-code="4xx">402</span> X-PAYMENT header is required</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">price\:</span> 1000 base units of <span className="sol-h" title="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"><span className="sol-h-f">4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU</span><span className="sol-h-s" aria-hidden="true">4zMM…ncDU</span></span> (0.001 USDC)</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">payTo\:</span> <span className="sol-h" title="4SnM7PENj3Amhyc6rRA5XG2rq3NpiyZbPvpgAQbA3FLE"><span className="sol-h-f">4SnM7PENj3Amhyc6rRA5XG2rq3NpiyZbPvpgAQbA3FLE</span><span className="sol-h-s" aria-hidden="true">4SnM…3FLE</span></span> <span className="sol-term-k">network\:</span> solana\:<span className="sol-h" title="EtWTRABZaYq6iMfeYKouRu166VU2xqa1"><span className="sol-h-f">EtWTRABZaYq6iMfeYKouRu166VU2xqa1</span><span className="sol-h-s" aria-hidden="true">EtWT…xqa1</span></span></div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="warn">402 Payment Required</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

## 3. Pay from a client

`fetchWithPayment` works like `fetch`, but pays when it gets a `402`.
`createPaymentHeader` picks the USDC option, refuses any price above
`maxAmount`, and signs a USDC transfer to `payTo`. `fetchWithPayment` then
retries with the signed transaction in the `X-PAYMENT` header. Save this as
`paywall-api/client.ts`:

```ts paywall-api/client.ts
import {
  address,
  appendTransactionMessageInstructions,
  createTransactionMessage,
  getBase64EncodedWireTransaction,
  pipe,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  signTransactionMessageWithSigners,
  type TransactionSigner,
} from "@solana/kit";
import {
  findAssociatedTokenPda,
  getTransferCheckedInstruction,
  TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import { rpc, USDC_DECIMALS, USDC_MINT } from "../checkout/config";
import {
  encodeHeader,
  NETWORK,
  X402_VERSION,
  type PaymentPayload,
  type PaymentRequired,
} from "./x402";

/**
 * fetch() that pays: on a 402 it signs a payment for the price and retries
 * with it in the X-PAYMENT header.
 */
export async function fetchWithPayment(
  url: string,
  options: { signer: TransactionSigner; maxAmount: bigint },
): Promise<Response> {
  const first = await fetch(url);
  if (first.status !== 402) return first;
  const header = await createPaymentHeader(
    (await first.json()) as PaymentRequired,
    options,
  );
  return fetch(url, { headers: { "X-PAYMENT": header } });
}

/**
 * Pick the USDC "exact" option from a 402 answer, refuse anything above
 * `maxAmount`, and sign a USDC transfer to `payTo`. Returns the X-PAYMENT
 * header value.
 */
export async function createPaymentHeader(
  { accepts }: PaymentRequired,
  options: { signer: TransactionSigner; maxAmount: bigint },
): Promise<string> {
  const option = accepts.find(
    (a) =>
      a.scheme === "exact" && a.network === NETWORK && a.asset === USDC_MINT,
  );
  if (!option) throw new Error("no supported payment option");
  const price = BigInt(option.maxAmountRequired);
  if (price > options.maxAmount) {
    throw new Error(
      `price ${price} is above maxAmount ${options.maxAmount}; not paying`,
    );
  }

  const [source] = await findAssociatedTokenPda({
    owner: options.signer.address,
    mint: USDC_MINT,
    tokenProgram: TOKEN_PROGRAM_ADDRESS,
  });
  const [destination] = await findAssociatedTokenPda({
    owner: address(option.payTo),
    mint: USDC_MINT,
    tokenProgram: TOKEN_PROGRAM_ADDRESS,
  });
  const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
  const message = pipe(
    createTransactionMessage({ version: 0 }),
    (m) => setTransactionMessageFeePayerSigner(options.signer, m),
    (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
    (m) =>
      appendTransactionMessageInstructions(
        [
          getTransferCheckedInstruction({
            source,
            mint: USDC_MINT,
            destination,
            authority: options.signer,
            amount: price,
            decimals: USDC_DECIMALS,
          }),
        ],
        m,
      ),
  );
  const signed = await signTransactionMessageWithSigners(message);

  const payment: PaymentPayload = {
    x402Version: X402_VERSION,
    scheme: "exact",
    network: option.network,
    payload: { transaction: getBase64EncodedWireTransaction(signed) },
  };
  return encodeHeader(payment);
}
```

Set `maxAmount`, the most a single request can cost, on every client you give
a wallet to, including AI agents.

## 4. Run it on your machine

This script plays both sides. It starts the paywall server on port 3000 with a
price of 0.001 USDC, paid to a new wallet whose USDC account it opens, then
makes four requests: one without paying, one that pays, the same payment sent
again, and one from a client whose `maxAmount` of 500 is below the price of
1,000. Save it as `paywall-api/run.ts`:

```ts paywall-api/run.ts
// paywall-api/run.ts: start the paywall server, call it without paying, pay,
// replay the same payment, and try a client whose cap is below the price.
//   npx tsx paywall-api/run.ts
// The client key is read from CLIENT_KEYPAIR, or from the Solana CLI default
// ~/.config/solana/id.json. It needs SOL for fees and 0.001 USDC.
import { readFile } from "node:fs/promises";
import type { AddressInfo } from "node:net";
import { homedir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import {
  appendTransactionMessageInstructions,
  assertIsTransactionWithBlockhashLifetime,
  createKeyPairSignerFromBytes,
  createTransactionMessage,
  generateKeyPairSigner,
  pipe,
  sendAndConfirmTransactionFactory,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  signature as toSignature,
  signTransactionMessageWithSigners,
  type Address,
  type TransactionSigner,
} from "@solana/kit";
import {
  findAssociatedTokenPda,
  getCreateAssociatedTokenIdempotentInstruction,
  TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import { rpc, rpcSubscriptions, USDC_MINT } from "../checkout/config";
import { createPaymentHeader, fetchWithPayment } from "./client";
import { createPaywallServer } from "./server";
import {
  decodeHeader,
  type PaymentRequired,
  type SettlementResponse,
} from "./x402";

export async function run(
  client: TransactionSigner,
  port = 3000,
): Promise<{
  payTo: Address;
  statuses: number[];
  signature: string;
  refused: boolean;
}> {
  // The wallet that gets paid. Use your own address in a real API.
  const payTo = (await generateKeyPairSigner()).address;
  const server = createPaywallServer({ payTo, price: 1_000n }); // 0.001 USDC
  await new Promise<void>((resolve, reject) =>
    server.once("error", reject).listen(port, resolve),
  );
  const { port: listening } = server.address() as AddressInfo;
  const url = `http://localhost:${listening}/api/forecast`;
  try {
    // Its USDC account must exist before it can receive USDC, so the client
    // opens it.
    const [ata] = await findAssociatedTokenPda({
      owner: payTo,
      mint: USDC_MINT,
      tokenProgram: TOKEN_PROGRAM_ADDRESS,
    });
    const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
    const open = await signTransactionMessageWithSigners(
      pipe(
        createTransactionMessage({ version: 0 }),
        (m) => setTransactionMessageFeePayerSigner(client, m),
        (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
        (m) =>
          appendTransactionMessageInstructions(
            [
              getCreateAssociatedTokenIdempotentInstruction({
                payer: client,
                ata,
                owner: payTo,
                mint: USDC_MINT,
              }),
            ],
            m,
          ),
      ),
    );
    assertIsTransactionWithBlockhashLifetime(open);
    await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(open, {
      commitment: "confirmed",
    });

    // 1. No payment: 402 with the price.
    const unpaid = await fetch(url);
    const required = (await unpaid.json()) as PaymentRequired;
    const [option] = required.accepts;
    console.log("GET /api/forecast ->", unpaid.status, required.error);
    console.log(
      `  price: ${option!.maxAmountRequired} base units of ${option!.asset} (${Number(option!.maxAmountRequired) / 1e6} USDC)`,
    );
    console.log("  payTo:", option!.payTo, "network:", option!.network);

    // 2. Pay (at most 0.005 USDC) and retry with the X-PAYMENT header.
    const header = await createPaymentHeader(required, {
      signer: client,
      maxAmount: 5_000n,
    });
    const paid = await fetch(url, { headers: { "X-PAYMENT": header } });
    const settlement = decodeHeader<SettlementResponse>(
      paid.headers.get("x-payment-response") ?? "",
    );
    console.log(
      "GET /api/forecast (paid) ->",
      paid.status,
      JSON.stringify(await paid.json()),
    );
    console.log("  settled signature:", settlement.transaction);
    const tx = await rpc
      .getTransaction(toSignature(settlement.transaction), {
        commitment: "confirmed",
        encoding: "json",
        maxSupportedTransactionVersion: 0,
      })
      .send();
    console.log("  fee:", String(tx?.meta?.fee), "lamports");

    // 3. The same X-PAYMENT header again: refused.
    const replay = await fetch(url, { headers: { "X-PAYMENT": header } });
    console.log(
      "GET /api/forecast (replayed X-PAYMENT) ->",
      replay.status,
      ((await replay.json()) as PaymentRequired).error,
    );

    // 4. A client that pays at most 0.0005 USDC refuses and signs nothing.
    let refused = false;
    try {
      await fetchWithPayment(url, { signer: client, maxAmount: 500n });
    } catch (err) {
      refused = true;
      console.log("client refused:", (err as Error).message);
    }
    return {
      payTo,
      statuses: [unpaid.status, paid.status, replay.status],
      signature: settlement.transaction,
      refused,
    };
  } finally {
    server.close();
    server.closeAllConnections();
  }
}

// Run when started directly (not when imported by the tests).
if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  const keyPath =
    process.env.CLIENT_KEYPAIR ??
    join(homedir(), ".config", "solana", "id.json");
  const bytes = new Uint8Array(JSON.parse(await readFile(keyPath, "utf8")));
  await run(
    await createKeyPairSignerFromBytes(bytes),
    Number(process.env.PORT ?? 3000),
  );
}
```

<div className="sol-term not-prose" data-term="paths/payments/paywall-api/run" data-tab="paywall-api/run.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of npx tsx paywall-api/run.ts</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of npx tsx paywall-api/run.ts: Output">
<div className="sol-term-step" data-step="1" data-pending="http">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\$</span> npx tsx paywall-api/run.ts</div>
<div className="sol-term-row sol-term-ln" data-tone="warn">GET /api/forecast -\> <span className="sol-term-code" data-code="4xx">402</span> X-PAYMENT header is required</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">price\:</span> 1000 base units of <span className="sol-h" title="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"><span className="sol-h-f">4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU</span><span className="sol-h-s" aria-hidden="true">4zMM…ncDU</span></span> (0.001 USDC)</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">payTo\:</span> <span className="sol-h" title="4SnM7PENj3Amhyc6rRA5XG2rq3NpiyZbPvpgAQbA3FLE"><span className="sol-h-f">4SnM7PENj3Amhyc6rRA5XG2rq3NpiyZbPvpgAQbA3FLE</span><span className="sol-h-s" aria-hidden="true">4SnM…3FLE</span></span> <span className="sol-term-k">network\:</span> solana\:<span className="sol-h" title="EtWTRABZaYq6iMfeYKouRu166VU2xqa1"><span className="sol-h-f">EtWTRABZaYq6iMfeYKouRu166VU2xqa1</span><span className="sol-h-s" aria-hidden="true">EtWT…xqa1</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="ok">GET /api/forecast (paid) -\> <span className="sol-term-code" data-code="2xx">200</span> `{"city":"Lisbon","tomorrow":"Sunny, 24°C"}`</div>
<div className="sol-term-row sol-term-ln" data-indent="2">settled <span className="sol-term-k">signature\:</span> <span className="sol-h" title="4JZW7fB3h53qP6f66eat4cwDVDFvxwTtKWbV8tfJJHVo4eHzK9riSvetQSwPEtungFxfbWC968JoyDoqRo7XauLZ"><span className="sol-h-f">4JZW7fB3h53qP6f66eat4cwDVDFvxwTtKWbV8tfJJHVo4eHzK9riSvetQSwPEtungFxfbWC968JoyDoqRo7XauLZ</span><span className="sol-h-s" aria-hidden="true">4JZW…auLZ</span></span></div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">fee\:</span> 5000 lamports</div>
<div className="sol-term-row sol-term-ln" data-tone="error">GET /api/forecast (replayed X-PAYMENT) -\> <span className="sol-term-code" data-code="4xx">402</span> payment already used</div>
<div className="sol-term-row sol-term-ln" data-tone="error">client refused\: price 1000 is above maxAmount 500; not paying</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="warn">402 Payment Required</span><span className="sol-term-badge" data-tone="ok">200 OK</span><span className="sol-term-badge" data-tone="error">402 Payment already used</span><span className="sol-term-badge" data-tone="error">Refused\: price above maxAmount</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

The script pays as the client with a key file: the one named in
`CLIENT_KEYPAIR`, or the Solana CLI default `~/.config/solana/id.json`. If you
don't have one yet, save this as `keygen.ts` in `solana-payments`. It writes a
new key file in the same format and prints its address:

```ts keygen.ts
import { generateKeyPairSync } from "node:crypto";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { createKeyPairSignerFromBytes } from "@solana/kit";

// Writes a new key file in the Solana CLI format (64 bytes as a JSON array).
const keyPath = join(homedir(), ".config", "solana", "id.json");
if (existsSync(keyPath)) throw new Error(`${keyPath} exists; not overwriting it`);
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
const bytes = new Uint8Array([
  ...privateKey.export({ format: "der", type: "pkcs8" }).subarray(-32),
  ...publicKey.export({ format: "der", type: "spki" }).subarray(-32),
]);
mkdirSync(dirname(keyPath), { recursive: true });
writeFileSync(keyPath, JSON.stringify([...bytes]), { mode: 0o600 });
console.log(`Address: ${(await createKeyPairSignerFromBytes(bytes)).address}`);
```

```bash Terminal
npx tsx keygen.ts
```

The key file is a private key. Keep it out of version control.

The client needs SOL for fees and at least 0.001 USDC on the same USDC mint the
code uses. Pick a network:

<Tabs>
<Tab title="Local (Surfpool)">

1. Install the [Surfpool CLI](/developers/docs/tools/surfpool/toolchain/getting-started)
   and start a local network that copies accounts from devnet, so the devnet
   USDC mint the code uses exists locally. It airdrops SOL to
   `~/.config/solana/id.json` when it starts (create the key file first):

   ```bash Terminal
   surfpool start --network devnet
   ```

2. In another terminal, in `solana-payments`, give the client 1 test USDC with
   Surfpool's
   [`surfnet_setTokenAccount`](/developers/docs/tools/surfpool/rpc/cheatcodes)
   cheatcode. Replace `<client address>` with the address of your key file:

   ```bash Terminal
   curl http://127.0.0.1:8899 -s -X POST -H "Content-Type: application/json" -d '
     {"jsonrpc": "2.0", "id": 1, "method": "surfnet_setTokenAccount",
      "params": ["<client address>", "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
                 {"amount": 1000000, "state": "initialized"},
                 "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"]}'
   ```

3. Point the code at Surfpool. `X402_NETWORK` stays at its devnet default,
   because Surfpool copies devnet:

   ```bash Terminal
   export RPC_URL=http://127.0.0.1:8899
   export RPC_SUBSCRIPTIONS_URL=ws://127.0.0.1:8900
   ```

</Tab>
<Tab title="Devnet">

Leave `RPC_URL` and `RPC_SUBSCRIPTIONS_URL` unset. Paste the client's address
into the [Solana Faucet](https://faucet.solana.com/) for devnet SOL, and into
[Circle's faucet](https://faucet.circle.com/) with **Solana Devnet** selected
for devnet USDC.

</Tab>
</Tabs>

Then run the script:

```bash Terminal
npx tsx paywall-api/run.ts
```

Expect the four answers shown under the script, with your own addresses and
signatures: `402` with the price, `200` with the forecast and the settled
signature, `402 payment already used` for the same `X-PAYMENT` header, and the
over-cap client refusing without signing anything. Port 3000 in use? Run it
with another port, for example `PORT=3001 npx tsx paywall-api/run.ts`.

### Run the tests instead

The code on these pages and its tests live in the docs repository under
`packages/docs-examples/paths/payments/paywall-api`. The test starts its own
Surfpool network and funds a test client, so you need no Surfpool CLI, keys,
SOL, or USDC. It also checks that malformed `X-PAYMENT` headers get `402`
without stopping the server, and that `payTo` is credited exactly the price:

```sh Terminal
git clone https://github.com/solana-foundation/solana-com.git
cd solana-com
corepack enable
pnpm install
pnpm --filter @workspace/docs-examples exec vitest run paths/payments/paywall-api
```

<Note>
  The full example is in
  [`packages/docs-examples/paths/payments/paywall-api`](https://github.com/solana-foundation/solana-com/tree/main/packages/docs-examples/paths/payments/paywall-api).
</Note>

<Note>
  If you have no Solana CLI key file at `~/.config/solana/id.json`, the test
  setup creates one there. To keep it out of your home folder, run the test
  with `HOME` set to a temporary folder.
</Note>

## 5. Move it into your app

Your server needs four files: `paywall-api/x402.ts`, `paywall-api/server.ts`,
`checkout/config.ts`, and `checkout/verify-payment.ts`. The project that pays
needs `paywall-api/client.ts`, `paywall-api/x402.ts`, and `checkout/config.ts`.
If you put them all in one folder, change the imports `../checkout/config` and
`../checkout/verify-payment` to `./config` and `./verify-payment`. Install
`@solana/kit` and `@solana-program/token`. Then call
`createPaywallServer({ payTo, price })` with your wallet address and a price in
USDC base units (`1_000n` is 0.001 USDC), and call `listen` on the server it
returns. The `payTo` wallet's USDC account must exist before the first payment.

The handler only uses the request method, URL, and `X-PAYMENT` header, and it
sets a status, headers, and a JSON body. To use Express, Fastify, or Hono, move
the body of the `createServer` callback into a route handler for your paid
route. The `usedSignatures` set must be shared by every request, as it is here.

<div className="sol-concept not-prose">
[<span className="sol-concept-name">Confirmation & finality</span> <span className="sol-concept-def">A transaction goes from processed to finalized in well under a second, and once finalized it can't be reversed.</span>](/developers/docs/core/transactions/confirmation)
</div>

The server answers a paid request only after the payment reaches *confirmed*,
so on a public network expect roughly the confirmation time added to your
normal response time.
