Automatic Client
The automatic client (X402AutoClient) automatically handles the X402 payment flow. When it receives a 402 response, it automatically creates a payment and retries the request.
When to Use
Use the automatic client when you want:
Simple payment handling
Automatic payment flow
Less boilerplate code
Standard payment behavior
Basic Usage
import { X402AutoClient } from '@shade402/client';
import { Keypair } from '@solana/web3.js';
const wallet = Keypair.generate();
const client = new X402AutoClient(wallet, process.env.SOLANA_RPC_URL, {
maxPaymentAmount: '1.0',
autoRetry: true,
});
try {
// Payment is handled automatically
const response = await client.get('https://api.example.com/data');
console.log(response.data);
} finally {
await client.close();
}Configuration Options
Maximum Payment Amount
Set a safety limit to prevent overpayment:
Auto Retry
Control automatic retry behavior:
HTTP Methods
All standard HTTP methods are supported:
Payment Flow
The automatic client handles the payment flow internally:
Makes initial HTTP request
If 402 received:
Parses payment request
Validates payment amount (checks
maxPaymentAmount)Creates Solana payment transaction
Broadcasts transaction
Encrypts resource if server public key available
Retries request with payment authorization
Returns response
All of this happens automatically without manual intervention.
Error Handling
The automatic client throws errors for payment issues:
Resource Encryption
Resource encryption is handled automatically:
Override Auto Retry
You can override auto-retry for specific requests:
Complete Example
Multiple Requests
Reuse the client for multiple requests:
Best Practices
Always set
maxPaymentAmountas a safety limitAlways close the client when done
Handle errors appropriately
Use
autoRetry: falsewhen you need manual controlStore wallet keys securely
Monitor payment amounts and transactions
Reuse client for multiple requests when possible
Comparison with Explicit Client
Automatic Client
Simpler API
Less boilerplate
Automatic payment handling
Good for standard use cases
Explicit Client
More control
Custom payment logic
Better for complex scenarios
More code required
Choose based on your needs. Use automatic client for simple cases, explicit client for complex scenarios.
Next Steps
Learn about Explicit Client for manual control
Check out Client Usage for overview
See Examples for more use cases
Last updated
