Complete reference for the DefiBrain Unified DeFi Router API
npm install @defibrain/sdk
import { DefiBrainClient } from '@defibrain/sdk';
const client = new DefiBrainClient({
apiKey: 'your-api-key',
apiUrl: 'https://apibrain.oxg.fi/v1',
chainId: 1, // Ethereum mainnet
});
// Optimize yield for an asset (direct mode by default)
const result = await client.optimizeYield({
asset: '0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9', // WETH
amount: '1000000000000000000', // 1 WETH
strategy: 'balanced',
});
console.log(`Best protocol: ${result.protocol}`);
console.log(`Estimated APR: ${result.estimatedAPR}%`);
All API requests require authentication using an API key. Include your API key in the Authorization header:
Authorization: Bearer your-api-key-here
Get your API key from the registration page.
/v1/health
Check the health status of the API and all connected services.
{
"status": "healthy",
"version": "1.0.0",
"uptime": 3600,
"services": {
"database": { "status": "healthy" },
"redis": { "status": "healthy" },
"rpc": {
"ethereum": { "status": "healthy" }
}
},
"protocols": ["pendle", "curve", "aave", "morpho"]
}
/v1/optimize-yield
Find the optimal protocol and strategy for maximizing yield on an asset.
{
"asset": "0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9",
"amount": "1000000000000000000",
"strategy": "balanced",
"minAPR": 3.0,
"maxRisk": "low",
"chainId": 1
}
{
"protocol": "aave",
"action": "supply",
"estimatedAPR": 5.5,
"estimatedGas": "200000",
"riskLevel": "low",
"confidence": 0.95,
"transaction": {
"to": "0x...",
"data": "0x...",
"value": "0"
}
}
/v1/swap/optimal
Find the optimal swap route between two tokens.
{
"tokenIn": "0x...",
"tokenOut": "0x...",
"amount": "1000000000000000000",
"slippage": 1.0,
"preferProtocol": "curve",
"chainId": 1
}
{
"protocol": "curve",
"route": {
"fromToken": "0x...",
"toToken": "0x...",
"amount": "1000000000000000000",
"estimatedAmount": "990000000000000000",
"protocols": ["curve"]
},
"estimatedGas": "150000",
"transaction": {
"to": "0x...",
"data": "0x...",
"value": "0"
}
}
/v1/protocols/available
Get list of available protocols. Optionally filter by action type.
action (optional): Filter by action type (supply, borrow, swap,
deposit, withdraw)chainId (optional): Chain ID (default: 1)GET /v1/protocols/available?action=swap&chainId=1
{
"action": "swap",
"chainId": 1,
"protocols": ["curve", "1inch"]
}
/v1/usage
Get your API usage statistics. This endpoint does not count against your rate limit.
{
"message": "Usage statistics",
"stats": {
"totalRequests": 150,
"requestsToday": 15,
"requestsThisMonth": 150,
"callsToday": 15,
"callsThisMonth": 150,
"limit": 100,
"endpoints": {
"/v1/optimize-yield": 10,
"/v1/swap/optimal": 5
},
"averageResponseTime": 342
}
}
/v1/execute
Execute an action on a specific protocol. Returns transaction data to be signed by the user.
{
"protocol": "aave",
"action": "supply",
"params": {
"asset": "0x...",
"amount": "1000000000000000000"
},
"chainId": 1
}
{
"transactionHash": "0x0000000000000000000000000000000000000000",
"protocol": "aave",
"action": "supply",
"status": "pending",
"transaction": {
"to": "0x...",
"data": "0x...",
"value": "0"
}
}
Main client class for interacting with the DefiBrain API.
new DefiBrainClient(config: {
apiKey: string;
apiUrl?: string;
chainId?: number;
})
optimizeYield(request: OptimizeYieldRequest): Promise<OptimizeYieldResponse>
Find optimal yield strategy for an asset.
findOptimalSwap(request: FindSwapRequest): Promise<FindSwapResponse>
Find optimal swap route between tokens.
executeAction(request: ExecuteActionRequest): Promise<ExecuteActionResponse>
Execute an action on a protocol.
getAvailableProtocols(action?: string): Promise<string[]>
Get available protocols, optionally filtered by action.
healthCheck(): Promise<HealthCheckResponse>
Check API health status.
getUsageStats(): Promise<UsageStats>
Get your API usage statistics.
The SDK includes powerful helpers to simplify common operations like wallet connection, transaction signing, and protocol-specific actions.
Connect to MetaMask or other Web3 wallets and manage wallet state.
import { WalletHelper } from '@defibrain/sdk';
const wallet = new WalletHelper();
connect(): Promise<WalletInfo>
Connect to MetaMask or injected wallet. Requests user permission.
getWalletInfo(): Promise<WalletInfo | null>
Get current wallet info without requesting connection.
getBalance(): Promise<string>
Get native token balance (ETH) in wei.
getTokenBalance(tokenAddress: string): Promise<string>
Get ERC-20 token balance.
getProvider(): WalletProvider | null
Get the wallet provider instance.
getChainId(): number
Get current chain ID.
import { WalletHelper } from '@defibrain/sdk';
const wallet = new WalletHelper();
// Connect wallet
const walletInfo = await wallet.connect();
console.log(`Connected: ${walletInfo.address}`);
console.log(`Chain ID: ${walletInfo.chainId}`);
// Get balances
const ethBalance = await wallet.getBalance();
const usdcBalance = await wallet.getTokenBalance('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');
console.log(`ETH: ${ethBalance} wei`);
console.log(`USDC: ${usdcBalance}`);
Sign and send transactions directly to the blockchain without going through the backend.
import { TransactionHelper, WalletHelper } from '@defibrain/sdk';
const wallet = new WalletHelper();
await wallet.connect();
const txHelper = new TransactionHelper(
wallet.getProvider()!,
wallet.getChainId()
);
signAndSend(tx: TransactionRequest): Promise<string>
Sign and send a transaction. Returns transaction hash.
waitForConfirmation(txHash: string, confirmations?: number): Promise<TransactionReceipt>
Wait for transaction confirmation. Default: 1 confirmation.
signSendAndWait(tx: TransactionRequest, confirmations?: number): Promise<TransactionReceipt>
Sign, send, and wait for confirmation in one call.
estimateGas(tx: TransactionRequest): Promise<string>
Estimate gas cost for a transaction.
getGasPrice(): Promise<string>
Get current gas price.
import { DefiBrainClient, TransactionHelper, WalletHelper } from '@defibrain/sdk';
const client = new DefiBrainClient({ apiKey: 'your-key' });
const wallet = new WalletHelper();
await wallet.connect();
const txHelper = new TransactionHelper(wallet.getProvider()!, wallet.getChainId());
// Optimize yield and get transaction
const result = await client.optimizeYield({
asset: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
amount: '1000000',
strategy: 'max_yield',
});
// Sign and send transaction
if (result.transaction) {
// Option 1: Sign and send, then wait
const txHash = await txHelper.signAndSend(result.transaction);
console.log(`Transaction sent: ${txHash}`);
const receipt = await txHelper.waitForConfirmation(txHash);
console.log(`Confirmed in block: ${receipt.blockNumber}`);
// Option 2: All in one call
// const receipt = await txHelper.signSendAndWait(result.transaction);
}
Protocol-specific helpers for Pendle PT/YT operations.
import { DefiBrainClient, PendleHelper, TransactionHelper, WalletHelper } from '@defibrain/sdk';
const client = new DefiBrainClient({ apiKey: 'your-key' });
const wallet = new WalletHelper();
await wallet.connect();
const txHelper = new TransactionHelper(wallet.getProvider()!, wallet.getChainId());
const pendleHelper = new PendleHelper(client, txHelper);
optimizeYieldWithPendle(asset: string, amount: string, strategy?: string): Promise<OptimizeYieldResponse>
Find best Pendle yield opportunities for an asset.
swapPTtoYT(market: string, amount: string, execute?: boolean): Promise<any>
Swap Principal Token (PT) to Yield Token (YT).
swapYTtoPT(market: string, amount: string, execute?: boolean): Promise<any>
Swap Yield Token (YT) to Principal Token (PT).
redeemPT(market: string, amount: string, execute?: boolean): Promise<any>
Redeem Principal Token (PT) at maturity.
getPTInfo(ptAddress: string): Promise<PendlePTInfo>
Get information about a Pendle PT token.
getYTInfo(ytAddress: string): Promise<PendleYTInfo>
Get information about a Pendle YT token.
import { DefiBrainClient, PendleHelper, TransactionHelper, WalletHelper } from '@defibrain/sdk';
const client = new DefiBrainClient({ apiKey: 'your-key' });
const wallet = new WalletHelper();
await wallet.connect();
const txHelper = new TransactionHelper(wallet.getProvider()!, wallet.getChainId());
const pendleHelper = new PendleHelper(client, txHelper);
// Optimize yield with Pendle
const result = await pendleHelper.optimizeYieldWithPendle(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
'1000000', // 1 USDC
'max_yield'
);
// Swap PT to YT (prepare only, don't execute)
const swapResult = await pendleHelper.swapPTtoYT(
'0x...', // Market address
'1000000',
false // Don't execute, just prepare
);
// Redeem PT at maturity
const redeemResult = await pendleHelper.redeemPT(
'0x...', // Market address
'1000000',
false
);
Protocol-specific helpers for Aave V3 lending and borrowing operations.
import { DefiBrainClient, AaveHelper, TransactionHelper, WalletHelper } from '@defibrain/sdk';
const client = new DefiBrainClient({ apiKey: 'your-key' });
const wallet = new WalletHelper();
await wallet.connect();
const txHelper = new TransactionHelper(wallet.getProvider()!, wallet.getChainId());
const aaveHelper = new AaveHelper(client, txHelper);
supply(asset: string, amount: string, execute?: boolean): Promise<any>
Supply assets to Aave V3. Set execute=true to automatically sign and send.
withdraw(asset: string, amount: string, execute?: boolean): Promise<any>
Withdraw assets from Aave V3.
borrow(asset: string, amount: string, execute?: boolean): Promise<any>
Borrow assets from Aave V3.
repay(asset: string, amount: string, execute?: boolean): Promise<any>
Repay borrowed assets to Aave V3.
import { DefiBrainClient, AaveHelper, TransactionHelper, WalletHelper } from '@defibrain/sdk';
const client = new DefiBrainClient({ apiKey: 'your-key' });
const wallet = new WalletHelper();
await wallet.connect();
const txHelper = new TransactionHelper(wallet.getProvider()!, wallet.getChainId());
const aaveHelper = new AaveHelper(client, txHelper);
// Supply to Aave (prepare only)
const supplyResult = await aaveHelper.supply(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
'1000000', // 1 USDC
false // Don't execute, just prepare
);
// Withdraw from Aave
const withdrawResult = await aaveHelper.withdraw(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
'1000000',
false
);
// Borrow from Aave
const borrowResult = await aaveHelper.borrow(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
'500000', // 0.5 USDC
false
);
// Repay borrowed amount
const repayResult = await aaveHelper.repay(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
'500000',
false
);
Utility functions for validating addresses and amounts.
validateAddress(address: string, name?: string): boolean
Validate Ethereum address format. Throws error if invalid.
validateAmount(amount: string, name?: string): boolean
Validate amount is a valid number string. Throws error if invalid.
formatAmount(amount: string, decimals: number): string
Format amount from wei to readable format (e.g., "1000000000000000000" → "1").
parseAmount(amount: string, decimals: number): string
Parse amount from readable format to wei (e.g., "1.5" → "1500000000000000000").
import { validateAddress, validateAmount, formatAmount, parseAmount } from '@defibrain/sdk';
// Validate address
validateAddress('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'); // true
validateAddress('invalid'); // throws error
// Validate amount
validateAmount('1000000'); // true
validateAmount('abc'); // throws error
// Format amount (wei to readable)
formatAmount('1000000000000000000', 18); // "1"
formatAmount('1000000', 6); // "1" (for USDC with 6 decimals)
// Parse amount (readable to wei)
parseAmount('1.5', 18); // "1500000000000000000"
parseAmount('100', 6); // "100000000" (for USDC)
Rate limits are enforced per API key and plan tier:
100 requests/day
60 requests/minute
10,000 requests/day
300 requests/minute
100,000 requests/day
1,000 requests/minute
When rate limits are exceeded, the API returns a 429 Too Many Requests status
code.
All errors follow a consistent format:
{
"error": {
"message": "Error description",
"code": "ERROR_CODE"
}
}
UNAUTHORIZED - Invalid or missing API keyVALIDATION_ERROR - Invalid request parametersRATE_LIMIT_EXCEEDED - Rate limit exceededPROTOCOLS_ERROR - Error getting protocolsOPTIMIZATION_ERROR - Error during optimizationCheck out the examples or reach out to our support team.