npm package: @perkos/service-x402
Description: Unified x402 payment protocol verification and settlement service
Author: PerkOS
Latest version: 1.1.1

# @perkos/service-x402

Unified x402 payment protocol verification and settlement service. Orchestrates payment verification across multiple blockchain networks using exact (EIP-3009) and deferred (EIP-712) payment schemes.

## Installation

```bash
npm install @perkos/service-x402
```

## Usage

### Basic Setup

```typescript
import { X402Service, createX402Service } from '@perkos/service-x402';

// Create service with default config
const x402 = createX402Service();

// Create service with custom config
const x402 = createX402Service({
  defaultNetwork: 'base',
  rpcUrls: {
    base: 'https://mainnet.base.org',
    'base-sepolia': 'https://sepolia.base.org'
  },
  deferredEnabled: true,
  escrowAddresses: {
    base: '0x...',
    'base-sepolia': '0x...'
  }
});
```

### Verify Payments

```typescript
import { createX402Service, type X402VerifyRequest } from '@perkos/service-x402';

const x402 = createX402Service();

// Verify exact payment
const request: X402VerifyRequest = {
  x402Version: 2,
  paymentPayload: {
    x402Version: 2,
    scheme: 'exact',
    network: 'eip155:8453', // CAIP-2 format (Base)
    payload: {
      signature: '0x...',
      authorization: {
        from: '0x...',
        to: '0x...',
        value: '1000000',
        validAfter: '0',
        validBefore: '1735689600',
        nonce: '0x...'
      }
    }
  },
  paymentRequirements: {
    scheme: 'exact',
    network: 'eip155:8453',
    maxAmountRequired: '1000000',
    resource: '/api/service',
    payTo: '0x...',
    maxTimeoutSeconds: 3600,
    asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
  }
};

const result = await x402.verify(request);

if (result.isValid) {
  console.log('Payment verified from:', result.payer);
} else {
  console.error('Invalid payment:', result.invalidReason);
}
```

### Verify Deferred Payments

```typescript
const x402 = createX402Service({
  deferredEnabled: true,
  escrowAddresses: {
    base: '0x...' // Escrow contract address
  }
});

const request: X402VerifyRequest = {
  x402Version: 2,
  paymentPayload: {
    x402Version: 2,
    scheme: 'deferred',
    network: 'base',
    payload: {
      voucher: {
        id: '0x...',
        buyer: '0x...',
        seller: '0x...',
        valueAggregate: '5000000',
        asset: '0x...',
        timestamp: '1735689600',
        nonce: '1',
        escrow: '0x...',
        chainId: '8453'
      },
      signature: '0x...'
    }
  },
  paymentRequirements: {
    scheme: 'deferred',
    network: 'base',
    maxAmountRequired: '1000000',
    resource: '/api/service',
    payTo: '0x...',
    maxTimeoutSeconds: 3600,
    asset: '0x...',
    extra: {
      type: 'aggregation',
      escrow: '0x...',
      facilitator: 'https://x402.example.com'
    }
  }
};

const result = await x402.verify(request);
```

### Check Supported Networks

```typescript
const x402 = createX402Service();

// Get all supported schemes and networks
const supported = x402.getSupported();
// => { kinds: [{ scheme: 'exact', network: 'base' }, ...] }

// Check if network is supported
x402.isNetworkSupported('base'); // true
x402.isNetworkSupported('eip155:8453'); // true (CAIP-2 format)

// Check if deferred is enabled
x402.isDeferredEnabled('base'); // depends on config
```

### Network Format Conversion

```typescript
const x402 = createX402Service();

// CAIP-2 to legacy format
x402.caip2ToLegacy('eip155:8453');     // 'base'
x402.caip2ToLegacy('eip155:43114');    // 'avalanche'

// Legacy to CAIP-2 format
x402.legacyToCaip2('base');           // 'eip155:8453'
x402.legacyToCaip2('avalanche');      // 'eip155:43114'

// Normalize any format to legacy
x402.normalizeNetwork('eip155:8453'); // 'base'
x402.normalizeNetwork('base');        // 'base'
```

### Access Scheme Verifiers

```typescript
const x402 = createX402Service({
  deferredEnabled: true,
  escrowAddresses: { base: '0x...' }
});

// Get exact scheme verifier
const exactScheme = x402.getExactScheme('base');
if (exactScheme) {
  // Use ExactSchemeVerifier directly
}

// Get deferred scheme verifier
const deferredScheme = x402.getDeferredScheme('base');
if (deferredScheme) {
  // Use DeferredSchemeVerifier directly
}
```

## API Reference

### X402Service

```typescript
class X402Service {
  constructor(config?: X402ServiceConfig);

  // Verification
  verify(request: X402VerifyRequest): Promise<VerifyResponse>;
  verifyPayload(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;

  // Network support
  getSupported(): SupportedResponse;
  isNetworkSupported(network: string): boolean;
  isDeferredEnabled(network: string): boolean;
  getDefaultNetwork(): SupportedNetwork;

  // Network conversion
  caip2ToLegacy(caip2: string): SupportedNetwork | null;
  legacyToCaip2(network: SupportedNetwork): string | null;
  normalizeNetwork(network: string): SupportedNetwork | null;

  // Scheme access
  getExactScheme(network: SupportedNetwork): ExactSchemeVerifier | undefined;
  getDeferredScheme(network: SupportedNetwork): DeferredSchemeVerifier | undefined;
}
```

### X402ServiceConfig

```typescript
interface X402ServiceConfig {
  /** Default network to use */
  defaultNetwork?: SupportedNetwork;
  /** RPC URL overrides by network */
  rpcUrls?: Partial<Record<SupportedNetwork, string>>;
  /** Enable deferred scheme */
  deferredEnabled?: boolean;
  /** Escrow addresses for deferred scheme by network */
  escrowAddresses?: Partial<Record<SupportedNetwork, Address>>;
  /** Token name overrides for exact scheme (by chainId) */
  tokenNames?: Record<number, string>;
  /** Token version overrides for exact scheme (by chainId) */
  tokenVersions?: Record<number, string>;
}
```

### Factory Functions

```typescript
// Create full-featured service
function createX402Service(config?: X402ServiceConfig): X402Service;

// Create verification-only service (no deferred)
function createVerificationService(
  networks?: SupportedNetwork[],
  rpcUrls?: Partial<Record<SupportedNetwork, string>>
): X402Service;
```

## Supported Networks

| Network | Chain ID | CAIP-2 | Status |
|---------|----------|--------|--------|
| Ethereum | 1 | eip155:1 | Mainnet |
| Sepolia | 11155111 | eip155:11155111 | Testnet |
| Base | 8453 | eip155:8453 | Mainnet |
| Base Sepolia | 84532 | eip155:84532 | Testnet |
| Avalanche | 43114 | eip155:43114 | Mainnet |
| Avalanche Fuji | 43113 | eip155:43113 | Testnet |
| Polygon | 137 | eip155:137 | Mainnet |
| Polygon Amoy | 80002 | eip155:80002 | Testnet |
| Arbitrum | 42161 | eip155:42161 | Mainnet |
| Arbitrum Sepolia | 421614 | eip155:421614 | Testnet |
| Optimism | 10 | eip155:10 | Mainnet |
| Optimism Sepolia | 11155420 | eip155:11155420 | Testnet |
| Celo | 42220 | eip155:42220 | Mainnet |
| Celo Sepolia | 11142220 | eip155:11142220 | Testnet |
| Monad | 10142 | eip155:10142 | Mainnet |
| Monad Testnet | 10143 | eip155:10143 | Testnet |

## Re-exported Utilities

The package re-exports utilities from underlying packages for convenience:

### From @perkos/util-chains

```typescript
import {
  SUPPORTED_NETWORKS,
  getChainIdFromNetwork,
  type SupportedNetwork
} from '@perkos/service-x402';
```

### From @perkos/scheme-exact

```typescript
import {
  ExactSchemeVerifier,
  parseExactSignature,
  createExactEIP712Domain,
  generateNonce
} from '@perkos/service-x402';
```

### From @perkos/scheme-deferred

```typescript
import {
  DeferredSchemeVerifier,
  parseDeferredSignature,
  createDeferredEIP712Domain,
  generateVoucherId,
  createVoucherMessage,
  createVoucherTuple
} from '@perkos/service-x402';
```

### From @perkos/types-x402

```typescript
import type {
  X402VerifyRequest,
  X402SettleRequest,
  VerifyResponse,
  SettleResponse,
  PaymentPayload,
  PaymentRequirements,
  ExactPayload,
  DeferredPayload,
  Voucher,
  Address,
  Hex,
  Resource,
  Extensions
} from '@perkos/service-x402';

// Type guards and helpers
import {
  getPaymentAmount,
  getResourceUrl,
  getResourceDescription,
  getResourceMimeType,
  isCAIP2,
  isResourceObject,
  isExactPayload,
  isDeferredPayload,
  isAddress,
  isHex
} from '@perkos/service-x402';
```

## Payment Schemes

### Exact Scheme (EIP-3009)

Immediate on-chain payment using `transferWithAuthorization`:
- Direct token transfer on transaction
- Signature-based authorization
- Nonce tracking prevents replay attacks

### Deferred Scheme (EIP-712)

Off-chain voucher aggregation with batch settlement:
- Client signs vouchers off-chain
- Vouchers accumulate value over time
- Batch settlement reduces gas costs
- Escrow contract holds funds

## Related Packages

- [@perkos/types-x402](https://www.npmjs.com/package/@perkos/types-x402) - Core x402 types
- [@perkos/util-chains](https://www.npmjs.com/package/@perkos/util-chains) - Chain utilities
- [@perkos/scheme-exact](https://www.npmjs.com/package/@perkos/scheme-exact) - Exact payment scheme
- [@perkos/scheme-deferred](https://www.npmjs.com/package/@perkos/scheme-deferred) - Deferred payment scheme

## License

MIT