Skip to content

Conversation

@luchobonatti
Copy link
Member

@luchobonatti luchobonatti commented Jun 3, 2025

Add Uniswap V4 Swap Calldata Builder

Overview

This PR adds a new utility function buildSwapCallData that generates the necessary calldata for executing token swaps through Uniswap V4's Universal Router. The implementation supports both token0-to-token1 and token1-to-token0 swaps, with configurable minimum output amounts and automatic deadline management.

Key Features

  • Generates calldata for Uniswap V4 swaps using the Universal Router
  • Supports both swap directions (token0→token1 and token1→token0)
  • Handles minimum output amount requirements
  • Automatically sets a 5-minute deadline for transactions
  • Includes comprehensive test coverage
  • Call getQuote inside and calculate amountOutMin using slippageTolerance param

Technical Details

  • Uses ethers.js for ABI encoding and parameter packing
  • Implements the Universal Router's command structure:
    • V4_ROUTER_EXECUTE (0x10) for V4 operations
    • SWAP_EXACT_IN_SINGLE (0x06) for single-hop swaps
    • SETTLE_ALL (0x0c) and TAKE_ALL (0x0f) for token settlement
  • Properly encodes pool keys, swap parameters, and token amounts

Testing

Added comprehensive test suite covering:

  • Token0 to Token1 swaps
  • Token1 to Token0 swaps
  • SlippageTolerance (default to 50 - 0.5%)
  • Deadline inclusion verification

Usage Example

const params = {
  tokenIn: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
  amountIn: parseUnits("100", 6), // 100 USDC
  slippageTolerance: 50 //default
  pool: pool,
};

const calldata = await buildSwapCallData(params);

// Send transaction
const tx = await sendTransaction({
  to: universalRouterAddress,
  data: calldata,
  value: 0,
});

Related Issues

Closes #74

@luchobonatti luchobonatti force-pushed the feat/buildSwapCallData branch from 82bc18e to 8486ca4 Compare June 3, 2025 15:13
@luchobonatti luchobonatti merged commit a81f910 into main Jun 3, 2025
1 check passed
@luchobonatti luchobonatti deleted the feat/buildSwapCallData branch June 3, 2025 19:05
@github-actions
Copy link

github-actions bot commented Jun 3, 2025

🎉 This PR is included in version 1.0.8 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants