This project demonstrates how to calculate the optimal way to split a trade across multiple decentralized exchanges (DEXs) to maximize returns. It uses mathematical optimization techniques to find the best trade allocation.
We have two different DEXs with different liquidity pools:
- DEX-A: 200,150 USDC and 100 ETH (1 WETH = 2001.5 USDC)
- DEX-B: 500,000 USDC and 250 ETH (1 WETH = 2000 USDC)
The goal is to sell 1 WETH to get the maximum possible amount of USDC. While it might seem intuitive to sell all WETH on DEX-A (which has a higher unit price), the optimal solution requires a mathematical approach due to the constant product AMM (Automated Market Maker) model used by DEXs.
DEXs typically use a constant product AMM principle, expressed as:
Where:
-
$x$ : Amount of WETH in the pool -
$y$ : Amount of USDC in the pool -
$k$ : Constant value (liquidity constant)
When selling WETH, the amount of USDC received is calculated as:
To maximize the total USDC received, we need to find the optimal way to split our 1 WETH between the two DEXs. The total output function is:
Where:
-
$w$ : Amount of WETH to send to DEX-A -
$1-w$ : Amount of WETH to send to DEX-B
To find the maximum point, we take the derivative of the function and set it to zero:
This project uses a binary search algorithm to find this optimal point numerically.
To install dependencies:
bun installTo run the calculation:
bun run index.tsThe code calculates:
- The optimal split of 1 WETH between DEX-A and DEX-B
- The total USDC output from this optimal trade
- Due to the constant product AMM model, the price in each DEX changes with each trade
- The optimal solution is to split the 1 WETH between both DEXs rather than trading on a single DEX
- The binary search algorithm finds the exact split that maximizes the total USDC received
This project demonstrates the concept of "Optimal trade" in DeFi, the principles of liquidity pools, and how calculus (derivatives) can be used to determine maximum profit in trading scenarios.
- TypeScript
- ethers.js for handling cryptocurrency units
- Bun as the JavaScript runtime
This project was created using bun init in bun v1.2.4. Bun is a fast all-in-one JavaScript runtime.