@homotopic-yoneda/sdk
v1.0.0-beta
Published
Yoneda SDK for AI agent payments and banking
Maintainers
Readme
Yoneda SDK
TypeScript SDK for Yoneda Protocol - AI agent payments and banking infrastructure.
Installation
npm install @homotopic-yoneda/sdkQuick Start
Production
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)
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:
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 transactionROUTE_NOT_FOUND- No route to recipientHUB_UNAVAILABLE- Hub is offline or unavailablePOLICY_VIOLATION- Transaction violates spending policyCOMPLIANCE_REQUIRED- Compliance check requiredCOMPLIANCE_FAILED- Compliance check failedINVALID_CONFIG- Invalid configurationREGISTRATION_FAILED- Agent registration failedCONNECTION_FAILED- Hub connection failedCLOSE_FAILED- Hub disconnection failedPAYMENT_FAILED- Payment transaction failed
Troubleshooting
Payment Fails with INSUFFICIENT_BALANCE
Check your balance:
const balance = await account.queryBalance();
console.log(`Current balance: $${balance}`);Payment Fails with POLICY_VIOLATION
Check your spending policy:
// 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:
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():
const stream = account.stream("agent:recipient", 0.01, "second");
// Stop after 5 seconds
setTimeout(() => {
stream.stop();
}, 5000);State Not Persisting
Check storage configuration:
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
- Update imports:
// Old
import { YonedaClient } from "@homotopic-yoneda/sdk";
// New - same import
import { createClient } from "@homotopic-yoneda/sdk";- Use sandbox mode for testing:
// Use sandbox mode instead of mock
const client = createClient({
apiKey: "sandbox-key",
network: "sandbox", // Changed from "testnet" to "sandbox"
});- Real cryptographic keys are now used automatically:
// No changes needed - keys are generated automatically
const account = await client.registerAgent({
name: "my-agent",
baseCurrency: "USD",
});Performance Optimization
Use WASM for Cryptographic Operations
// 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 JSBatch Operations
For multiple payments, consider using the Account's batch capabilities:
// SDK automatically batches operations when possible
// No manual batching neededConnection Pooling
The SDK manages connections automatically. Reuse account instances:
// 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 operationDocumentation
See docs.yoneda.io for complete documentation.
License
MIT
