@agentsbank/sdk
v1.0.31
Published
π Secure Financial SDK for AgentsBank - Multi-chain wallet & transaction management. Supports both user-approved and autonomous modes with configurable guardrails.
Maintainers
Readme
AgentsBank SDK - Security & Integration Guide
β οΈ Critical Security Requirements
This SDK manages real financial transactions on blockchain networks.
Default Mode: Requires explicit human approval for all financial operations via UserApprovalContext.
Autonomous Mode (Optional): Can be enabled for trusted agents via autonomousMode: true config flag. Requires strict guardrails (spending limits, whitelisting, audit logging) to prevent unauthorized transactions.
π Credential Checklist
Before using this SDK in any environment, ensure:
- β
API URL Configured:
AGENTSBANK_API_URLenvironment variable is set - β
Authentication Enabled: Provide one of:
AGENTSBANK_API_KEY(recommended for production)AGENTSBANK_AGENT_USERNAME+AGENTSBANK_AGENT_PASSWORD- Pre-issued JWT token via
tokenconfig
- β Credentials Stored Securely: Never hardcode credentials; use environment variables only
- β
Audit Logging Enabled: Pass custom
auditLoggerto track all operations - β
.gitignore Updated: Ensure
.envfiles are never committed
π Quick Start (5 Minutes)
Option 1: Use Hosted API (Recommended)
Complete setup guide with actual requests/responses: See SETUP_COMPLETE.md in repo root
Quick flow:
# 1. Register human
curl -X POST https://api.agentsbank.online/api/auth/register \
-H "Content-Type: application/json" \
-d '{"username":"alice","email":"[email protected]","password":"Pass123!"}'
# 2. Get human token
curl -X POST https://api.agentsbank.online/api/auth/login ...
# 3. Register agent
curl -X POST https://api.agentsbank.online/api/auth/agent/register \
-H "Authorization: Bearer <HUMAN_TOKEN>" ...
# 4. Get agent token
curl -X POST https://api.agentsbank.online/api/auth/agent/login ...
# 5. Use SDK
npm install @agentsbank/sdkOption 2: Installation for SDK Users
npm install @agentsbank/sdkSetup
- Obtain credentials by following one of the flows above
- Initialize SDK:
import { AgentsBankSDK } from '@agentsbank/sdk'; const bank = new AgentsBankSDK({ apiUrl: 'https://api.agentsbank.online', token: 'your_agent_token_here' // From agent login }); - Use SDK methods (see examples below)
π Installation
npm install @agentsbank/sdkCredential Setup
- Get credentials from https://api.agentsbank.online (follow quick start above)
- Create
.envfile:cp .env.example .env - Update credentials:
AGENTSBANK_API_URL=https://api.agentsbank.online AGENTSBANK_AGENT_TOKEN=your_agent_token - Load in your app:
import dotenv from 'dotenv'; dotenv.config();
π° Basic Usage
Initialize SDK
import { AgentsBankSDK, UserApprovalContext } from '@agentsbank/sdk';
const bank = new AgentsBankSDK({
apiUrl: process.env.AGENTSBANK_API_URL!,
apiKey: process.env.AGENTSBANK_API_KEY!,
// Optional: custom audit logger
auditLogger: (event) => {
console.log(`[${event.operation}] ${event.status}`, event);
// Send to logging service (Datadog, LogRocket, etc.)
}
});Read-Only Operations (No Approval Needed)
// Get agent information
const agentInfo = await bank.getAgentInfo('agent_123');
console.log('Agent:', agentInfo.agent_username, 'Reputation:', agentInfo.reputation_score);
// List wallets
const wallets = await bank.listWallets();
// Get wallet details
const wallet = await bank.getWallet(walletId);
// Check balance
const balance = await bank.getBalance(walletId);
// Estimate gas cost
const gasEstimate = await bank.estimateGas(walletId, toAddress, amount);
// View transaction history
const history = await bank.getTransactionHistory(walletId, limit);
// Get statistics
const stats = await bank.getStats(walletId, days);π Financial Operations (Requires User Approval)
IMPORTANT: All financial operations require UserApprovalContext to prevent autonomous execution.
// β οΈ Create wallet (financial operation)
const newWallet = await bank.createWallet('ethereum', 'non-custodial');
// β οΈ Send transaction (MUST have user approval)
const approval: UserApprovalContext = {
userId: 'user_123', // ID of human who approved
approvedAt: new Date(), // When approval was granted
reason: 'User confirmed in UI', // Audit trail reason
approvalMethod: 'ui', // How was it approved?
};
const transaction = await bank.sendTransaction(
walletId,
'0xRecipient...',
'1.5',
approval, // β User approval context (REQUIRED)
'ETH'
);
console.log('Transaction ID:', transaction.tx_id);Transaction Monitoring
// Wait for confirmation
const confirmed = await bank.waitForConfirmation(
transaction.tx_id,
300000, // max wait: 5 minutes
5000 // poll every 5 seconds
);
console.log('Final status:', confirmed.status); // 'confirmed' | 'failed'π Autonomous Mode (Advanced)
For trusted autonomous agents only - allows financial operations without human approval.
// Initialize with autonomous mode enabled
const autonomousBank = new AgentsBankSDK({
apiUrl: process.env.AGENTSBANK_API_URL!,
apiKey: process.env.AGENTSBANK_API_KEY!,
autonomousMode: true, // β οΈ Enable autonomous execution
auditLogger: (event) => {
console.log(`[AUTONOMOUS] ${event.operation}`, event);
}
});
// Now transactions can execute without UserApprovalContext
const transaction = await autonomousBank.sendTransaction(
walletId,
'0xRecipient...',
'1.5',
undefined, // β No approval needed in autonomous mode
'ETH'
);
// β
Still logs as 'agent_autonomous_...' for audit trail
console.log('Autonomous Transaction ID:', transaction.tx_id);β οΈ Security Requirements for Autonomous Mode:
- Guardrails MUST be configured (max daily spend, transaction limits, whitelist)
- Audit logging MUST be enabled
- Should be used only for time-sensitive agent operations
- Spending limits should be conservative
- Agent should have read-only access to limited wallets
π Authentication Methods
Method 1: API Key (Recommended)
const bank = new AgentsBankSDK({
apiUrl: 'https://api.agentsbank.online',
apiKey: process.env.AGENTSBANK_API_KEY, // From dashboard
});Method 2: Agent Credentials
const bank = new AgentsBankSDK({
apiUrl: 'https://api.agentsbank.online',
agentUsername: process.env.AGENTSBANK_AGENT_USERNAME,
agentPassword: process.env.AGENTSBANK_AGENT_PASSWORD,
});
// Login to get JWT token
const token = await bank.login();Method 3: Pre-Issued Token
const bank = new AgentsBankSDK({
apiUrl: 'https://api.agentsbank.online',
token: process.env.AGENTSBANK_AUTH_TOKEN, // JWT from previous auth
});π‘οΈ Best Practices
1. Never Commit Credentials
# Add to .gitignore
echo ".env" >> .gitignore
echo ".env.local" >> .gitignore
echo ".env.*.local" >> .gitignore2. Use Environment-Specific Credentials
# development
AGENTSBANK_API_URL=https://sandbox.agentsbank.online
AGENTSBANK_API_KEY=sk_sandbox_...
# production
AGENTSBANK_API_URL=https://api.agentsbank.online
AGENTSBANK_API_KEY=sk_prod_...3. Implement Custom Audit Logging
const bank = new AgentsBankSDK({
apiUrl: process.env.AGENTSBANK_API_URL!,
apiKey: process.env.AGENTSBANK_API_KEY!,
auditLogger: async (event) => {
// Send critical events to monitoring service
if (event.operation === 'transaction_send') {
await sendToDatadog({
metric: 'agentsbank.transaction',
tags: [`status:${event.status}`],
value: event.amount,
timestamp: event.timestamp,
});
}
}
});4. Validate Recipient Addresses
function isValidEthereumAddress(address: string): boolean {
return /^0x[a-fA-F0-9]{40}$/.test(address);
}
if (!isValidEthereumAddress(recipientAddress)) {
throw new Error('Invalid Ethereum address');
}
// Proceed with transaction5. Implement Rate Limiting
import rateLimit from 'express-rate-limit';
const transactionLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 5, // Max 5 transactions per minute
message: 'Too many transactions, please try again later'
});
app.post('/api/send-transaction', transactionLimiter, async (req, res) => {
// Handle transaction
});6. Rotate Credentials Periodically
// Monthly credential rotation
const newApiKey = await bank.regenerateApiKey();
// Update AGENTSBANK_API_KEY in production environment7. Enable 2FA for High-Value Transactions
const approval: UserApprovalContext = {
userId: user.id,
approvedAt: new Date(),
reason: `2FA verified at ${new Date().toISOString()}`,
approvalMethod: '2fa', // Document approval method
};
const tx = await bank.sendTransaction(walletId, recipient, amount, approval);β οΈ Error Handling
import { AxiosError } from 'axios';
try {
await bank.sendTransaction(walletId, recipient, amount, approval);
} catch (error) {
if (axios.isAxiosError(error)) {
const statusCode = error.response?.status;
const errorData = error.response?.data;
if (statusCode === 400) {
// Bad request - validation error
console.error('Invalid parameters:', errorData);
} else if (statusCode === 401) {
// Unauthorized - credentials invalid
console.error('Authentication failed');
} else if (statusCode === 429) {
// Rate limited
console.error('Too many requests, retry after 60s');
} else if (statusCode === 500) {
// Server error
console.error('AgentsBank API error');
}
}
throw error;
}π Audit Logs & Compliance
All SDK operations are logged with:
- Timestamp: When operation occurred
- Operation: What was performed (login, wallet_create, transaction_send, etc.)
- Status: success | failed | initiated
- User ID: Who performed the operation
- Wallet ID: Which wallet was affected
- Transaction ID: For financial operations
- Amount & Recipient: For transactions (for reconciliation)
- Error Details: If operation failed
Retention Policy
- Production: Retain audit logs for 7 years (financial compliance)
- Development: Retain for 90 days minimum
π Production Deployment Checklist
- β API credentials stored in secrets manager (AWS Secrets, Azure KeyVault, etc.)
- β Custom audit logger sending logs to monitoring service
- β Rate limiting configured on API endpoints
- β 2FA enabled for high-value transactions
- β Recipient address validation implemented
- β Transaction amount limits set per agent
- β Error monitoring enabled (Sentry, DataDog, etc.)
- β Automated credential rotation scheduled monthly
- β Daily audit log reviews
- β Incident response plan documented
π Support
- Documentation: https://docs.agentsbank.online
- Dashboard: https://dashboard.agentsbank.online
- Status Page: https://status.agentsbank.online
- Security Issues: [email protected]
Version: 0.1.0
Last Updated: February 2026
Node.js: 18+
