Package Exports
- hedera-x402
- hedera-x402/erc8004
- hedera-x402/server
- hedera-x402/types
Readme
The Enterprise-Grade Micropayment Standard: Powering the Agentic Economy with Sub-Second Settlement on Hedera.
Hedera x402
Preface: The "Micropayment Gap"
The original HTTP 402 "Payment Required" status code has remained largely theoretical due to three critical friction points in traditional and blockchain systems:
The Gas Paradox: On most blockchains, paying $0.01 for an API call costs $0.50+ in gas fees, making micro-transactions mathematically impossible.
Latency Friction: Traditional block times (12s - 15min) force API consumers to wait, destroying the real-time nature of software requests.
The Identity Void: Autonomous AI agents lack a standardized way to prove their reputation and identity before a transaction is even authorized.
Hedera x402 solves this by leveraging Hedera’s HTS (Token Service) and HCS (Consensus Service) to provide $0.0001 fixed fees, 3-second finality, and the ERC-8004 Agent Trust Layer.
Overview
Hedera x402 is a TypeScript SDK implementing the x402 payment protocol for the Hedera blockchain. It acts as a "Self-Sovereign Stripe," enabling APIs to demand HBAR or USDC micropayments before serving responses.
Key Features
For the Agentic Economy
- Machine-to-Machine (M2M) Payments: AI agents and headless clients can autonomously intercept 402 responses, request cryptographic signatures, and pay for the resources they consume.
- Universal API & dApp Gating: Drop-in, decentralized paywalls using standard HTTP headers.
For the Developer & User Experience
- Sponsored Transactions (Zero-Gas UX): Leverages Hedera’s fee delegation to allow facilitators to pay network fees. Users and agents pay only the API price in HBAR or USDC, delivering a seamless "one-click" experience without requiring extra gas funds.
- ERC-8004 Agent Trust Layer: A native implementation of the Agent Trust Layer using HTS for on-chain identity (NFTs) and HCS for immutable reputation audit logs, enabling verifiable machine-to-machine commerce.
For Security & Infrastructure
- aBFT-Backed Settlement: Utilizes Hedera’s asynchronous Byzantine Fault Tolerance (aBFT) to achieve 100% finality in 3–5 seconds. The facilitator settles signed transactions directly on-chain, ensuring high-throughput and enterprise-grade security.
- Native Self-Sovereignty: Ensures zero centralized custody. All payments are authorized via secure, local cryptographic signatures (ECDSA/ED25519) that are verified and settled using native Hedera services.
The "Offloading" Advantage
Hedera x402 removes the heavy lifting of blockchain integration by automating:
- Protocol Negotiation: Automatic interception of 402 "Payment Required" headers and transparent retry logic.
- On-Chain Orchestration: Handling the complexities of HTS token associations, HBAR transfers, and HCS message formatting behind a standard Axios interface.
- Identity Management: Managing the minting, metadata anchoring, and verification of Agent ID NFTs automatically through the ERC-8004 client.
Key Use Cases
- API Monetization (Machine-to-Machine): Charge per API call without requiring users to buy subscriptions. Perfect for AI models, oracle data feeds, or heavy compute tasks.
- Decentralized Paywalls: Monetize premium content, articles, or digital media natively via user wallets.
- Frictionless Token-Gating: Verify NFT or token holdings directly at the HTTP layer before serving content.
- Automated Micro-transactions: Enable streaming payments for continuous services (e.g., video streaming, cloud storage).
Architecture & Protocol Flow
The SDK abstracts the negotiation between the Client/Agent, the Protected API, and the Hedera Network via a Facilitator Service. Instead of manual transaction management, the SDK orchestrates the signing of native Hedera transfers and offloads the settlement to a dedicated facilitator that interacts with Hedera's nodes.
sequenceDiagram
autonumber
participant Agent as AI Agent (Client)
participant API as API Server (Middleware)
participant Facil as Facilitator Service
box rgba(139, 92, 246, 0.1) Hedera Network
participant HTS as Token Service (HTS)
participant SC as Smart Contracts
participant HCS as Consensus Service (HCS)
end
%% Phase 1: Identity
Note over Agent, HTS: Phase 1: Agent Identity (ERC-8004)
Agent->>HTS: Present Agent Identity NFT (AGID)
HTS-->>API: Confirm Agent Capabilities & Registration
%% Phase 2: Challenge
Note over Agent, API: Phase 2: The Protocol Handshake
Agent->>API: Request Premium API Resource
API-->>Agent: HTTP 402: Payment Required (Amount, Network, Recipient)
%% Phase 3: Payment
Note over Agent, HTS: Phase 3: Zero-Custody Settlement
Agent->>Agent: Locally sign HBAR/USDC transfer (Private keys stay local)
Agent->>API: Retry Request + Signed Transaction Header
API->>Facil: Forward transaction for verification & settlement
Facil->>HTS: Submit to Hedera nodes for aBFT Finality
HTS-->>Facil: Settlement Confirmed (Returns Tx Hash)
Facil-->>API: Payment Successful
%% Phase 4: Validation
Note over API, SC: Phase 4: Cryptographic Task Validation
API->>API: Execute Business Logic / Data Fetch
API->>SC: Record task result hash (ValidationRegistry)
SC-->>API: Proof of execution anchored on-chain
%% Phase 5: Delivery & Reputation
Note over Agent, HCS: Phase 5: Delivery & Reputation Logging
API-->>Agent: HTTP 200: Deliver Resource + Payment Receipt
Agent->>HCS: Submit Trust Score & Feedback (ReputationRegistry)
HCS-->>Agent: Immutable, timestamped audit log savedKey Architectural Components
- Client Layer (
x402axios): Intercepts standard 402 responses, requests local cryptographic signatures for HBAR or HTS USDC, and automatically retries requests with theX-PAYMENTheader. - Middleware Layer (
paymentMiddleware): Gates Next.js API routes, requiring no change to your business logic. It extracts payment headers and communicates with the facilitator for validation. - Facilitator Layer: Acts as the bridge to the Hedera network. It verifies transaction signatures, manages sponsored transaction fees if enabled, and submits transfers to Hedera nodes for consensus.
- Hedera Network: Provides the finality layer. HTS (Hedera Token Service) manages the actual movement of value, while HCS (Hedera Consensus Service) provides an immutable audit trail for the ERC-8004 Trust Layer.
SDK Usage
We built this SDK to be as intuitive as Web2 payment gateways. You don't need to be a blockchain expert to use it—you can refer to the SDK Documentation for more details.
1. The Agentic Use Case (Buyer)
Perfect for autonomous AI agents or scripts that need to pay for premium API resources. The x402axios client handles the entire 402 challenge-response loop automatically.
import { x402axios } from "hedera-x402";
async function fetchAgentData() {
// x402axios intercepts 402s, signs the Hedera transaction locally,
// and retries with the payment header automatically.
const response = await x402axios.get(
"https://api.example.com/api/protected/weather",
{
privateKey: process.env.HEDERA_PRIVATE_KEY, // Hex ECDSA or ED25519 key
accountId: process.env.HEDERA_ACCOUNT_ID, // e.g., "0.0.12345"
},
);
console.log("Data:", response.data);
console.log("Payment Hash:", response.paymentInfo?.transactionHash);
}- Local Signing: Private keys never leave your machine; the SDK signs the
TransferTransactionbefore sending the hex-encoded payload to the server. - Automatic Detection: The client extracts requirements (amount, recipient) directly from the
X-PAYMENT-REQUIREDheader.
2. The API Monetization Use Case (Seller)
Protect your Next.js API routes with zero changes to your actual business logic. The middleware handles verification and triggers settlement via the facilitator.
Step 1: Configure Middleware
// middleware.ts
import { paymentMiddleware } from "hedera-x402";
const routeMap = {
"/api/protected/weather": {
price: "1000", // Amount in tinybars
network: "hedera-testnet",
},
};
export const middleware = paymentMiddleware(
process.env.PAYMENT_RECIPIENT_ADDRESS!,
routeMap,
{ url: "https://your-domain.com/api/facilitator" },
);
export const config = { matcher: ["/api/protected/:path*"] };Step 2: Simple Route Handler
// app/api/protected/weather/route.ts
import { NextResponse } from "next/server";
export async function GET() {
// This code is only reached if a valid Hedera payment was settled
return NextResponse.json({ temp: 22, city: "London" });
}- Zero-Logic Gating: Your route handlers remain pure; the middleware ensures only paid requests reach your code.
- Sub-Second Settlement: Transactions reach finality on Hedera in approximately 3–5 seconds, allowing for real-time API responses.
3. HCS-8004 Trust Layer (Agent Identity)
Register an agent identity as an HTS NFT and manage reputation through HCS audit logs.
import { createERC8004Client } from "hedera-x402/arc8004";
const client = await createERC8004Client();
// Register on-chain identity
const { identity } = await client.identity.register({
agentId: "weather-bot-01",
agentCard: {
name: "WeatherBot",
capabilities: ["data-fetch", "x402-payments"],
owner: { address: "0.0.12345", publicKey: "0x..." },
// ...other agent metadata
},
});
// Submit reputation feedback after a transaction
await client.reputation.submitFeedback({
agentId: "weather-bot-01",
overallScore: 5,
paymentHash: "0.0.x@123456789",
});- On-Chain Reputation: Feedback is recorded as immutable messages on a Hedera Consensus Service (HCS) topic.
- NFT Identity: Every verified agent is represented by a unique NFT on the Hedera Token Service (HTS).
AI agent/Backend workflow example:
Workflow tx: https://hashscan.io/testnet/transaction/0.0.8325660@1774262944.983927091
Contributing & Next Steps
This project is open-source and actively seeking contributions to define the future of machine-to-machine commerce on Hedera. Future roadmap items include:
- Mainnet Deployment: Transitioning the SDK and Facilitator from testnet to Hedera Mainnet for production-grade API monetization.
- Advanced HCS Reputation: Implementing automated, weighted trust scoring algorithms based on historical HCS audit logs.
- Multi-Asset Expansion: Native support for additional HTS stablecoins and automated HBAR/USDC liquidity swaps during checkout.
- AI Framework Plugins: Deep integration with LangChain and Vercel AI SDK to allow agents to handle 402 challenges natively.
- Browser Wallet Injection: A dedicated extension to sign x402 headers directly from HashPack or Blade wallet.
Contact
Twitter - @Krieger
Mail - prsumit35@gmail.com
Acknowledgment
Special thanks to Hedera for providing the high-throughput, low-latency infrastructure specifically the Hedera Token Service (HTS) and Consensus Service (HCS) that makes micro-transactions economically viable. This project was inspired by the need for a truly scalable, enterprise-grade implementation of the x402 protocol.
References
- Hedera Developer Portal: docs.hedera.com
- x402 Protocol Specification: github.com/coinbase/x402
- ERC-8004 Standard: Hedera Agent Trust Layer