npm package: @paydirect/sdk
Description: TypeScript SDK for PayDirect settlement API on Base — supports REST API and x402 protocol by Coinbase
Latest version: 0.3.0

# @paydirect/sdk

TypeScript SDK for the PayDirect settlement API on Base.

**v0.3.0** — Adds payouts, wallet balance, smart wallets, workspaces, withdraw, input validation, and request timeouts.

## Install

```bash
npm install @paydirect/sdk
```

## Quick Start

```typescript
import { PayDirectClient } from "@paydirect/sdk";

const client = new PayDirectClient({
  apiKey: "pd_live_your_key_here",
  baseUrl: "https://paydirect.com/api/v1", // optional
  timeoutMs: 30000, // optional, default 30s
});
```

## Payments

```typescript
// Create a payment
const { payment, receivingAddress } = await client.createPayment({
  tokenSymbol: "USDC",
  amount: "100",
  merchantWallet: "0xYourWalletAddress",
  description: "Order #1234",
  walletType: "smart_wallet", // optional: "eoa" | "smart_wallet"
});

console.log(`Send ${payment.grossAmount} USDC to ${receivingAddress}`);

// Get payment details
const { payment: updated } = await client.getPayment(payment.id);

// List payments
const { payments, total } = await client.listPayments({
  status: "completed",
  limit: 25,
  offset: 0,
});

// Cancel a pending payment
await client.cancelPayment(payment.id);

// Verify a payment was forwarded
const { verified } = await client.verifyPayment(payment.id);
```

## Payouts

Send tokens from your workspace wallet to any destination.

```typescript
const { payout } = await client.sendPayout({
  tokenSymbol: "ADAO",
  amount: "500",
  destinationAddress: "0xRecipient...",
  walletType: "smart_wallet", // optional
  description: "Agent payment",
});

console.log(`Sent! TX: ${payout.txHash}`);

// List payout history
const { payouts } = await client.listPayouts({ limit: 50 });
```

## Wallet Balance

```typescript
const balance = await client.getBalance();

console.log(`EOA: ${balance.eth} ETH, ${balance.usdc} USDC, ${balance.adao} ADAO`);
if (balance.smartWallet) {
  console.log(`Smart Wallet: ${balance.smartWallet.adao} ADAO`);
}
```

## Withdraw

Withdraw funds to your configured settlement address.

```typescript
const result = await client.withdraw({
  tokenSymbol: "USDC",
  amount: "50", // or omit for full balance
  walletType: "smart_wallet",
});

console.log(`Withdrawn: ${result.explorerUrl}`);
```

## Workspaces (Admin)

Create and manage workspaces programmatically. Requires an admin API key.

```typescript
const adminClient = new PayDirectClient({
  apiKey: process.env.PAYDIRECT_ADMIN_SECRET!,
});

// Create a workspace for a user
const workspace = await adminClient.createWorkspace({
  name: "alice-workspace",
  ownerEmail: "alice@example.com",
  platform: "cowork",
  settlementWallet: "0xSettlement...",
});

console.log(`Workspace: ${workspace.workspaceId}`);
console.log(`API Key (sandbox): ${workspace.apiKeys.sandbox}`);
console.log(`API Key (live): ${workspace.apiKeys.live}`);

// List all workspaces
const { workspaces } = await adminClient.listWorkspaces({ platform: "cowork" });

// Get workspace details
const info = await adminClient.getWorkspace(workspace.workspaceId);
```

## Smart Wallets

Provision ERC-4337 smart wallets with gasless transaction support.

```typescript
// Create a smart wallet for a workspace
const result = await client.createSmartWallet(workspaceId, {
  setDefault: true,
});

console.log(`Smart Wallet: ${result.smartWallet.address}`);

// Get smart wallet info
const info = await client.getSmartWallet(workspaceId);
console.log(`Default type: ${info.defaultWalletType}`);

// Switch default wallet type
await client.setDefaultWallet(workspaceId, "smart_wallet");
```

## Webhooks

```typescript
// Register a webhook
const { webhook } = await client.createWebhook(
  "https://myapp.com/webhooks/paydirect",
  ["payment.completed", "payment.failed", "payout.completed"]
);

// List webhooks
const { webhooks } = await client.listWebhooks();

// Delete a webhook
await client.deleteWebhook(webhook.id);
```

## Webhook Signature Verification

```typescript
import { PayDirectClient } from "@paydirect/sdk";

const isValid = PayDirectClient.verifyWebhookSignature(
  "whsec_your_signing_secret",
  rawRequestBody,
  request.headers["x-paydirect-signature"]
);
```

## API Keys

```typescript
const { keys } = await client.listKeys();
const { apiKey } = await client.createKey("my-key", "live");
await client.revokeKey(keyId);
```

## Error Handling

```typescript
import { PayDirectClient, PayDirectError } from "@paydirect/sdk";

try {
  await client.sendPayout({ ... });
} catch (err) {
  if (err instanceof PayDirectError) {
    console.error(`PayDirect error: ${err.message} (HTTP ${err.status})`);
    console.error("Details:", err.data);
  }
}
```

Timeout errors return status `408`. Network errors return status `0`.

## Fee Rates

| Token | Fee    |
| ----- | ------ |
| USDC  | 0.50%  |
| ETH   | 0.50%  |
| ADAO  | 0.25%  |

## Changelog

### 0.3.0

- Added `sendPayout()` and `listPayouts()` for token transfers
- Added `getBalance()` for wallet balance queries
- Added `withdraw()` for settlement withdrawals
- Added `createWorkspace()`, `listWorkspaces()`, `getWorkspace()` for programmatic workspace management
- Added `createSmartWallet()`, `getSmartWallet()`, `setDefaultWallet()` for ERC-4337 smart wallet provisioning
- Added input validation (addresses, amounts, token symbols)
- Added configurable request timeouts (default 30s)
- Added path segment sanitization to prevent injection
- Improved error handling with robust JSON parsing fallback
- `walletType` option on `createPayment` and `sendPayout`

### 0.2.0

- Initial public release with payments, webhooks, and API key management