AlcorDocs

Price Oracle (TWAP)

On-chain time-weighted average prices from Alcor Swap pools.

Alcor TWAP price oracle

Every Alcor Swap pool works as an on-chain price oracle, following the design of the Uniswap v3 oracle. Other contracts can read a pool's time-weighted average price (TWAP) directly from the swap.alcor tables, for any pair that trades on Alcor Swap.

How it works

Each pool stores a list of observations in the observations table (scoped by pool ID). An observation records a timestamp and cumulative values of the price tick and of seconds per liquidity. A new observation is written, at most once per second, when a swap moves the price to a new tick or liquidity changes at the current price.

The average price between two moments is calculated from the difference between their cumulative values. A contract usually asks for the average over the last N seconds, for example 30 minutes.

Observation history

A new pool keeps one observation, overwritten as new ones arrive, so on its own it gives little history. Anyone can raise the number of observations a pool keeps by paying for the RAM: see Expanding Price Availability. There is no upper limit.

Manipulation risk

A spot price can be moved cheaply within one transaction. A TWAP can only be moved by holding the pool price away from the market for the whole averaging window, paying swap fees and losing to arbitrage the entire time. The cost grows with the pool's liquidity and the length of the window. Use a rolling TWAP rather than the spot price, and prefer pools with deep liquidity.

On this page