[Ethereum] How to calculate the gas fee of a swap on Uniswap

gasgas-estimategas-priceuniswap

According to gas tracker on Etherscan the average gas price is 212 gwei and the average Uniswap swap estimate is $70.26 which implies that the gas fee is around 201101.
To my knowledge swap gas fee is 21000 or so. What other operations are associated with a Uniswap swap that burn the extra gas?

Best Answer

To my knowledge swap gas fee is 21000 or so

A transfer between two EOAs (i.e. normal wallet accounts) is 21,000 gas.

As soon as you include smart contracts in the equation the gas cost increases: each opcode associated with each step in the execution of a smart contract incurs a cost. (As outlined in Appendix G of the Yellow Paper.)

Without actually digging into the opcodes associated with a Uniswap (v2) swap operation, just looking at an example transaction gives an idea that there's a lot going on when swapping from token A -> token B.

Generally it's a 3-part process (this is for the swapExactTokensForTokens() path):

  1. User transfers token A to Uniswap where it's converted to wrapped ETH (WETH)
  2. The WETH is swapped for token B
  3. Token B is transferred to the user

However, if you look a bit deeper at the example above, this 3-part process actually involves 13 internal transactions (i.e. messages between contracts) - there's a lot going on.

(If you want to dig deeper, then the v2 contracts are here: https://github.com/Uniswap/uniswap-v2-core)