Skip to main content
This example demonstrates how to swap tokens on the same blockchain network using the Deframe API with JavaScript/TypeScript.

Overview

This example covers:
  • Getting a swap quote
  • Generating transaction bytecode
  • Executing the swap transaction
  • Handling approvals

Prerequisites

  • Node.js 18+
  • Deframe API key
  • Ethereum wallet with tokens to swap
  • Basic understanding of async/await

Choose Your Library

Using ethers.js v6 for blockchain interactions - the most popular Ethereum library.

Installation

npm install axios ethers

Environment Variables

Create a .env file:
DEFRAME_API_KEY=your-api-key
WALLET_ADDRESS=0x...
PRIVATE_KEY=0x...
RPC_URL=https://eth-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. Get Swap Quote

const { data } = await deframe.get('/swap/quote', {
  params: {
    originChain: 'ethereum',
    destinationChain: 'ethereum',
    tokenIn: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
    tokenOut: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
    amountIn: '1000000000' // 1000 USDC (6 decimals)
  }
})

const quote = data.quote

console.log('Quote ID:', quote.quoteId)
console.log('Expected output:', quote.tokenOut.amount)
console.log('Provider:', quote.provider)
console.log('Deadline:', quote.deadline)

3. Generate Bytecode

const { data: bytecode } = await deframe.post('/swap/bytecode', {
  quoteId: quote.quoteId,
  originAddress: walletAddress,
  destinationAddress: walletAddress,
  rawQuote: quote.rawQuote
})

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

4. Execute Transactions

import { ethers } from 'ethers'

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

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

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

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

console.log('✅ Swap completed successfully!')

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)

    if (apiError.code === 'QUOTE_NOT_FOUND') {
      console.log('Quote not found or expired')
    } else if (apiError.code === 'NO_ROUTE_FOUND') {
      console.log('No swap route available')
    }
  } 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 same-chain-swap.js

Expected Output

1️⃣  Getting swap quote...
✅ Quote received:
   Quote ID: 550e8400-e29b-41d4-a716-446655440000
   Provider: 1inch
   Amount in: 1000 USDC
   Expected out: 0.384 WETH
   Deadline: 2024-01-24T12:35:00.000Z

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

3️⃣  Executing transactions...
   Transaction 1/2 (Approve)...
   Transaction sent: 0x123...
   ✅ Confirmed in block 12345678

   Transaction 2/2 (Swap)...
   Transaction sent: 0x456...
   ✅ Confirmed in block 12345679

🎉 Swap completed successfully!

Next Steps