Sitemap
Anoop Singh

Anoop Singh

web3 developer | finance nerd | computer science student

xTag — An x402 native agent

6 min readSep 28, 2025

--

An AI-native interface for a 402-enabled world.

Table of Contents

  1. Project Vision & Goal
  2. Architectural Blueprint
  3. Core Components Deep Dive
  4. The x402 Interaction Flow
  5. Guide: Setting Up an x402-Enabled Server
  6. User Guide
  7. Sample API Interactions (Requests & Responses)
  8. Future Integrations & Scalability
Press enter or click to view image in full size

1. Project Vision & Goal

The fundamental goal of xTag is to bridge the gap between the powerful, reasoning capabilities of Large Language Models (LLMs) and the economic realities of the digital world. Today’s AI agents are largely confined to accessing free resources, which limits their ability to perform meaningful, real-world tasks.

xTag demonstrates a future where AI agents are first-class economic actors. By equipping an AI with its own wallet and the ability to autonomously pay for resources using the x402 protocol, we unlock a new paradigm of “agentic” AI that can:

  • Access premium, high-quality data from paid APIs.
  • Execute on-chain transactions.
  • Interact with a decentralized economy of services.
  • Perform complex workflows, all while abstracting the underlying complexity from the end-user.

This blueprint details the architecture and technology that make this vision a reality.

2. Architectural Blueprint

The system is designed as a three-part ecosystem: the User Interface, the xTag Backend (which houses the AI agent), and one or more external Paid Resource Servers.

Architectural Diagram (ASCII)

+--------------------------------+      +-------------------------------------+      +--------------------------------+
| USER INTERFACE | | xTAG BACKEND (Agent) | | PAID RESOURCE SERVER |
| (Next.js, React, Tailwind) | | (Next.js API, Prisma, Gemini) | | (Node.js, x402-js) |
+--------------------------------+ +-------------------------------------+ +--------------------------------+
| | | | | |
| [Login Page] --(NFC Scan)----->| | [Auth API] -> Creates/Finds User | | |
| | | -> Generates Wallet | | |
| [Chat UI] <-----(JWT)----------| | -> Issues JWT | | |
| | | | | | | |
| |---(User Message)-------->| | [Chat API] ------+----------------->| | [Protected API] |
| | | | | | (LLM Call) | | (e.g., /api/nft-metadata) |
| | | | | v | | | |
| |<----(AI Response)--------| | | [Google Gemini] | | |---(402 Payment Required) |
| | | | | | | | |
| |---("run" command)------->| | | (Intent -> Tool) | | |
| | | | | | | | |
| | | | | [x402-axios Wrapper] <---+ | |
| | | | | | (Handles Payment)| | |
| | | | +------------+------------------------>| |
| | | | | (Paid Request) | |<----(200 OK + Data)-----------|
| |<----(Final Result)-------| | <----------------+ (Formats & | | |
| | | Returns Result) | | |
+--------------------------------+ +-------------------------------------+ +--------------------------------+

3. Core Components Deep Dive

Frontend

  • Framework: Next.js (App Router) & React
  • Styling: Tailwind CSS with shadcn/ui components
  • State Management: React Context (for Auth) and component state
  • Key Functionality: Provides the chat interface, NFC login flow, and renders data fetched by the backend

Backend (The Agent)

  • Runtime: Next.js API Routes (Serverless Functions)
  • Database: Supabase (PostgreSQL) with Prisma ORM for type-safe access
  • AI Model: Google Gemini (gemini-2.5-flash) for natural language understanding and tool selection

Blockchain

  • Protocol: x402 Protocol for standardized API payments
  • Client Library: x402-axios for automated client payment flows
  • EVM Interaction: viem for wallet creation and management
  • Network: Polygon Amoy Testnet

4. The x402 Interaction Flow

The x402-axios library automates payment handling.

Sequence Diagram (ASCII)

User        xTag Backend (with x402-axios)      Paid Resource Server
| | |
|---[run "cmd"]--->| |
| |---(1) GET /api/resource-------------->|
| |<--(2) 402 Payment Required-----------|
| | (Headers: x-payment-challenge) |
| | (3) Signs + submits tx to chain |
| |---(4) On-chain payment--------------->|
| |---(5) Retry request w/ proof-------->|
| |<--(6) 200 OK + Resource Data---------|
|<--[Formatted Data]| |

Flow Steps:

  1. User triggers an action.
  2. Resource server responds with 402 Payment Required.
  3. x402-axios auto-handles signing & payment.
  4. Payment sent to Polygon Amoy.
  5. Request retried with x-payment-response.
  6. Server verifies on-chain and returns data.

5. Guide: Setting Up an x402-Enabled Server

This part explains how to create a simple, x402-enabled server using Node.js, Express, and the x402-express middleware.

Get Anoop Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

This allows you to protect API endpoints and require a cryptocurrency payment for access.

Flow of a paid request:

+---------+        +----------------+        +--------------+
| Client | | Resource Server| | Facilitator |
+---------+ +----------------+ +--------------+
| | |
| 1. Request -------->| |
| | |
| | 2. 402 Challenge ----->|
| | |
|<------- 402 --------| |
| | |
| 3. Payment -------->|----------------------->|
| | |
| |<------ 4. Token -------|
|<------- Token ------| |
| | |
| 5. Authenticated -->| |
| Request | |
| | |
|<---- 6. Access -----| |
| (Content) | |
  1. Set up & install dependencies:
npm init -y
npm install express cors x402-express dotenv

2. Create a Server file, refer to this example:

import dotenv from "dotenv";
import express from "express";
import cors from "cors";
import { paymentMiddleware } from "x402-express";

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

// --- x402 Middleware Configuration ---
app.use(
paymentMiddleware(
// 1. Your receiving wallet address
"0x123...abc",

// 2. Configuration for protected routes
{
"GET /api/documentation": {
price: "$2.50", // Price in USD (facilitator handles conversion)
network: "polygon-amoy",
},
// Add more routes if needed
// "POST /api/generate-image": { price: "0.1 MATIC", network: "polygon-amoy" }
},

// 3. Public facilitator URL
{ url: "https://x402.polygon.technology" }
)
);

// --- Protected Route Handler ---
app.get("/api/documentation", async (req, res) => {
const documentation = getPremiumDocumentation();
const accessToken = `DOC-${Date.now()}-${Math.random()
.toString(36)
.substr(2, 8)
.toUpperCase()}`;

res.json({
message: "Premium documentation access granted!",
accessToken: accessToken,
documentation: documentation,
});
});

// A helper function to provide the premium content
const getPremiumDocumentation = () => {
return {
title: "Advanced Web3 API Integration Guide",
content: "This comprehensive guide covers advanced Web3 API integrations..."
// ... more fields
};
};

// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(`Protected endpoint: GET http://localhost:${PORT}/api/documentation`);
});

// For serverless environments like Vercel
export default app;

3. Running the Server

  • Run the server locally:
node server.js
  • Now, if you visit:
http://localhost:8080/api/documentation

You’ll receive a 402 Payment Required response instead of the JSON content. An x402-enabled client(like xTag) can then parse this challenge, complete the payment, and retry the request with the access token to retrieve the premium content.

6. User Guide

Logging In

  • NFC Login: Tap “Scan NFC Tag”.
  • Manual Login: Enter NFC ID manually.
  • First login auto-generates a secure wallet.
Login Window

Using the Chat

Example:

  1. You: “Get me trading signals”
  2. AI: “This costs 0.10 USDC. Proceed?” → [Yes, run "trading-signals"]
  3. You: Click confirm.
  4. AI: Handles payment + fetch → shows results with transaction link.
Press enter or click to view image in full size
Agent getting the 402 response and asking for confirmation before paying.
Successful fetch after paying along with the transaction details.

7. Sample API Interactions

Frontend Request:

{ "message": "Can you get me the latest trading signals?" }

Response:

{
"role": "assistant",
"content": "This costs 0.10 USDC. Proceed? [DYAD_ACTION:run \"trading-signals\"]"
}

8. Future Integrations

  • Currently the agent can only request resources defined in our own server, in further integrations, the Agent should be able to call any 402 protected server.
  • A complete SDK, to set up your servers for protecting your resources in minutes.

Built with love by 0xanoop, at ETHGlobal, for Polygon. ❤️

--

--

Written by Anoop Singh

web3 developer | finance nerd | computer science student