Last active
September 11, 2023 22:22
-
-
Save chuckbergeron/8bda10f3a38ed91770af9b81cf4acc4d to your computer and use it in GitHub Desktop.
PoolTogether v5 Hyperstructure - Arbitrage Bot, Calculate Profit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ethers, BigNumber } from 'ethers'; | |
const { profitable, selectedIndex } = await calculateProfit(wantedAmountsIn, wantedAmountsOut); | |
// Calculates the amount of profit the bot will make on this swap | |
// and if it's profitable or not | |
const calculateProfit = async ( | |
wantedAmountsIn: BigNumber[], | |
wantedAmountsOut: BigNumber[], | |
): Promise<{ profitable: boolean; selectedIndex: number }> => { | |
console.log('Gross profit = tokenOut - tokenIn'); | |
const grossProfitsUsd = []; | |
for (let i = 0; i < wantedAmountsIn.length; i++) { | |
const amountOut = wantedAmountsOut[i]; | |
const amountIn = wantedAmountsIn[i]; | |
const underlyingAssetTokenUsd = | |
parseFloat(ethers.utils.formatUnits(amountOut, tokenOut.decimals)) * | |
underlyingAssetToken.assetRateUsd; | |
const tokenInUsd = | |
parseFloat(ethers.utils.formatUnits(amountIn, tokenIn.decimals)) * tokenIn.assetRateUsd; | |
const grossProfitUsd = underlyingAssetTokenUsd - tokenInUsd; | |
console.log(`Index ${i}: $${grossProfitUsd} = $${underlyingAssetTokenUsd} - $${tokenInUsd}`); | |
grossProfitsUsd.push(grossProfitUsd); | |
} | |
const getMaxGrossProfit = (grossProfitsUsd: number[]) => { | |
const max = grossProfitsUsd.reduce((a, b) => Math.max(a, b), -Infinity); | |
return { maxGrossProfit: max, selectedIndex: grossProfitsUsd.indexOf(max) }; | |
}; | |
const { selectedIndex, maxGrossProfit } = getMaxGrossProfit(grossProfitsUsd); | |
console.log(`Selected Index ${selectedIndex} - $${maxGrossProfit}`); | |
// Compare the profit with the gas costs to learn if transaction will be profitable | |
const estimatedProfitUsd = maxGrossProfit - gasFeeUsd; | |
const profitable = estimatedProfitUsd > 0; | |
return { profitable, selectedIndex }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment