How Astroport can be your price source

1. Overview

A price oracle is any tool used to view fetch information about a given asset. Astroport built fully decentralized and manipulation resistant oracles that other Terra developers to use.
Every Astroport pool checks its tokens' market prices at the beginning of each block, before any trades take place. This price is expensive to manipulate because it is set by the last transaction in a previous block. In this scenario, an attacker would have to make a bad trade in the last block in order to change the pool price far away from a token's global market price.
Once the pool checks its token prices, it adds them to accumulators (described in the sections below) which can be used by external actors to compute time-weighted average prices (TWAPs).

2. Accumulating Token Prices

On each liquidity provision or withdrawal, as well as on each swap, the Astroport pool runs the accumulate_prices function. This function checks how many blocks have passed since it was last called, calculates the elapsed time between the current and the last call and then accumulates the prices for all assets in the pool.
The accumulated prices can later be fetched using query_cumulative_prices.

3. Time-Weighted Average Prices

A TWAP can be constructed by reading the cumulative prices for an asset from an Astroport pair at the beginning and at the end of the desired interval. The difference in this cumulative price can then be divided by the length of the interval to create a TWAP for that period.
How an Astroport TWAP is calculated
The cost of of an attack for a specific time period can be estimated fairly easily. For large liquidity pools and over longer time periods, this attack is impractical, as the cost of manipulation typically exceeds the value at stake.
You should keep in mind some details when working with Astroport TWAPs:
  • For a 30 minute TWAP, sample once every 30 minutes. For a 1 day TWAP, sample once every day
  • For a simple TWAP, the cost of manipulation increases with the amount of liquidity on Astroport, as well as with the length of time over which you average
  • Moving the price 10% on a 30 minute TWAP is approximately equal to the amount lost to arbitrage and fees for moving the price 10% every block for 30 minutes
Make sure to check out the basic TWAP oracle implementation in the core Astroport Github repo that queries cumulative prices from a XYK pool and computes the average daily price for the two pool assets.