> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pods.finance/llms.txt
> Use this file to discover all available pages before exploring further.

# Same-Chain Swap

> Complete example of executing a same-chain token swap

This example demonstrates how to swap tokens on the same blockchain network using the Pods 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+
* Pods API key
* Ethereum wallet with tokens to swap
* Basic understanding of async/await

## Choose Your Library

<Tabs>
  <Tab title="ethers.js">
    Using ethers.js v6 for blockchain interactions - the most popular Ethereum library.
  </Tab>

  <Tab title="viem">
    Using viem for blockchain interactions - a modern, TypeScript-first alternative with better performance.
  </Tab>
</Tabs>

## Installation

<Tabs>
  <Tab title="ethers.js">
    ```bash theme={null}
    npm install axios ethers
    ```
  </Tab>

  <Tab title="viem">
    ```bash theme={null}
    npm install axios viem
    ```
  </Tab>
</Tabs>

## Environment Variables

Create a `.env` file:

```bash theme={null}
PODS_API_KEY=your-api-key
WALLET_ADDRESS=0x...
PRIVATE_KEY=0x...
RPC_URL=https://eth-mainnet.g.alchemy.com/v2/your-key
```

<Warning>
  Never commit your `.env` file to version control. Add it to `.gitignore`.
</Warning>

## Step-by-Step Walkthrough

### 1. Initialize API Client

```javascript theme={null}
import axios from 'axios'

const pods = axios.create({
  baseURL: 'https://api.pods.finance',
  headers: {
    'x-api-key': process.env.PODS_API_KEY,
    'Content-Type': 'application/json'
  }
})
```

### 2. Get Swap Quote

```javascript theme={null}
const { data } = await pods.get('/v2/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

```javascript theme={null}
const { data: bytecode } = await pods.post('/v2/swap/bytecode', {
  quoteId: quote.quoteId,
  originAddress: walletAddress,
  destinationAddress: walletAddress,
  ...(quote.rawQuote && { rawQuote: quote.rawQuote })
})

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

### 4. Execute Transactions (atomic batch)

<Warning>
  Batch all `transactionData` legs into **one transaction** on the origin chain. See
  [Executing Bytecode](/getting-started/executing-bytecode) and
  [`same-chain-swap.js`](/examples/javascript/same-chain-swap.js) (EIP-7702 via `eip7702-batch.js`).
</Warning>

```javascript theme={null}
import { http, createWalletClient, publicActions } from 'viem'
import { mainnet } from 'viem/chains'
import { privateKeyToAccount } from 'viem/accounts'
import { executeLegsViaEip7702 } from './eip7702-batch.js'

const account = privateKeyToAccount(process.env.PRIVATE_KEY)
const walletClient = createWalletClient({
  account,
  chain: mainnet,
  transport: http(process.env.RPC_URL)
}).extend(publicActions)

const receipt = await executeLegsViaEip7702(walletClient, bytecode.transactionData)
console.log('✅ Swap batch confirmed in block', receipt.blockNumber)
```

Smart accounts: request `output=userOperation` on `POST /v2/swap/bytecode` instead.

## Error Handling

```javascript theme={null}
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

```bash theme={null}
# 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: 1706098500

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

3️⃣  Executing atomic EIP-7702 batch...
   ✅ Confirmed in block 12345678

🎉 Swap completed successfully!
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Cross-Chain Swap" icon="bridge" href="/examples/javascript/cross-chain-swap">
    Execute cross-chain token swaps
  </Card>

  <Card title="Strategy Deposit" icon="arrow-up-right-dots" href="/examples/javascript/strategy-deposit">
    Deposit into yield strategies
  </Card>

  <Card title="Swap Guide" icon="book" href="/guides/swaps/get-quote">
    Learn more about swaps
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference">
    View complete API documentation
  </Card>
</CardGroup>
