I recently realised not everyone is aware that Uniswap v3 has a TWAP feature baked right into it. To be honest I never gave it too much thought, but was reminded of it last year when completing Damn Vulnerable Defi Challenge #14.
In my opinion, the existence of the Uniswap TWAP is pretty significant. We often can’t have a Chainlink oracle for small pairs, so this TWAP may be the only decentralised option. The fact that it is a TWAP is also important in that it is more resistant to flash-loan attacks than the simple spot oracle.
A use-case for the TWAP could be that it is used in a lending protocol that wants to allow permissionless loans on *any* Uniswap pair, not just whitelisted pairs. The exact implementation would need to be fleshed out more, but it is a simple high-level example.
Anyways, let’s run through how we can find the TWAP for the past hour on the FUMO/WETH pair (0x78d4e81fc84a1ce367e90936e49a74a9052137e8).
If we look at the `observe` function, and put in the array [0,3600], we receive data from 0 seconds ago and 1 hour ago.
The math to find the TWAP for this period is as follows:
1.0001 ** ((55811710140–55738177572) / 3600) = 7.7096 (price in WETH)
Convert to USD (ETH@1898.39)
7.7096 * 1898.39 = 14635.8275
I checked Dextools and this was around the current price 👍
Current time is 2023/07/20 00:15:00 (UTC+9)
It may not always work for a longer time interval of 1 hour (3600s), because the contract can only store a limited amount of data. If you want to know the reason why, I’d suggest reading deeper into the docs. Also feel free to ask me.
That’s the high level overview of finding the TWAP. Remember, the quiddity of this is that everything I did above can all be done on-chain in real time, which is incredibly powerful.
It is worth noting there are still theoretical ways to manipulate the TWAP. An example for a larger liquidity pool:
In lower liquidity pools, which may be used for the permissionless lending protocol example I gave before, the implementation needs to be thorough since there will be more edge cases to consider. For example, if the lending protocol used a 10 minute TWAP, a whale could simply dump the price and hope that any vigilant buyers aren’t watching the market at the time.
Class concluded, thanks for coming. Feedback and all else is appreciated — I check my Twitter DMs regularly.