Skip to main content

Uniswap V2

Uniswap V2 is a decentralized exchange protocol that allows for automated token swaps through liquidity pools. It uses a constant product formula (x * y = k) to determine token prices.

Overview

Uniswap V2 introduced several improvements over V1, including:

  • Direct ERC20-to-ERC20 swaps (no ETH intermediary required)
  • Price oracles for time-weighted average prices (TWAP)
  • Flash swaps for capital-efficient arbitrage
  • More efficient gas usage

Integration with Bloctopus

When using Bloctopus with a forked Ethereum network, you can interact with Uniswap V2 contracts that are already deployed on mainnet. This allows you to test your DeFi applications against real Uniswap V2 liquidity pools.

info

This sample guide is for forked Ethereum networks but you can adapt the respective contract addresses when using other forked networks (e.g. Optimism, Arbitrum)

Key Contracts

The main Uniswap V2 contracts you'll interact with:

  • Factory: 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
  • Router: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
  • Pair Contract: Generated for each token pair

Sample Implementation

The DeFi Samples repository contains ready-to-use scripts for interacting with Uniswap V2:

  • Query: query.js - Get information about Uniswap V2 pairs and reserves
  • Quote: quote.js - Get price quotes for token swaps
  • Swap: swap.js - Execute token swaps on Uniswap V2

Running the Scripts

To run these scripts with Bloctopus:

  1. Clone the DeFi Samples repository:

    git clone https://github.com/LZeroAnalytics/defi-samples.git
    cd defi-samples
  2. Install dependencies:

    npm install
  3. Create a .env file with your Bloctopus RPC endpoint and private key:

    RPC_URL=https://your-bloctopus-rpc-endpoint
    PRIVATE_KEY=your-private-key
  4. Run a script:

    npx hardhat run scripts/protocols/uniswap-v2/query.js
    npx hardhat run scripts/protocols/uniswap-v2/quote.js
    npx hardhat run scripts/protocols/uniswap-v2/swap.js

Resources