Skip to main content
This example demonstrates how to deposit funds into a DeFi yield strategy (e.g., Aave lending) using the Deframe API with JavaScript/TypeScript.

Overview

This example covers:
  • Fetching available strategies
  • Getting strategy details
  • Requesting a quote
  • Generating transaction bytecode
  • Executing transactions
  • Verifying the deposit

Prerequisites

  • Node.js 18+
  • Deframe API key
  • Ethereum wallet with USDC balance
  • Basic understanding of async/await

Installation

npm install axios ethers

Environment Variables

Create a .env file:
DEFRAME_API_KEY=your-api-key
WALLET_ADDRESS=0x...
PRIVATE_KEY=0x...
ETHEREUM_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/your-key
POLYGON_RPC_URL=https://polygon-mainnet.g.alchemy.com/v2/your-key
Never commit your .env file to version control. Add it to .gitignore.

Step-by-Step Walkthrough

1. Initialize API Client

import axios from 'axios'

const deframe = axios.create({
  baseURL: 'https://api.deframe.io',
  headers: {
    'x-api-key': process.env.DEFRAME_API_KEY,
    'Content-Type': 'application/json'
  }
})

2. Fetch Available Strategies

const { data: strategies } = await deframe.get('/strategies', {
  params: { page: '1', limit: '10' }
})

console.log('Available strategies:')
strategies.docs.forEach(strategy => {
  console.log(`- ${strategy.name} (${strategy.protocol})`)
  console.log(`  APY: ${strategy.apy}%`)
})

3. Get Strategy Details

const strategyId = 'aave-usdc-polygon'
const { data: strategy } = await deframe.get(`/strategies/${strategyId}`)

console.log('Strategy:', strategy.name)
console.log('Protocol:', strategy.protocol)
console.log('Network:', strategy.network)
console.log('APY:', strategy.apy + '%')
console.log('Status:', strategy.paused ? 'Paused' : 'Active')

4. Request Quote (Optional)

The strategy quote endpoint is under active development and will return detailed pre-deposit estimates in a future release. This step can be skipped — proceed to Step 5 to generate bytecode directly.
// Quote endpoint coming soon
// For now, proceed directly to generating bytecode (Step 5)

5. Generate Bytecode

const { data: result } = await deframe.get('/strategies/aave-usdc-polygon/bytecode', {
  params: {
    action: 'lend',
    amount: '1000000000',
    wallet: walletAddress
  }
})

console.log('Transactions to execute:', result.bytecode.length)

Same-Chain Swap + Deposit

If you hold a different token (e.g., WETH) and want to deposit into a USDC strategy, pass the fromToken parameter. The API will return swap transaction(s) followed by the deposit bytecode:
const { data: result } = await deframe.get('/strategies/aave-usdc-polygon/bytecode', {
  params: {
    action: 'lend',
    amount: '1000000000000000000', // 1 WETH (amount is in fromToken units)
    wallet: walletAddress,
    fromToken: '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619' // WETH on Polygon
  }
})

console.log('Same-chain swap:', result.metadata.isSameChainSwap) // true
console.log('Transactions to execute:', result.bytecode.length) // e.g. 2 (swap + deposit)
When fromToken is provided, the amount parameter refers to the amount of fromToken to swap, not the strategy’s underlying asset. The API handles the swap routing automatically on the same chain.

6. Execute Transactions

import { ethers } from 'ethers'

const provider = new ethers.JsonRpcProvider(process.env.POLYGON_RPC_URL)
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider)

for (const tx of result.bytecode) {
  const transaction = await wallet.sendTransaction({
    to: tx.to,
    data: tx.data,
    value: tx.value || '0',
    chainId: tx.chainId
  })

  console.log('Transaction sent:', transaction.hash)

  const receipt = await transaction.wait()
  console.log('Confirmed in block:', receipt.blockNumber)
}

7. Verify Deposit

// Wait for indexing
await new Promise(resolve => setTimeout(resolve, 5000))

const { data: walletData } = await deframe.get(`/wallets/${walletAddress}`)

console.log('Wallet positions:')
walletData.positions.forEach(position => {
  console.log(`${position.strategy.name}:`)
  console.log(`  Balance: ${position.spotPosition.currentPosition} (raw)`)
  console.log(`  Value: $${position.spotPosition.underlyingBalanceUSD}`)
  console.log(`  APY: ${(position.spotPosition.apy * 100).toFixed(2)}%`)
})

console.log('Total portfolio value: $' + walletData.summary.totalUnderlyingBalanceUSD)

Error Handling

The example includes comprehensive error handling:
try {
  // Your code here
} catch (error) {
  if (error.response?.data?.error) {
    const apiError = error.response.data.error
    console.error('API Error:', apiError.code)
    console.error('Message:', apiError.message)

    // Handle specific errors
    if (apiError.code === 'STRATEGY_NOT_FOUND') {
      console.log('Strategy does not exist or is not available')
    } else if (apiError.code === 'INSUFFICIENT_BALANCE') {
      console.log('Wallet does not have enough tokens')
    }
  } else {
    console.error('Unexpected error:', error.message)
  }
}

Running the Example

# Install dependencies
npm install

# Set environment variables
cp .env.example .env
# Edit .env with your values

# Run the example
node strategy-deposit.js

Expected Output

1️⃣  Fetching available strategies...
✅ Available strategies:
   - Aave USDC Lending (Aave on polygon)
     APY: 4.5% | TVL: $1,234,567,890
   - Morpho BTC Base (Morpho on base)
     APY: 3.2% | TVL: $456,789,012

2️⃣  Getting details for aave-usdc-polygon...
✅ Strategy details:
   Name: Aave USDC Lending
   Protocol: Aave
   Network: polygon
   APY: 4.5%
   Asset: USDC
   Status: ✅ Active

3️⃣  Quote endpoint coming soon — skipping to bytecode generation...

4️⃣  Generating deposit bytecode...
✅ Bytecode generated:
   Transactions: 2

5️⃣  Executing deposit transactions...
   Executing transaction 1/2...
   Transaction sent: 0x123...
   ✅ Transaction confirmed in block 12345678
   Executing transaction 2/2...
   Transaction sent: 0x456...
   ✅ Transaction confirmed in block 12345679

6️⃣  Verifying deposit...
✅ Wallet positions:
   Aave USDC Lending:
      Balance: 1000000000 (raw)
      Value: $1000.00
      APY: 4.17%

   Total Portfolio Value: $1000.00

🎉 Strategy deposit completed successfully!

Next Steps