acceso-x402-sdk
v1.0.0
Published
TypeScript SDK for Acceso x402 - Solana USDC Payment Protocol
Maintainers
Readme
Acceso x402 SDK
The official TypeScript SDK for x402 Payment Protocol on Solana
Documentation • API Reference • Examples • GitHub
🚀 Overview
The Acceso x402 SDK enables seamless HTTP 402 micropayments using USDC on Solana. Integrate pay-per-request APIs, premium content access, and microtransactions with just a few lines of code.
Key Features
- ⚡ Instant Payments - Sub-second USDC transactions on Solana
- 🔐 Secure - Facilitator-based transaction signing
- 🌐 Universal - Works in Node.js and browsers
- 📦 Zero Config - Sensible defaults, easy customization
- 💰 Low Fees - Only $0.01 per transaction
📦 Installation
# npm
npm install @acceso/x402-sdk
# yarn
yarn add @acceso/x402-sdk
# pnpm
pnpm add @acceso/x402-sdk⚡ Quick Start
Basic Usage
import { X402Client, createPhantomAdapter } from "@acceso/x402-sdk";
// Initialize the client
const client = new X402Client({
apiUrl: "https://api.acceso.dev",
debug: true,
});
// Connect wallet (browser)
const wallet = createPhantomAdapter();
// Access a protected resource
const result = await client.payAndAccess(
"https://api.example.com/premium-content",
wallet
);
if (result.success) {
console.log("Content:", result.data);
console.log("Transaction:", result.txHash);
}Server-Side Usage
import { X402Client, createKeypairAdapter } from "@acceso/x402-sdk";
import { Keypair } from "@solana/web3.js";
import nacl from "tweetnacl";
// Load your keypair
const keypair = Keypair.fromSecretKey(yourSecretKey);
// Create adapter for server-side signing
const wallet = createKeypairAdapter(
keypair.publicKey.toBase58(),
(message) => nacl.sign.detached(message, keypair.secretKey)
);
// Initialize client
const client = new X402Client({
apiUrl: "https://api.acceso.dev",
rpcUrl: "https://api.mainnet-beta.solana.com",
});
// Make payment
const result = await client.payAndAccess(
"https://api.example.com/ai-endpoint",
wallet
);📖 API Reference
X402Client
The main client for interacting with x402-enabled APIs.
const client = new X402Client(config: X402Config);Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiUrl | string | Required | Base URL of the x402 API |
| rpcUrl | string | Mainnet | Solana RPC endpoint |
| timeout | number | 30000 | Request timeout in ms |
| debug | boolean | false | Enable debug logging |
Methods
payAndAccess(url, wallet, options?)
Access a protected resource with automatic payment handling.
const result = await client.payAndAccess(
"https://api.example.com/resource",
wallet,
{
method: "POST",
body: { query: "example" },
}
);getRequirements(resource, amount, recipient)
Generate payment requirements for a resource.
const requirements = await client.getRequirements(
"https://api.example.com/resource",
"0.01", // Amount in USD
"RecipientPublicKey..."
);verify(transaction, requirements)
Verify a signed transaction before settlement.
const verification = await client.verify(signedTx, requirements);
if (verification.isValid) {
// Proceed with settlement
}settle(transaction, requirements)
Settle a verified transaction on-chain.
const settlement = await client.settle(signedTx, requirements);
console.log("TX Hash:", settlement.txHash);🔌 Wallet Adapters
Browser Wallets
import {
createPhantomAdapter,
createSolflareAdapter,
detectWallet
} from "@acceso/x402-sdk";
// Auto-detect available wallet
const wallet = detectWallet();
// Or specify a wallet
const phantom = createPhantomAdapter();
const solflare = createSolflareAdapter();Server-Side (Keypair)
import { createKeypairAdapter } from "@acceso/x402-sdk";
const wallet = createKeypairAdapter(
publicKey,
signFunction
);🛠️ Low-Level API
For more control, use the low-level API client directly:
import { X402ApiClient, TransactionBuilder } from "@acceso/x402-sdk";
// API client
const api = new X402ApiClient({ apiUrl: "https://api.acceso.dev" });
// Get fee payer
const { feePayer } = await api.getFeePayer();
// Build transaction manually
const builder = new TransactionBuilder({
rpcUrl: "https://api.mainnet-beta.solana.com",
});
const transaction = await builder.buildPaymentTransaction({
requirements,
payerPublicKey: wallet.publicKey,
});💡 Examples
Pay for AI API Call
const result = await client.payAndAccess(
"https://ai.acceso.dev/v1/chat/completions",
wallet,
{
method: "POST",
body: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello!" }],
},
}
);Access Premium Content
const article = await client.payAndAccess(
"https://news.example.com/premium/article-123",
wallet
);Streaming with Payments
// Check requirements first
const requirements = await client.api.getRequirements({
price: "0.05",
payTo: creatorWallet,
resource: streamUrl,
});
// Pay and get access token
const payment = await client.payAndAccess(streamUrl, wallet);
// Use token for streaming
const stream = await fetch(streamUrl, {
headers: { Authorization: `Bearer ${payment.data.token}` },
});🔧 Utilities
The SDK includes helpful utility functions:
import {
encodeBase64,
decodeBase64,
usdcToAtomic,
atomicToUsdc,
formatUsdc,
isValidPublicKey,
isValidSignature,
retry,
} from "@acceso/x402-sdk";
// Convert USDC amounts
const atomic = usdcToAtomic(0.01); // 10000n
const usdc = atomicToUsdc(10000n); // 0.01
// Format for display
formatUsdc(0.01); // "$0.01 USDC"
// Validate addresses
isValidPublicKey("4zMMC9..."); // true/false
// Retry with backoff
const result = await retry(() => api.settle(tx), 3, 1000);📊 Constants
import { USDC_CONSTANTS, NETWORKS, VERSION } from "@acceso/x402-sdk";
// USDC configuration
USDC_CONSTANTS.MAINNET_MINT; // USDC mint address
USDC_CONSTANTS.DECIMALS; // 6
// Network endpoints
NETWORKS.mainnet.rpc; // Mainnet RPC
NETWORKS.devnet.rpc; // Devnet RPC
// SDK version
VERSION; // "1.0.0"🧪 Testing
# Run tests
npm test
# Run with coverage
npm run test:coverage
# Lint
npm run lint📋 TypeScript Support
This SDK is written in TypeScript and includes full type definitions:
import type {
X402Config,
PaymentRequirements,
VerifyResponse,
SettleResponse,
WalletAdapter,
} from "@acceso/x402-sdk";🔒 Security
- All transactions are verified before settlement
- Facilitator co-signing prevents unauthorized payments
- No private keys are transmitted or stored
- Open-source and auditable
🤝 Contributing
Contributions are welcome! Please read our Contributing Guide first.
# Clone the repo
git clone https://github.com/Acceso-dev/acceso-x402-sdk.git
# Install dependencies
npm install
# Build
npm run build
# Test
npm test📄 License
MIT © Acceso
Built with ❤️ by the Acceso Team
