> ## 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.

# Read the paywall server

> Read the server that answers 402 with a price, checks the signed payment and settles it, then step through its output to see what an unpaid request gets.

<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="current"><a href="/developers/docs/payments/paywall-api/browser" aria-current="step"><span className="sol-stepper-n">Step 2<span className="sol-vh">: </span></span><span className="sol-stepper-t">Read the code</span></a></li>
<li data-state="todo"><a href="/developers/docs/payments/paywall-api/server"><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>

Now the server side. The paywall is one function, `createPaywallServer`, that
takes the wallet address to pay and a price, and returns a Node.js `node:http`
server. Read the code, then press **Run** to step through its responses on a
local test network (Surfpool). You run it yourself in the next step.

## 1. The messages

x402 messages are JSON objects, sent base64-encoded in HTTP headers. These are
the types the server and client share:

```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;
```

- `PaymentRequirements` is one way to pay. `maxAmountRequired` is the price in
  the token's base units, `asset` is the token's mint address, and `payTo` is
  the wallet that gets paid.
- `PaymentPayload` is what the client sends back in the `X-PAYMENT` header: a
  fully signed transaction, base64-encoded.
- `SettlementResponse` is the receipt the server returns in the
  `X-PAYMENT-RESPONSE` header. `transaction` is the transaction's signature.
- `network` is a [CAIP-2](https://chainagnostic.org/CAIPs/caip-2) identifier.
  `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` is Solana devnet.

## 2. The server

```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>

What the code does, in order:

1. **No payment, no data.** A request without an `X-PAYMENT` header gets `402`
   with `accepts: [requirements]`. That is the output above.
2. **Decode, never trust.** The header is untrusted input. Any decoding
   problem is a `402 malformed X-PAYMENT header`, not a crash. The server also
   refuses transactions that use address lookup tables, because it only checks
   accounts listed in the transaction itself.
3. **Check that it pays the price.** The server looks for a USDC
   `TransferChecked` instruction whose destination is the `payTo` wallet's USDC
   <span className="sol-chip" data-concept="token-account"><Tooltip headline="Token accounts" tip="Wallets don't hold tokens directly. Each token (USDC, or your own asset) gets a small account owned by the wallet, and transfers move between these accounts." cta="Learn more" href="/developers/docs/tokens/basics/create-token-account">token account</Tooltip><span className="nojs-only"> ([Token accounts](/developers/docs/tokens/basics/create-token-account): Wallets don't hold tokens directly. Each token (USDC, or your own asset) gets a small account owned by the wallet, and transfers move between these accounts.)</span></span>
   and whose amount is at least the price.
4. **One payment, one response.** The transaction's
   <span className="sol-chip" data-concept="signature"><Tooltip headline="Signatures" tip="Every transaction is signed by the wallets it spends from. The first signature doubles as the transaction's ID, which is what your code gets back and looks up later." cta="Learn more" href="/developers/docs/core/transactions#signatures">signature</Tooltip><span className="nojs-only"> ([Signatures](/developers/docs/core/transactions#signatures): Every transaction is signed by the wallets it spends from. The first signature doubles as the transaction's ID, which is what your code gets back and looks up later.)</span></span> is its
   ID. The server remembers every signature it has accepted and refuses a
   repeat with `payment already used`.
5. **Settle.** The server sends the transaction to the network and waits until
   it reaches `confirmed`.
6. **Check again on the network.** `verifyPayment`, the same check as in the
   [checkout tutorial](/developers/docs/payments/checkout/backend), reads the settled
   transaction back and confirms that `payTo` received the amount. Only then
   does the server return `200` with the data and an `X-PAYMENT-RESPONSE`
   header.

<div className="sol-concept not-prose">
[<span className="sol-concept-name">Token accounts</span> <span className="sol-concept-def">Wallets don't hold tokens directly.</span>](/developers/docs/tokens/basics/create-token-account)
</div>

<Note>
  The client pays the network fee here, because it signs as the fee payer. With
  the x402 SDK, a facilitator can pay it instead (step 4).
</Note>
