forked from Balmy-protocol/sdk
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprice-sources.spec.ts
More file actions
199 lines (190 loc) · 8.79 KB
/
Copy pathprice-sources.spec.ts
File metadata and controls
199 lines (190 loc) · 8.79 KB
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
import ms from 'ms';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import dotenv from 'dotenv';
import { DefiLlamaPriceSource } from '@services/prices/price-sources/defi-llama-price-source';
import { OdosPriceSource } from '@services/prices/price-sources/odos-price-source';
import { CoingeckoPriceSource } from '@services/prices/price-sources/coingecko-price-source';
import { CachedPriceSource } from '@services/prices/price-sources/cached-price-source';
import { FetchService } from '@services/fetch/fetch-service';
import { Chains, getChainByKey } from '@chains';
import { Addresses } from '@shared/constants';
import { ChainId, TokenAddress } from '@types';
import { IPriceSource, PriceInput, PricesQueriesSupport } from '@services/prices/types';
import { PrioritizedPriceSource } from '@services/prices/price-sources/prioritized-price-source';
import { FastestPriceSource } from '@services/prices/price-sources/fastest-price-source';
import { AggregatorPriceSource } from '@services/prices/price-sources/aggregator-price-source';
import { CodexPriceSource } from '@services/prices/price-sources/codex-price-source';
import { AlchemyPriceSource } from '@services/prices/price-sources/alchemy-price-source';
import { BatchPriceSource } from '@services/prices/price-sources/batch-price-source';
chai.use(chaiAsPromised);
dotenv.config();
const TESTS: Record<ChainId, { address: TokenAddress; symbol: string }> = {
[Chains.OPTIMISM.chainId]: { address: '0xda10009cbd5d07dd0cecc66161fc93d7c9000da1', symbol: 'DAI' },
[Chains.POLYGON.chainId]: { address: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174', symbol: 'USDC' },
[Chains.ARBITRUM.chainId]: { address: '0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a', symbol: 'GMX' },
[Chains.BNB_CHAIN.chainId]: { address: '0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82', symbol: 'Cake' },
[Chains.ETHEREUM.chainId]: { address: '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599', symbol: 'WBTC' },
};
const FETCH_SERVICE = new FetchService();
const DEFI_LLAMA_PRICE_SOURCE = new DefiLlamaPriceSource(FETCH_SERVICE);
const ODOS_PRICE_SOURCE = new OdosPriceSource(FETCH_SERVICE);
const CACHED_PRICE_SOURCE = new CachedPriceSource(DEFI_LLAMA_PRICE_SOURCE, {
expiration: {
useCachedValue: 'always',
useCachedValueIfCalculationFailed: 'always',
},
maxSize: 100,
});
const CODEX_PRICE_SOURCE = new CodexPriceSource(FETCH_SERVICE, process.env.CODEX_API_KEY!);
const ALCHEMY_PRICE_SOURCE = new AlchemyPriceSource({
key: process.env.ALCHEMY_API_KEY!,
fetch: FETCH_SERVICE,
});
const PRIORITIZED_PRICE_SOURCE = new PrioritizedPriceSource([ODOS_PRICE_SOURCE, DEFI_LLAMA_PRICE_SOURCE]);
const FASTEST_PRICE_SOURCE = new FastestPriceSource([ODOS_PRICE_SOURCE, DEFI_LLAMA_PRICE_SOURCE]);
const AGGREGATOR_PRICE_SOURCE = new AggregatorPriceSource([ODOS_PRICE_SOURCE, DEFI_LLAMA_PRICE_SOURCE], 'median');
const BATCH_PRICE_SOURCE = new BatchPriceSource(DEFI_LLAMA_PRICE_SOURCE, { maxSize: 1000, maxDelay: '1s' });
const COINGECKO_PRICE_SOURCE = new CoingeckoPriceSource(FETCH_SERVICE);
jest.retryTimes(2);
jest.setTimeout(ms('1m'));
describe('Token Price Sources', () => {
priceSourceTest({ title: 'Defi Llama Source', source: DEFI_LLAMA_PRICE_SOURCE });
priceSourceTest({ title: 'Odos Source', source: ODOS_PRICE_SOURCE });
priceSourceTest({ title: 'Cached Price Source', source: CACHED_PRICE_SOURCE });
priceSourceTest({ title: 'Prioritized Source', source: PRIORITIZED_PRICE_SOURCE });
priceSourceTest({ title: 'Fastest Source', source: FASTEST_PRICE_SOURCE });
priceSourceTest({ title: 'Aggregator Source', source: AGGREGATOR_PRICE_SOURCE });
// priceSourceTest({ title: 'Coingecko Source', source: COINGECKO_PRICE_SOURCE }); Commented out because of rate limiting issues
// priceSourceTest({ title: 'Codex Source', source: CODEX_PRICE_SOURCE }); Commented out because of rate limiting issues
priceSourceTest({ title: 'Alchemy Source', source: ALCHEMY_PRICE_SOURCE });
priceSourceTest({ title: 'Batch Source', source: BATCH_PRICE_SOURCE });
function priceSourceTest({ title, source }: { title: string; source: IPriceSource }) {
describe(title, () => {
queryTest({
source,
query: 'getCurrentPrices',
getResult: (source, tokens) =>
source.getCurrentPrices({
tokens,
config: { timeout: '10s' },
}),
validation: (price) => {
expect(typeof price.price).to.equal('number');
expect(typeof price.closestTimestamp).to.equal('number');
},
});
queryTest({
source,
query: 'getHistoricalPrices',
getResult: (source, tokens) =>
source.getHistoricalPrices({
tokens: tokens.map((token) => ({
...token,
timestamp: 1760054400, // Sat, 10 Oct 2025 00:00:00 GMT
})),
config: { timeout: '10s' },
searchWidth: undefined,
}),
validation: ({ [1760054400]: { price, closestTimestamp: timestamp } }) => {
expect(typeof price).to.equal('number');
expect(typeof timestamp).to.equal('number');
},
});
const from = 1760054400; // Sat, 10 Oct 2025 00:00:00 GMT
const span = 5;
const period = '1d';
queryTest({
source,
query: 'getChart',
getResult: (source, tokens) =>
source.getChart({
tokens,
span,
period,
bound: { from },
config: { timeout: '10s' },
}),
validation: (prices) => {
expect(prices).to.length(span);
prices.forEach((price) => {
expect(typeof price.price).to.equal('number');
expect(typeof price.closestTimestamp).to.equal('number');
});
},
});
});
}
function queryTest<T>({
source,
query,
getResult,
validation: validate,
}: {
source: IPriceSource;
getResult: (source: IPriceSource, input: PriceInput[]) => Promise<Record<ChainId, Record<TokenAddress, T>>>;
query: keyof PricesQueriesSupport;
validation: (value: T) => void;
}) {
describe(query, () => {
const { supported, notSupported } = calculateChainSupport(source, query);
if (supported.length > 0) {
const addresses = getAddressesForChains(supported);
describe('Supported chains', () => {
let result: Record<ChainId, Record<TokenAddress, T>>;
beforeAll(async () => {
result = await getResult(source, addresses);
});
test(`Returned amount of chains is as expected`, () => {
expect(Object.keys(result)).to.have.lengthOf(supported.length);
});
for (const chainId of supported) {
const chain = getChainByKey(chainId);
describe(chain?.name ?? `Chain with id ${chainId}`, () => {
test(`Returned amount of prices is as expected`, () => {
const tokensInChain = addresses.filter(({ chainId }) => chainId == chain?.chainId);
expect(Object.keys(result[chainId])).to.have.lengthOf(tokensInChain.length);
});
test(chain?.nativeCurrency?.symbol ?? 'Native token', () => {
validate(result[chainId][Addresses.NATIVE_TOKEN]);
});
if (chainId in TESTS) {
test(`${TESTS[chainId].symbol}`, () => {
validate(result[chainId][TESTS[chainId].address]);
});
}
});
}
});
}
if (notSupported.length > 0) {
describe('Unsupported chains', () => {
for (const chainId of notSupported) {
const chain = getChainByKey(chainId);
test(`${chain?.name ?? `Chain with id ${chainId}`} fails as it's not supported`, async () => {
const promise = getResult(source, [{ chainId, token: Addresses.NATIVE_TOKEN }]);
await expect(promise).to.eventually.be.rejectedWith('Operation not supported');
});
}
});
}
});
}
function calculateChainSupport(source: IPriceSource, query: keyof PricesQueriesSupport) {
const support = source.supportedQueries();
const allChains = Object.entries(support).map(([chainId, support]) => ({ chainId: Number(chainId), supported: support[query] }));
const supported = allChains.filter(({ supported }) => supported).map(({ chainId }) => chainId);
const notSupported = allChains.filter(({ supported }) => !supported).map(({ chainId }) => chainId);
return { supported, notSupported };
}
function getAddressesForChains(chainIds: ChainId[]): PriceInput[] {
const result: PriceInput[] = [];
for (const chainId of chainIds) {
result.push({ chainId, token: Addresses.NATIVE_TOKEN });
if (chainId in TESTS) {
result.push({ chainId, token: TESTS[chainId].address });
}
}
return result;
}
});