Integrating x402 Payments with Rootstock
The x402 protocol (deriving from HTTP Status 402 Payment Required) is emerging as the standard for Agentic Commerce. It allows AI agents, automated scripts, and browsers to autonomously negotiate and pay for resources, such as premium APIs, gated content, or computational tasks, without human intervention.
While some chains rely on centralized facilitators, Rootstock is uniquely positioned for Sovereign Mode integration. As the EVM-compatible Bitcoin sidechain, Rootstock allows you to verify payments with Bitcoin-level security directly on your server.
In this guide, we will build a Sovereign x402 Server that:
- Intercepts requests to premium endpoints.
- Challenges unpaid requests with a 402 status and payment metadata.
- Verifies on-chain tRBTC transaction proofs directly against the Rootstock ledger.
- Enforces idempotency via Redis to prevent replay attacks.
The Protocol Flow
Unlike hosted solutions, "Sovereign Mode" means your API acts as its own payment processor. This eliminates middleman fees and reliance on third-party gateways.
- Challenge (Handshake): The client requests a resource (e.g., /api/premium). The server detects a missing payment header and responds with 402 Payment Required. Crucially, it returns a WWW-Authenticate header containing the Price, Asset (tRBTC), and Target Address.
- Execution: The client (or AI Agent) parses these details, signs a transaction, and broadcasts it to the Rootstock network.
- Proof: The client retries the original request, this time including the Transaction Hash in the X-Payment (or Payment-Signature) header.
- Settlement: The server validates the transaction on-chain, ensures it hasn't been used before (via Redis), and serves the content.
Prerequisites
- Node.js (v18.x or higher)
- Redis (Required for replay protection/idempotency)
- Rootstock Testnet Wallet funded with tRBTC.
- RPC Endpoint: * Testnet:
https://public-node.testnet.rsk.co- Recommendation: For production, use a dedicated RPC key from Rootstock RPC API or providers, such as Alchemy or NOWNodes (see RPC Nodes tools) to avoid rate limits.
1. Project Setup
Initialize a strictly typed Node.js environment. We will use web3.js for blockchain interaction and Redis for state management.
mkdir rootstock-x402
cd rootstock-x402
npm init -y
# Core dependencies:
# express: Web server
# web3: Interface for the Rootstock Blockchain
# redis: In-memory store for idempotency (anti-replay)
# dotenv: Environment variable management
npm install express redis dotenv web3
Ensure your package.json supports ES6 modules:
"type": "module"