x402pp-client

Client SDK for AI agents and applications

Installation

npm install x402pp-client @solana/web3.js

X402Client

Main client class for interacting with x402++ providers.

Constructor

import { Connection, Keypair } from '@solana/web3.js';
import { X402Client } from 'x402pp-client';

const client = new X402Client({
  connection: Connection,    // Solana connection
  wallet: Keypair,          // Agent's keypair
  httpConfig?: {            // Optional
    timeout?: number,
    headers?: Record<string, string>
  }
});

createIntent()

Creates a new Intent expressing agent's needs

const intent = client.createIntent({
  capability: string,           // e.g., 'gpt-4-inference'
  maxPricePerRequest: number,   // Max price willing to pay
  token: 'SOL' | 'USDC' | 'USDT' | 'BONK',
  maxSessionBudget?: number,    // Optional: total budget
  sessionDurationMs?: number,   // Optional: session length
  sla?: {
    maxLatencyMs?: number,
    minUptimePercent?: number
  },
  metadata?: Record<string, any>
});

// Returns: Intent object

negotiate()

Negotiates with provider and receives signed Offer

const offer = await client.negotiate(
  providerEndpoint: string,    // Provider's URL
  intent: Intent,              // Your Intent
  options?: {
    headers?: Record<string, string>,
    timeout?: number
  }
);

// Returns: Signed Offer from provider
// Throws: Error if negotiation fails

createSession()

Creates prepaid session from accepted Offer

const session = await client.createSession(
  offer: Offer,
  options?: {
    depositAmount?: number,      // Custom deposit
    anchorOnChain?: boolean     // Store on Solana (optional)
  }
);

// Behind the scenes:
// 1. Transfers funds to provider on Solana
// 2. Provider verifies transaction
// 3. Session created with balance tracking
// 4. Returns active Session object

// Returns: Active Session
// Throws: Error if session creation fails

executeRequest()

Executes request within a Session

const result = await client.executeRequest(
  sessionId: string,
  requestData: any
);

// Returns:
// {
//   data: any,           // API response
//   receipt: Receipt     // Cryptographic proof
// }

// Receipt includes:
// - inputHash (SHA-256)
// - outputHash (SHA-256)
// - latencyMs
// - slaVerification { met: boolean }
// - signature (Ed25519)

// Throws:
// - SessionExpiredError
// - InsufficientFundsError

closeSession()

Closes session and receives refund for remaining balance

const refund = await client.closeSession(sessionId: string);

// Returns:
// {
//   refundAmount: number,
//   txSignature: string    // Solana transaction
// }

Complete Example

Complete AI Agent
1import { Connection, Keypair } from '@solana/web3.js';
2import { X402Client } from 'x402pp-client';
3
4async function main() {
5  // Setup
6  const connection = new Connection('https://api.devnet.solana.com');
7  const wallet = Keypair.generate();
8  
9  // Get free devnet SOL
10  await connection.requestAirdrop(wallet.publicKey, 1e9);
11  
12  const client = new X402Client({ connection, wallet });
13  
14  // Create Intent
15  const intent = client.createIntent({
16    capability: 'gpt-4-inference',
17    maxPricePerRequest: 0.01,
18    token: 'USDC',
19    sla: { maxLatencyMs: 2000 }
20  });
21  
22  // Negotiate
23  const offer = await client.negotiate(
24    'https://ai-api.example.com',
25    intent
26  );
27  
28  if (offer.pricePerRequest > intent.maxPricePerRequest) {
29    throw new Error('Price too high!');
30  }
31  
32  // Create Session
33  const session = await client.createSession(offer, {
34    depositAmount: 1.0  // 1 USDC
35  });
36  
37  console.log(`Session created! Can make ${
38    Math.floor(session.remainingBalance / session.pricePerRequest)
39  } requests`);
40  
41  // Execute multiple requests
42  for (let i = 0; i < 5; i++) {
43    const result = await client.executeRequest(
44      session.sessionId,
45      { prompt: `Request #${i + 1}` }
46    );
47    
48    console.log(`Request ${i + 1}:`, result.data);
49    console.log('SLA met:', result.receipt.slaVerification.met);
50  }
51  
52  // Close session
53  const refund = await client.closeSession(session.sessionId);
54  console.log('Refunded:', refund.refundAmount, 'USDC');
55}
56
57main();

Error Handling

import { 
  SessionExpiredError, 
  InsufficientFundsError,
  InvalidOfferError 
} from 'x402pp-core';

try {
  const result = await client.executeRequest(sessionId, data);
} catch (error) {
  if (error instanceof SessionExpiredError) {
    console.log('Session expired, creating new one...');
    await createNewSession();
  } else if (error instanceof InsufficientFundsError) {
    console.log('Balance too low, closing and refunding...');
    await client.closeSession(sessionId);
  } else {
    console.error('Unexpected error:', error);
  }
}
X (Twitter)