@kova402/sdk
v1.0.2
Published
Official TypeScript SDK for KOVA - Multi-chain x402 payment facilitator supporting Solana, BASE, BSC, and Bitcoin
Maintainers
Readme
@kova402/sdk
TypeScript SDK for integrating x402 payments with KOVA - Multi-chain payment facilitator
What is x402?
x402 is a protocol for HTTP-based payments that enables developers to accept payments via cryptographically signed payloads. Instead of traditional payment processing, users sign transactions with their crypto wallet and include them in HTTP headers.
KOVA is a complete x402 payment facilitator supporting Solana, BASE, BSC, and Bitcoin that verifies and settles payments on-chain.
Features
✅ Client-Side Integration - Automatic 402 payment handling in browser/Node.js
✅ Server-Side Middleware - Express/Connect middleware for payment-gated APIs
✅ Solana Wallet Support - Works with any Solana wallet adapter
✅ Type-Safe - Full TypeScript support with detailed types
✅ Zero Configuration - Sensible defaults, minimal setup required
Installation
npm install @kova402/sdkPeer Dependencies
npm install @solana/web3.js @solana/spl-token zodQuick Start
Client-Side (Browser/Frontend)
Use the KOVA client to automatically handle 402 payment responses:
import { createKovaClient } from '@kova402/sdk/client';
// Initialize client with wallet adapter
const kova = createKovaClient({
facilitatorUrl: 'https://kova402.com/api/v1',
network: 'solana-devnet',
wallet: myWalletAdapter, // Any Solana wallet adapter
maxPaymentAmount: BigInt('1000000000'), // Optional: max 1 SOL
});
// Automatically handles 402 payments
const response = await kova.fetch('https://api.example.com/premium-data', {
method: 'POST',
body: JSON.stringify({ query: 'something' }),
});
const data = await response.json();
console.log('Got data:', data);What happens:
- First request gets 402 Payment Required
- SDK automatically creates and signs payment
- SDK retries request with payment header
- Payment is verified and settled by KOVA
- Your app gets the response seamlessly
Server-Side (Node.js/Express)
Protect your API endpoints with payment requirements:
import express from 'express';
import { KovaPaymentHandler } from '@kova402/sdk/server';
const app = express();
const kova = new KovaPaymentHandler({
facilitatorUrl: 'https://kova402.com/api/v1',
network: 'solana-devnet',
treasuryAddress: process.env.TREASURY_WALLET!,
});
// Payment-gated endpoint using middleware
app.get('/api/premium-data',
kova.middleware({
amount: '1000000000', // 1 SOL in lamports
onPaymentVerified: (payment) => {
console.log('Payment received:', payment);
},
}),
(req, res) => {
res.json({ data: 'Premium content!' });
}
);
// Manual payment handling
app.post('/api/custom', async (req, res) => {
const payment = kova.extractPayment(req.headers);
if (!payment) {
const requirements = await kova.createPaymentRequirements({
amount: '500000000', // 0.5 SOL
resource: '/api/custom',
description: 'Custom API access',
});
const response = kova.create402Response(requirements);
return res.status(response.status).json(response.body);
}
// Verify payment
const requirements = await kova.createPaymentRequirements({
amount: '500000000',
resource: '/api/custom',
});
const isValid = await kova.verifyPayment(payment, requirements);
if (!isValid) {
return res.status(402).json({ error: 'Invalid payment' });
}
// Settle payment (async, don't wait)
kova.settlePayment(payment, requirements).catch(console.error);
res.json({ success: true, data: 'Your data' });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});API Reference
Client API
createXchangeX402Client(config)
Creates a XchangeX402 client for handling payments.
Parameters:
facilitatorUrl(string) - XchangeX402 facilitator URLnetwork('solana-mainnet' | 'solana-devnet') - Solana networkwallet(WalletAdapter) - Solana wallet adapter for signingmaxPaymentAmount(bigint, optional) - Maximum payment amount in lamports
Returns: XchangeX402Client with methods:
fetch(url, options)- Enhanced fetch with automatic 402 handlinggetHealth()- Get facilitator health statusgetSupported()- Get supported networks and assets
Server API
new XchangeX402PaymentHandler(config)
Creates a payment handler for server-side verification.
Parameters:
facilitatorUrl(string) - XchangeX402 facilitator URLnetwork('solana-mainnet' | 'solana-devnet') - Solana networktreasuryAddress(string) - Your Solana wallet address for receiving payments
Methods:
extractPayment(headers)- Extract payment from request headerscreatePaymentRequirements(config)- Create payment requirements objectverifyPayment(payment, requirements)- Verify payment with facilitatorsettlePayment(payment, requirements)- Settle payment on-chaincreate402Response(requirements)- Create 402 response objectmiddleware(config)- Express/Connect middleware
Examples
React + Phantom Wallet
import { useWallet } from '@solana/wallet-adapter-react';
import { createXchangeX402Client } from '@xchangex402/sdk/client';
function MyComponent() {
const wallet = useWallet();
const fetchPremiumData = async () => {
const xchangex402 = createXchangeX402Client({
facilitatorUrl: 'https://xchangeswap.com/api/v1',
network: 'solana-devnet',
wallet: wallet,
});
const response = await xchangex402.fetch('/api/premium-data');
const data = await response.json();
console.log(data);
};
return (
<button onClick={fetchPremiumData}>
Get Premium Data
</button>
);
}Next.js API Route
import { XchangeX402PaymentHandler } from '@xchangex402/sdk/server';
import type { NextApiRequest, NextApiResponse } from 'next';
const xchangex402 = new XchangeX402PaymentHandler({
facilitatorUrl: process.env.XCHANGEX402_URL!,
network: 'solana-mainnet',
treasuryAddress: process.env.TREASURY_WALLET!,
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const payment = xchangex402.extractPayment(req.headers);
if (!payment) {
const requirements = await xchangex402.createPaymentRequirements({
amount: '1000000000', // 1 SOL
resource: '/api/premium',
});
const response = xchangex402.create402Response(requirements);
return res.status(response.status).json(response.body);
}
const requirements = await xchangex402.createPaymentRequirements({
amount: '1000000000',
resource: '/api/premium',
});
const isValid = await xchangex402.verifyPayment(payment, requirements);
if (!isValid) {
return res.status(402).json({ error: 'Invalid payment' });
}
// Settlement happens async
xchangex402.settlePayment(payment, requirements).catch(console.error);
res.json({ data: 'Premium content' });
}Networks & Assets
Supported Networks
- Solana Mainnet (chainId: 101)
- Solana Devnet (chainId: 102)
Supported Assets
- SOL (9 decimals)
- USDC (SPL Token, 6 decimals)
- USDT (SPL Token, 6 decimals)
Payment Amounts
All amounts are in the smallest unit (lamports for SOL):
- 1 SOL = 1,000,000,000 lamports
- 1 USDC = 1,000,000 (6 decimals)
// 1 SOL payment
amount: '1000000000'
// 0.1 SOL payment
amount: '100000000'
// 10 USDC payment
amount: '10000000'Environment Variables
Client-Side
No environment variables needed - configuration is passed to the client.
Server-Side
XCHANGEX402_URL=https://xchangeswap.com/api/v1
TREASURY_WALLET=YourSolanaWalletAddress...Testing
Use Solana devnet for testing:
// Client
const xchangex402 = createXchangeX402Client({
facilitatorUrl: 'https://xchangeswap.com/api/v1',
network: 'solana-devnet',
wallet: testWallet,
});
// Server
const xchangex402 = new XchangeX402PaymentHandler({
facilitatorUrl: 'https://xchangeswap.com/api/v1',
network: 'solana-devnet',
treasuryAddress: testWalletAddress,
});Get devnet SOL from the Solana Faucet.
Error Handling
try {
const response = await xchangex402.fetch('/api/endpoint');
const data = await response.json();
} catch (error) {
if (error.message.includes('Payment amount')) {
console.error('Payment exceeds maximum allowed');
} else {
console.error('Request failed:', error);
}
}TypeScript Support
Full TypeScript support with exported types:
import type {
PaymentPayload,
PaymentRequirements,
VerifyResponse,
SettleResponse,
XchangeX402Config,
} from '@kova402/sdk';Resources
- Documentation: https://kova402.com
- GitHub: https://github.com/Iamthetachi/Kova402
- NPM: https://www.npmjs.com/package/@kova402/sdk
- x402 Protocol: https://x402.org
- Support: [email protected]
License
MIT © XchangeX402
Built with ❤️ for the Solana ecosystem
