@humandividendprotocol/sdk
v0.1.0
Published
TypeScript SDK for Human Dividend Protocol
Maintainers
Readme
@hdp/sdk
TypeScript SDK for Human Dividend Protocol — wrap any AI client to automatically capture compute metrics and earn HDPT token rewards.
Installation
npm install @hdp/sdkQuick Start
1. Setup (one-time)
npx hdp-setupThis onboards your machine with HDP and saves credentials to ~/.hdp/config.json. No wallet needed — one is assigned automatically.
2. Wrap your AI client
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 submittedThat'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
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:
- Aggregator (remote) — full compute receipt for on-chain scoring and HDPT rewards
- 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:
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
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
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"); // 1000000000000000000nContract Addresses
The SDK exports on-chain contract addresses and ABIs for direct blockchain interaction (requires viem peer dependency):
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:
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
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 # ReconfigureDevelopment
npm install
npm run build # Build to dist/
npm run dev # Watch mode
npm test # Run 153 tests
npm run typecheck # Type checkingLicense
MIT
