@vouchaai/sdk
v0.1.1
Published
Voucha AI client: call machine payable APIs on Solana. Handles the 402 pay per request flow and returns the verifiable receipt id.
Downloads
72
Maintainers
Readme
@vouchaai/sdk
The official client for Voucha AI, the payment and trust rail for the agent economy.
Voucha turns any API into a pay per request endpoint on Solana. There are no accounts and no API keys: a wallet signature is the authentication, and a tiny on chain payment is the access. This SDK is the caller side. It wraps a single function, vouchaFetch, that performs the entire payment handshake for you and returns the response plus a verifiable receipt id.
- Site: https://vouchaai.com
- Docs: https://vouchaai.com/docs
- Whitepaper: https://vouchaai.com/whitepaper.pdf
Why this exists
Every paid API today is gated by an API key: you sign up, generate a secret, store it, scope it, rotate it, and guard it forever. That is friction for a human and a liability for software. Autonomous agents make it worse, because handing a key to a system that improvises is unsafe.
Voucha replaces the standing secret with a one time act. Your code makes a request. If it is unpaid, the gateway answers with a price. Your code pays a few cents on Solana and retries, and the call goes through. You never create or store a key. For an AI agent you give it a wallet, fund it once, and it pays as it goes.
This package does that payment dance in one call.
Install
npm install @vouchaai/sdk @solana/web3.js@solana/web3.js is a peer dependency. The package ships both ESM and CommonJS builds with TypeScript types.
Quickstart
import { Connection, Keypair } from '@solana/web3.js';
import { vouchaFetch } from '@vouchaai/sdk';
const connection = new Connection('https://api.mainnet-beta.solana.com');
const signer = Keypair.fromSecretKey(/* your wallet secret key bytes */);
const { body, receiptId, paymentSig } = await vouchaFetch(
'https://api.vouchaai.com/gw/test/ping',
{ signer, connection }
);
console.log(body); // the API response
console.log(receiptId); // verifiable receipt id
console.log(paymentSig); // the Solana payment signatureThat call hits the live Voucha test API, pays 0.00001 SOL on mainnet, and returns the answer. The whole 402 handshake is handled for you.
How it works
When you call a Voucha gated URL, the gateway answers one of two ways.
- If the request is unpaid, it returns HTTP
402 Payment Requiredwith aWWW-Payheader that states the token, the price, the recipient, and a single use nonce. vouchaFetchreads that challenge, sends the payment on Solana with the nonce written into a memo (which binds the payment to this exact request), waits for confirmation, and retries the same request with anX-Payheader carrying the signature and nonce.- The gateway verifies the payment on chain, forwards the request to the real API, and returns the response with an
X-Pay-Receiptheader.
If the first response is not a 402, vouchaFetch returns it unchanged, so wrapping a free endpoint is harmless.
API reference
vouchaFetch(url, options?)
Performs a paid request and returns the result.
Parameters
url is the Voucha gated endpoint to call.
options is an object with these fields, all optional unless noted:
inita standardfetchRequestInit(method, headers, body). Use it for POST, custom headers, and so on.signera SolanaKeypairused to pay. Required for real payments.connectiona SolanaConnectionused to send and confirm the payment. Required for real payments.simulatewhentrue, sends a simulated proof instead of a real payment. Only works against a gateway running in open mode, for local testing. No funds move.
Returns a Promise of an object with:
responsethe finalfetchResponse.statusthe final HTTP status code.bodythe parsed JSON body, or the raw text if it is not JSON.paymentSigthe Solana signature of the payment, ornullif none was made.receiptIdthe receipt id from theX-Pay-Receiptheader, ornull.simulatedwhether a simulated proof was used.challengethe parsedWWW-Payfields, when a payment was required.
parseWWWPay(header)
Parses a WWW-Pay header string into a PayChallenge object. Useful if you want to implement the flow yourself or inspect the price before paying.
MEMO_PROGRAM_ID
The Solana SPL Memo program public key used to attach the nonce to the payment.
Examples
A simple GET
const { body } = await vouchaFetch(
'https://api.vouchaai.com/gw/test/quote',
{ signer, connection }
);
console.log(body.quote);A POST with a JSON body
const { body, receiptId } = await vouchaFetch(
'https://api.vouchaai.com/gw/acme/summarize',
{
signer,
connection,
init: {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'long input to summarize' }),
},
}
);Local testing without spending (simulate mode)
Run a gateway with open mode on, then:
const { body, status } = await vouchaFetch(
'http://localhost:8100/gw/test/ping',
{ simulate: true }
);No signer or connection is needed in simulate mode.
Inspecting the price before paying
import { parseWWWPay } from '@vouchaai/sdk';
const res = await fetch('https://api.vouchaai.com/gw/test/ping');
if (res.status === 402) {
const challenge = parseWWWPay(res.headers.get('WWW-Pay'));
console.log('price in lamports:', challenge.price);
console.log('recipient:', challenge.recipient);
}Handling errors
const { status, body } = await vouchaFetch(url, { signer, connection });
if (status !== 200) {
console.error('call failed', status, body);
}vouchaFetch throws if the wallet rejects the payment, if the network is unreachable, or if the challenge is malformed. Wrap it in a try / catch for production use.
Loading a wallet for an agent
For a server or an agent, load a Keypair from a secret key you control.
import { Keypair } from '@solana/web3.js';
// from a JSON array secret key (Solana CLI format)
const secret = JSON.parse(process.env.WALLET_SECRET!);
const signer = Keypair.fromSecretKey(Uint8Array.from(secret));Fund this wallet with a small amount of SOL and the agent pays for every call by itself. Treat the secret key like any sensitive credential.
Receipts
Every paid call returns a receiptId. A receipt is a tamper evident record of the call (route, payer, amount, request and response hashes, slot), chained to the previous one. You can verify it against the gateway:
const r = await fetch(`https://api.vouchaai.com/receipt/${receiptId}/verify`);
console.log(await r.json()); // { ok, valid, chain, receipt }This lets any party prove what was paid for, without trusting the gateway.
Mainnet and devnet
The SDK does not pick a network. You do, through the Connection you pass and the gateway you call. The gateway states its cluster in the WWW-Pay challenge. For real usage, point the Connection at a mainnet RPC and call a mainnet gateway such as https://api.vouchaai.com.
TypeScript
The package is written in TypeScript and ships full types. The main types are VouchaOptions, VouchaResult, and PayChallenge. vouchaFetch is generic over the body type:
interface PingBody { pong: boolean; ts: string }
const { body } = await vouchaFetch<PingBody>(url, { signer, connection });
body.pong; // typedLicense
MIT
