npm package: @logiccrafterdz/xpay-sdk
Description: A TypeScript SDK for automatic x402 payments on Base and other L2s
Latest version: 0.1.0

# XPay SDK

[![npm version](https://img.shields.io/npm/v/@logiccrafterdz/xpay-sdk)](https://www.npmjs.com/package/@logiccrafterdz/xpay-sdk)
[![CI](https://github.com/logiccrafterdz/xpay-sdk/workflows/CI/badge.svg)](https://github.com/your-username/xpay-sdk/actions)
[![License: MIT](https://img.shields.io/npm/l/@logiccrafterdz/xpay-sdk)](https://opensource.org/licenses/MIT)

A TypeScript SDK for handling X402 payment protocol on Base and other Layer 2 networks. Automatically handles payment flows when accessing paid APIs that return 402 Payment Required responses.

## Installation

```bash
npm install @logiccrafterdz/xpay-sdk
```

## Quick Start

```typescript
import { createWalletClient, http } from 'viem';
import { baseSepolia } from 'viem/chains';
import { privateKeyToAccount } from 'viem/accounts';
import { createX402Client, createXPayWalletClient } from '@logiccrafterdz/xpay-sdk';

// Initialize wallet
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const viemWallet = createWalletClient({
  account,
  chain: baseSepolia,
  transport: http()
});

// Create XPay wallet wrapper
const xpayWallet = createXPayWalletClient({ 
  walletClient: viemWallet,
  chain: 'base-sepolia'
});

// Create X402 client
const client = createX402Client({
  walletClient: xpayWallet,
  chain: 'base-sepolia',
  maxRetries: 3,
  confirmationTimeout: 30000
});

// Make request to paid API - payment handled automatically
const response = await client.request({
  method: 'GET',
  url: 'https://api.example.com/premium-endpoint'
});
```

## Supported Chains and Tokens

| Chain | Chain ID | Supported Tokens |
|-------|----------|------------------|
| Base Mainnet | 8453 | USDC |
| Base Sepolia | 84532 | USDC |

## Core Features

- 🚀 **TypeScript Support**: Full type definitions and IntelliSense
- 🔗 **Multi-Chain**: Support for Base mainnet and testnet
- 💰 **Automatic Payments**: Handles X402 payment flow seamlessly  
- 🛡️ **Error Handling**: Comprehensive error types and retry logic
- ⚡ **Viem Integration**: Built on top of the modern viem library
- 🧪 **Well Tested**: Comprehensive unit and integration test coverage

## API Reference

### `createX402Client(config)`

Creates an HTTP client that automatically handles X402 payment flows.

**Parameters:**
- `walletClient`: XPayWalletClient instance
- `chain`: Supported chain ('base' | 'base-sepolia')
- `maxRetries?`: Maximum payment retry attempts (default: 1)
- `confirmationTimeout?`: Transaction confirmation timeout in ms (default: 60000)

### `createXPayWalletClient(viemWallet)`

Wraps a viem WalletClient with XPay-specific functionality.

**Parameters:**
- `viemWallet`: A configured viem WalletClient instance

### Payment Parser

```typescript
import { parsePaymentInfo } from '@logiccrafterdz/xpay-sdk';

// Parse payment info from 402 response headers
const paymentInfo = parsePaymentInfo(response.headers);
```

### Chain Configuration

```typescript
import { getTokenAddress, getChainConfig } from '@logiccrafterdz/xpay-sdk';

// Get USDC token address for a specific chain
const usdcAddress = getTokenAddress('base-sepolia', 'USDC');

// Get viem chain configuration
const chainConfig = getChainConfig('base-sepolia');
```

## Example

See [`examples/pay-for-api.ts`](./examples/pay-for-api.ts) for a complete working example.

To run the example:

```bash
# Set your private key (testnet only!)
export PRIVATE_KEY="0x..."

# Run the example
npm run example
```

## Security Notes

⚠️ **Important Security Guidelines:**

- **Never hardcode private keys in production code**
- Use environment variables or secure key management systems
- Only use testnet private keys for development and testing
- Ensure your wallet has sufficient USDC balance and ETH for gas fees
- Always validate payment amounts and recipients before confirming transactions

## Development

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Run example
npm run example
```

## Error Handling

The SDK provides specific error types for different failure scenarios:

```typescript
import { InsufficientBalanceError, InsufficientAllowanceError } from '@logiccrafterdz/xpay-sdk';

try {
  const response = await client.request({ ... });
} catch (error) {
  if (error instanceof InsufficientBalanceError) {
    console.log('Not enough USDC balance');
  } else if (error instanceof InsufficientAllowanceError) {
    console.log('Need to approve USDC spending');
  }
}
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure all tests pass
5. Submit a pull request

## License

MIT

## Support & Contact

Developer: LogicCrafterDZ
Email: logiccrafterdz@gmail.com
Twitter: @Arana_lib
Telegram: https://t.me/LogicCrafterDZ
Farcaster : @esta