比特幣交易所 比特幣交易所
Ctrl+D 比特幣交易所
ads

價格預言機的使用總結(二):UniswapV2篇_AMP

Author:

Time:1900/1/1 0:00:00

前言

該系列的前一篇文章介紹了Chainlink價格預言機的使用,其目前也被大部分DeFi應用所使用,但依然存在局限性。首先是所支持的Token的覆蓋率還不全,尤其是長尾資產,大多還未支持,比如SHIB,目前只在BSC主網有SHIB/USD的PriceFeed,而其它網絡的都還沒有,連Ethereum的都還沒支持。其次,有些資產的偏差閾值較大,價格更新也比較慢,可能長達十幾二十個小時才會更新價格,比如BNT。

這時候就需要考慮其它價格預言機了,而UniswapV2和UniswapV3都是不錯的選擇。

本篇先來聊聊如何使用UniswapV2作為價格預言機。

UniswapV2價格預言機

UniswapV2使用的價格預言機稱為TWAP,即時間加權平均價格。不同于鏈下聚合的Chainlink取自多個不同交易所的數據作為數據源,TWAP的數據源來自于Uniswap自身的交易數據,價格的計算也都是在鏈上執行的,因此,TWAP屬于鏈上預言機。

TWAP的原理比較簡單,首先,在UniswapV2Pair合約中,會存儲兩個變量price0CumulativeLast和price1CumulativeLast,在_update()函數中會更新這兩個變量,其相關代碼如下:

contract?UniswapV2Pair?{

??...

??uint32?private?blockTimestampLast;

??uint?public?price0CumulativeLast;

??uint?public?price1CumulativeLast;

??...

??//?update?reserves?and,?on?the?first?call?per?block,?price?accumulators

??function?_update(uint?balance0,?uint?balance1,?uint112?_reserve0,?uint112?_reserve1)?private?{

????...

????uint32?blockTimestamp?=?uint32(block.timestamp?%?2**32);

????uint32?timeElapsed?=?blockTimestamp?-?blockTimestampLast;

????if?(timeElapsed?&ampgt;?0?&ampamp;&ampamp;?_reserve0?!=?0?&ampamp;&ampamp;?_reserve1?!=?0)?{

??????//?*?never?overflows,?and?+?overflow?is?desired

??????price0CumulativeLast?+=?uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0))?*?timeElapsed;

??????price1CumulativeLast?+=?uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1))?*?timeElapsed;

????}

????blockTimestampLast?=?blockTimestamp;

????...

??}

}

price0CumulativeLast和price1CumulativeLast分別記錄了token0和token1的累計價格。所謂累計價格,其代表的是整個合約歷史中每一秒的Uniswap價格總和。且只會在每個區塊第一筆交易時執行累加計算,累加的值不是當前區塊的第一筆交易的價格,而是在這之前的最后一筆交易的價格,所以至少也是上個區塊的價格。取自之前區塊的價格,可以大大提高操控價格的成本,所以自然也提高了安全性。

Coinbase推出價格預言服務:金色財經報道,據官方博客消息,Coinbase宣布推出價格預言服務Coinbase Price Oracle。從今天起,任何人可以通過Coinbase Oracle API獲得BTC/USD和ETH/USD的價格數據。價格信息來自Coinbase Pro,并每分鐘更新一次。任何人都可以在鏈上發布價格,并且由于價格已由Coinbase的私鑰簽名,所以用戶可以使用公鑰驗證該數據的真實性。Compound首席執行官Robert Leshner表示,Coinbase Oracle將提升Compound價格源的安全性和去中心化程度。[2020/4/24]

如上圖所示,合約的第一個區塊為Block122,這時候,價格和時間差都為0,所以累計價格也為?0。到了下一個區塊Block123,這時候取自上個區塊的最后一口價格10.2,且經過的時間差為7,因此就可以計算出累計價格priceCumulative=10.2*7=71.4。再到下個區塊Block124,取自上一口價格10.3,兩個區塊間的時間差為8,那此時的累計價格就變成了71.4+(10.3*8)=153.8。Block125的時候也同理,上口價格為10.5,區塊時間差為5,所以最新的累計價格就變成了153.8+(10.5*5)=206.3。

有了這個基礎之后,就可以計算TWAP了。

固定時間窗口TWAP

計算TWAP的原理也是非常簡單,如上圖所示,這是計算時間間隔為1小時的TWAP,取自開始和結束時的累計價格和兩區塊當時的時間戳,兩者的累計價格相減,再除以兩者之間的時間差,就算出這1小時內的TWAP價格了。

這是TWAP最簡單的計算方式,也稱為固定時間窗口的TWAP。下面來講講具體如何實現。

Uniswap官方也有提供了一個示例代碼來計算固定時間窗口的TWAP,其代碼放在v2-periphery項目中:

https://github.com/Uniswap/v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol

該示例代碼也比較簡單,我們直接貼上代碼看看:

pragma?solidity?=0.6.6;

import?'

????function?update()?external?{

????????(uint?price0Cumulative,?uint?price1Cumulative,?uint32?blockTimestamp)?=

????????????UniswapV2OracleLibrary.currentCumulativePrices(address(pair));

????????uint32?timeElapsed?=?blockTimestamp?-?blockTimestampLast;?//?overflow?is?desired

????????//?ensure?that?at?least?one?full?period?has?passed?since?the?last?update

????????require(timeElapsed?&ampgt;=?PERIOD,?'ExampleOracleSimple:?PERIOD_NOT_ELAPSED');

動態 | Max Keiser將BTC價格預期提高至40萬美元:華爾街金融分析師、比特幣支持者Max Keiser近期在節目中表示,他“正式”將其對比特幣的目標價格提高到40萬美元:“這是八年來我第一次把它提高到40萬美元。這是我的最新正式目標。”(U.Today)[2020/2/17]

????????//?overflow?is?desired,?casting?never?truncates

????????//?cumulative?price?is?in?(uq112x112?price?*?seconds)?units?so?we?simply?wrap?it?after?division?by?time?elapsed

????????price0Average?=?FixedPoint.uq112x112(uint224((price0Cumulative?-?price0CumulativeLast)?/?timeElapsed));

????????price1Average?=?FixedPoint.uq112x112(uint224((price1Cumulative?-?price1CumulativeLast)?/?timeElapsed));

????????price0CumulativeLast?=?price0Cumulative;

????????price1CumulativeLast?=?price1Cumulative;

????????blockTimestampLast?=?blockTimestamp;

????}

????//?note?this?will?always?return?0?before?update?has?been?called?successfully?for?the?first?time.

????function?consult(address?token,?uint?amountIn)?external?view?returns?(uint?amountOut)?{

????????if?(token?==?token0)?{

????????????amountOut?=?price0Average.mul(amountIn).decode144();

????????}?else?{

????????????require(token?==?token1,?'ExampleOracleSimple:?INVALID_TOKEN');

????????????amountOut?=?price1Average.mul(amountIn).decode144();

????????}

????}

}

PERIOD指定為了24小時,說明這個示例計算TWAP的固定時間窗口為24小時,即每隔24小時才更新一次價格。

該示例也只保存一個交易對的價格,即token0-token1的價格。price0Average和price1Average分別就是token0和token1的TWAP價格。比如,token0為WETH,token1為USDC,那price0Average就是WETH對USDC的價格,而price1Average則是USDC對WETH的價格。

update()函數就是更新TWAP價格的函數,這一般需要鏈下程序的定時任務來觸發,按照這個示例的話,就是鏈下的定時任務需要每隔24小時就定時觸發調用update()函數。

update()函數的實現邏輯也和上面所述的公式一致:

聲音 | John McAfee:仍堅信比特幣5萬美元中期價格預測,也堅信2020年底將達100萬美元:殺軟件之父、加密貨幣支持者John McAfee發推稱:“忽略掉比特幣價格的下跌吧。我堅定地支持Peter Brandt對5萬美元中期價格的預測。我對2020年底前100萬美元的價格也很堅定。”[2019/9/30]

讀取出當前最新的累計價格和當前的時間戳;

計算出當前時間和上一次更新價格時的時間差timeElapsed,要求該時間差需要達24小時;

根據公式TWAP=(priceCumulative-priceCumulativeLast)/timeElapsed計算得到最新的TWAP,即priceAverage;

更新priceCumulativeLast和blockTimestampLast為當前最新的累計價格和時間戳。

不過,有一點需要注意,因為priceCumulative本身計算存儲時是做了左移112位的操作的,所以計算所得的priceAverage也是左移了112位的。

consult()函數則可查詢出用TWAP價格計算可兌換的數量。比如,token0為WETH,token1為USDC,假設WETH的價格為3000USDC,查詢consult()時,若傳入的參數token為token0的地址,amountIn為2,那輸出的amountOut則為3000*2=6000,可理解為若支付2WETH,就可根據價格換算成6000USDC。

滑動時間窗口TWAP

固定時間窗口TWAP的原理和實現,比較簡單,但其最大的不足就是價格變化不夠平滑,時間窗口越長,價格變化就可能會越陡峭。因此,在實際應用中,更多其實是用滑動時間窗口的TWAP。

所謂滑動時間窗口TWAP,就是說,計算TWAP的時間窗口并非固定的,而是滑動的。這種算法的主要原理就是將時間窗口劃分為多個時間片段,每過一個時間片段,時間窗口就會往右滑動一格,如下圖所示:

上圖所示的時間窗口為1小時,劃分為了6個時間片段,每個時間片段則為10分鐘。那每過10分鐘,整個時間窗口就會往右滑動一格。而計算TWAP時的公式則沒有變,依然還是取自時間窗口的起點和終點。如果時間窗口為24小時,按照固定時間窗口算法,每隔24小時TWAP價格才會更新,但使用滑動時間窗口算法后,假設時間片段為1小時,則TWAP價格是每隔1小時就會更新。

Uniswap官方也同樣提供了這種滑動時間窗口TWAP實現的示例代碼,其Github地址為:

https://github.com/Uniswap/v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol

我們也貼上代碼看看:

pragma?solidity?=0.6.6;

import?'

????address?public?immutable?factory;

????//?the?desired?amount?of?time?over?which?the?moving?average?should?be?computed,?e.g.?24?hours

????uint?public?immutable?windowSize;

????//?the?number?of?observations?stored?for?each?pair,?i.e.?how?many?price?observations?are?stored?for?the?window.

動態 | 以太坊開源銀行Marble推出基于Uniswap的價格預言機Polaris:以太坊開源銀行Marble推出基于去中心化交易所Uniswap的價格預言機Polaris。Marble表示Polaris通過選取Uniswap價格檢查點的中位數,使價格攻擊成本更高。價格操縱在單一交易所需的時間被延長,因而變得更加困難和昂貴。此外,Polaris采用一系列激勵措施鼓勵第三方參與者定期檢查價格,從而保持價格準確。[2019/4/2]

????//?as?granularity?increases?from?1,?more?frequent?updates?are?needed,?but?moving?averages?become?more?precise.

????//?averages?are?computed?over?intervals?with?sizes?in?the?range:

????//???

????//?e.g.?if?the?window?size?is?24?hours,?and?the?granularity?is?24,?the?oracle?will?return?the?average?price?for

????//???the?period:

????//???,?now]

????uint8?public?immutable?granularity;

????//?this?is?redundant?with?granularity?and?windowSize,?but?stored?for?gas?savings?&ampamp;?informational?purposes.

????uint?public?immutable?periodSize;

????//?mapping?from?pair?address?to?a?list?of?price?observations?of?that?pair

????mapping(address?=&ampgt;?Observation)?public?pairObservations;

????constructor(address?factory_,?uint?windowSize_,?uint8?granularity_)?public?{

????????require(granularity_?&ampgt;?1,?'SlidingWindowOracle:?GRANULARITY');

????????require(

????????????(periodSize?=?windowSize_?/?granularity_)?*?granularity_?==?windowSize_,

????????????'SlidingWindowOracle:?WINDOW_NOT_EVENLY_DIVISIBLE'

????????);

????????factory?=?factory_;

????????windowSize?=?windowSize_;

????????granularity?=?granularity_;

????}

????//?returns?the?index?of?the?observation?corresponding?to?the?given?timestamp

????function?observationIndexOf(uint?timestamp)?public?view?returns?(uint8?index)?{

動態 | Bitmex構建數字貨幣定價模型 內含2019年價格預測:據Bitmex Research消息,Bitmex現構建了一種新的數字貨幣定價模型,內含2019年價格預測。[2018/7/16]

????????uint?epochPeriod?=?timestamp?/?periodSize;

????????return?uint8(epochPeriod?%?granularity);

????}

????//?returns?the?observation?from?the?oldest?epoch?(at?the?beginning?of?the?window)?relative?to?the?current?time

????function?getFirstObservationInWindow(address?pair)?private?view?returns?(Observation?storage?firstObservation)?{

????????uint8?observationIndex?=?observationIndexOf(block.timestamp);

????????//?no?overflow?issue.?if?observationIndex?+?1?overflows,?result?is?still?zero.

????????uint8?firstObservationIndex?=?(observationIndex?+?1)?%?granularity;

????????firstObservation?=?pairObservations;

????}

????//?update?the?cumulative?price?for?the?observation?at?the?current?timestamp.?each?observation?is?updated?at?most

????//?once?per?epoch?period.

????function?update(address?tokenA,?address?tokenB)?external?{

????????address?pair?=?UniswapV2Library.pairFor(factory,?tokenA,?tokenB);

????????//?populate?the?array?with?empty?observations?(first?call?only)

????????for?(uint?i?=?pairObservations.length;?i?&amplt;?granularity;?i++)?{

????????????pairObservations.push();

????????}

????????//?get?the?observation?for?the?current?period

????????uint8?observationIndex?=?observationIndexOf(block.timestamp);

????????Observation?storage?observation?=?pairObservations;

????????//?we?only?want?to?commit?updates?once?per?period?(i.e.?windowSize?/?granularity)

????????uint?timeElapsed?=?block.timestamp?-?observation.timestamp;

????????if?(timeElapsed?&ampgt;?periodSize)?{

????????????(uint?price0Cumulative,?uint?price1Cumulative,)?=?UniswapV2OracleLibrary.currentCumulativePrices(pair);

????????????observation.timestamp?=?block.timestamp;

????????????observation.price0Cumulative?=?price0Cumulative;

????????????observation.price1Cumulative?=?price1Cumulative;

????????}

????}

????//?given?the?cumulative?prices?of?the?start?and?end?of?a?period,?and?the?length?of?the?period,?compute?the?average

????//?price?in?terms?of?how?much?amount?out?is?received?for?the?amount?in

????function?computeAmountOut(

????????uint?priceCumulativeStart,?uint?priceCumulativeEnd,

????????uint?timeElapsed,?uint?amountIn

????)?private?pure?returns?(uint?amountOut)?{

????????//?overflow?is?desired.

????????FixedPoint.uq112x112?memory?priceAverage?=?FixedPoint.uq112x112(

????????????uint224((priceCumulativeEnd?-?priceCumulativeStart)?/?timeElapsed)

????????);

????????amountOut?=?priceAverage.mul(amountIn).decode144();

????}

????//?returns?the?amount?out?corresponding?to?the?amount?in?for?a?given?token?using?the?moving?average?over?the?time

????//?range?,?now]

????//?update?must?have?been?called?for?the?bucket?corresponding?to?timestamp?`now?-?windowSize`

????function?consult(address?tokenIn,?uint?amountIn,?address?tokenOut)?external?view?returns?(uint?amountOut)?{

????????address?pair?=?UniswapV2Library.pairFor(factory,?tokenIn,?tokenOut);

????????Observation?storage?firstObservation?=?getFirstObservationInWindow(pair);

????????uint?timeElapsed?=?block.timestamp?-?firstObservation.timestamp;

????????require(timeElapsed?&amplt;=?windowSize,?'SlidingWindowOracle:?MISSING_HISTORICAL_OBSERVATION');

????????//?should?never?happen.

????????require(timeElapsed?&ampgt;=?windowSize?-?periodSize?*?2,?'SlidingWindowOracle:?UNEXPECTED_TIME_ELAPSED');

????????(uint?price0Cumulative,?uint?price1Cumulative,)?=?UniswapV2OracleLibrary.currentCumulativePrices(pair);

????????(address?token0,)?=?UniswapV2Library.sortTokens(tokenIn,?tokenOut);

????????if?(token0?==?tokenIn)?{

????????????return?computeAmountOut(firstObservation.price0Cumulative,?price0Cumulative,?timeElapsed,?amountIn);

????????}?else?{

????????????return?computeAmountOut(firstObservation.price1Cumulative,?price1Cumulative,?timeElapsed,?amountIn);

????????}

????}

}

要實現滑動時間窗口算法,就需要將時間分段,還需要保存每個時間段的priceCumulative。在這實現的示例代碼中,定義了結構體Observation,用來保存每個時間片段的數據,包括兩個token的priceCumulative和記錄的時間點timestamp。還定義了pairObservations用來存儲每個pair的Observation數組,而數組實際的長度取決于將整個時間窗口劃分為多少個時間片段。

windowSize表示時間窗口大小,比如24小時,granularity是劃分的時間片段數量,比如24段,periodSize則是每時間片段的大小,比如1小時,是由windowSize/granularity計算所得。這幾個值都在構造函數中進行了初始化。

觸發update()函數則更新存儲最新時間片段的observation,如時間片段大小為1小時,即每隔1小時就要觸發update()函數一次。因為這個示例中是支持多個pair的,所以update()時需要指定所要更新的兩個token。

而查詢當前TWAP價格的計算就在consult()函數里實現了。首先,先獲取到當前時間窗口里的第一個時間片段的observation,也算出當前時間與第一個observation時間的時間差,且讀取出當前最新的priceCumulative,之后就在computeAmountOut()函數里計算得到最新的TWAP價格priceAverage,且根據amountIn算出了amountOut并返回。

總結

本文我們主要介紹了被廣泛使用的一種鏈上預言機TWAP,且介紹了固定時間窗口和滑點時間窗口兩種算法的TWAP。雖然,TWAP是由Uniswap推出的,但因為很多其他DEX也采用了和Uniswap一樣的底層實現,如SushiSwap、PancakeSwap等,所以這些DEX也可以用同樣的算法計算出對應的TWAP。

但使用UniswapV2的TWAP,其主要缺陷就是需要鏈下程序定時觸發update()函數,存在維護成本。UniswapV3的TWAP則解決了這個問題,下一篇會來聊聊其具體是如何實現的。

文章首發于「Keegan小鋼」公眾號:

https://mp.weixin.qq.com/s?__biz=MzA5OTI1NDE0Mw==&mid=2652494441&idx=1&sn=57a97690390b93770c5a906dce4157c8&chksm=8b685079bc1fd96f9ab60cc1b41b8642abf807a13a37c12f05a280be2e03f3a9288a047b5739&token=1584634265&lang=zh_CN#rd

Tags:AMPPRIICERICEbitstamp比特幣PRINCESSjustice幣怎么樣goldricetoken

幣安下載
以太坊開發社區都在忙啥?參加了以太坊 DevConnect 大會 我學到了這五件事_CON

我剛從阿姆斯特丹的以太坊DevConnect大會回來。DevConnect由以太坊基金會組織,目標是讓所有以太坊開發人員集中在一個地方,這樣他們就可以同步進度.

1900/1/1 0:00:00
提營收、破圈層、擴社群 2022年國漫IP扎根數字藏品_預言家

2022年即將過去4個月,人們還在苦等第一個國漫爆款。然而,國漫領域的頭部IP們,已經把他們的觸手伸向了新的領域——數字藏品.

1900/1/1 0:00:00
金色午報 | 5月4日午間重要動態一覽_NFT

7:00-12:00關鍵詞:荔枝FM、Moonbirds、星巴克、MicroStrategy1.UGC音頻社區荔枝FM將于5月20日發布首款多人共創音頻數字藏品;2.

1900/1/1 0:00:00
金色觀察 | 以太坊擴容方案Optimism宣布將發行代幣OP并公布代幣經濟學_IMI

4月27日消息,以太坊擴容方案Optimism正式宣布將發行代幣OP并公布代幣經濟學,代幣初始總供應量為4,294,967,296個OP代幣,總供應量將以每年2%的速度膨脹.

1900/1/1 0:00:00
論述:NFT借貸及其運作方式_DEFI

加密領域的兩個方面正越來越受歡迎--NFT和DeFi。NFT,即非同質化代幣,是一類不能被復制或替代的加密資產.

1900/1/1 0:00:00
著名歷史學家尼爾·弗格森撰文:加密貨幣和美元是合作伙伴而不是競爭對手_加密貨幣

原標題:《CryptoandtheDollarArePartners,NotRivals》“我希望它能創造世界和平,或有助于創造世界和平.

1900/1/1 0:00:00
ads