@ziongateway/sdk
v0.1.9
Published
TypeScript SDK for Zion x402 Facilitator
Readme
Zion SDK
The Zion SDK allows AI Agents and developers to easily monetize their APIs using the Zion X-402 Facilitator. It handles the HTTP 402 Payment Required protocol, standardizing payment requests, verification, and settlement on the Solana blockchain.
Features
- Middleware Protection: Automatically blocks unpaid requests with a
402status. - Subscription Model: Payments are direct transfers (0% protocol fee). Usage is tracked for overage billing.
- Instant Settlement: Verifies and settles payments via the Facilitator.
- Framework Agnostic: Works with Express, Next.js, NestJS, etc.
Installation
npm install @ziongateway/sdkUsage (Server-Side)
1. Express Middleware
Protect your API routes by adding ZionGate middleware.
import express from "express";
import { ZionGate } from "@ziongateway/sdk";
const app = express();
// Initialize Zion Gate
const zion = new ZionGate({
apiKey: "YOUR_DEVELOPER_API_KEY", // Get this from Zion Dashboard
price: 0.1, // Price per request in USDC
network: "solana-devnet", // or "solana-mainnet"
resource: "ai-agent-api" // Optional, default: "api-access"
});
// Protect a specific route
app.get("/ai-agent-api", zion.express(), (req, res) => {
res.json({
success: true,
message: "You have paid for this content! 🚀",
data: "SECRET_DATA"
});
});
app.listen(3000, () => console.log("Server running on port 3000"));2. Next.js (App Router)
Use the nextServer helper in your route handlers.
import { ZionGate } from "@ziongateway/sdk";
const zion = new ZionGate({ /* config */ });
export async function GET(req: Request) {
const authorized = await zion.nextServer(req);
// If not authorized, 'authorized' is a 402 Response object. Return it.
if (authorized !== true) return authorized;
return Response.json({ success: true, data: "Paid Content" });
}Usage (Client-Side / AI Agent)
The SDK provides a ZionAgent class that makes integrating paid APIs as simple as a standard fetch call. It automatically handles the entire 402 Payment Required flow, including:
- Detecting 402 responses
- Creating and signing the transaction
- Submitting to the Solana blockchain
- Retrying the request with payment proof
1. Initialize the Agent
Initialize the agent with your Solana private key.
import { ZionAgent } from "@ziongateway/sdk";
const agent = new ZionAgent({
privateKey: process.env.SOLANA_PRIVATE_KEY!, // Base58 encoded
rpcUrl: "https://api.mainnet-beta.solana.com" // Optional
});2. Make Requests
Use agent.fetch() exactly like the standard fetch API. If payment is required, it happens automatically in the background.
// 1. Just call fetch
const response = await agent.fetch("https://api.merchant.com/premium-data");
// 2. Handle the response
if (response.ok) {
const data = await response.json();
console.log("Received paid content:", data);
}
// Optional: Check if a payment was responsible for this success
if (response.paymentMade) {
console.log(`Paid via tx: ${response.txSignature}`);
}That's it! No transaction building, no buffer decoding, no manual retries.
Manual Integration (Advanced)
If you prefer to build the transaction manually (or are using a different language), follow these steps when you receive a 402 Payment Required response:
1. Handling the 402 Response
The server returns payment requirements (x402 v2):
{
"scheme": "exact",
"payTo": "FjK...", // Developer's Wallet
"amount": "100000", // Atomic units (0.1 USDC)
"asset": "EPj...", // USDC Mint
"network": "solana:5ey..." // CAIP-2 Network ID
}2. Creating the Transaction
Transfer the exact amount to the payTo address. No fee splitting is required.
import { PaymentBuilder } from "@ziongateway/sdk";
const instructions = await PaymentBuilder.createExactInstructions({
sender: wallet.publicKey.toBase58(),
recipient: requirements.payTo,
amount: requirements.amount,
asset: requirements.asset,
connection
});
const tx = new Transaction().add(...instructions);
const signature = await wallet.sendTransaction(tx, connection);
await connection.confirmTransaction(signature, "confirmed");3. Creating the Payment Header
After confirmation, create the payment header and retry the request. The header is a base64-encoded JSON object containing the transaction signature.
const paymentHeader = PaymentBuilder.createHeader({
transaction: signature,
resource: "api-access",
paymentRequirements: requirements
});
const response = await fetch("/api/protected", {
headers: { "Authorization": `Bearer ${paymentHeader}` }
});Webhooks
Webhooks allow your application to receive asynchronous notifications when payments are successfully settled.
Do I need Webhooks?
- No, if you only need to gate a synchronous API response (like the example above). The SDK handles verification immediately before serving the response.
- Yes, if you need to:
- Trigger a background job (e.g., generate a video, fine-tune a model).
- Update a user's credit balance in your database.
- Send a confirmation email.
Setting up Webhooks
- Register your Webhook URL in the Facilitator Database (table:
webhooks). - Listen for the
payment.successevent.
Example Payload:
{
"event": "payment.success",
"payload": {
"settlementId": "stl_12345",
"amount": "100000",
"payer": "UserAddress...",
"resource": "api-access"
}
}