Lending Protocol Operations
This example demonstrates how to interact with DeFi lending protocols like Aave, including querying yield opportunities and executing supply operations.
The Code
import {
Chaos,
WALLET_MODEL,
extractText,
extractBlocks,
isTableBlock,
isTransactionActionBlock,
hasRisks,
type Response,
type RequestMetadata,
} from '@chaoslabs/ai-sdk';
const config = {
apiKey: process.env.CHAOS_STAGING_API_KEY || 'your-api-key',
baseUrl: process.env.CHAOS_STAGING_URL || 'https://ai-staging.chaoslabs.co',
};
const walletConfig: RequestMetadata = {
user_id: 'example-user',
session_id: `example-session-${Date.now()}`,
wallet_id: process.env.TEST_PORTFOLIO_ID || '0x...',
};
async function main() {
const chaos = new Chaos({
apiKey: config.apiKey,
baseUrl: config.baseUrl,
});
// Different lending operations to test
const lendingQueries = [
{
name: 'Check Yield Opportunities',
query: "What's the best yield I can get on my USDC?",
},
{
name: 'Supply to Aave',
query: 'Supply 100 USDC to Aave on Ethereum',
},
{
name: 'Check Lending Positions',
query: 'Show my current Aave positions',
},
];
for (const { name, query } of lendingQueries) {
console.log(`\n--- ${name} ---`);
console.log(`Query: "${query}"`);
try {
const response = await chaos.chat.responses.create({
model: WALLET_MODEL,
input: [{ type: 'message', role: 'user', content: query }],
metadata: walletConfig,
});
displayLendingResponse(response);
} catch (error) {
console.log(`Error: ${(error as Error).message}`);
}
}
}
function displayLendingResponse(response: Response) {
if (response.status === 'failed') {
console.log(`Failed: ${response.error?.message}`);
return;
}
// Display text explanation
const text = extractText(response);
if (text) {
console.log('\nAgent Response:');
console.log(text.slice(0, 300));
if (text.length > 300) console.log('...');
}
const blocks = extractBlocks(response);
// Display yield/position tables
const tables = blocks.filter(isTableBlock);
for (const table of tables) {
console.log(`\nTable: ${table.title}`);
console.log(` Columns: ${table.tableHeaders.join(', ')}`);
console.log(` Rows: ${table.tableRows.length}`);
// Preview data
for (const row of table.tableRows.slice(0, 3)) {
const formatted = row.map(cell => String(cell).slice(0, 20)).join(' | ');
console.log(` ${formatted}`);
}
}
// Display transaction actions (supply, withdraw)
const actions = blocks.filter(isTransactionActionBlock);
for (const action of actions) {
console.log(`\nTransaction: ${action.notes || 'Lending Operation'}`);
if (action.primitives) {
for (const prim of action.primitives) {
console.log(` ${prim.primitive}`);
if (prim.display?.headline) {
console.log(` ${prim.display.headline}`);
}
}
}
if (action.risks?.level) {
console.log(`\n Risk Level: ${action.risks.level}`);
}
}
// Overall risk check
if (hasRisks(response)) {
console.log('\n[!] This operation has associated risks. Review carefully.');
}
}
main();Lending Query Types
The AI understands various lending-related queries:
Yield Discovery
// Find best yields
await query("What's the best yield I can get on my USDC?");
await query('Where can I earn the most on my ETH?');
await query('Compare USDC yields across protocols');
// Response includes tables with:
// - Protocol name
// - APY/APR
// - TVL
// - Risk indicatorsSupply Operations
// Supply to specific protocol
await query('Supply 100 USDC to Aave on Ethereum');
await query('Deposit 1 ETH into Compound');
await query('Lend my stablecoins for the best yield');
// Response includes:
// - TransactionActionBlock with supply primitive
// - Protocol details
// - Expected APY
// - Risk assessmentPosition Management
// Check positions
await query('Show my current Aave positions');
await query('What am I lending on Compound?');
await query("What's my health factor?");
// Response includes tables with:
// - Supplied assets and amounts
// - Earned interest
// - Health factor (if borrowing)
// - Liquidation thresholdsLending Primitives
Lending operations return specific primitive types:
// Supply primitive
{
primitive: 'supply',
params: {
amount_in: '100',
token_in: 'USDC',
protocol: 'Aave V3',
chain: 'ethereum',
apy: '4.5%',
},
display: {
headline: 'Supply 100 USDC to Aave V3',
action_verb: 'Supply',
line_items: [
{ label: 'Amount', value: '100 USDC' },
{ label: 'Protocol', value: 'Aave V3' },
{ label: 'Current APY', value: '4.5%' },
],
},
}
// Withdraw primitive
{
primitive: 'withdraw',
params: {
amount_out: '50',
token_out: 'USDC',
protocol: 'Aave V3',
},
display: {
headline: 'Withdraw 50 USDC from Aave V3',
action_verb: 'Withdraw',
line_items: [
{ label: 'Amount', value: '50 USDC' },
{ label: 'Remaining', value: '50 USDC' },
],
},
}Supported Protocols
The Chaos AI supports major lending protocols:
- Aave V2/V3 - Multi-chain lending
- Compound V2/V3 - Ethereum lending
- Morpho - Optimized lending rates
- Spark - DAI-focused lending
The AI automatically finds the best opportunities across supported protocols.
Next Steps
- Review error handling for production code
- Explore perpetuals trading