> For the complete documentation index, see [llms.txt](https://docs.pharos.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pharos.xyz/developer-guide/x402.md).

# x402

## Overview

x402 is an open, internet-native payment protocol. The HTTP 402 status code was defined in the early HTTP/1.1 specification as “Payment Required.” However, for a long time, it served only as a reserved status code with few practical applications. With the maturation of blockchain and crypto-payment infrastructure, this status code has been reactivated, evolving into a lightweight, trustless mechanism for content payment.

In this model, when a client requests protected resources (such as articles, API responses, or data streams), the server does not return the content directly. Instead, it returns an HTTP 402 response accompanied by payment instructions (e.g., recipient address, amount, supported payment networks, etc.). The client initiates a micro-payment—either on-chain or off-chain—via a wallet. Once the server verifies the validity of the transaction, it unlocks and delivers the requested content. In decentralized networks like Pharos, this process is typically implemented as follows: the user sends a micro-token transfer to a specified address → the network node or server-side listens for and verifies the transaction → the original requested resource is automatically returned upon successful verification. The entire process requires no registration, login, or traditional payment gateways, truly achieving “pay-as-you-go, instant access.”

This mechanism provides native, programmable payment capabilities for AI agents, automated services, or IoT devices, serving as one of the key infrastructures for building an Autonomous Economy.

## Working

<figure><img src="/files/HR9JX0A0Mxg4HIh8zx9b" alt="x402 Flowchart"><figcaption><p>x402 Flowchart</p></figcaption></figure>

### Initial Request and Payment Requirements

* **Resource Request Initiation:** The client initiates an HTTP request (e.g., `GET /api`) to the resource server for a specific protected resource.
* **Payment Trigger Response:** The server returns an `HTTP 402 Payment Required` status code. A Base64-encoded `PaymentRequired` object is carried in the response body via the `PAYMENT-REQUIRED` header. This object defines the payment scheme, target network, and specific payment parameters required for the current transaction.

### Payment Credential Construction and Signing

* **Scheme Selection and Payment Payload Generation:** The client parses the payment requirements returned by the server and selects a specific payment scheme based on its own supported payment capabilities. Subsequently, the client constructs a `PaymentPayload` containing the necessary metadata according to the protocol specifications of that scheme.
* **Secondary Request Submission:** The client re-initiates the resource request and attaches the signed `PaymentPayload` in the `PAYMENT-SIGNATURE` HTTP header.

### Verification

* **Verification Routing:** Upon receiving the signed request, the resource server executes validation logic. The server can choose to perform local verification or forward the `PaymentPayload` and the original `PaymentRequirements` to the Facilitator's `/verify` interface for remote verification.

**Compliance Check:** The Facilitator verifies the payload according to the specified payment scheme and blockchain network rules, then returns a `Verification Response` to the resource server.

* **Access Control Decisions:**
  * **Verification Failed:** If the verification does not pass, the resource server returns a 402 status code and error details again.
  * **Verification Succeeded:** If the verification passes, the resource server confirms the payment credential is valid and immediately initiates business logic processing (Do Work), preparing for on-chain settlement.

### On-chain Settlement and Confirmation

* **Transaction Broadcasting:** The resource server is responsible for initiating fund settlement. This can be completed by interacting directly with a blockchain node or by delegating it to a Facilitator. If delegated, the server sends the payment credential to the Facilitator's `/settle` interface.
* **Block Inclusion:** The Facilitator submits the transaction to the blockchain network (Submit tx).

### Delivery and Receipt

* **Settlement Feedback:** Once the on-chain transaction is confirmed, the Facilitator returns a settlement execution response (Settlement Response) containing the transaction hash (`tx_hash`) to the resource server.
* **Resource Delivery:** The resource server sends an `HTTP 200 OK` response to the client, placing the requested resource content in the response body. Simultaneously, to provide proof of payment, the server attaches Base64-encoded settlement response information in the `PAYMENT-RESPONSE` response header, marking the completion of the entire "pay-before-receive" closed loop.

**Pharos Support:** The x402 protocol itself is chain-agnostic. On Pharos, it supports all ERC-20 tokens. Pharos’s high-performance features (30,000 TPS, sub-second finality) make it particularly suitable for x402 micro-payment scenarios.

## Use Cases

x402 enables micro-payment and pay-per-use scenarios that were previously impossible due to economic unfeasibility. Below are some possible application scenarios:

### Agent Commerce

* **AI Agents subscribing to content services with auto-renewal:** AI agents can represent users in subscribing to content services such as industry updates, financial newsletters, or in-depth analysis reports, automatically completing periodic fee payments and renewal operations through integrated digital wallets.
* **Pay-per-use AI capability calls:** Users or systems pay based on the actual number of uses when calling Large Language Model (LLM) inference, image generation, or other AI APIs.
* **Payments between agents:** Supports peer-to-peer payments between multiple autonomous agents for data sharing, task collaboration, or service provision without human intervention.
* **Automated financial trading agents:** Based on real-time market data and external information sources (e.g., paid data streams), these agents autonomously execute high-frequency trading strategies and dynamically procure necessary data resources to optimize decision-making.

### Medical and Health Tech

* **AI-assisted diagnostic reports:** After users upload medical images, they pay to unlock structured diagnostic suggestions.
* **Personalized health advice APIs:** Wearable devices call health analysis models and pay-per-call to obtain deep insights.
* **Access to electronic medical record fragments:** Third-party applications request specific medical visit records, and patients authorize and pay a small fee to share data.

### Education and Knowledge Services

* **AI Tutor single-question answering:** Basic prompts are free, while in-depth analysis requires payment to unlock.
* **Professional course fragment unlocking:** After a trial preview, users pay by the minute or chapter to continue learning.
* **Single academic paper access:** No subscription required; pay per paper for instant PDF access.

### E-commerce and Consumer Services

* **Personalized recommendation engine calls:** E-commerce platforms pay AI service providers based on successful conversions.
* **AR try-on/make-up experience:** Payment is required to unlock real-time rendering before high-precision virtual trials.
* **Supply chain risk assessment queries:** Enterprises pay-per-query for supplier risks, which can be used for procurement decision-making.

### Other Scenarios

* **Computing power rental:** Billing by the second for using GPU/CPU resources for training or inference.
* **IoT micro-transactions:** Sensor networks pay automatically based on data points or events (e.g., environmental monitoring, smart meters).
* **Sustainability and carbon credits:** Companies or individuals purchase carbon offsets on demand, with the API returning a 402 to trigger instant settlement.

**Key Advantage:** x402 transaction costs on Pharos are extremely low, making true micro-payments possible. Combined with instant finality, this enables real-time access control.

## x402 SDK for Pharos

### Server-side: Using Express + x402 Middleware

For Express applications, you can use the middleware pattern:

```ts

// Load .env environment variables
import { config } from "dotenv";
config();
// Import required modules
import express from "express";
import { paymentMiddleware, x402ResourceServer } from "@x402/express";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { HTTPFacilitatorClient } from "@x402/core/server";

// === Environment Configuration ===
const payToAddress = process.env.PAY_TO_ADDRESS as `0x${string}`;
if (!payToAddress) {
  console.error("❌ Please set the PAY_TO_ADDRESS environment variable");
  console.error('Example: export PAY_TO_ADDRESS=0xYourAddressHere');
  process.exit(1);
  }
  const facilitatorUrl = process.env.FACILITATOR_URL; // Facilitator service URL
const port = parseInt(process.env.PORT || "4021", 10); // Listening port

// USDC Configuration
const usdcAddress = process.env.USDC_ADDRESS; // USDC contract address on Pharos
const usdcName = process.env.USDC_NAME || "USDC";

// === Initialize Client and Resource Server ===
const facilitatorClient = new HTTPFacilitatorClient({ url: facilitatorUrl });
const resourceServer = new x402ResourceServer(facilitatorClient);

// === Create EVM Payment Scheme and Register Custom Amount Parser ===
const evmScheme = new ExactEvmScheme();
// Convert USD amount to USDC (6 decimals precision)
evmScheme.registerMoneyParser(async (amount: number, network: string) => {
  if (network === "eip155:688689") {
    return {
      amount: Math.round(amount * 1e6).toString(), // Convert to integer string (e.g., 0.01 → "10000")
      asset: usdcAddress,                          // USDC contract address
      extra: {
        token: usdcName,
        name: usdcName,
        version: "2",
      },
    };
  }
  return null;
});
// Register Pharos Atlantic Testnet (Chain ID: 688689)
resourceServer.register("eip155:688689", evmScheme);

// === Create Express App ===
const app = express();

// Use payment middleware to protect routes
app.use(
  paymentMiddleware(
    {
      // Premium endpoint: $0.01
      "GET /data": {
        accepts: {
          scheme: "exact",
          price: "0.01",
          network: "eip155:688689",
          payTo: payToAddress,
        },
        description: "Paid data endpoint",
        mimeType: "application/json",
      },
// Low-cost endpoint: $0.005
      "GET /api/info": {
        accepts: {
          scheme: "exact",
          price: "0.005",
          network: "eip155:688689",
          payTo: payToAddress,
        },
        description: "Low-cost info endpoint",
        mimeType: "application/json",
      },
    },
    resourceServer
  )
);

// === Protected Business Endpoints ===
app.get("/data", (req, res) => {
  res.json({ message: "Hello, paid user!", timestamp: Date.now() });
});
app.get("/api/info", (req, res) => {
  res.json({
    name: "Pharos x402 Server",
    network: "Pharos Atlantic Testnet",
    chainId: 688689,
    timestamp: Date.now(),
  });
});

// === Health Check (No Payment Required) ===
app.get("/health", (req, res) => {
  res.json({ status: "ok" });
});
// === Start Server ===
app.listen(port, () => {
  console.log(`✅ Server started, listening on http://localhost:${port}`);
  console.log(`📡 Network: Pharos Atlantic Testnet (Chain ID: 688689)`);
  console.log(`💰 Payment receiver address: ${payToAddress}`);
  console.log(`🪙 USDC contract: ${usdcAddress}`);
});

```

### Client-side: Using Fetch + x402 SDK

```ts

// Load environment variables
import { config } from "dotenv";
config();
// Import required modules
import { wrapFetchWithPayment, x402Client, decodePaymentResponseHeader } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import fs from "fs";

// === Get EVM private key (prefer environment variable, fall back to .private_key file) ===
const privateKey = 
  process.env.EVM_PRIVATE_KEY || 
  (fs.existsSync(".private_key") ? fs.readFileSync(".private_key", "utf-8").trim() : null);
if (!privateKey) {
  console.error("❌ Please set the EVM_PRIVATE_KEY environment variable, or create a .private_key file");
  process.exit(1);
}

// === Initialize EVM account and x402 client ===
const signer = privateKeyToAccount(privateKey as `0x${string}`);
const client = new x402Client();

// Register payment scheme for Pharos Atlantic Testnet (Chain ID: 688689)
client.register("eip155:688689", new ExactEvmScheme(signer));

// Wrap fetch to enable automatic payments
const fetchWithPayment = wrapFetchWithPayment(fetch, client);

// === Get target URL (from command-line argument, defaulting to local /data endpoint) ===
const url = process.argv[2] || "http://localhost:4021/data";
console.log(`📡 Request URL: ${url}`);
console.log(`💳 Payer account: ${signer.address}`);

// === Make a request with automatic payment ===
try {
  const response = await fetchWithPayment(url);
  const data = await response.json();
  console.log("✅ Request succeeded!");
  console.log("📦 Response data:", JSON.stringify(data, null, 2));

// If the response includes payment info, decode and print transaction details
  const paymentResponseHeader = response.headers.get("PAYMENT-RESPONSE");
  if (paymentResponseHeader) {
    const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader);
    console.log("💰 Transaction hash:", paymentResponse.transaction);
    console.log("🌐 Network:", paymentResponse.network);
    console.log("📤 Payer address:", paymentResponse.payer);
  }
} catch (error) {
  console.error("❌ Request failed:", error);
  process.exit(1);
}

```

### Facilitator Implementation

```ts
import dotenv from "dotenv";
import express from "express";
import { privateKeyToAccount } from "viem/accounts";
import { createWalletClient, http, publicActions, defineChain } from "viem";
import { x402Facilitator } from "@x402/core/facilitator";
import { toFacilitatorEvmSigner } from "@x402/evm";
import { ExactEvmScheme } from "@x402/evm/exact/facilitator";

dotenv.config();

// Check for EVM private key
if (!process.env.EVM_PRIVATE_KEY) {
  console.error("❌ Please set EVM_PRIVATE_KEY");
  process.exit(1);
}

// Define Pharos testnet (ID: 688689)
const pharos = defineChain({
  id: 688_689,
  name: "Pharos",
  nativeCurrency: { name: "PHRS", symbol: "PHRS", decimals: 18 },
  rpcUrls: { default: { http: ["https://atlantic.dplabs-internal.com/"] } }, // Pharos RPC endpoint
  testnet: true,
});

// Create wallet client
const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = createWalletClient({
  account,
  chain: pharos,
  transport: http(undefined, { timeout: 30_000 }),
}).extend(publicActions);

// Create EVM signer required by the Facilitator
const signer = toFacilitatorEvmSigner({
  address: account.address,
  getCode: (args) => client.getCode(args),
  readContract: (args) => client.readContract({ ...args, args: args.args || [] }),
  verifyTypedData: (args) => client.verifyTypedData(args as any),
  writeContract: (args) => client.writeContract({ ...args, args: args.args || [] }),
  sendTransaction: (args) => client.sendTransaction(args),
  waitForTransactionReceipt: (args) => client.waitForTransactionReceipt(args),
});

// Initialize Facilitator and register Pharos chain
const facilitator = new x402Facilitator();
facilitator.register("eip155:688689", new ExactEvmScheme(signer, { deployERC4337WithEIP6492: true }));

// Create Express app
const app = express();
app.use(express.json());

// Verify payment
app.post("/verify", async (req, res) => {
  try {
    const { paymentPayload, paymentRequirements } = req.body;
    const result = await facilitator.verify(paymentPayload, paymentRequirements);
    res.json(result);
  } catch (e) {
    res.status(500).json({ error: (e as Error).message });
  }
});

// Settle payment on-chain
app.post("/settle", async (req, res) => {
  try {
    const { paymentPayload, paymentRequirements } = req.body;
    const result = await facilitator.settle(paymentPayload, paymentRequirements);
    res.json(result);
  } catch (e) {
    res.status(500).json({ error: (e as Error).message });
  }
});

// Return supported payment schemes
app.get("/supported", (req, res) => {
  res.json(facilitator.getSupported());
});

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`✅ Facilitator is running on port: ${PORT}`);
  console.log(`⛓️ Supported network: eip155:688689 (Pharos Atlantic)`);
});

```

### Skill

**Skill Repository:** `https://github.com/PharosNetwork/examples/tree/main/skills/x402-pharos`

This skill facilitates using the x402 SDK to construct the Pharos x402 server and the corresponding test client. Currently, this skill only supports the Pharos Atlantic testnet with chain ID 688689 and a test USDC token address (`0xE0BE08c77f415F577A1B3A9aD7a1Df1479564ec8`), which is not an official address.

The following demonstrates building a server and client demo using this skill, taking opencode as an example.

**Create Server:** Enter the prompt: "Help me create a pharos-x402 server." It will ask for corresponding parameters (recipient address, Facilitator URL, etc.) and automatically generate the corresponding code files and configuration files.

<figure><img src="/files/7kongUBWMWzumzwz2n1w" alt="x402-2"><figcaption></figcaption></figure>

During the process, you can ask it to generate simple example code through conversation, including `/data` and `/premium` endpoints.

<figure><img src="/files/U1LXqlNLBwMPjHP1IY94" alt="x402-3"><figcaption></figcaption></figure>

The service can then be started.

<figure><img src="/files/lhrtnmLuPaDAdf6ZUQ4r" alt="x402-4"><figcaption></figcaption></figure>

Next, you can ask it to write a test client.

<figure><img src="/files/mtmlQDpsLmULaAXfox0m" alt="x402-5"><figcaption></figcaption></figure>

Once the private key is configured, you can test the payment process.

**Please note: never reveal your private key to large models. Configure it via environment variables or file writing.**

<figure><img src="/files/nm50rAuA6yEL511XUVzA" alt="x402-6"><figcaption></figcaption></figure>

## Advantages of x402 on Pharos

| Features                | Pharos         | Other EVM Chains        |
| ----------------------- | -------------- | ----------------------- |
| TPS                     | 30,000         | Usually < 5,000         |
| Block Time              | < 1 Second     | Usually 2 - 15 Seconds  |
| Finality Time           | Sub-second     | Usually several minutes |
| Micro-payment Viability | Extremely High | Low - High              |

### Why Choose Pharos for x402?

* **Ultra-low transaction costs:** Pharos's high throughput and efficient consensus minimize transaction costs, making micro-payments truly economically viable.
* **Instant Finality:** Sub-second finality means users can access content immediately after payment without waiting for multiple block confirmations.
* **EVM Compatibility:** Fully compatible with Ethereum tools (ethers.js, viem, Hardhat, etc.); existing developers do not need to learn new tools.
* **Compliance-Friendly:** Pharos's built-in compliance modules (ZK-KYC/AML) allow x402 payments to meet regulatory requirements, making it suitable for institutional adoption.
* **Modular Architecture:** Through SPN (Specialized Processing Network), the execution environment can be customized for specific payment scenarios.

## Development Recommendations

* **Temporary Access Authorization based on JWT:** After the user completes payment verification, the server can issue a short-term valid JSON Web Token (JWT) as a credential for subsequent resource access. This token should have a reasonable expiration time to avoid repeated payments while reducing the overhead of frequent on-chain verification by the server.
* **Security Management of Sensitive Information:** All confidential data such as private keys and API keys should be injected into the application through environment variables or dedicated secret management services. Hardcoding them in source code or configuration files is strictly prohibited to prevent accidental leakage.
* **Transaction Idempotency and Retry Support:** The client should be able to initiate a retry request based on the original transaction hash after a network interruption or request failure. The server must implement idempotency processing logic to ensure that the same on-chain transaction is not billed multiple times or granted permissions repeatedly.
* **Introducing Facilitator Service to Decouple Blockchain Interaction:** Design a middleware service (Facilitator) to encapsulate complex logic such as blockchain node communication, transaction listening, and verification, simplifying the main business code. However, note that this component could become a performance bottleneck or a single point of failure; it is recommended to combine redundant deployment, health checks, multi-account strategies, and downgrade policies to improve system resilience.

## Reference Resources

* **Pharos Official Website:** `https://www.pharos.xyz/`
* **Pharos Documentation:** `https://docs.pharos.xyz/`
* **x402 Specification:** `https://x402.org/`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.pharos.xyz/developer-guide/x402.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
