npm package: @shade402/core
Description: Core TypeScript library for X402 payment protocol
Author: shade402
Latest version: 0.0.1

# @shade402/core

Core TypeScript library implementing the X402 payment protocol for autonomous AI agent payments on Solana.

## Overview

The core package provides the foundational building blocks for the X402 payment protocol. It includes payment models, Solana blockchain integration, encryption utilities, and error handling. This package is used by all other Shade402 packages and can be used directly for custom implementations.

## Features

- Payment request and authorization models with validation
- Solana blockchain payment processing
- SPL token transfer support
- Payment verification and expiration handling
- RSA encryption for resource field privacy
- Comprehensive error types and handling
- Full TypeScript support with Zod schema validation
- Network support for Solana mainnet and devnet

## Installation

```bash
npm install @shade402/core
# or
pnpm add @shade402/core
# or
yarn add @shade402/core
```

## Dependencies

- `@solana/web3.js`: Solana blockchain interactions
- `@solana/spl-token`: SPL token operations
- `zod`: Runtime schema validation

## Usage

### Payment Models

The core package provides two main model classes for representing payment data:

```typescript
import { PaymentRequest, PaymentAuthorization } from '@shade402/core';

// Create payment request from server response
const requestData = {
  max_amount_required: '0.01',
  asset_type: 'spl-token',
  asset_address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  payment_address: 'PaymentWalletAddress...',
  network: 'solana-devnet',
  expires_at: new Date(Date.now() + 300000),
  nonce: 'unique-nonce',
  payment_id: 'payment-id',
  resource: 'encrypted-resource-data',
  description: 'Payment for API access'
};

const paymentRequest = new PaymentRequest(requestData);

// Create authorization after payment
const authData = {
  payment_id: paymentRequest.paymentId,
  nonce: paymentRequest.nonce,
  transaction_hash: 'transaction-signature',
  public_key: 'wallet-public-key'
};

const authorization = new PaymentAuthorization(authData);
```

### Solana Payment Processor

The SolanaPaymentProcessor handles all blockchain operations for creating and verifying payments:

```typescript
import { SolanaPaymentProcessor } from '@shade402/core';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.generate();
const processor = new SolanaPaymentProcessor(
  'https://api.devnet.solana.com',
  wallet,
  { defaultDecimals: 6 }
);

// Create payment transaction
const paymentRequest = new PaymentRequest(requestData);
const authorization = await processor.createPayment(
  paymentRequest,
  '0.01' // amount to pay
);

// Verify payment
const isValid = await processor.verifyPayment(
  paymentRequest,
  authorization
);
```

### Encryption Utilities

The package provides RSA encryption for protecting sensitive resource data:

```typescript
import { generateKeyPair, encryptResource, decryptResource } from '@shade402/core';

// Generate key pair (server-side)
const { publicKey, privateKey } = await generateKeyPair();

// Encrypt resource data (server-side)
const encrypted = await encryptResource(
  'sensitive-resource-data',
  publicKey
);

// Decrypt resource data (client-side)
const decrypted = await decryptResource(
  encrypted,
  privateKey
);
```

### Error Handling

Comprehensive error types for different failure scenarios:

```typescript
import {
  X402Error,
  PaymentRequiredError,
  PaymentExpiredError,
  InsufficientFundsError,
  PaymentVerificationError,
  TransactionBroadcastError,
  InvalidPaymentRequestError,
  ERROR_CODES
} from '@shade402/core';

try {
  await processor.createPayment(paymentRequest, amount);
} catch (error) {
  if (error instanceof PaymentExpiredError) {
    console.error('Payment request expired');
  } else if (error instanceof InsufficientFundsError) {
    console.error('Insufficient wallet balance');
  } else if (error instanceof PaymentVerificationError) {
    console.error('Payment verification failed');
  } else if (error instanceof TransactionBroadcastError) {
    console.error('Transaction broadcast failed:', error.message);
  }
}
```

## API Reference

### PaymentRequest

Represents a payment request from a server.

**Constructor:**
- `new PaymentRequest(data: PaymentRequestData)`

**Properties:**
- `maxAmountRequired: string` - Maximum amount required for payment
- `assetType: string` - Asset type (e.g., 'spl-token')
- `assetAddress: string` - Asset contract/mint address
- `paymentAddress: string` - Wallet address to receive payment
- `network: string` - Blockchain network identifier
- `expiresAt: Date` - Payment request expiration time
- `nonce: string` - Unique nonce for this payment
- `paymentId: string` - Unique payment identifier
- `resource: string` - Encrypted resource identifier
- `description?: string` - Optional payment description

**Methods:**
- `isExpired(): boolean` - Check if payment request has expired
- `toJSON(): PaymentRequestData` - Convert to JSON format

### PaymentAuthorization

Represents a payment authorization after successful payment.

**Constructor:**
- `new PaymentAuthorization(data: PaymentAuthorizationData)`

**Properties:**
- `paymentId: string` - Payment identifier
- `nonce: string` - Payment nonce
- `transactionHash: string` - Blockchain transaction hash
- `publicKey: string` - Payer's public key

**Methods:**
- `toJSON(): PaymentAuthorizationData` - Convert to JSON format

### SolanaPaymentProcessor

Handles Solana blockchain operations for payments.

**Constructor:**
- `new SolanaPaymentProcessor(rpcUrl: string, keypair?: Keypair, options?: SolanaPaymentProcessorOptions)`

**Methods:**
- `async createPayment(request: PaymentRequest, amount: string, memo?: string): Promise<PaymentAuthorization>` - Create and broadcast payment transaction
- `async verifyPayment(request: PaymentRequest, authorization: PaymentAuthorization): Promise<boolean>` - Verify payment on blockchain
- `async getBalance(tokenMint?: string): Promise<number>` - Get wallet token balance

### Encryption Functions

- `async generateKeyPair(): Promise<{ publicKey: string, privateKey: string }>` - Generate RSA key pair
- `async encryptResource(data: string, publicKey: string): Promise<string>` - Encrypt resource data
- `async decryptResource(encrypted: string, privateKey: string): Promise<string>` - Decrypt resource data

## Error Types

### X402Error

Base error class for all X402-related errors.

### PaymentRequiredError

Thrown when a payment is required but not provided.

### PaymentExpiredError

Thrown when a payment request has expired.

### InsufficientFundsError

Thrown when wallet lacks sufficient funds for payment.

### PaymentVerificationError

Thrown when payment verification fails.

### TransactionBroadcastError

Thrown when transaction broadcast to blockchain fails.

### InvalidPaymentRequestError

Thrown when payment request data is invalid.

## Configuration

### SolanaPaymentProcessorOptions

```typescript
interface SolanaPaymentProcessorOptions {
  defaultDecimals?: number; // Default: 6 (common for USDC)
  memo?: string; // Optional memo text for transactions
}
```

## Examples

### Basic Payment Flow

```typescript
import {
  PaymentRequest,
  PaymentAuthorization,
  SolanaPaymentProcessor
} from '@shade402/core';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.generate();
const processor = new SolanaPaymentProcessor(
  'https://api.devnet.solana.com',
  wallet
);

// Parse payment request from server
const requestData = {
  max_amount_required: '0.01',
  asset_type: 'spl-token',
  asset_address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  payment_address: 'PaymentWalletAddress...',
  network: 'solana-devnet',
  expires_at: new Date(Date.now() + 300000),
  nonce: 'unique-nonce',
  payment_id: 'payment-id',
  resource: 'resource-data'
};

const paymentRequest = new PaymentRequest(requestData);

// Check expiration
if (paymentRequest.isExpired()) {
  throw new Error('Payment request expired');
}

// Create payment
const authorization = await processor.createPayment(
  paymentRequest,
  paymentRequest.maxAmountRequired
);

// Verify payment
const isValid = await processor.verifyPayment(paymentRequest, authorization);
console.log('Payment verified:', isValid);
```

### Error Handling

```typescript
import {
  PaymentExpiredError,
  InsufficientFundsError,
  PaymentVerificationError,
  TransactionBroadcastError
} from '@shade402/core';

try {
  const authorization = await processor.createPayment(request, amount);
} catch (error) {
  if (error instanceof PaymentExpiredError) {
    console.error('Payment request has expired');
  } else if (error instanceof InsufficientFundsError) {
    console.error('Insufficient funds in wallet');
  } else if (error instanceof PaymentVerificationError) {
    console.error('Payment verification failed');
  } else if (error instanceof TransactionBroadcastError) {
    console.error('Transaction failed:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## TypeScript Support

The package is written in TypeScript and provides full type definitions. All types are exported and can be imported directly:

```typescript
import type {
  PaymentRequestData,
  PaymentAuthorizationData,
  SolanaPaymentProcessorOptions,
  ErrorDetails
} from '@shade402/core';
```

## Network Support

The package supports Solana networks:
- `solana-mainnet`: Solana mainnet
- `solana-devnet`: Solana devnet

## Security Considerations

- Always validate payment requests before processing
- Check expiration times before creating payments
- Verify payments on-chain before granting access
- Use HTTPS for all network communications
- Store private keys securely
- Never expose private keys in client-side code
- Use encryption for sensitive resource data

## License

MIT