-
Notifications
You must be signed in to change notification settings - Fork 93
/
pricing.ts
425 lines (359 loc) · 15.1 KB
/
pricing.ts
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
import { Address, Bytes, BigInt, BigDecimal, log, dataSource } from '@graphprotocol/graph-ts';
import { Pool, TokenPrice, Balancer, PoolHistoricalLiquidity, LatestPrice, Token, FXOracle } from '../types/schema';
import { VNXAU_ADDRESS } from './helpers/assets';
import {
ZERO_BD,
PRICING_ASSETS,
USD_STABLE_ASSETS,
ONE_BD,
ZERO_ADDRESS,
MIN_POOL_LIQUIDITY,
} from './helpers/constants';
import { hasVirtualSupply, isComposableStablePool, isLinearPool, isFXPool, PoolType } from './helpers/pools';
import {
bytesToAddress,
createPoolSnapshot,
getBalancerSnapshot,
getToken,
getTokenPriceId,
loadPoolToken,
scaleDown,
} from './helpers/misc';
import { AaveLinearPool } from '../types/AaveLinearPoolFactory/AaveLinearPool';
import {
FX_ASSET_AGGREGATORS,
MAX_POS_PRICE_CHANGE,
MAX_NEG_PRICE_CHANGE,
MAX_TIME_DIFF_FOR_PRICING,
} from './helpers/constants';
import { AnswerUpdated } from '../types/templates/OffchainAggregator/AccessControlledOffchainAggregator';
export function isPricingAsset(asset: Address): boolean {
for (let i: i32 = 0; i < PRICING_ASSETS.length; i++) {
if (PRICING_ASSETS[i] == asset) return true;
}
return false;
}
export function getPreferentialPricingAsset(assets: Address[]): Address {
// Assumes PRICING_ASSETS are sorted by order of preference
for (let i: i32 = 0; i < PRICING_ASSETS.length; i++) {
if (assets.includes(PRICING_ASSETS[i])) return PRICING_ASSETS[i];
}
return ZERO_ADDRESS;
}
export function addHistoricalPoolLiquidityRecord(poolId: string, block: BigInt, pricingAsset: Address): boolean {
let pool = Pool.load(poolId);
if (pool == null) return false;
let tokensList: Bytes[] = pool.tokensList;
if (tokensList.length < 2) return false;
if (hasVirtualSupply(pool) && pool.address == pricingAsset) return false;
let poolValue: BigDecimal = ZERO_BD;
for (let j: i32 = 0; j < tokensList.length; j++) {
let tokenAddress: Address = Address.fromString(tokensList[j].toHexString());
let poolToken = loadPoolToken(poolId, tokenAddress);
if (poolToken == null) continue;
if (tokenAddress == pricingAsset) {
poolValue = poolValue.plus(poolToken.balance);
continue;
}
let poolTokenQuantity: BigDecimal = poolToken.balance;
let price: BigDecimal = ZERO_BD;
let latestPriceId = getLatestPriceId(tokenAddress, pricingAsset);
let latestPrice = LatestPrice.load(latestPriceId);
// note that we can only meaningfully report liquidity once assets are traded with
// the pricing asset
if (latestPrice) {
// value in terms of priceableAsset
price = latestPrice.price;
} else if (pool.poolType == PoolType.StablePhantom || isComposableStablePool(pool)) {
// try to estimate token price in terms of pricing asset
let pricingAssetInUSD = valueInUSD(ONE_BD, pricingAsset);
let currentTokenInUSD = valueInUSD(ONE_BD, tokenAddress);
if (pricingAssetInUSD.equals(ZERO_BD) || currentTokenInUSD.equals(ZERO_BD)) {
continue;
}
price = currentTokenInUSD.div(pricingAssetInUSD);
}
// Exclude virtual supply from pool value
if (hasVirtualSupply(pool) && pool.address == tokenAddress) {
continue;
}
if (price.gt(ZERO_BD)) {
let poolTokenValue = price.times(poolTokenQuantity);
poolValue = poolValue.plus(poolTokenValue);
}
}
const newPoolLiquidity: BigDecimal = valueInUSD(poolValue, pricingAsset) || ZERO_BD;
// If the pool isn't empty but we have a zero USD value then it's likely that we have a bad pricing asset
// Don't commit any changes and just report the failure.
if (poolValue.gt(ZERO_BD) != newPoolLiquidity.gt(ZERO_BD)) {
return false;
}
// Take snapshot of pool state
let phlId = getPoolHistoricalLiquidityId(poolId, pricingAsset, block);
let phl = new PoolHistoricalLiquidity(phlId);
phl.poolId = poolId;
phl.pricingAsset = pricingAsset;
phl.block = block;
phl.poolTotalShares = pool.totalShares;
phl.poolLiquidity = poolValue;
phl.poolShareValue = pool.totalShares.gt(ZERO_BD) ? poolValue.div(pool.totalShares) : ZERO_BD;
phl.save();
return true;
}
export function updatePoolLiquidity(poolId: string, block_number: BigInt, timestamp: BigInt): boolean {
let pool = Pool.load(poolId);
if (pool == null) return false;
let tokensList: Bytes[] = pool.tokensList;
let newPoolLiquidity: BigDecimal = ZERO_BD;
let newPoolLiquiditySansBPT: BigDecimal = ZERO_BD;
for (let j: i32 = 0; j < tokensList.length; j++) {
let tokenAddress: Address = Address.fromString(tokensList[j].toHexString());
// Exclude virtual supply from pool value
if (hasVirtualSupply(pool) && pool.address == tokenAddress) {
continue;
}
let poolToken = loadPoolToken(poolId, tokenAddress);
if (poolToken == null) continue;
let poolTokenQuantity: BigDecimal = poolToken.balance;
let poolTokenValue: BigDecimal = ZERO_BD;
if (!isFXPool(pool)) {
poolTokenValue = valueInUSD(poolTokenQuantity, tokenAddress);
} else {
// Custom computation for FXPool tokens
poolTokenValue = valueInFX(poolTokenQuantity, tokenAddress);
}
newPoolLiquidity = newPoolLiquidity.plus(poolTokenValue);
let token = getToken(tokenAddress);
if (token.pool == null) {
newPoolLiquiditySansBPT = newPoolLiquiditySansBPT.plus(poolTokenValue);
}
}
// Update pool stats
let liquidityChange = ZERO_BD;
let oldPoolLiquidity = pool.totalLiquidity;
let oldPoolLiquiditySansBPT = pool.totalLiquiditySansBPT;
if (dataSource.network() == 'arbitrum' || dataSource.network() == 'matic') {
// keep old logic on arbitrum and polygon to avoid breaking liquidity charts
liquidityChange = newPoolLiquidity.minus(oldPoolLiquidity);
} else if (oldPoolLiquiditySansBPT) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
liquidityChange = newPoolLiquiditySansBPT.minus(oldPoolLiquiditySansBPT!);
}
pool.totalLiquiditySansBPT = newPoolLiquiditySansBPT;
pool.totalLiquidity = newPoolLiquidity;
pool.save();
// We want to avoid too frequently calling setWrappedTokenPrice because it makes a call to the rate provider
// Doing it here allows us to do it only once, when the MIN_POOL_LIQUIDITY threshold is crossed
if (oldPoolLiquidity < MIN_POOL_LIQUIDITY) {
setWrappedTokenPrice(pool, poolId, block_number, timestamp);
}
// update BPT price
if (newPoolLiquidity.gt(MIN_POOL_LIQUIDITY)) {
updateBptPrice(pool);
}
// Create or update pool daily snapshot
createPoolSnapshot(pool, timestamp.toI32());
// Update global stats
let vault = Balancer.load('2') as Balancer;
vault.totalLiquidity = vault.totalLiquidity.plus(liquidityChange);
vault.save();
let vaultSnapshot = getBalancerSnapshot(vault.id, timestamp.toI32());
vaultSnapshot.totalLiquidity = vault.totalLiquidity;
vaultSnapshot.save();
return true;
}
export function valueInUSD(value: BigDecimal, asset: Address): BigDecimal {
let usdValue = ZERO_BD;
if (isUSDStable(asset)) {
usdValue = value;
} else {
// convert to USD
let token = getToken(asset);
if (token.latestUSDPrice) {
const latestUSDPrice = token.latestUSDPrice as BigDecimal;
usdValue = value.times(latestUSDPrice);
}
}
return usdValue;
}
export function valueInFX(value: BigDecimal, asset: Address): BigDecimal {
let token = getToken(asset);
if (token.latestFXPrice) {
// convert to USD using latestFXPrice
const latestFXPrice = token.latestFXPrice as BigDecimal;
return value.times(latestFXPrice);
} else {
// fallback if latestFXPrice is not available
return valueInUSD(value, asset);
}
}
export function updateBptPrice(pool: Pool): void {
if (pool.totalShares.equals(ZERO_BD)) return;
const bptAddress = Address.fromString(pool.address.toHexString());
let bptToken = getToken(bptAddress);
bptToken.latestUSDPrice = pool.totalLiquidity.div(pool.totalShares);
bptToken.save();
}
export function swapValueInUSD(
tokenInAddress: Address,
tokenAmountIn: BigDecimal,
tokenOutAddress: Address,
tokenAmountOut: BigDecimal
): BigDecimal {
let swapValueUSD = ZERO_BD;
if (isUSDStable(tokenOutAddress)) {
// if one of the tokens is a stable, it takes precedence
swapValueUSD = valueInUSD(tokenAmountOut, tokenOutAddress);
return swapValueUSD;
} else if (isUSDStable(tokenInAddress)) {
// if one of the tokens is a stable, it takes precedence
swapValueUSD = valueInUSD(tokenAmountIn, tokenInAddress);
return swapValueUSD;
}
if (isPricingAsset(tokenInAddress) && !isPricingAsset(tokenOutAddress)) {
// if only one of the tokens is a pricing asset, it takes precedence
swapValueUSD = valueInUSD(tokenAmountIn, tokenInAddress);
if (swapValueUSD.gt(ZERO_BD)) return swapValueUSD;
}
if (isPricingAsset(tokenOutAddress) && !isPricingAsset(tokenInAddress)) {
// if only one of the tokens is a pricing asset, it takes precedence
swapValueUSD = valueInUSD(tokenAmountOut, tokenOutAddress);
if (swapValueUSD.gt(ZERO_BD)) return swapValueUSD;
}
// if none or both tokens are pricing assets, take the average of the known prices
let tokenInSwapValueUSD = valueInUSD(tokenAmountIn, tokenInAddress);
let tokenOutSwapValueUSD = valueInUSD(tokenAmountOut, tokenOutAddress);
let divisor =
tokenInSwapValueUSD.gt(ZERO_BD) && tokenOutSwapValueUSD.gt(ZERO_BD) ? BigDecimal.fromString('2') : ONE_BD;
swapValueUSD = tokenInSwapValueUSD.plus(tokenOutSwapValueUSD).div(divisor);
return swapValueUSD;
}
export function getLatestPriceId(tokenAddress: Address, pricingAsset: Address): string {
return tokenAddress.toHexString().concat('-').concat(pricingAsset.toHexString());
}
export function updateLatestPrice(tokenPrice: TokenPrice, blockTimestamp: BigInt): void {
let tokenAddress = Address.fromString(tokenPrice.asset.toHexString());
let pricingAsset = Address.fromString(tokenPrice.pricingAsset.toHexString());
let latestPriceId = getLatestPriceId(tokenAddress, pricingAsset);
let latestPrice = LatestPrice.load(latestPriceId);
if (latestPrice == null) {
latestPrice = new LatestPrice(latestPriceId);
latestPrice.asset = tokenPrice.asset;
latestPrice.pricingAsset = tokenPrice.pricingAsset;
}
latestPrice.block = tokenPrice.block;
latestPrice.poolId = tokenPrice.poolId;
latestPrice.price = tokenPrice.price;
latestPrice.save();
let token = getToken(tokenAddress);
const pricingAssetAddress = Address.fromString(tokenPrice.pricingAsset.toHexString());
const currentUSDPrice = valueInUSD(tokenPrice.price, pricingAssetAddress);
if (currentUSDPrice == ZERO_BD) return;
let oldUSDPrice = token.latestUSDPrice;
if (!oldUSDPrice || oldUSDPrice.equals(ZERO_BD)) {
token.latestUSDPriceTimestamp = blockTimestamp;
token.latestUSDPrice = currentUSDPrice;
token.latestPrice = latestPrice.id;
token.save();
return;
}
let change = currentUSDPrice.minus(oldUSDPrice).div(oldUSDPrice);
if (
!token.latestUSDPriceTimestamp ||
(change.lt(MAX_POS_PRICE_CHANGE) && change.gt(MAX_NEG_PRICE_CHANGE)) ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
blockTimestamp.minus(token.latestUSDPriceTimestamp!).gt(MAX_TIME_DIFF_FOR_PRICING)
) {
token.latestUSDPriceTimestamp = blockTimestamp;
token.latestUSDPrice = currentUSDPrice;
token.latestPrice = latestPrice.id;
token.save();
}
}
function getPoolHistoricalLiquidityId(poolId: string, tokenAddress: Address, block: BigInt): string {
return poolId.concat('-').concat(tokenAddress.toHexString()).concat('-').concat(block.toString());
}
export function isUSDStable(asset: Address): boolean {
for (let i: i32 = 0; i < USD_STABLE_ASSETS.length; i++) {
if (USD_STABLE_ASSETS[i] == asset) return true;
}
return false;
}
// The wrapped token in a linear pool is hardly ever traded, meaning we rarely compute its USD price
// This creates an exceptional entry for the token price of the wrapped token,
// with the main token as the pricing asset even if it's not globally defined as one
export function setWrappedTokenPrice(pool: Pool, poolId: string, block_number: BigInt, timestamp: BigInt): void {
if (isLinearPool(pool)) {
if (pool.totalLiquidity.gt(MIN_POOL_LIQUIDITY)) {
const poolAddress = bytesToAddress(pool.address);
let poolContract = AaveLinearPool.bind(poolAddress);
let rateCall = poolContract.try_getWrappedTokenRate();
if (rateCall.reverted) {
log.info('getWrappedTokenRate reverted', []);
} else {
const rate = rateCall.value;
const amount = BigDecimal.fromString('1');
const asset = bytesToAddress(pool.tokensList[pool.wrappedIndex]);
const pricingAsset = bytesToAddress(pool.tokensList[pool.mainIndex]);
const price = scaleDown(rate, 18);
let tokenPriceId = getTokenPriceId(poolId, asset, pricingAsset, block_number);
let tokenPrice = new TokenPrice(tokenPriceId);
tokenPrice.poolId = poolId;
tokenPrice.block = block_number;
tokenPrice.timestamp = timestamp.toI32();
tokenPrice.asset = asset;
tokenPrice.pricingAsset = pricingAsset;
tokenPrice.amount = amount;
tokenPrice.price = price;
tokenPrice.save();
updateLatestPrice(tokenPrice, timestamp);
}
}
}
}
export function handleAnswerUpdated(event: AnswerUpdated): void {
const aggregatorAddress = event.address;
const answer = event.params.current;
const tokenAddressesToUpdate: Address[] = [];
// Check if the aggregator is under FX_ASSET_AGGREGATORS first (FXPoolFactory version)
for (let i = 0; i < FX_ASSET_AGGREGATORS.length; i++) {
if (aggregatorAddress == FX_ASSET_AGGREGATORS[i][1]) {
tokenAddressesToUpdate.push(FX_ASSET_AGGREGATORS[i][0]);
}
}
// Also check if aggregator exists from FXOracle entity (FXPoolDeployer version)
let oracle = FXOracle.load(aggregatorAddress.toHexString());
if (oracle) {
for (let i = 0; i < oracle.tokens.length; i++) {
const tokenAddress = Address.fromBytes(oracle.tokens[i]);
const tokenExists = tokenAddressesToUpdate.includes(tokenAddress);
if (!tokenExists) {
tokenAddressesToUpdate.push(tokenAddress);
}
}
}
// Update all tokens using this aggregator
for (let i = 0; i < tokenAddressesToUpdate.length; i++) {
const tokenAddress = tokenAddressesToUpdate[i];
const token = Token.load(tokenAddress.toHexString());
if (token == null) {
log.warning('Token with address {} not found', [tokenAddress.toHexString()]);
return;
}
// All tokens we track have oracles with 8 decimals
if (!token.fxOracleDecimals) {
token.fxOracleDecimals = 8; // @todo: get decimals on-chain
}
if (tokenAddress != ZERO_ADDRESS && tokenAddress == VNXAU_ADDRESS) {
// XAU-USD oracle returns an answer with price unit of "USD per troy ounce"
// For VNXAU however, we wanna use a price unit of "USD per gram"
const divisor = '3110347680'; // 31.1034768 * 1e8 (31.10 gram per troy ounce)
const multiplier = '100000000'; // 1 * 1e8
const pricePerGram = answer.times(BigInt.fromString(multiplier)).div(BigInt.fromString(divisor));
token.latestFXPrice = scaleDown(pricePerGram, 8);
} else {
token.latestFXPrice = scaleDown(answer, 8);
}
token.save();
}
}