npm package: @homotopic-yoneda/sdk
Description: Yoneda SDK for AI agent payments and banking
Author: Yoneda Protocol
Latest version: 1.0.0-beta

# Yoneda SDK

TypeScript SDK for Yoneda Protocol - AI agent payments and banking infrastructure.

## Installation

```bash
npm install @homotopic-yoneda/sdk
```

## Quick Start

### Production

```typescript
import { createClient } from "@homotopic-yoneda/sdk";

const client = createClient({ 
  apiKey: process.env.YONEDA_API_KEY!,
  network: "testnet" // or "mainnet"
});

const account = await client.registerAgent({
  name: "my-agent",
  baseCurrency: "USD"
});

await account.openConnection("yoneda-hub-northamerica", 100);
const receipt = await account.pay("agent:recipient", 10, "USD", "payment memo");
console.log(`Payment completed: ${receipt.transactionId}`);
```

### Sandbox Mode (Local Testing)

```typescript
import { createClient } from "@homotopic-yoneda/sdk";

// Sandbox mode works without backend connectivity
const client = createClient({ 
  apiKey: "sandbox-key",
  network: "sandbox"
});

const account = await client.registerAgent({
  name: "test-agent",
  baseCurrency: "USD"
});

await account.openConnection("yoneda-hub-northamerica", 100);

// Send payment
await account.pay("agent:recipient", 10, "USD");

// Stream payments
const stream = account.stream(
  "agent:recipient",
  0.01,
  "second", // or "minute", "hour", or milliseconds
  "USD",
  "streaming payment",
  {
    duration: 5000, // Stop after 5 seconds
    totalAmount: 0.1 // Or stop after total amount sent
  }
);

stream.on("end", () => console.log("Stream ended"));
stream.on("error", (error) => console.error("Stream error:", error));

// Stop stream manually
setTimeout(() => stream.stop(), 3000);

// Query balance
const balance = await account.queryBalance();
console.log(`Current balance: $${balance}`);

// Listen to events
account.on("paymentReceived", (info) => {
  console.log(`Received $${info.amount} from ${info.from}`);
});

account.on("balanceChanged", (newBalance) => {
  console.log(`Balance updated: $${newBalance}`);
});
```

## Features

- **Agent Registration**: Create and manage agent identities
- **Hub Connections**: Connect to Channel Factory Hubs for payments
- **One-time Payments**: Send discrete payments to other agents
- **Streaming Payments**: Continuous micropayments with rate control
- **Balance Queries**: Query balances in any supported currency
- **Event System**: Subscribe to payment, balance, and connection events
- **Sandbox Mode**: Test locally without backend connectivity
- **Real Cryptography**: Secp256k1 key generation and signing
- **Multi-hop Routing**: Automatic routing through hub network
- **Currency Conversion**: Automatic fiat-to-sats conversion

## Error Handling

The SDK uses typed errors for better error handling:

```typescript
import { YonedaError } from "@homotopic-yoneda/sdk";

try {
  await account.pay("agent:recipient", 1000, "USD");
} catch (error) {
  if (error instanceof YonedaError) {
    switch (error.code) {
      case "INSUFFICIENT_BALANCE":
        console.log("Not enough funds");
        break;
      case "ROUTE_NOT_FOUND":
        console.log("Cannot reach recipient");
        break;
      case "HUB_UNAVAILABLE":
        console.log("Hub is offline");
        break;
      case "COMPLIANCE_REQUIRED":
        console.log("Compliance check required");
        break;
      default:
        console.error("Payment failed:", error.message);
    }
  }
}
```

## Error Codes

The SDK uses typed errors with specific error codes:

- `INSUFFICIENT_BALANCE` - Not enough balance for transaction
- `ROUTE_NOT_FOUND` - No route to recipient
- `HUB_UNAVAILABLE` - Hub is offline or unavailable
- `POLICY_VIOLATION` - Transaction violates spending policy
- `COMPLIANCE_REQUIRED` - Compliance check required
- `COMPLIANCE_FAILED` - Compliance check failed
- `INVALID_CONFIG` - Invalid configuration
- `REGISTRATION_FAILED` - Agent registration failed
- `CONNECTION_FAILED` - Hub connection failed
- `CLOSE_FAILED` - Hub disconnection failed
- `PAYMENT_FAILED` - Payment transaction failed

## Troubleshooting

### Payment Fails with INSUFFICIENT_BALANCE

Check your balance:
```typescript
const balance = await account.queryBalance();
console.log(`Current balance: $${balance}`);
```

### Payment Fails with POLICY_VIOLATION

Check your spending policy:
```typescript
// Policy limits transactions
const policy = {
  maxTransactionAmount: 10, // $10 max per transaction
  maxDailySpend: 100, // $100 max per day
  allowlist: ["agent:allowed-recipient"],
  blocklist: ["agent:blocked-recipient"],
};
await account.setPolicy(policy);
```

### Connection Fails

Ensure the hub ID is correct and the hub is available:
```typescript
try {
  await account.openConnection("yoneda-hub-northamerica", 100);
} catch (error) {
  if (error.code === "HUB_UNAVAILABLE") {
    console.error("Hub is unavailable, try a different hub");
  }
}
```

### Stream Not Stopping

Ensure you call `stream.stop()`:
```typescript
const stream = account.stream("agent:recipient", 0.01, "second");

// Stop after 5 seconds
setTimeout(() => {
  stream.stop();
}, 5000);
```

### State Not Persisting

Check storage configuration:
```typescript
import { FileStorage } from "@homotopic-yoneda/sdk";

// Use file storage for persistence
const storage = new FileStorage(".yoneda-state.json");
// Pass storage when creating account (via client config)
```

## Migration Guide

### From Mock SDK to Real SDK

1. Update imports:
```typescript
// Old
import { YonedaClient } from "@homotopic-yoneda/sdk";

// New - same import
import { createClient } from "@homotopic-yoneda/sdk";
```

2. Use sandbox mode for testing:
```typescript
// Use sandbox mode instead of mock
const client = createClient({
  apiKey: "sandbox-key",
  network: "sandbox", // Changed from "testnet" to "sandbox"
});
```

3. Real cryptographic keys are now used automatically:
```typescript
// No changes needed - keys are generated automatically
const account = await client.registerAgent({
  name: "my-agent",
  baseCurrency: "USD",
});
```

## Performance Optimization

### Use WASM for Cryptographic Operations

```typescript
// Optional: Use WASM for better performance
import { WasmCrypto } from "@yoneda/wasm";
import init from "@yoneda/wasm/pkg/yoneda_core_wasm";

await init(); // Initialize WASM module
const keypair = WasmCrypto.generate_keypair(); // Faster than JS
```

### Batch Operations

For multiple payments, consider using the Account's batch capabilities:
```typescript
// SDK automatically batches operations when possible
// No manual batching needed
```

### Connection Pooling

The SDK manages connections automatically. Reuse account instances:
```typescript
// Good: Reuse account instance
const account = await client.registerAgent({ name: "agent" });
await account.openConnection("hub-1", 100);
await account.pay("agent:recipient", 10);
await account.pay("agent:recipient2", 10); // Reuses connection

// Bad: Creating new account for each operation
```

## Documentation

See [docs.yoneda.io](https://docs.yoneda.io) for complete documentation.

## License

MIT