DeFi Swap

Updated

This recipe shows the complete flow for executing a token swap through the Chaos AI SDK: sending a wallet request, extracting the transaction action block, identifying the swap primitive, and checking risk information before proceeding.

[@portabletext/react] Unknown block type "callout", specify a component for it in the `components.types` prop

Full Example

swap.ts
import {
  Chaos,
  WALLET_MODEL,
  extractTransactionBlocks,
  extractPrimitives,
  isSwapPrimitive,
  hasRisks,
  hasBlockers,
  getAllWarnings,
  getAllBlockers,
  getHighestRiskLevel,
} from '@chaoslabs/ai-sdk';
 
const chaos = new Chaos({ apiKey: process.env.CHAOS_API_KEY! });
 
// Step 1: Send a swap request
const response = await chaos.chat.responses.create({
  model: WALLET_MODEL,
  input: [
    {
      type: 'message',
      role: 'user',
      content: 'Swap 1 ETH for USDC on Ethereum',
    },
  ],
  metadata: {
    user_id: 'user-123',
    session_id: 'session-swap-demo',
    wallets: [{ address: '0xYourWalletAddress', chain: 'ethereum' }],
  },
});
 
console.log('Response status:', response.status);
 
// Step 2: Extract transaction action blocks
const txBlocks = extractTransactionBlocks(response);
console.log(`Found ${txBlocks.length} transaction block(s)`);
 
// Step 3: Extract and identify swap primitives
const primitives = extractPrimitives(response);
const swapPrimitives = primitives.filter(isSwapPrimitive);
 
for (const swap of swapPrimitives) {
  console.log('Swap primitive:', {
    type: swap.type,
    params: swap.params,
    display: swap.display,
  });
}
 
// Step 4: Check risks before proceeding
if (hasBlockers(response)) {
  const blockers = getAllBlockers(response);
  console.error('Transaction blocked:', blockers);
  process.exit(1);
}
 
if (hasRisks(response)) {
  const riskLevel = getHighestRiskLevel(response);
  const warnings = getAllWarnings(response);
  console.warn(`Risk level: ${riskLevel}`);
  console.warn('Warnings:', warnings.map((w) => w.message));
}
 
// Step 5: Access transaction data from the action block
for (const block of txBlocks) {
  console.log('Risk level:', block.risks.level);
  console.log('Notes:', block.notes);
 
  if (block.transactions) {
    for (const seq of block.transactions) {
      console.log('Requires approval:', seq.requiresApproval);
      for (const tx of seq.transactions) {
        console.log('Transaction:', {
          to: tx.to,
          data: tx.data?.slice(0, 20) + '...',
          value: tx.value,
          protocolName: tx.protocolName,
        });
      }
    }
  }
}

Step-by-Step Breakdown

1. Initialize the Client

Create a Chaos instance with your API key. The SDK defaults to https://ai.chaoslabs.co.

init.ts
import { Chaos, WALLET_MODEL } from '@chaoslabs/ai-sdk';
 
const chaos = new Chaos({ apiKey: process.env.CHAOS_API_KEY! });

2. Create the Swap Request

Use WALLET_MODEL for any DeFi operation that produces transactions. Provide the wallet address and chain in metadata.wallets.

request.ts
const response = await chaos.chat.responses.create({
  model: WALLET_MODEL,
  input: [
    { type: 'message', role: 'user', content: 'Swap 1 ETH for USDC on Ethereum' },
  ],
  metadata: {
    user_id: 'user-123',
    session_id: 'session-swap-demo',
    wallets: [{ address: '0xYourWalletAddress', chain: 'ethereum' }],
  },
});

3. Extract Transaction Blocks

extractTransactionBlocks returns all ActionBlock objects from the response. Each action block contains primitives, risk data, and transaction sequences.

extract.ts
import { extractTransactionBlocks, extractPrimitives, isSwapPrimitive } from '@chaoslabs/ai-sdk';
 
const txBlocks = extractTransactionBlocks(response);
const primitives = extractPrimitives(response);
const swaps = primitives.filter(isSwapPrimitive);
 
// Each SwapPrimitive has typed params
for (const swap of swaps) {
  console.log(swap.params); // SwapParams with token_in, token_out, amount_in, chain, etc.
}

4. Check Risk Levels

Always check risks before forwarding transactions to a wallet for signing.

risks.ts
import {
  hasRisks,
  hasBlockers,
  getAllWarnings,
  getAllBlockers,
  getHighestRiskLevel,
} from '@chaoslabs/ai-sdk';
 
if (hasBlockers(response)) {
  console.error('Blocked:', getAllBlockers(response));
} else if (hasRisks(response)) {
  console.warn('Risk:', getHighestRiskLevel(response));
  console.warn('Warnings:', getAllWarnings(response));
} else {
  console.log('No risks detected - safe to proceed');
}
[@portabletext/react] Unknown block type "callout", specify a component for it in the `components.types` prop
Was this helpful?