npm package: @hauska-sdk/payment
Description: CNS Protocol Payment SDK - x402 protocol implementation
Author: Hauska SDK Team
Latest version: 0.1.0

# @hauska-sdk/payment

CNS Protocol Payment SDK - x402 protocol implementation for crypto and fiat payments.

## Installation

```bash
npm install @hauska-sdk/payment
```

## Quick Start

```typescript
import { PaymentSDK } from "@hauska-sdk/payment";
import { MockStorageAdapter } from "@hauska-sdk/adapters-storage-mock";
import { WalletManager } from "@hauska-sdk/wallet";

// Initialize SDK
const sdk = new PaymentSDK({
  walletManager: new WalletManager(),
  blockchain: {
    chain: "base",
    token: "USDC",
    facilitatorWallet: "0xYourFacilitatorWallet",
    baseRpcUrl: "https://mainnet.base.org",
  },
  storage: new MockStorageAdapter(), // Use PostgreSQL adapter in production
});

// Generate payment request
const response = await sdk.generate402Response({
  resourceId: "invoice-123",
  amount: "450000", // $450.00 USDC (6 decimals)
  currency: "USDC",
  expiresAt: Date.now() + 3600000, // 1 hour
});

// Return 402 response to client
res.status(402).json(response.body);
```

## Features

- ✅ **HTTP 402 Response Generation** - x402 protocol support
- ✅ **Crypto Payment Verification** - USDC on Base L2
- ✅ **Automatic Wallet Creation** - Seamless wallet management
- ✅ **Payment Record Storage** - Audit trail and duplicate prevention
- ✅ **EIP-712 Signing** - Standard typed data signing

## API Reference

### PaymentSDK

Main SDK class that provides all payment functionality.

#### Constructor

```typescript
new PaymentSDK(config: PaymentSDKConfig)
```

#### Methods

##### `generate402Response(request: PaymentRequest): Promise<HTTP402Response>`

Generate HTTP 402 Payment Required response.

```typescript
const response = await sdk.generate402Response({
  resourceId: "invoice-123",
  amount: "450000",
  currency: "USDC",
  expiresAt: Date.now() + 3600000,
});
```

##### `verifyPayment(proof: PaymentVerificationProof): Promise<PaymentVerificationResult>`

Verify a crypto payment transaction.

```typescript
const result = await sdk.verifyPayment({
  txHash: "0x...",
  fromAddress: "0x...",
  toAddress: "0x...",
  amount: "450000",
  chainId: 8453, // Base
});

if (result.verified) {
  // Payment verified!
}
```

##### `recordPayment(record): Promise<PaymentRecord>`

Record a payment in storage.

```typescript
const record = await sdk.recordPayment({
  resourceId: "invoice-123",
  amount: "450000",
  currency: "USDC",
  method: "crypto",
  txHash: "0x...",
  fromAddress: "0x...",
  toAddress: "0x...",
});
```

##### `processPaymentFlow(params): Promise<{response, verification, record}>`

Complete payment flow: Generate 402 → Verify → Record.

```typescript
const flow = await sdk.processPaymentFlow({
  request: {
    resourceId: "invoice-123",
    amount: "450000",
    currency: "USDC",
    expiresAt: Date.now() + 3600000,
  },
  verificationProof: {
    txHash: "0x...",
    fromAddress: "0x...",
    toAddress: "0x...",
    amount: "450000",
    chainId: 8453,
  },
});
```

##### `createWalletIfNeeded(userId: string, password: string): Promise<string>`

Create wallet automatically if user doesn't have one.

```typescript
const walletAddress = await sdk.createWalletIfNeeded("user-123", "password");
```

## Configuration

```typescript
interface PaymentSDKConfig {
  walletManager?: WalletManager;
  blockchain?: {
    chain: "base" | "ethereum" | "polygon";
    token: "USDC" | "USDT";
    facilitatorWallet: string;
    baseRpcUrl?: string;
  };
  fiat?: {
    provider: "circle";
    apiKey: string;
  };
  storage?: StorageAdapter;
}
```

## Examples

### Express.js Integration

```typescript
import express from "express";
import { PaymentSDK } from "@hauska-sdk/payment";

const app = express();
const sdk = new PaymentSDK({
  // ... config
});

app.post("/api/payment/request", async (req, res) => {
  const response = await sdk.generate402Response({
    resourceId: req.body.invoiceId,
    amount: req.body.amount,
    currency: "USDC",
    expiresAt: Date.now() + 3600000,
  });

  res.status(402).json(response.body);
});

app.post("/api/payment/verify", async (req, res) => {
  const result = await sdk.verifyPayment({
    txHash: req.body.txHash,
    fromAddress: req.body.fromAddress,
    toAddress: req.body.toAddress,
    amount: req.body.amount,
    chainId: 8453,
  });

  if (result.verified) {
    await sdk.markPaymentVerified(req.body.resourceId, {
      txHash: req.body.txHash,
    });
    res.json({ success: true });
  } else {
    res.status(400).json({ error: result.error });
  }
});
```

## License

MIT