---
title: x402 Integration with Kora
description:
  Learn how to integrate the x402 payment protocol with Kora's gasless Solana
  signing infrastructure, enabling micropayments for API access with zero gas
  fees.
---

## What You'll Build

This guide walks you through implementing a complete x402 (HTTP 402 Payment
Required) integration with Kora, Solana gasless signing infrastructure. By the
end, you'll have a working system where:

- APIs can charge micropayments for access using the x402 protocol
- Users pay in USDC without needing SOL for gas fees
- Kora handles all transaction fees as the gasless facilitator
- Payments are settled atomically on Solana blockchain

The final result will be a fully functional payment-protected API:

```shell
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
X402 + KORA PAYMENT FLOW DEMONSTRATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

[1/4] Initializing payment signer
  → Network: solana-devnet
  → Payer address: BYJV...TbBc
  ✓ Signer initialized

[2/4] Attempting to access protected endpoint without payment
  → GET http://localhost:4021/protected
  → Response: 402 Payment Required
  ✅ Status code: 402

[3/4] Accessing protected endpoint with x402 payment
  → Using x402 fetch wrapper
  → Payment will be processed via Kora facilitator
  → Transaction submitted to Solana
  ✅ Status code: 200

[4/4] Processing response data
  ✓ Payment response decoded

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SUCCESS: Payment completed and API accessed
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Response Data:
{
    "data": {
        "message": "Protected endpoint accessed successfully",
        "timestamp": "2025-09-25T20:14:04.242Z"
    },
    "status_code": 200,
    "payment_response": {
        "transaction": "5ULZpdeThaMAy6hcEGfAoMFqJqPpCtxdCxb6JYUV6nA4x8Lk2hKEuzofGUPoe1pop6BdWMSmF5oRPrXsbdWmpruf",
        "success": true,
        "network": "solana-devnet"
    }
}
```

## What is x402?

[x402](https://www.x402.org/) is an open payment standard that enables seamless
micropayments for API access. Instead of traditional subscription models or API
keys, x402 allows servers to charge for individual API calls, creating true
pay-per-use infrastructure.

Key benefits of x402:

- **Instant Micropayments**: Pay fractions of a cent per API call
- **Enable AI agents to pay for API calls**: Pay for API calls with AI agents
- **No Subscriptions**: Users only pay for what they use
- **Web3 Payments**: Transparent, verifiable payments on-chain
- **Standard HTTP**: Works with existing web infrastructure using an HTTP 402
  status code when payment is required

Servers using x402 to require micropayments for API access will return an HTTP
402 status code when payment is required. To access protected endpoints, clients
must pass a valid payment to the server in a `X-PAYMENT` header. x402 relies on
"Facilitators" to verify and settle transactions so that servers don't need to
directly interact with blockchain infrastructure.

### Understanding Facilitators

Facilitators are a crucial component in the x402 ecosystem. They act as
specialized services that abstract blockchain payments on behalf of API servers.

**What Facilitators Do:**

- **Verify Payments**: Validate that client's payment payloads are correctly
  formed and sufficient
- **Abstract Complexity**: Remove the need for servers to directly interact with
  blockchain infrastructure (signing and paying network fees)
- **Settle Transactions**: Submit validated transactions to Solana (or other
  networks)

In our demo, we create a facilitator that leverages Kora to verify and settle
transactions (more details below).

## What is Kora?

Kora is a Solana signer node that provides signing and gasless transaction
services. It enables applications to abstract away gas fees, allowing users to
pay transaction costs in tokens other than SOL, or have fees sponsored entirely.

Key features of Kora:

- **Gasless Transactions**: Users don't need SOL to execute transactions
- **Fee Abstraction**: Pay fees in USDC or other SPL tokens
- **JSON-RPC Interface**: Simple HTTP API for transaction handling
- **Flexible Signers**: Support for multiple signer backends (memory, Vault,
  Turnkey, Privy)
- **Policy Engine**: Granular control over transaction validation and fee
  policies

In the context of x402, Kora serves as the perfect backend for facilitators: it
handles network fees, it signs transactions, and it validates transactions.
Because Kora introspects every transaction before signing, Kora nodes offer an
additional layer of security and more finite control of transaction validation
and fee policies.

## Architecture Overview

Our x402 + Kora integration consists of four interconnected components with a
complete request/response cycle:

Complete Payment Flow:

1. Client requests protected resource → API returns 402 Payment Required
2. Client creates payment transaction with x402 fetch wrapper (which assembles a
   Solana transaction with a payment instruction)
3. Client sends payment to Facilitator for verification
4. Facilitator validates via Kora, which signs and submits to Solana
5. Transaction confirmed on-chain, Facilitator notifies API
6. API returns protected content with payment receipt to Client

### Component Breakdown

1. **Kora RPC Server** (Port 8080)
   - Core gasless transaction service
   - Handles transaction signing as fee payer
   - Validates transactions against configured policies

2. **Facilitator Wrapper/Proxy Server** (Port 3000)
   - Adapts Kora to x402 protocol
   - Implements `/verify`, `/settle`, and `/supported` endpoints
   - Translates between x402 and Kora data formats

3. **Protected API** (Port 4021)
   - Demo API server with payment-protected endpoints
   - Uses x402-express middleware for payment handling
   - Returns data only after successful payment

4. **Client Application**
   - Demonstrates x402 fetch wrapper usage
   - Signs transactions with user's private key

The multi-component approach might seem complex, but it mirrors real-world
production systems where payment processing, API serving, and client
applications are separate concerns.

## Prerequisites

Before starting, ensure you have:

- [**Rust**](https://www.rust-lang.org/tools/install) (latest stable version)
- [**Node.js**](https://nodejs.org/en/download) (LTS or later)
- [**Kora CLI**](https://github.com/solana-foundation/kora/releases/latest)
  (latest version - `cargo install kora-cli`)
- [**pnpm**](https://pnpm.io/installation) (latest version)
- Basic understanding of
  [Solana transactions](https://solana.com/docs/core/transactions) and
  [SPL tokens](https://solana.com/docs/tokens)

## Project Setup

### Step 1: Clone and Build Kora

> **Important:** Kora's `main` branch is an integration branch and may contain
> unreleased or beta changes. Always use the latest stable release tag. You can
> find the latest stable release on the
> [Kora releases page](https://github.com/solana-foundation/kora/releases).

```bash
# Clone the repository
git clone https://github.com/solana-foundation/kora.git
cd kora

# Checkout the latest stable tag
git checkout v2.0.5

# Build and install Kora
just install
```

This installs the `kora` binary to your system, which we'll use to run the RPC
server.

### Step 2: Navigate to Demo Directory

```bash
cd examples/x402/demo
```

### Step 3: Install Dependencies

Install Node.js dependencies for all demo components:

```bash
# Install dependencies for all components (facilitator, API, and client)
pnpm run install:all
```

This script installs dependencies for:

- The facilitator wrapper service
- The protected API server
- The client demonstration app

### Step 4: Configure Environment

The demo includes a `.env.example` file with the required environment variables.
First, let's set up the basic configuration:

```bash
# Copy the example environment file
cp .env.example .env
```

Now you need to generate or provide keypairs for the demo. Run the following
command to generate the keypairs:

```bash
pnpm run setup
```

This will generate the keypairs and add them to the `.env` file:

- `KORA_SIGNER_ADDRESS` - The address of the Kora signer
- `KORA_SIGNER_PRIVATE_KEY` - The private key of the Kora signer
- `PAYER_ADDRESS` - The address of the payer who will pay to access the
  protected API
- `PAYER_PRIVATE_KEY` - The private key of the payer

### Step 5: Update Configuration Files

#### kora.toml

The `kora/kora.toml` file configures the Kora RPC server. You should not need to
make any changes to this file, but you can verify the following settings:

1. **Payment Token**: Ensure the Devnet USDC mint is in the allowlist:

```toml
allowed_tokens = [
    "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", # USDC devnet
]
```

2. **API Authentication**: The demo uses an API key for Kora access. This should
   match the `KORA_API_KEY` in the `.env` file:

```toml
[kora.auth]
api_key = "kora_facilitator_api_key_example"
```

3. **Fee Payer Policy**: Configured to restrict signing unwanted transactions
   using granular controls:

```toml
[validation.fee_payer_policy.system]
allow_transfer = false
allow_assign = false
allow_create_account = false
allow_allocate = false

[validation.fee_payer_policy.system.nonce]
allow_initialize = false
allow_advance = false
allow_authorize = false
allow_withdraw = false

[validation.fee_payer_policy.spl_token]
allow_transfer = false
allow_burn = false
allow_close_account = false
allow_approve = false
allow_revoke = false
allow_set_authority = false
allow_mint_to = false
allow_initialize_mint = false
allow_initialize_account = false
allow_initialize_multisig = false
allow_freeze_account = false
allow_thaw_account = false

[validation.fee_payer_policy.token_2022]
allow_transfer = false
allow_burn = false
allow_close_account = false
allow_approve = false
allow_revoke = false
allow_set_authority = false
allow_mint_to = false
allow_initialize_mint = false
allow_initialize_account = false
allow_initialize_multisig = false
allow_freeze_account = false
allow_thaw_account = false
```

4. **Allowed Programs**: Ensure the system program, token program, associated
   token program, and compute budget program are in the allowlist:

```toml
allowed_programs = [
    "11111111111111111111111111111111",             # System Program
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",  # Token Program
    "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Program
    "ComputeBudget111111111111111111111111111111",  # Compute Budget Program
]
```

#### signers.toml

The `kora/signers.toml` file configures the Kora signer. You should not need to
make any changes to this file, but you can verify the following settings:

1. **Signer Environment Variable**: Ensure the signer environment variable,
   `private_key_env` is set to `KORA_SIGNER_PRIVATE_KEY` (matching the env
   variable name in the `.env` file).

```toml
[[signers]]
name = "main_signer"
type = "memory"
private_key_env = "KORA_SIGNER_PRIVATE_KEY"
weight = 1
```

### Step 6: Fund Accounts

#### Devnet SOL

Our Kora signer address will need SOL for paying transaction fees. You can
airdrop devnet SOL to the Kora signer address using the Solana CLI:

```bash
# Airdrop SOL
solana airdrop 1 <KORA_SIGNER_ADDRESS> --url devnet
```

Alternatively, you can use the [Solana Faucet](https://faucet.solana.com/) to
airdrop SOL to the Kora signer address.

#### Devnet USDC

Your `PAYER_ADDRESS` is set in the `.env` file will need USDC for paying
transaction fees.

Get Devnet USDC from [Circle's Faucet](https://faucet.circle.com/). Make sure to
select "Solana Devnet" and use your `PAYER_ADDRESS` to request USDC.

## Running the Demo

You'll need four terminal windows to run all components from the
`examples/x402/demo` directory.

### Terminal 1: Start Kora RPC Server

Run the following command to start the Kora RPC server:

```bash
pnpm run start:kora
```

You should see a series of logs indicating that the Kora RPC server is running,
including:

```
INFO kora_lib::rpc_server::server: RPC server started on 0.0.0.0:8080, port 8080
```

### Terminal 2: Start Facilitator

Run the following command to start the Facilitator:

```bash
pnpm run start:facilitator
```

You should see:

```
Server listening at http://localhost:3000
```

### Terminal 3: Start Protected API

Run the following command to start the Protected API:

```bash
pnpm run start:api
```

You should see:

```
Server listening at http://localhost:4021
```

### Terminal 4: Run Client Demo

```bash
pnpm run demo
```

## Understanding the Implementation

Here's what happens during a successful payment flow:

1. **Client Request** → API returns 402 with payment requirements
2. **Payment Creation** → Client creates Solana transaction with payment
3. **Payment Submission** → Client sends request to server with payment in the
   `X-PAYMENT` header
4. **Verification** → Facilitator verifies via Kora's `signTransaction`
5. **Settlement** → Facilitator settles via Kora's `signAndSendTransaction`
   (sending the payment transaction to Solana)
6. **Access Granted** → Facilitator returns transaction signature and API
   returns protected content with payment receipt

![Transaction Flow](/assets/docs/tools/kora/x402-protocol-flow.png) _Source:
[x402 GitHub](https://github.com/coinbase/x402/)_

Let's dive into how each component works:

- **Kora RPC** (Port 8080): Handles gasless transaction signing
- **Facilitator** (Port 3000): Bridges x402 protocol to Kora
- **Protected API** (Port 4021): Your monetized API endpoint
- **Client**: Demonstrates automatic payment flow

### The Facilitator Wrapper/Proxy Server

The Facilitator runs on port 3000. This is the server that handles communication
with Solana (in our case, via Kora). It is used to verify and settle x402
payments.

The facilitator (`facilitator/src/facilitator.ts`) is the bridge between x402
protocol and Kora RPC. It implements three key endpoints:

#### 1. `/verify` Endpoint

This endpoint:

- Receives an x402 payment payload from the Protected API server
- Extracts the Solana transaction using x402 helpers
- Uses Kora's `signTransaction` to verify validity without broadcasting
- Returns verification status, `isValid`

#### 2. `/settle` Endpoint

This endpoint:

- Receives the the x402 payment payload after the payment has been verified by
  the `/verify` endpoint
- Uses Kora's `signAndSendTransaction` to sign and broadcast the transaction
- Returns the transaction signature as proof of settlement

#### 3. `/supported` Endpoint

This endpoint effectively advertises the facilitator's capabilities, including:

- Supported x402 version
- Payment scheme (exact payments)
- Network (solana-devnet)
- Fee payer address which we fetch from Kora using the `getPayerSigner` method

### The Protected API

The API server (`api/src/api.ts`) uses x402-express middleware to protect
endpoints:

```typescript
app.use(
  paymentMiddleware(
    KORA_PAYER_ADDRESS, // Where payments should go
    {
      "GET /protected": {
        price: "$0.0001", // Price in USD
        network: NETWORK // solana-devnet
      }
    },
    {
      url: FACILITATOR_URL // Our facilitator wrapper
    }
  )
);
```

The middleware:

- Intercepts requests to protected endpoints (in our case, the `/protected`
  endpoint)
- Returns 402 status if payment is missing
- Validates and handles payments via the facilitator
- Allows access after successful payment

Though we are using Express, the x402 library includes middleware support for
many common frameworks. See the
[x402 TypeScript Packages](https://github.com/coinbase/x402/tree/main/typescript/packages)
for more information.

### The Client Application

The client (`client/src/index.ts`) demonstrates automatic how x402 works by
sending a request with a standard `fetch` call and then retrying the request
with the payment wrapper:

```typescript
// Create a signer from private key
const payer = await createSigner(NETWORK, PAYER_PRIVATE_KEY);

// Wrap fetch with x402 payment capabilities
const fetchWithPayment = wrapFetchWithPayment(fetch, payer);

// First attempt: Regular fetch (will fail with 402)
const expect402Response = await fetch(PROTECTED_API_URL);
console.log(`Status: ${expect402Response.status}`); // 402

// Second attempt: Fetch with payment wrapper (succeeds)
const response = await fetchWithPayment(PROTECTED_API_URL);
console.log(`Status: ${response.status}`); // 200
```

The x402 fetch wrapper:

- Detects 402 responses
- Automatically creates payment transaction based on the protected API's payment
  requirements
- Signs with user's private key
- Sends payment to the facilitator for verification and processing
- Retries request with payment proof in the `x-payment-response` header
- Returns successful response

## Wrapping Up

Congratulations! 🔥 You've successfully implemented a complete x402 payment flow
with Kora's gasless infrastructure. This demonstration shows how:

- **x402 Protocol** enables frictionless API monetization through micropayments
- **Kora RPC** works as a facilitator for x402 payments by verifying and
  settling transactions
- **Users** can pay for API access without holding SOL or managing gas fees

This architecture creates a powerful foundation for:

- AI Agent marketplaces
- Pay-per-use APIs
- Micropayment content platforms
- Usage-based SaaS pricing
- Any service requiring instant, verifiable payments

The combination of x402 and Kora bring the power of Solana to traditional web
infrastructure.

### Keep Building

- **Customize Pricing**: Modify the API to charge different amounts for
  different endpoints
- **Add Multiple Tokens**: Configure Kora to accept various SPL tokens for
  payment
- **Production Deployment**: Deploy to mainnet with production signers (Vault,
  Turnkey, or Privy)
- **Build Your Own API**: Create a real service that monetizes through x402
  payments

## Additional Resources

#### x402 Protocol

- [x402 Documentation](https://x402.gitbook.io/x402/)
- [x402 GitHub](https://github.com/coinbase/x402)
- [x402 TypeScript SDK](https://www.npmjs.com/package/x402)

#### Kora

- [Kora Configuration Guide](/docs/tools/kora/operators/configuration)
- [Kora Signers Guide](/docs/tools/kora/operators/signers)
- [Kora API Reference](/docs/tools/kora/json-rpc-api)

#### Solana

- [Solana Documentation](https://solana.com/docs)
- [SPL Token Program](https://spl.solana.com/token)

## Support

Need help?

- Ask questions on [Solana Stack Exchange](https://solana.stackexchange.com/)
  with `kora` and `x402` tags
- Open issues on the
  [Kora GitHub repository](https://github.com/solana-foundation/kora)
