Site icon Chainstack

x402 on Solana: developer guide to micro-payments

Solana X402 logo

A hands-on deep dive into building autonomous micro-payment infrastructure with x402 on Solana, enabling Telegram bots to pay per API request with on-chain USDC settlement.

❓ Prefer diving straight into the code? Get the x402Bot on Utkarshini’s GitHub: https://github.com/utkarshiniarora/x402-bot

TL;DR

Modern AI systems are increasingly autonomous. Agents call APIs, fetch data, execute strategies, and coordinate across services without human intervention. What they lack is a native way to pay for the resources they consume.

In this guide, we’ll build a Telegram bot that pays per API request using x402, settles on Solana, uses USDC via the Exact SVM scheme, integrates a PayAI facilitator, and runs on a reliable Chainstack RPC endpoint. The bot will automatically deduct funds from a wallet and pay for every request it makes to a protected API server.

We will implement:

By the end, you’ll understand how to build pay-per-request infrastructure for a telegram bot, without API keys, subscription dashboards, or centralized billing systems.

📖 Before jumping into this blog, you may read in detail about x402: x402 protocol: Architecture and payment flow for AI agents

What is x402?

➡️ If you are already familiar with x402 and and ready to dive into coding, jump to “Build bot x402 on Solana step-by-step” section below.

x402 is a protocol that revives the unused HTTP 402 Payment Required status code and turns it into a native web monetization primitive. Historically, HTTP 402 was reserved but never standardized. x402 gives it concrete meaning:

Instead of API keys or subscription tokens, access is granted per request based on payment.

Why micro-payments matter for AI Agents

AI agents operate independently and execute tasks.

Micro-payments on Solana with x402 solve this. Instead of committing to a monthly subscription, agents pay per call. If an agent needs one request, it pays once. If it needs 1,000, it pays 1,000 times.

Why Solana?

With Solana, per-request settlement becomes economically viable. Why this matters for builders: you monetize APIs instantly, benefit from very low Solana transaction fees, no billing infrastructure required, revenue captured at the application layer, no API key leaks, fully programmatic access. This is foundational infrastructure for AI-native services.

Build bot x402 on Solana step-by-step

We will use:

Environment setup

Set up Solana RPC on Chainstack

In the next step, select the type of node. For this project, choose “Global Node.” Give your node a name, review all the settings in the summary, and click “Deploy Node”.

Once the node is deployed, click “View Node Details”. Scroll down to the “Access and credentials” section. Here you will find the endpoint URL, copy it and keep it safe. It will be needed in the next step.

⚠️ Do not expose your URL. Store it securely in a .env file and add it to your .gitignore before pushing the code to GitHub. Consider using password-protected endpoints to enhance security.

Install dependencies:

npm init -y

npm install express dotenv
npm install @x402/express @x402/fetch @x402/svm @payai/facilitator @scure/base @solana/kit @solana/web3.js
npm install node-telegram-bot-api

Create an .env file

BOT_TOKEN=
SVM_PRIVATE_KEY=
SELLER_ADDRESS=
SOLANA_RPC=

⚠️ Never commit .env. For best security practices use separate wallets for dev and production

Build the x402 server

⚠️ If you do not wish to run a server , you can use x402 Echo https://x402.payai.network/ payai facilitator for testing purposes. All test payment will be instantly refunded.

server.js is the payment-protected API layer

Import the dependencies:

import expressfrom"express";
import {paymentMiddleware,x402ResourceServer }from"@x402/express";
import {ExactSvmScheme }from"@x402/svm/exact/server";
import {HTTPFacilitatorClient }from"@x402/core/server";
import {facilitator }from"@payai/facilitator";

Initialize facilitator:

constfacilitatorClient=newHTTPFacilitatorClient(facilitator);

Create resource server:

constresourceServer=newx402ResourceServer(facilitatorClient)
.register(
"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
newExactSvmScheme()
  );

This registers the network, payment scheme and facilitator

Protect Routes with paymentMiddleware

Protected routes are /alpha and /track which will trigger a HTTP 402 USDC payment on Solana:

app.use(
paymentMiddleware(
    {
"GET /alpha": {
        accepts: [
          {
            scheme:"exact",
            price:"$0.001",
            network:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
            payTo:CONFIG.SELLER_ADDRESS,
          },
        ],
        description:"Premium Solana news feed",
        mimeType:"application/json",
      },
"GET /track": {
        accepts: [
          {
            scheme:"exact",
            price:"$0.001",
            network:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
            payTo:CONFIG.SELLER_ADDRESS,
          },
        ],
        description:"Paid Solana price feed via Chainstack RPC",
        mimeType:"application/json",
      },
    },
resourceServer
  )
);

Routes are declared payable.

Run the server:

node server.js

Build the x402 client

Now the Telegram bot must pay automatically.

services.js defines utility functions:

Solana Signer: This derives a signer from base58 private key

asyncfunctiongetSigner() {
returnawaitcreateKeyPairSignerFromBytes(
base58.decode(CONFIG.SVM_PRIVATE_KEY)
  );
}

Payment Logic : wrapFetchWithPayment expects fetch and client

constclient=newx402Client();
client.register("solana:*",newExactSvmScheme(signer));

constfetchWithPayment=wrapFetchWithPayment(fetch,client);

When calling endpoint:

constresponse=awaitfetchWithPayment(url, {
  method:"GET",
});

wrapFetchWithPayment: Detects 402, signs transaction, retries request & attaches PAYMENT-SIGNATURE

Build the Telegram Bot

bot.js initializes:

exportfunctioninitBot(token) {
constbot=newTelegramBot(token, { polling:true });
}

On /start: Initializes subscription entry, explains pricing and lists commands

On track: Pays $0.001, fetches Solana market data and returns structured market info

On alpha: Cron-based auto-fetch of /alpha keep going on until stop or wallet balance below $10

Run a cron job:

schedule("0 * * * * *",async () => {
for (const [userId]ofsubscriptions) {
awaitrunJob(userId);
  }
});

Every minute:

You can set this to daily or trigger dynamically.

This enables:

Run client:

node index.js

Checking the bot execution

Go to Telegram and send /start to the bot.

Send command track to get latest insights on Solana

Then send alpha to get latest news on Solana

Cron job sends alpha when new news pops up

Optionally, send stop to terminate the bot from giving alpha and auto deduct payments via x402.

Security and production considerations

When building autonomous micro-payment infrastructure, security and operational discipline are critical. Small mistakes can compound quickly when payments are triggered programmatically.

Below are key safeguards to implement:

Conclusion

x402 on Solana turns HTTP 402 into a practical monetization layer for AI agents. With pay-per-request micro-payments, developers can build scalable API businesses without traditional billing complexity.

In this guide, we built a complete pay-per-request architecture: a payment-protected resource server, an automated client that signs transactions, a Telegram bot interface, cron-based execution loops, and wallet-based micro-deductions settled on Solana using USDC. With a facilitator coordinating payments and reliable RPC infrastructure from Chainstack, the system operates without API keys, subscription dashboards, or centralized billing backends.

Now you have the context and architectural blueprint to implement per-call monetization in your own stack, and with dependable infrastructure in place, you can deploy and scale your first x402-powered application with confidence.

Reliable Solana RPC infrastructure

Getting started with Solana on Chainstack is fast and straightforward. Developers can deploy a reliable Solana node within seconds through an intuitive Console — no complex setup or hardware management required. 

Chainstack provides low-latency Solana RPC access and real-time gRPC data streaming via Yellowstone Geyser Plugin, ensuring seamless connectivity for building, testing, and scaling DeFi, analytics, and trading applications. With Solana low-latency endpoints powered by global infrastructure, you can achieve lightning-fast response times and consistent performance across regions. 

Start for free, connect your app to a reliable Solana RPC endpoint, and experience how easy it is to build and scale on Solana with Chainstack – one of the best RPC providers.

Exit mobile version