npm package: @humandividendprotocol/sdk
Description: TypeScript SDK for Human Dividend Protocol
Latest version: 0.1.0

# @hdp/sdk

**TypeScript SDK for Human Dividend Protocol** — wrap any AI client to automatically capture compute metrics and earn HDPT token rewards.

## Installation

```bash
npm install @hdp/sdk
```

## Quick Start

### 1. Setup (one-time)

```bash
npx hdp-setup
```

This onboards your machine with HDP and saves credentials to `~/.hdp/config.json`. No wallet needed — one is assigned automatically.

### 2. Wrap your AI client

```typescript
import Anthropic from '@anthropic-ai/sdk';
import { track } from '@hdp/sdk';

const client = track(new Anthropic());

// Use the client normally — HDP captures every API call
const response = await client.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello!' }],
});
// A compute receipt is automatically built and submitted
```

That's it. The `track()` wrapper is transparent — all methods and properties pass through unchanged. It intercepts the response to extract token usage, builds a cryptographic compute receipt, and submits it to the HDP aggregator in the background.

## Supported Providers

`track()` auto-detects the AI provider from the client object:

| Provider | Client | Intercepted Method |
|----------|--------|--------------------|
| **Anthropic** | `new Anthropic()` | `client.messages.create()` |
| **OpenAI** | `new OpenAI()` | `client.chat.completions.create()` |
| **Google** | Generative AI clients | `client.generateContent()` |
| **Generic** | Any object | Any async method returning `{ usage }` |

No AI SDK is a hard dependency — `track()` inspects the object structure at runtime.

## Options

```typescript
const client = track(new Anthropic(), {
  // Machine ID (auto-loaded from ~/.hdp/config.json if not set)
  machineId: 'my-machine-id',

  // Wallet address for reward attribution
  walletAddress: '0x...',

  // Custom aggregator URL (default: https://aggregator.humandividendprotocol.com)
  aggregatorUrl: 'https://aggregator.humandividendprotocol.com',

  // Submit receipts automatically (default: true)
  autoSubmit: true,

  // Callback for every captured receipt
  onReceipt: (receipt) => console.log('Captured:', receipt.computation.input_tokens, 'tokens'),

  // Local Desktop App IPC (default: http://127.0.0.1:19876, set false to disable)
  localIpcUrl: 'http://127.0.0.1:19876',
});
```

## Dual Submission

When the HDP Desktop App is running, `track()` submits receipts to **both**:

1. **Aggregator** (remote) — full compute receipt for on-chain scoring and HDPT rewards
2. **Desktop App** (local IPC) — lightweight usage record so the desktop dashboard shows SDK activity

Local IPC is fire-and-forget — if the Desktop App isn't running, it silently skips.

## HDPClient API

The SDK also includes `HDPClient` for direct interaction with the HDP backend API:

```typescript
import { HDPClient } from '@hdp/sdk';

const client = new HDPClient({ sessionToken: 'your-token' });

// Network stats
const stats = await client.getNetworkStats();

// Machine management
const machines = await client.getMachinesByOwner('0x...');
const machineStats = await client.getMachineStats('fingerprint');

// Proofs
const proofs = await client.getProofsByOwner('0x...');
const proof = await client.getProof('proof-id');

// Validators
const validators = await client.getActiveValidators();

// Compute receipts (via interceptor augmentation)
await client.submitComputeReceipt(receipt);
const history = await client.getReceiptHistory('machine-id');
const status = await client.getMachineStatus('machine-id');
```

### Authentication

```typescript
const client = new HDPClient();

// Challenge-response auth with wallet signature
const challenge = await client.getChallenge();
// Sign challenge.message with your wallet...
const session = await client.createSession(address, signature, challenge.message, challenge.timestamp);
// Session token is now stored on the client

// Or set a token directly
client.setSessionToken('existing-token');
```

## Utility Functions

```typescript
import { calculateComputeUnits, isValidAddress, formatHDPT, parseHDPT } from '@hdp/sdk';

// Calculate compute units from token usage
const cu = calculateComputeUnits(inputTokens, outputTokens, latencyMs);

// Validate Ethereum address
isValidAddress('0x...'); // true/false

// Format/parse HDPT amounts (wei ↔ human-readable)
formatHDPT(1000000000000000000n); // "1.0"
parseHDPT("1.0"); // 1000000000000000000n
```

## Contract Addresses

The SDK exports on-chain contract addresses and ABIs for direct blockchain interaction (requires `viem` peer dependency):

```typescript
import { CONTRACT_ADDRESSES, CHAIN_ID, HDPTokenABI } from '@hdp/sdk';

console.log(CONTRACT_ADDRESSES.hdpToken);     // "0xd72b..."
console.log(CONTRACT_ADDRESSES.proofRegistry); // "0x5F0c..."
console.log(CHAIN_ID);                         // 84532 (Base Sepolia)
```

## Error Handling

All API errors are typed:

```typescript
import {
  HDPApiError,        // Generic API error (includes status code)
  HDPAuthError,       // 401 — invalid or expired session
  HDPValidationError, // 400 — invalid input
  HDPNotFoundError,   // 404 — resource not found
  HDPRateLimitError,  // 429 — rate limited (includes retryAfter)
  HDPNetworkError,    // Network failure
} from '@hdp/sdk';

try {
  await client.getProof('invalid-id');
} catch (err) {
  if (err instanceof HDPNotFoundError) {
    console.log('Proof not found');
  }
  if (err instanceof HDPRateLimitError) {
    console.log(`Retry after ${err.retryAfter} seconds`);
  }
}
```

## Reward Tier

SDK receipts are scored as **Orchestrator tier (0.6x multiplier)**. For the full 1.0x Provider multiplier, use the Desktop App or CLI instead.

## Setup CLI Options

```bash
npx hdp-setup                          # Auto-onboard (default)
npx hdp-setup --agent-name my-bot      # Set an agent name
npx hdp-setup --token <t> --machine-id <id>  # Manual credentials
npx hdp-setup --api-url <url>          # Custom API endpoint
npx hdp-setup --force                  # Reconfigure
```

## Development

```bash
npm install
npm run build     # Build to dist/
npm run dev       # Watch mode
npm test          # Run 153 tests
npm run typecheck # Type checking
```

## License

MIT