generated from ZeframLou/foundry-template
/
BunniOracle.sol
727 lines (663 loc) · 30.9 KB
/
BunniOracle.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// SPDX-License-Identifier: AGPL-v3
pragma solidity ^0.8.4;
import {IBunniToken} from "bunni/src/interfaces/IBunniToken.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeCastLib} from "solmate/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
import {LiquidityAmounts} from "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import {Denominations} from "./external/Denominations.sol";
import {FeedRegistryInterface, AggregatorV2V3Interface} from "./external/FeedRegistryInterface.sol";
/// @title Price oracle for Bunni tokens and generalized Uniswap V3 positions
/// @author zefram.eth
/// @notice Uses a combination of Chainlink price oracles and Uniswap V3 built-in TWAP oracles
/// to compute the value of a Uniswap V3 liquidity position without being vulnerable to flashloan
/// manipulation attacks.
contract BunniOracle {
/// -----------------------------------------------------------------------
/// Libraries usage
/// -----------------------------------------------------------------------
using SafeCastLib for uint256;
using FixedPointMathLib for uint256;
/// -----------------------------------------------------------------------
/// Constants
/// -----------------------------------------------------------------------
uint256 internal constant BASE = 1e18; // result of quoteUSD uses 18 decimals
uint256 internal constant GRACE_PERIOD_TIME = 1 hours; // grace period after L2 sequencer downtime
/// -----------------------------------------------------------------------
/// Immutable args
/// -----------------------------------------------------------------------
/// @notice The Chainlink Feed Registry contract
/// @dev Since the Feed Registry only exists on Ethereum, this value will be
/// address(0) on non-Ethereum networks.
FeedRegistryInterface public immutable chainlink;
/// @notice The Chainlink uptime feed for deployment on L2s (e.g. Arbitrum, Optimism)
/// @dev Is address(0) for non-L2 networks (e.g. Ethereum, Polygon)
AggregatorV2V3Interface public immutable sequencerUptimeFeed;
address internal immutable WETH;
address internal immutable WBTC;
address internal immutable USDC;
address internal immutable USDT;
address internal immutable DAI;
address internal immutable FRAX;
/// -----------------------------------------------------------------------
/// Errors
/// -----------------------------------------------------------------------
error BunniOracle__SequencerDown();
error BunniOracle__GracePeriodNotOver();
error BunniOracle__ChainlinkPriceTooOld();
error BunniOracle__NoChainlinkPriceAvailable();
/// -----------------------------------------------------------------------
/// Constructor
/// -----------------------------------------------------------------------
constructor(
FeedRegistryInterface chainlink_,
AggregatorV2V3Interface sequencerUptimeFeed_,
address WETH_,
address WBTC_,
address USDC_,
address USDT_,
address DAI_,
address FRAX_
) {
chainlink = chainlink_;
sequencerUptimeFeed = sequencerUptimeFeed_;
WETH = WETH_;
WBTC = WBTC_;
USDC = USDC_;
USDT = USDT_;
DAI = DAI_;
FRAX = FRAX_;
}
/// -----------------------------------------------------------------------
/// External functions
/// -----------------------------------------------------------------------
/// @notice Computes the USD value of a Uniswap V3 liquidity position.
/// @dev This function is meant for ease of use: the number of input parameters is minimized
/// and we make external contract calls to obtain the token & price feed addresses. Only works
/// on Ethereum since the Feed Registry is only available there.
/// @param pool The Uniswap V3 pool
/// @param tickLower The lower tick of the liquidity position
/// @param tickUpper The upper tick of the liquidity position
/// @param liquidity The liquidity value of the position
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @return valueUSD The value of the liquidity position in USD, 18 decimals
function quoteUSD(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs
) external view returns (uint256 valueUSD) {
address token0 = pool.token0();
address token1 = pool.token1();
AggregatorV2V3Interface feed0;
AggregatorV2V3Interface feed1;
try chainlink.getFeed(_transformToken(token0), Denominations.USD) returns (AggregatorV2V3Interface f) {
feed0 = f;
} catch {}
try chainlink.getFeed(_transformToken(token1), Denominations.USD) returns (AggregatorV2V3Interface f) {
feed1 = f;
} catch {}
uint256 token0Base = _getTokenBase(token0);
uint256 token1Base = _getTokenBase(token1);
return _quoteUSD(
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
liquidity,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// @notice Computes the USD value of a Uniswap V3 liquidity position.
/// @dev This function is meant for ease of use: the number of input parameters is minimized
/// and we make external contract calls to obtain the token & price feed addresses. Only works
/// on Ethereum since the Feed Registry is only available there. Lets the user provide whether
/// a chainlink price feed exists for each token to save gas (~5k) in the case where only one token
/// has a feed
/// @param pool The Uniswap V3 pool
/// @param tickLower The lower tick of the liquidity position
/// @param tickUpper The upper tick of the liquidity position
/// @param liquidity The liquidity value of the position
/// @param feed0Exists Whether a chainlink price feed exists for token0 of the pool
/// @param feed1Exists Whether a chainlink price feed exists for token1 of the pool
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @return valueUSD The value of the liquidity position in USD, 18 decimals
function quoteUSD(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
bool feed0Exists,
bool feed1Exists,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs
) external view returns (uint256 valueUSD) {
address token0 = pool.token0();
address token1 = pool.token1();
AggregatorV2V3Interface feed0 = feed0Exists
? chainlink.getFeed(_transformToken(token0), Denominations.USD)
: AggregatorV2V3Interface(address(0));
AggregatorV2V3Interface feed1 = feed1Exists
? chainlink.getFeed(_transformToken(token1), Denominations.USD)
: AggregatorV2V3Interface(address(0));
uint256 token0Base = _getTokenBase(token0);
uint256 token1Base = _getTokenBase(token1);
return _quoteUSD(
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
liquidity,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// @notice Computes the USD value of a Uniswap V3 liquidity position.
/// @dev This function is meant for ease of use: the number of input parameters is minimized
/// and we make external contract calls to obtain the token & price feed addresses. Used on non-Ethereum
/// chains since there's no Feed Registry available.
/// If the Feed Registry is available and has a valid feed for a token, the feed from the registry will be used
/// instead of feed0/feed1.
/// @param pool The Uniswap V3 pool
/// @param tickLower The lower tick of the liquidity position
/// @param tickUpper The upper tick of the liquidity position
/// @param liquidity The liquidity value of the position
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @param feed0 The Chainlink price feed for token0. Use address(0) if not available.
/// @param feed1 The Chainlink price feed for token1. Use address(0) if not available.
/// @return valueUSD The value of the liquidity position in USD, 18 decimals
function quoteUSD(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs,
AggregatorV2V3Interface feed0,
AggregatorV2V3Interface feed1
) external view returns (uint256 valueUSD) {
address token0 = pool.token0();
address token1 = pool.token1();
uint256 token0Base = _getTokenBase(token0);
uint256 token1Base = _getTokenBase(token1);
return _quoteUSD(
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
liquidity,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// @notice Computes the USD value of a Uniswap V3 liquidity position.
/// @dev This function is meant for maximum gas efficiency: many parameters that could've been fetched
/// via external calls are instead input arguments. Used on non-Ethereum
/// chains since there's no Feed Registry available. If the wrong values are given for input arguments, the result
/// is undefined.
/// If the Feed Registry is available and has a valid feed for a token, the feed from the registry will be used
/// instead of feed0/feed1.
/// @param pool The Uniswap V3 pool
/// @param token0 token0 of the Uniswap pool
/// @param token1 token1 of the Uniswap pool
/// @param token0Base 10 ** token0Decimals
/// @param token1Base 10 ** token1Decimals
/// @param tickLower The lower tick of the liquidity position
/// @param tickUpper The upper tick of the liquidity position
/// @param liquidity The liquidity value of the position
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @param feed0 The Chainlink price feed for token0. Use address(0) if not available.
/// @param feed1 The Chainlink price feed for token1. Use address(0) if not available.
/// @return valueUSD The value of the liquidity position in USD, 18 decimals
function quoteUSD(
IUniswapV3Pool pool,
address token0,
address token1,
uint256 token0Base,
uint256 token1Base,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs,
AggregatorV2V3Interface feed0,
AggregatorV2V3Interface feed1
) external view returns (uint256 valueUSD) {
return _quoteUSD(
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
liquidity,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// @notice Computes the USD price of a Bunni LP token.
/// @dev This function is meant for ease of use: the number of input parameters is minimized
/// and we make external contract calls to obtain the token & price feed addresses. Only works
/// on Ethereum since the Feed Registry is only available there.
/// @param bunniToken The Bunni LP token
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @return priceUSD The price of the Bunni LP token in USD, 18 decimals
function bunniTokenPriceUSD(IBunniToken bunniToken, uint32 uniV3OracleSecondsAgo, uint256 chainlinkPriceMaxAgeSecs)
external
view
returns (uint256 priceUSD)
{
IUniswapV3Pool pool = bunniToken.pool();
address token0 = pool.token0();
address token1 = pool.token1();
AggregatorV2V3Interface feed0;
AggregatorV2V3Interface feed1;
try chainlink.getFeed(_transformToken(token0), Denominations.USD) returns (AggregatorV2V3Interface f) {
feed0 = f;
} catch {}
try chainlink.getFeed(_transformToken(token1), Denominations.USD) returns (AggregatorV2V3Interface f) {
feed1 = f;
} catch {}
int24 tickLower = bunniToken.tickLower();
int24 tickUpper = bunniToken.tickUpper();
uint256 token0Base = _getTokenBase(token0);
uint256 token1Base = _getTokenBase(token1);
return _bunniTokenPriceUSD(
bunniToken,
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// @notice Computes the USD price of a Bunni LP token.
/// @dev This function is meant for ease of use: the number of input parameters is minimized
/// and we make external contract calls to obtain the token & price feed addresses. Only works
/// on Ethereum since the Feed Registry is only available there. Lets the user provide whether
/// a chainlink price feed exists for each token to save gas (~5k) in the case where only one token
/// has a feed
/// @param bunniToken The Bunni LP token
/// @param feed0Exists Whether a chainlink price feed exists for token0 of the pool
/// @param feed1Exists Whether a chainlink price feed exists for token1 of the pool
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @return priceUSD The price of the Bunni LP token in USD, 18 decimals
function bunniTokenPriceUSD(
IBunniToken bunniToken,
bool feed0Exists,
bool feed1Exists,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs
) external view returns (uint256 priceUSD) {
IUniswapV3Pool pool = bunniToken.pool();
address token0 = pool.token0();
address token1 = pool.token1();
AggregatorV2V3Interface feed0 = feed0Exists
? chainlink.getFeed(_transformToken(token0), Denominations.USD)
: AggregatorV2V3Interface(address(0));
AggregatorV2V3Interface feed1 = feed1Exists
? chainlink.getFeed(_transformToken(token1), Denominations.USD)
: AggregatorV2V3Interface(address(0));
int24 tickLower = bunniToken.tickLower();
int24 tickUpper = bunniToken.tickUpper();
uint256 token0Base = _getTokenBase(token0);
uint256 token1Base = _getTokenBase(token1);
return _bunniTokenPriceUSD(
bunniToken,
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// @notice Computes the USD price of a Bunni LP token.
/// @dev This function is meant for ease of use: the number of input parameters is minimized
/// and we make external contract calls to obtain the token & price feed addresses. Used on non-Ethereum
/// chains since there's no Feed Registry available.
/// If the Feed Registry is available and has a valid feed for a token, the feed from the registry will be used
/// instead of feed0/feed1.
/// @param bunniToken The Bunni LP token
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @param feed0 The Chainlink price feed for token0. Use address(0) if not available.
/// @param feed1 The Chainlink price feed for token1. Use address(0) if not available.
/// @return priceUSD The price of the Bunni LP token in USD, 18 decimals
function bunniTokenPriceUSD(
IBunniToken bunniToken,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs,
AggregatorV2V3Interface feed0,
AggregatorV2V3Interface feed1
) external view returns (uint256 priceUSD) {
IUniswapV3Pool pool = bunniToken.pool();
address token0 = pool.token0();
address token1 = pool.token1();
int24 tickLower = bunniToken.tickLower();
int24 tickUpper = bunniToken.tickUpper();
uint256 token0Base = _getTokenBase(token0);
uint256 token1Base = _getTokenBase(token1);
return _bunniTokenPriceUSD(
bunniToken,
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// @notice Computes the USD price of a Bunni LP token.
/// @dev This function is meant for maximum gas efficiency: many parameters that could've been fetched
/// via external calls are instead input arguments. Used on non-Ethereum
/// chains since there's no Feed Registry available. If the wrong values are given for input arguments, the result
/// is undefined.
/// If the Feed Registry is available and has a valid feed for a token, the feed from the registry will be used
/// instead of feed0/feed1.
/// @param bunniToken The Bunni LP token
/// @param uniV3OracleSecondsAgo The size of the TWAP window used by the Uniswap V3 TWAP oracle in seconds.
/// Ignored if both token0 and token1 have chainlink price feeds. The call reverts if the TWAP oracle
/// doesn't have observations old enough in the past to support the window size.
/// @param chainlinkPriceMaxAgeSecs The maximum age of the results returned by chainlink in seconds.
/// The call reverts if the result is older than this value.
/// @param feed0 The Chainlink price feed for token0. Use address(0) if not available.
/// @param feed1 The Chainlink price feed for token1. Use address(0) if not available.
/// @return priceUSD The price of the Bunni LP token in USD, 18 decimals
function bunniTokenPriceUSD(
IBunniToken bunniToken,
IUniswapV3Pool pool,
address token0,
address token1,
uint256 token0Base,
uint256 token1Base,
int24 tickLower,
int24 tickUpper,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs,
AggregatorV2V3Interface feed0,
AggregatorV2V3Interface feed1
) external view returns (uint256 priceUSD) {
return _bunniTokenPriceUSD(
bunniToken,
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
/// -----------------------------------------------------------------------
/// Internal functions
/// -----------------------------------------------------------------------
function _quoteUSD(
IUniswapV3Pool pool,
address token0,
address token1,
uint256 token0Base,
uint256 token1Base,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs,
AggregatorV2V3Interface feed0,
AggregatorV2V3Interface feed1
) internal view returns (uint256 valueUSD) {
uint256 price0USD;
uint256 price1USD;
uint256 decimals0; // num of decimals used by price0USD
uint256 decimals1; // num of decimals used by price1USD
// handle different cases based on availability of chainlink price feed
{
if (address(feed0) != address(0) && address(feed1) != address(0)) {
// both tokens have chainlink price
// fetch prices from chainlink
(price0USD, decimals0) = _getPriceUSDFromFeed(feed0, token0, chainlinkPriceMaxAgeSecs);
(price1USD, decimals1) = _getPriceUSDFromFeed(feed1, token1, chainlinkPriceMaxAgeSecs);
} else if (address(feed0) != address(0)) {
// feed0 != 0, feed1 == 0
// token0 has chainlink price
// fetch prices from chainlink
(price0USD, decimals0) = _getPriceUSDFromFeed(feed0, token0, chainlinkPriceMaxAgeSecs);
// compute price1USD using Uniswap v3 TWAP oracle
(int24 arithmeticMeanTick,) = OracleLibrary.consult(address(pool), uniV3OracleSecondsAgo);
uint256 quoteAmount =
OracleLibrary.getQuoteAtTick(arithmeticMeanTick, token1Base.safeCastTo128(), token1, token0); // price of token1 in token0
(price1USD, decimals1) = (quoteAmount.mulDivDown(price0USD, token0Base), decimals0);
} else if (address(feed1) != address(0)) {
// feed0 == 0, feed1 != 0
// token1 has chainlink price
// fetch prices from chainlink
(price1USD, decimals1) = _getPriceUSDFromFeed(feed1, token1, chainlinkPriceMaxAgeSecs);
// compute price0USD using Uniswap v3 TWAP oracle
(int24 arithmeticMeanTick,) = OracleLibrary.consult(address(pool), uniV3OracleSecondsAgo);
uint256 quoteAmount =
OracleLibrary.getQuoteAtTick(arithmeticMeanTick, token0Base.safeCastTo128(), token0, token1); // price of token0 in token1
(price0USD, decimals0) = (quoteAmount.mulDivDown(price1USD, token1Base), decimals1);
} else {
// neither token has chainlink price
// cannot compute USD price in this case
revert BunniOracle__NoChainlinkPriceAvailable();
}
}
// use token prices to compute sqrtRatioX96 and then compute token amounts for liquidity
(uint256 amount0, uint256 amount1) = LiquidityAmounts.getAmountsForLiquidity(
_getSqrtRatioX96(price0USD, price1USD, decimals0, decimals1, token0Base, token1Base),
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
// add up position value of both tokens
valueUSD = amount0.mulDivDown(price0USD, 10 ** decimals0).mulDivDown(BASE, token0Base)
+ amount1.mulDivDown(price1USD, 10 ** decimals1).mulDivDown(BASE, token1Base);
}
function _bunniTokenPriceUSD(
IBunniToken bunniToken,
IUniswapV3Pool pool,
address token0,
address token1,
uint256 token0Base,
uint256 token1Base,
int24 tickLower,
int24 tickUpper,
uint32 uniV3OracleSecondsAgo,
uint256 chainlinkPriceMaxAgeSecs,
AggregatorV2V3Interface feed0,
AggregatorV2V3Interface feed1
) internal view returns (uint256 priceUSD) {
uint128 liquidity;
{
uint256 existingShareSupply = bunniToken.totalSupply();
if (existingShareSupply == 0) {
return 0;
} else {
// fetch total liquidity of Bunni token's position
(liquidity,,,,) = pool.positions(keccak256(abi.encodePacked(bunniToken.hub(), tickLower, tickUpper)));
// compute liquidity per Bunni token
// liquidity is uint128, BASE uses 60 bits
// so liquidity * BASE can't overflow 256 bits
liquidity = uint128((liquidity * BASE) / existingShareSupply);
}
}
return _quoteUSD(
pool,
token0,
token1,
token0Base,
token1Base,
tickLower,
tickUpper,
liquidity,
uniV3OracleSecondsAgo,
chainlinkPriceMaxAgeSecs,
feed0,
feed1
);
}
function _getPriceUSDFromFeed(AggregatorV2V3Interface feed, address token, uint256 chainlinkPriceMaxAgeSecs)
internal
view
returns (uint256 priceUSD, uint256 decimals)
{
// ensure the L2 sequencer is up if this is an L2 deployment
if (address(sequencerUptimeFeed) != address(0)) {
(, int256 answer, uint256 startedAt,,) = sequencerUptimeFeed.latestRoundData();
// Answer == 0: Sequencer is up
// Answer == 1: Sequencer is down
if (answer != 0) {
revert BunniOracle__SequencerDown();
}
// Make sure the grace period has passed after the
// sequencer is back up.
uint256 timeSinceUp = block.timestamp - startedAt;
if (timeSinceUp <= GRACE_PERIOD_TIME) {
revert BunniOracle__GracePeriodNotOver();
}
}
// fetch USD price of tokens from chainlink
// prices use 8 decimals
int256 priceUSDInt;
uint256 updatedAt;
if (address(chainlink) != address(0)) {
// FeedRegistry is available
(, priceUSDInt,, updatedAt,) = chainlink.latestRoundData(_transformToken(token), Denominations.USD);
if (token == WETH || token == USDC || token == WBTC || token == USDT || token == DAI || token == FRAX) {
decimals = 8;
} else {
decimals = chainlink.decimals(_transformToken(token), Denominations.USD);
}
} else {
// FeedRegistry is not available
(, priceUSDInt,, updatedAt,) = feed.latestRoundData();
if (token == WETH || token == USDC || token == WBTC || token == USDT || token == DAI || token == FRAX) {
decimals = 8;
} else {
decimals = feed.decimals();
}
}
// revert if the result is stale
if (block.timestamp - updatedAt > chainlinkPriceMaxAgeSecs) revert BunniOracle__ChainlinkPriceTooOld();
// set return priceUSD value
priceUSD = uint256(priceUSDInt);
}
function _getSqrtRatioX96(
uint256 price0USD,
uint256 price1USD,
uint256 decimals0,
uint256 decimals1,
uint256 token0Base,
uint256 token1Base
) internal pure returns (uint160) {
// Note: amount1 and amount0 may have different decimals which needs to be accounted for via token0Base and token1Base
// sqrtRatioX96 = sqrt(amount1 / amount0) * 2**96
// = sqrt((price0USD * 10**decimals1 * token1Base) / (price1USD * 10**decimals0 * token0Base)) * 2**96
// = sqrt((price0USD * 10**decimals1 * token1Base * 2**96) / (price1USD * 10**decimals0 * token0Base)) * 2**48
return (
(((price0USD * 10 ** decimals1 * token1Base) << 96) / (price1USD * 10 ** decimals0 * token0Base)).sqrt()
<< 48
).safeCastTo160();
}
function _transformToken(address token) internal view returns (address) {
// transforms WETH and WBTC to addresses accepted by chainlink
if (token == WETH) {
return Denominations.ETH;
} else if (token == WBTC) {
return Denominations.BTC;
} else {
return token;
}
}
function _getTokenBase(address token) internal view returns (uint256) {
// use hardcoded values for common tokens
// to save gas
if (token == WETH) {
return BASE;
} else if (token == USDC) {
return 1e6;
} else if (token == WBTC) {
return 1e8;
} else if (token == USDT) {
return 1e6;
} else if (token == DAI) {
return BASE;
} else if (token == FRAX) {
return BASE;
} else {
return 10 ** uint256(ERC20(token).decimals());
}
}
}