TWAP Oracle

Understanding Attack Vectors

Spot price oracles (provided by AMM DEX LPs) calculate the price of an asset by simply dividing the amount of the asset against another asset in a two-asset liquidity pool.
The problem with this approach? An attacker could drain liquidity from one side of the pool using a flash loan and thus trigger the price oracle to quote an abnormally high price for an asset. Since flash loans are typically borrowed without any collateral, spot price oracles become targets of risk-free manipulation attempts.
To mitigate this sort of attack Elephant Money has implemented a TWAP (Time-Weighted Average Price) oracle.

How It Works

A TWAP oracle is programmed to measure prices over long pre-set "time" intervals helping to protect to some degree against flash loan attacks. For example, if the algorithm is set to a 4H interval for the TWAP oracle, the latter returns the average price of the asset across the last 4 hours.
TWAP oracles are designed to solve a problem associated with using on-chain oracles: price manipulation.
A weighted average simply means that values in a dataset are multiplied by predetermined “weights” before being summed up as part of the calculation. Weighting assigns significance to certain values in a distribution and is thus considered more accurate than naively summing up all values and dividing by n number of values to get the average of a dataset.
A TWAP oracle uses duration (time) as a weight. The price (P) is continuously multiplied by how long it lasts for (T) and added to a cumulative value (C) at different checkpoints (usually at the end of a block). In the end, the total cumulative value is divided by the total duration to get the average price across the specified period.
Since the TWAP algorithm derives price from an average of multiple prices across a pre-set time interval from the previous block(s); this rules out the single-transaction exploit where an attacker drains liquidity via a flash loan and promptly sells an asset at an inflated price in the same transaction (block).