joshstevens19 / simple-uniswap-sdk

Uniswap SDK which handles the routes automatically for you, changes in trade quotes reactive subscriptions, exposure to formatted easy to understand information, bringing back the best trade quotes automatically, generating transactions for you and much more.
MIT License
188 stars 95 forks source link

How to compute Gas + Uniswap Fees needed for a trade? #42

Open thegitparticle opened 2 years ago

thegitparticle commented 2 years ago

After constructing a trade, how do I go about calculating gas fees + uniswap fees needed for a trade?

niZmosis commented 2 years ago

Once you call the trade (which I like to call the quote function, as it doesn't make a transaction) function of the UniswapPairFactory, the gas information will be in the object returned. You would have needed to provide the gas price in the UniswapPairSettings constructor. If you don't have enough balance for the input token, it will not be able to calculate it for you and will be undefined.

It'll look similar to this. I made my own gas function since BSC wants to use the old gasGasPrice function

// EIP-1559 supported chains use getFeeData export async function getGasPriceForProvider(provider) { return [bscChainId].includes(provider._network.chainId) ? await provider?.getGasPrice() : (await provider?.getFeeData()).maxFeePerGas }

let settings = new UniswapPairSettings({ slippage, deadlineMinutes, disableMultihops: false, uniswapVersions, gasSettings: { getGasPrice: async () => formatUnits(await getGasPriceForProvider(provider), 'gwei') } })

Everything should be taken care of for you for tokens as far as gas ect go. If you are using Ethers, you don't need to provide the gasprice, limit, nonce ect, it's all automatic, just call wallet.sendTransaction(trade.transaction)

For the native coin for the chain you are using you will need to cacluate it yourself it looks like. From the docs for the input token balance

// if the balance of the users has enough to perform this trade, does not consider gas prices // right now if your doing ETH > ERC20

thegitparticle commented 2 years ago

Yes, this makes sense for gas. But how about the uniswap swap fee?