pipegate-sdk
v0.6.0
Published
A TypeScript client-side payment authentication SDK for stablecoins used with axios
Downloads
49
Maintainers
Readme
PipeGate TS SDK Documentation
Overview
PipeGate SDK enables developers to interact with the PipeGate protocol for API monetization using multiple payment schemes. This guide covers SDK installation, configuration, and usage for both API consumers and providers.
Installation
npm install pipegate-sdk
# or
yarn add pipegate-sdk
# or
bun add pipegate-sdk🆕 Unified x402 Payment Interceptor (Recommended)
NEW: As of version 0.6.0, we've upgraded to a unified payment interceptor that supports the x402 standard. This single function replaces the need for separate per-scheme interceptors and provides a standardized payment header format.
Why it’s simpler
- One interceptor factory instead of separate helpers per scheme
- Normalized
X-PaymentJSON:{ x402Version, network, scheme, payload } - Automatically signs / attaches scheme specific data
- Re-uses updated channel state from responses (when scheme =
channel)
Quick Start
import axios from "axios";
import { withPaymentInterceptor } from "pipegate-sdk";
const PRIVATE_KEY = "0x..."; // Your wallet private key
// One-time payment
const client = withPaymentInterceptor(
axios.create({ baseURL: "http://localhost:8000" }),
PRIVATE_KEY,
{ oneTimePaymentTxHash: "0x..." }
);
// Stream payment
const streamClient = withPaymentInterceptor(
axios.create({ baseURL: "http://localhost:8000" }),
PRIVATE_KEY,
{ streamSender: "0xSenderAddress" }
);
// Payment channel
const channelClient = withPaymentInterceptor(
axios.create({ baseURL: "http://localhost:8000" }),
PRIVATE_KEY,
{ channel: channelResponse }
);
// Make requests - payment headers added automatically
const response = await client.get("/api/endpoint");How it works
First request: If server returns
402 Payment Required, interceptor automatically:- Parses payment requirements from server response
- Selects matching payment scheme from your config
- Signs and constructs x402-compliant payment header
- Retries the request with payment
Subsequent requests: Payment headers included automatically
Channel updates: For payment channels, response headers update local state
x402 Header Format
The interceptor generates standardized payment headers:
{
"x402Version": 1,
"network": "base-sepolia",
"scheme": "one-time",
"payload": {
"signature": "0x...",
"tx_hash": "0x..."
}
}Configuration Options
Choose exactly one payment method:
// One-time payment (transaction hash)
{
oneTimePaymentTxHash: "0x...";
}
// Stream payment (sender address)
{
streamSender: "0x...";
}
// Payment channel (channel response object)
{
channel: CreateChannelResponse;
}Migrating from Legacy Interceptors
If you're using the old per-scheme interceptors, upgrade to withPaymentInterceptor:
| Old Method | New Unified Method |
| --------------------------------------------------- | ---------------------------------------------------------------------- |
| createOneTimePaymentRequestInterceptor(txHash) | withPaymentInterceptor(axios, key, { oneTimePaymentTxHash: txHash }) |
| createStreamRequestInterceptor(sender) | withPaymentInterceptor(axios, key, { streamSender: sender }) |
| createPaymentChannelRequestInterceptor(channelId) | withPaymentInterceptor(axios, key, { channel: channelResponse }) |
Legacy Methods (Deprecated)
The following methods are deprecated in favor of the unified withPaymentInterceptor. They will be removed in a future major release.
- Create a
.envfile in your project root:
WALLET_PRIVATE_KEY=your_private_key_here- Initialize the SDK:
import { ClientInterceptor } from "pipegate-sdk";
// Create SDK instance
const pipeGate = new ClientInterceptor();
await pipeGate.initialize();Core Features
Creating a Payment Channel
To start using an API, first create a payment channel & add it:
const channelParams = {
recipient: "0x...", // API provider's address
duration: 2592000, // Channel duration in seconds (30 days)
tokenAddress: "0x...", // Payment token address (e.g., USDC)
amount: "100", // Amount in tokens to deposit (in decimals ) 100 USDC
};
const channel = await pipeGate.createPaymentChannel(channelParams);
await pipeGate.addNewChannel(channel.channelId, channel);Making API Calls with Payment Channel method
Using with Axios
- Create an Axios instance with PipeGate interceptors:
import axios from "axios";
const api = axios.create({
baseURL: "https://api.example.com",
});
// Add request interceptor for automatic signing
api.interceptors.request.use(
pipeGate.createPaymentChannelRequestInterceptor(channelId).request
);
// Add response interceptor for state management
api.interceptors.response.use(
pipeGate.createPaymentChannelResponseInterceptor().response
);
// Make API calls as normal
const response = await api.get("/endpoint");Monitoring Channel State
// Get current channel state
const channelState = pipeGate.getChannelState(channelId);
console.log("Current Balance:", channelState?.balance);
console.log("Channel Status:", channelState?.status);Adding a new Channel
// Get current channel state
await pipeGate.addNewChannel(channel.channelId, channel);Making API Calls with One time Payment method
Using with Axios
Create an Axios instance with PipeGate interceptors and the txHash of the transaction that was used to pay for the request:
import axios from "axios";
const api = axios.create({
baseURL: "https://api.example.com",
});
// Add request interceptor for automatic signing
api.interceptors.request.use(
pipeGate.createOneTimePaymentRequestInterceptor(txHash).request
);
// Make API calls as normal
const response = await api.get("/endpoint");Making API Calls with Superfluid streams method
Using with Axios
Create an Axios instance with PipeGate interceptors and the txHash of the transaction that was used to pay for the request:
import axios from "axios";
const api = axios.create({
baseURL: "https://api.example.com",
});
const streamSender = "0x898d0DBd5850e086E6C09D2c83A26Bb5F1ff8C33";
// Add request interceptor for automatic signing
api.interceptors.request.use(
pipeGate.createStreamRequestInterceptor(streamSender).request
);
// Make API calls as normal
const response = await api.get("/endpoint");Advanced Usage
Manual Request Signing
If you need to sign requests manually:
const channelState = pipeGate.getChannelState(channelId);
if (!channelState) throw new Error("Channel not found");
const requestBody = { foo: "bar" };
const signedRequest = await pipeGate.signRequest(channelState, requestBody);
// Use the signed request in your API call
const response = await fetch("https://api.example.com/endpoint", {
method: "POST",
headers: {
"x-Message": signedRequest.message,
"x-Signature": signedRequest.signature,
"x-Timestamp": signedRequest.timestamp,
"x-Payment": JSON.stringify(channelState),
},
body: JSON.stringify(requestBody),
});WASM exported functions - Verifiers & Extra
PaymentChannelVerifier can be used as such:
await init();
const rpc_url = "https://base-sepolia-rpc.publicnode.com";
const verifier = new PaymentChannelVerifier(rpc_url);
const updatedChannel = await verifier.verify_request(
data.message,
data.signature,
data.paymentChannelJSON,
data.paymentAmount,
data.bodyBytes
);
console.log(updatedChannel);Test script can be found in tests/wasm.ts
Best Practices
Channel Management
- Create channels with appropriate duration and funding
- Monitor channel balance and top up when needed
- Close channels when they're no longer needed
Error Handling
- Always handle potential errors in channel creation
- Monitor for signature verification failures
- Handle channel state updates appropriately
Security
- Never commit private keys or
.envfiles - Validate channel states before making requests
- Keep track of nonces to prevent replay attacks
- Never commit private keys or
Types Reference
interface CreateChannelParams {
recipient: `0x${string}`;
duration: number;
tokenAddress: `0x${string}`;
amount: number;
}
interface CreateChannelResponse {
channelId: bigint;
channelAddress: `0x${string}`;
sender: `0x${string}`;
recipient: `0x${string}`;
duration: bigint;
tokenAddress: `0x${string}`;
amount: bigint;
price: bigint;
timestamp: bigint;
}
interface PaymentChannelResponse {
address: string;
sender: string;
recipient: string;
balance: string;
nonce: string;
expiration: string;
channel_id: string;
}
interface SignedRequest {
message: string;
signature: string;
timestamp: string;
}Error Handling
The SDK throws specific errors that should be handled in your application:
try {
await pipeGate.createPaymentChannel(params);
} catch (error) {
if (error.message.includes("insufficient funds")) {
// Handle insufficient funds error
} else if (error.message.includes("invalid recipient")) {
// Handle invalid recipient error
} else {
// Handle other errors
}
}Examples
Complete API Integration Example with recurring Payment Channel method
import { ClientInterceptor } from "pipegate-sdk";
import axios from "axios";
async function setupApiClient() {
// Initialize SDK
const pipeGate = new ClientInterceptor();
await pipeGate.initialize();
// Create payment channel
const channel = await pipeGate.createPaymentChannel({
recipient: "0x123...",
duration: (365 / 12) * 24 * 60 * 60, // 30 days
tokenAddress: "0x456...",
amount: "100",
});
await pipeGate.addNewChannel(channel.channelId, channel);
// Setup API client
const api = axios.create({
baseURL: "https://api.example.com",
});
// Add interceptors
api.interceptors.request.use(
pipeGate.createRequestInterceptor(channel.channelId).request
);
api.interceptors.response.use(pipeGate.createResponseInterceptor().response);
return api;
}
// Usage
const api = await setupApiClient();
const data = await api.get("/endpoint");Complete API Integration Example with One time Payment method
import { ClientInterceptor } from "pipegate-sdk";
import axios from "axios";
async function setupApiClient() {
// Initialize SDK
const pipeGate = new ClientInterceptor();
await pipeGate.initialize();
// Define the txHash
const txHash = "0x123...";
// Setup API client
const api = axios.create({
baseURL: "https://api.example.com",
});
// Add interceptors
api.interceptors.request.use(
pipeGate.createOneTimePaymentRequestInterceptor(txHash).request
);
return api;
}
// Usage
const api = await setupApiClient();
const data = await api.get("/endpoint");Note: This SDK supports the x402 payment standard and is designed to work with the PipeGate protocol. For optimal compatibility, use the unified withPaymentInterceptor function with the latest version of the SDK and smart contracts.
