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:

  1. Makes initial HTTP request

  2. 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

  3. 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

  1. Always set maxPaymentAmount as a safety limit

  2. Always close the client when done

  3. Handle errors appropriately

  4. Use autoRetry: false when you need manual control

  5. Store wallet keys securely

  6. Monitor payment amounts and transactions

  7. 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

Last updated