@agentsbankai/sdk
v1.0.32
Published
Official SDK for AgentsBank.ai - Crypto banking infrastructure for AI agents
Maintainers
Readme
@agentsbank/sdk
Official TypeScript/JavaScript SDK for AgentsBank - Crypto banking infrastructure for AI agents.
Version: 1.0.32 - Wallet creation fixed! All 4 chains working. JWT auto-refresh production-ready.
What's Fixed in v1.0.6
- ✅ Wallet Creation Working - Ethereum, BSC, Solana, Bitcoin all working perfectly
- ✅ JWT Auto-Refresh - Tokens automatically renew before 7-day expiration (no more 401s!)
- ✅ Better Error Messages - Clearer error responses from wallet operations
- ✅ Unique Wallet Constraint - One wallet per agent per chain enforced
- 🚀 Ready for Production - All critical features tested and working
Features
- 🔐 Full Authentication - Register, login, API keys, JWT tokens with auto-refresh
- 💰 Multi-Chain Wallets - ✅ Ethereum, ✅ BSC, ✅ Solana, ✅ Bitcoin (all working!)
- 📤 Send Transactions - Native tokens + USDC/USDT on all chains
- ✍️ Message Signing - Prove wallet ownership
- 📊 Balance & History - Real-time blockchain data
- 🔒 TypeScript First - Full type safety
- 🔄 Token Auto-Refresh - Automatic JWT renewal every 6 days (NEW!)
- ⚡ Enterprise Features
- Automatic retry with exponential backoff (3 attempts by default)
- Response caching (50-70x faster reads)
- Typed error handling (19 error codes)
- Webhook notifications (7 event types)
- Guardrails (spending limits, whitelisting)
- SDK helpers (sendSafe, sendMultiple, hasEnoughFunds)
- 💰 Always Free - 0% platform fees, pay only network gas
- 📈 Monitoring - Health checks, metrics, real-time dashboard
Installation
npm install @agentsbank/sdk
# or
yarn add @agentsbank/sdk
# or
pnpm add @agentsbank/sdkQuick Start
import { createClient } from '@agentsbank/sdk';
// Create client
const client = createClient({
baseUrl: 'https://api.agentsbank.online'
});
// Register a new agent
const agent = await client.register({
human_username: 'myuser',
human_email: '[email protected]',
first_name: 'John',
last_name: 'Doe',
agent_password: 'SecurePass123!'
});
// Token is auto-set after registration
console.log('Agent ID:', agent.agent_id);
console.log('Wallets:', agent.wallets);
// ⚠️ SAVE RECOVERY WORDS SECURELY!
console.log('Recovery:', agent.recovery_words);Authentication
Using API Key
const client = createClient({
apiKey: 'your-api-key'
});Using JWT Token
const client = createClient({
token: 'your-jwt-token'
});
// Or set later
client.setToken(token);Login
await client.login({
agent_username: 'agent_123456_abc',
agent_password: 'SecurePass123!'
});
// Token is auto-setWallets
Create Wallet
// Supported chains: 'ethereum', 'bsc', 'solana', 'bitcoin'
const wallet = await client.createWallet('solana');
console.log(wallet.address); // Solana address
console.log(wallet.wallet_id); // Use for transactionsGet Balance
const { balance } = await client.getBalance(walletId);
console.log(`SOL: ${balance.SOL}`);
console.log(`USDC: ${balance.USDC}`);Transactions
Send Native Token
const tx = await client.send(walletId, {
to_address: 'recipient_address',
amount: '0.1' // 0.1 SOL/ETH/BNB/BTC
});
console.log(`TX Hash: ${tx.tx_hash}`);
console.log(`Status: ${tx.status}`);Send Token (USDC/USDT)
const tx = await client.send(walletId, {
to_address: 'recipient_address',
amount: '100',
currency: 'USDC'
});Estimate Fees
const estimate = await client.estimateGas(
walletId,
'recipient_address',
'1.0'
);
console.log(`Estimated gas: ${estimate.estimated_gas}`);Message Signing
Sign messages for authentication with external services:
const { signature } = await client.signMessage(
walletId,
'Sign in to MyApp: nonce=abc123'
);
// signature can be verified on-chainTransaction History
const { transactions } = await client.getTransactionHistory(walletId, 50);
for (const tx of transactions) {
console.log(`${tx.type}: ${tx.amount} ${tx.currency} -> ${tx.to_address}`);
}Supported Chains
| Chain | Native Token | Tokens | Address Format | |-------|--------------|--------|----------------| | Ethereum | ETH | USDT, USDC | 0x... | | BSC | BNB | USDT, USDC | 0x... | | Solana | SOL | USDT, USDC | Base58 | | Bitcoin | BTC | - | bc1... (SegWit) |
Error Handling
AgentsBank SDK includes 19 typed error codes for precise error handling:
import { AgentsBankError, ErrorCode } from '@agentsbank/sdk';
try {
await client.send(walletId, { to_address, amount: '1000' });
} catch (error) {
if (error instanceof AgentsBankError) {
switch (error.code) {
case ErrorCode.INSUFFICIENT_FUNDS:
console.error('Not enough balance');
break;
case ErrorCode.INVALID_ADDRESS:
console.error('Invalid recipient address');
break;
case ErrorCode.TIMEOUT:
console.error('Request timeout (SDK already retried)');
break;
case ErrorCode.RATE_LIMITED:
console.error('Rate limited (SDK already retried)');
break;
default:
console.error(`Error ${error.code}: ${error.message}`);
}
}
}Automatic Retry
Transient errors (network timeouts, temporary 5xx errors, rate limits) are automatically retried with exponential backoff:
// Configure retry behavior
const client = createClient({
baseUrl: 'https://api.agentsbank.online',
retryConfig: {
maxAttempts: 3, // Default
initialDelayMs: 100, // Default
maxDelayMs: 5000 // Default
}
});Automatic retry applies to:
- ✅ Network timeouts
- ✅ Temporary 5xx server errors
- ✅ Rate limit (429) responses
- ✅ RPC failures
Not retried (fail immediately):
- ❌ Invalid address format
- ❌ Insufficient funds
- ❌ Authentication errors
- ❌ Permission denied
- ❌ Resource not found
Configuration Options
const client = createClient({
// API endpoint (default: https://api.agentsbank.online)
baseUrl: 'https://api.agentsbank.online',
// Authentication (pick one)
apiKey: 'your-api-key',
token: 'your-jwt-token',
// Request timeout in ms (default: 30000)
timeout: 60000,
// Retry configuration (default shown)
retryConfig: {
maxAttempts: 3,
initialDelayMs: 100,
maxDelayMs: 5000
},
// Guardrails for spending limits
guardrails: {
dailyLimitUSD: 5000,
maxPerTxUSD: 1000,
whitelistedAddresses: ['0x...']
},
// Custom fetch implementation (for Node.js < 18)
fetch: customFetch,
// Automatic token refresh (NEW!)
autoRefresh: {
enabled: true, // Default: true
refreshBeforeDays: 6, // Refresh at 6 days (default)
storeCredentials: true, // Store for auto re-login (default: false)
credentials: { // Auto re-login if token expires
agent_username: 'agent_xxx',
agent_password: 'your_password'
}
}
});Automatic Token Refresh (NEW!)
JWT tokens expire after 7 days. The SDK automatically refreshes them on the same device to prevent wallet access loss.
How It Works
- Automatic Background Refresh: SDK checks token age every 6 hours
- Proactive Refresh: Refreshes at 6 days (before 7-day expiration)
- Device-Local: No credential exposure; everything on same device
- Auto Re-login: If token expires, SDK can automatically re-authenticate
Enable Auto-Refresh with Credentials
const client = createClient({
autoRefresh: {
enabled: true,
storeCredentials: true,
credentials: {
agent_username: 'agent_xxx_abc123',
agent_password: 'YourPassword123!' // Stored securely on device
}
}
});
// Now use SDK normally for 7+ days without manual token refresh!
const balance = await client.getBalance(walletId);
// ↑ If token would expire, SDK refreshes it automaticallyManual Token Status Check
// Check token age
const ageInDays = client.getTokenAgeInDays();
console.log(`Token age: ${ageInDays?.toFixed(1)} days`);
// Check time until expiration
const expiresInDays = client.getTokenExpiresInDays();
console.log(`Expires in: ${expiresInDays?.toFixed(1)} days`);Recovery Flows
If auto-refresh is disabled or re-login fails:
// Path A: Manual refresh (before expiry)
await client.refreshToken();
// Path B: Re-login with credentials
await client.login({
agent_username: 'agent_xxx',
agent_password: 'your_password'
});
// Path C: Use API key (no expiration)
const client = createClient({
apiKey: 'your-api-key-uuid'
});Production Recommendations
import fs from 'fs';
import crypto from 'crypto';
// 1. Encrypt credentials before storing
function storeCredentialsSecurely(username, password) {
const encrypted = encrypt(
JSON.stringify({ username, password }),
process.env.ENCRYPTION_KEY
);
fs.writeFileSync('./credentials.enc', encrypted);
fs.chmodSync('./credentials.enc', 0o600);
}
// 2. Load and use
const credentials = JSON.parse(decrypt(
fs.readFileSync('./credentials.enc'),
process.env.ENCRYPTION_KEY
));
const client = createClient({
autoRefresh: {
enabled: true,
storeCredentials: true,
credentials
}
});
// 3. Monitor expiration
setInterval(() => {
const expiresIn = client.getTokenExpiresInDays();
if (expiresIn && expiresIn < 1) {
logger.warn('⚠️ Token expiring soon');
}
}, 60000);Configuration Options
Available since v1.0.5: Convenient helper methods that combine best practices:
sendSafe - Pre-flight Validation
// Includes balance check, gas estimation, and auto-retry
const tx = await client.sendSafe(walletId, {
to_address: recipient,
amount: '1.0'
});sendMultiple - Batch Operations
// Send to multiple recipients efficiently
const results = await client.sendMultiple(walletId, [
{ to_address: '0x111...', amount: '1.0' },
{ to_address: '0x222...', amount: '2.0' },
{ to_address: '0x333...', amount: '1.5' }
]);
results.forEach((tx, i) => {
console.log(`Recipient ${i+1}: ${tx.tx_hash}`);
});hasEnoughFunds - Balance Check
const hasEnough = await client.hasEnoughFunds(walletId, '100');
if (!hasEnough) {
console.log('Insufficient balance');
}Webhooks
Subscribe to transaction events:
// Register webhook
const webhook = await client.registerWebhook({
url: 'https://your-server.com/webhook',
events: ['transaction.sent', 'transaction.received']
});
// Verify webhook signature (HMAC-SHA256)
import crypto from 'crypto';
const signature = req.headers['x-agentsbank-signature'];
const payload = req.body;
const verified = crypto
.createHmac('sha256', webhook.secret)
.update(JSON.stringify(payload))
.digest('hex') === signature;Supported events:
transaction.sent- Outgoing transactiontransaction.received- Incoming transactiontransaction.confirmed- Transaction confirmedwallet.created- New walletbalance.changed- Balance updateerror.occurred- Error eventagent.login- Agent login
Guardrails
Enforce spending limits and whitelisting:
// Set on client
const client = createClient({
guardrails: {
dailyLimitUSD: 10000,
maxPerTxUSD: 5000,
whitelistedAddresses: [
'0x1234567890123456789012345678901234567890'
]
}
});
// Automatic enforcement
try {
await client.send(walletId, {
to_address: '0xunknown...', // Not whitelisted
amount: '6000' // Over max per tx
});
} catch (e) {
// "Rejected: transaction exceeds max per tx limit"
}Caching
Responses are automatically cached for performance:
Balance lookup: 30 seconds (50-70x faster)
Transaction list: 2 minutes
Gas estimate: 5 minutes
Wallet info: 24 hoursCaching is transparent and automatic. Failed cache lookups gracefully fall back to direct RPC calls.
Monitoring
Check system health and metrics:
// Health check
const health = await fetch('https://api.agentsbank.online/health');
// { status: 'ok', timestamp: '...', version: '1.0.6' }
// Metrics
const metrics = await fetch('https://api.agentsbank.online/api/metrics');
// { requests_per_second: 45, cache_hit_rate: 0.68, ... }
// Live dashboard
// https://api.agentsbank.online/api/monitoring/dashboardTypeScript
Full type definitions included:
import type {
Chain,
Currency,
WalletInfo,
Transaction,
SendTransactionRequest
} from '@agentsbank/sdk';
const chain: Chain = 'solana';
const currency: Currency = 'USDC';Support
- 📧 Email: [email protected]
- 🌐 Website: https://agentsbank.online
- 📚 Docs: https://docs.agentsbank.online
- 📊 API Docs: https://api.agentsbank.online/docs
- 📈 Dashboard: https://api.agentsbank.online/api/monitoring/dashboard
Pricing
Always Free 🎉
- 0% platform fees (completely free)
- Only blockchain network/gas fees apply
- Unlimited wallets and transactions
- No credit card required
Deployment
Auto-Updates
The SDK automatically checks for updates from the server:
// Automatic version checking (24-hour intervals)
const client = createClient({
baseUrl: 'https://api.agentsbank.online'
// Auto-update checking enabled by default
});Check version status manually:
const response = await fetch('https://api.agentsbank.online/api/sdk/version');
const { version, required, releaseDate } = await response.json();Node.js Version
Requires Node.js 18+ (for native fetch support). For older versions, provide custom fetch:
import fetch from 'node-fetch';
const client = createClient({
baseUrl: 'https://api.agentsbank.online',
fetch
});License
MIT © AgentsBank
