This repository has been archived by the owner on Jan 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 381
/
app-token.template.position-fetcher.ts
387 lines (322 loc) · 15.2 KB
/
app-token.template.position-fetcher.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
import { Inject } from '@nestjs/common';
import { BigNumberish, Contract } from 'ethers/lib/ethers';
import _, { isEqual, isNumber, uniqWith } from 'lodash';
import { compact, intersection, isArray, partition, sortBy, sum } from 'lodash';
import { drillBalance } from '~app-toolkit';
import { APP_TOOLKIT, IAppToolkit } from '~app-toolkit/app-toolkit.interface';
import { ZERO_ADDRESS } from '~app-toolkit/constants/address';
import {
buildDollarDisplayItem,
buildPercentageDisplayItem,
} from '~app-toolkit/helpers/presentation/display-item.present';
import { getImagesFromToken } from '~app-toolkit/helpers/presentation/image.present';
import { IMulticallWrapper } from '~multicall';
import { isMulticallUnderlyingError } from '~multicall/multicall.ethers';
import { ContractType } from '~position/contract.interface';
import { DisplayProps, StatsItem } from '~position/display.interface';
import { AppTokenPositionBalance, RawAppTokenBalance } from '~position/position-balance.interface';
import { PositionFetcher } from '~position/position-fetcher.interface';
import { AppTokenPosition } from '~position/position.interface';
import { Network } from '~types/network.interface';
import {
DefaultAppTokenDefinition,
DefaultAppTokenDataProps,
GetAddressesParams,
GetDataPropsParams,
GetDefinitionsParams,
GetDisplayPropsParams,
GetPricePerShareParams,
GetPriceParams,
GetTokenPropsParams,
GetUnderlyingTokensParams,
UnderlyingTokenDefinition,
} from './app-token.template.types';
import { PositionFetcherTemplateCommons } from './position-fetcher.template.types';
export abstract class AppTokenTemplatePositionFetcher<
T extends Contract,
V extends DefaultAppTokenDataProps = DefaultAppTokenDataProps,
R extends DefaultAppTokenDefinition = DefaultAppTokenDefinition,
> implements PositionFetcher<AppTokenPosition<V>>, PositionFetcherTemplateCommons
{
appId: string;
groupId: string;
network: Network;
isDebt = false;
abstract groupLabel: string;
isExcludedFromBalances = false;
isExcludedFromExplore = false;
isExcludedFromTvl = false;
minLiquidity = 1000;
constructor(@Inject(APP_TOOLKIT) protected readonly appToolkit: IAppToolkit) {}
// 1. Get token contract instance
abstract getContract(address: string): T;
// 2. Get token addresses
abstract getAddresses(params: GetAddressesParams): string[] | Promise<string[]>;
// 3. (Optional) Get token definitions (i.e.: token addresses and additional context)
async getDefinitions(params: GetDefinitionsParams): Promise<R[]> {
const addresses = await this.getAddresses({ ...params, definitions: [] });
return addresses.map(address => ({ address: address.toLowerCase() } as R));
}
// 4. Get underlying token addresses
abstract getUnderlyingTokenDefinitions(
_params: GetUnderlyingTokensParams<T, R>,
): Promise<UnderlyingTokenDefinition[]>;
// 5A. Get symbol (ERC20 standard)
async getSymbol({ address, multicall }: GetTokenPropsParams<T, R>): Promise<string> {
const erc20 = this.appToolkit.globalContracts.erc20({ address, network: this.network });
return multicall.wrap(erc20).symbol();
}
// 5B. Get decimals (ERC20 standard)
async getDecimals({ address, multicall }: GetTokenPropsParams<T, R>): Promise<number> {
const erc20 = this.appToolkit.globalContracts.erc20({ address, network: this.network });
return multicall.wrap(erc20).decimals();
}
// 5C. Get supply (ERC20 standard)
async getSupply({ address, multicall }: GetTokenPropsParams<T, R>): Promise<BigNumberish> {
const erc20 = this.appToolkit.globalContracts.erc20({ address, network: this.network });
return multicall.wrap(erc20).totalSupply();
}
// 6. Get price per share (ratio between token and underlying token)
async getPricePerShare(_params: GetPricePerShareParams<T, V, R>): Promise<number | number[]> {
return 1;
}
// 7. Get price using the price per share
async getPrice({ appToken }: GetPriceParams<T, V, R>): Promise<number> {
return sum(appToken.tokens.map((v, i) => v.price * appToken.pricePerShare[i]));
}
async getLiquidity({ appToken }: GetDataPropsParams<T, V, R>) {
return appToken.supply * appToken.price;
}
async getReserves({ appToken }: GetDataPropsParams<T, V, R>) {
return (appToken.pricePerShare as number[]).map(v => v * appToken.supply);
}
async getApy(_params: GetDataPropsParams<T, V, R>) {
return 0;
}
async getDataProps(params: GetDataPropsParams<T, V, R>): Promise<V> {
const [liquidity, reserves, apy] = await Promise.all([
this.getLiquidity(params),
this.getReserves(params),
this.getApy(params),
]);
return { liquidity, reserves, apy } as V;
}
// Display Properties
async getLabel({ appToken }: GetDisplayPropsParams<T, V, R>): Promise<DisplayProps['label']> {
return appToken.symbol;
}
async getLabelDetailed(_params: GetDisplayPropsParams<T, V, R>): Promise<DisplayProps['labelDetailed']> {
return undefined;
}
async getSecondaryLabel({ appToken }: GetDisplayPropsParams<T, V, R>): Promise<DisplayProps['secondaryLabel']> {
return buildDollarDisplayItem(appToken.price);
}
async getTertiaryLabel({ appToken }: GetDisplayPropsParams<T, V, R>): Promise<DisplayProps['tertiaryLabel']> {
if (typeof appToken.dataProps.apy === 'number' && appToken.dataProps.apy > 0)
return `${appToken.dataProps.apy.toFixed(3)}% APY`;
return undefined;
}
async getImages({ appToken }: GetDisplayPropsParams<T, V, R>): Promise<DisplayProps['images']> {
return appToken.tokens.flatMap(v => getImagesFromToken(v));
}
async getBalanceDisplayMode(_params: GetDisplayPropsParams<T, V, R>): Promise<DisplayProps['balanceDisplayMode']> {
return undefined;
}
async getStatsItems({ appToken }: GetDisplayPropsParams<T, V, R>): Promise<DisplayProps['statsItems']> {
const statsItems: StatsItem[] = [];
// Standardized Fields
if (typeof appToken.dataProps.liquidity === 'number')
statsItems.push({ label: 'Liquidity', value: buildDollarDisplayItem(appToken.dataProps.liquidity) });
if (typeof appToken.dataProps.apy === 'number' && appToken.dataProps.apy > 0)
statsItems.push({ label: 'APY', value: buildPercentageDisplayItem(appToken.dataProps.apy) });
return statsItems;
}
async getPositionsForBatch(definitions: R[]) {
const multicall = this.appToolkit.getMulticall(this.network);
const tokenLoader = this.appToolkit.getTokenDependencySelector({
tags: { network: this.network, context: `${this.appId}__template` },
});
const maybeSkeletons = await Promise.all(
definitions.map(async definition => {
const address = definition.address.toLowerCase();
const contract = multicall.wrap(this.getContract(address));
const context = { address, definition, contract, multicall, tokenLoader };
const underlyingTokenDefinitions = await this.getUnderlyingTokenDefinitions(context)
.then(v => v.map(t => ({ address: t.address.toLowerCase(), network: t.network, tokenId: t.tokenId })))
.catch(err => {
if (isMulticallUnderlyingError(err)) return null;
throw err;
});
if (!underlyingTokenDefinitions) return null;
return { address, definition, underlyingTokenDefinitions };
}),
);
const skeletons = compact(maybeSkeletons);
const [base, meta] = partition(skeletons, t => {
const tokenAddresses = skeletons.map(v => v.address);
const underlyingTokenAddresses = t.underlyingTokenDefinitions.map(v => v.address);
return intersection(underlyingTokenAddresses, tokenAddresses).length === 0;
});
const currentTokens: AppTokenPosition<V>[] = [];
for (const skeletonsSubset of [base, meta]) {
const underlyingTokenQueries = skeletons.flatMap(v => v.underlyingTokenDefinitions);
const underlyingTokenRequestsUnique = uniqWith(underlyingTokenQueries, isEqual);
const tokenDependencies = await tokenLoader
.getMany(underlyingTokenRequestsUnique)
.then(tokenDeps => compact(tokenDeps));
const allTokens = [...currentTokens, ...tokenDependencies];
const skeletonsWithResolvedTokens = await Promise.all(
skeletonsSubset.map(async ({ address, definition, underlyingTokenDefinitions }) => {
const maybeTokens = underlyingTokenDefinitions.map(definition => {
const match = allTokens.find(token => {
const isAddressMatch = token.address === definition.address;
const isNetworkMatch = token.network === definition.network;
const isMaybeTokenIdMatch =
!isNumber(definition.tokenId) ||
(token.type === ContractType.APP_TOKEN && token.dataProps.tokenId === definition.tokenId) ||
(token.type === ContractType.NON_FUNGIBLE_TOKEN &&
Number(token.assets?.[0].tokenId) === definition.tokenId);
return isAddressMatch && isNetworkMatch && isMaybeTokenIdMatch;
});
return match;
});
const tokens = compact(maybeTokens);
if (maybeTokens.length !== tokens.length) return null;
return { address, definition, tokens };
}),
);
const tokens = await Promise.all(
compact(skeletonsWithResolvedTokens).map(async ({ address, definition, tokens }) => {
const contract = multicall.wrap(this.getContract(address));
const baseContext = { address, contract, multicall, tokenLoader, definition };
const baseFragment: GetTokenPropsParams<T, V, R>['appToken'] = {
type: ContractType.APP_TOKEN,
appId: this.appId,
groupId: this.groupId,
network: this.network,
address,
tokens,
};
const tokenPropsContext = { ...baseContext, appToken: baseFragment };
const [symbol, decimals, totalSupplyRaw] = await Promise.all([
this.getSymbol(tokenPropsContext),
this.getDecimals(tokenPropsContext),
this.getSupply(tokenPropsContext),
]);
const supply = Number(totalSupplyRaw) / 10 ** decimals;
// Resolve price per share stage
const pricePerShareStageFragment = { ...baseFragment, symbol, decimals, supply };
const pricePerShareContext = { ...baseContext, appToken: pricePerShareStageFragment };
const pricePerShare = await this.getPricePerShare(pricePerShareContext).then(v => (isArray(v) ? v : [v]));
// Resolve Price Stage
const priceStageFragment = { ...pricePerShareStageFragment, pricePerShare };
const priceContext = { ...baseContext, appToken: priceStageFragment };
const price = await this.getPrice(priceContext);
// Resolve Data Props Stage
const dataPropsStageFragment = { ...priceStageFragment, price };
const dataPropsStageParams = { ...baseContext, appToken: dataPropsStageFragment };
const dataProps = await this.getDataProps(dataPropsStageParams);
// Resolve Display Props Stage
const displayPropsStageFragment = { ...dataPropsStageFragment, dataProps };
const displayPropsStageParams = { ...baseContext, appToken: displayPropsStageFragment };
const displayProps = {
label: await this.getLabel(displayPropsStageParams),
labelDetailed: await this.getLabelDetailed(displayPropsStageParams),
secondaryLabel: await this.getSecondaryLabel(displayPropsStageParams),
tertiaryLabel: await this.getTertiaryLabel(displayPropsStageParams),
images: await this.getImages(displayPropsStageParams),
statsItems: await this.getStatsItems(displayPropsStageParams),
balanceDisplayMode: await this.getBalanceDisplayMode(displayPropsStageParams),
};
const appToken = { ...displayPropsStageFragment, displayProps };
const key = this.appToolkit.getPositionKey(appToken);
return { key, ...appToken };
}),
);
const positionsSubset = compact(tokens);
currentTokens.push(...positionsSubset);
}
return sortBy(currentTokens, t => {
if (typeof t.dataProps.liquidity === 'number') return -t.dataProps.liquidity;
return 1;
});
}
// Default (adapted) Template Runner
// Note: This will be removed in favour of an orchestrator at a higher level once all groups are migrated
async getPositions(): Promise<AppTokenPosition<V>[]> {
const multicall = this.appToolkit.getMulticall(this.network);
const tokenLoader = this.appToolkit.getTokenDependencySelector({
tags: { network: this.network, context: `${this.appId}__template` },
});
const definitions = await this.getDefinitions({ multicall, tokenLoader });
return this.getPositionsForBatch(definitions);
}
async getAccountAddress(address: string) {
return address;
}
async getPositionsForBalances() {
return this.appToolkit.getAppTokenPositions<V>({
appId: this.appId,
network: this.network,
groupIds: [this.groupId],
});
}
async getBalancePerToken({
address,
appToken,
multicall,
}: {
address: string;
appToken: AppTokenPosition;
multicall: IMulticallWrapper;
}): Promise<BigNumberish> {
return multicall.wrap(this.getContract(appToken.address)).balanceOf(address);
}
async getBalances(_address: string): Promise<AppTokenPositionBalance<V>[]> {
const multicall = this.appToolkit.getMulticall(this.network);
const address = await this.getAccountAddress(_address);
const appTokens = await this.getPositionsForBalances();
if (address === ZERO_ADDRESS) return [];
const balances = await Promise.all(
appTokens.map(async appToken => {
const balanceRaw = await this.getBalancePerToken({ multicall, address, appToken });
const tokenBalance = drillBalance(appToken, balanceRaw.toString(), { isDebt: this.isDebt });
return tokenBalance;
}),
);
return balances as AppTokenPositionBalance<V>[];
}
async getRawBalances(_address: string): Promise<RawAppTokenBalance[]> {
const multicall = this.appToolkit.getMulticall(this.network);
const address = await this.getAccountAddress(_address);
if (address === ZERO_ADDRESS) return [];
const appTokens = await this.getPositionsForBalances();
let results: RawAppTokenBalance[] = [];
for (const batch of _.chunk(appTokens, 100).values()) {
results = results.concat(
await Promise.all(
batch.map(async appToken => ({
key: this.appToolkit.getPositionKey(appToken),
balance: (await this.getBalancePerToken({ multicall, address, appToken })).toString(),
})),
),
);
}
return results;
}
async drillRawBalances(balances: RawAppTokenBalance[]): Promise<AppTokenPositionBalance<V>[]> {
const appTokens = await this.getPositionsForBalances();
const balancesByKey = _(balances)
.groupBy(b => b.key)
.mapValues(v => v[0])
.value();
const appTokenBalances = appTokens.map(token => {
const key = this.appToolkit.getPositionKey(token);
const tokenBalance = balancesByKey[key];
if (!tokenBalance) return null;
const result = drillBalance<typeof token, V>(token, tokenBalance.balance, { isDebt: this.isDebt });
return result;
});
return compact(appTokenBalances);
}
}