@talismn/token-rates 3.0.15 → 3.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,251 +0,0 @@
1
- import { evmErc20TokenId } from '@talismn/chaindata-provider';
2
-
3
- const tryToDeleteOldTokenRatesDb = () => {
4
- try {
5
- // try and delete it if it's still there
6
- indexedDB.deleteDatabase("TalismanTokenRates");
7
- } catch {
8
- // dont care if it fails
9
- }
10
- };
11
-
12
- const SUPPORTED_CURRENCIES = {
13
- btc: {
14
- name: "Bitcoin",
15
- symbol: "₿"
16
- },
17
- eth: {
18
- name: "Ethereum",
19
- symbol: "Ξ"
20
- },
21
- dot: {
22
- name: "Polkadot",
23
- symbol: "D"
24
- },
25
- tao: {
26
- name: "Bittensor",
27
- symbol: "τ"
28
- },
29
- usd: {
30
- name: "US Dollar",
31
- symbol: "$"
32
- },
33
- cny: {
34
- name: "Chinese Yuan",
35
- symbol: "¥"
36
- },
37
- eur: {
38
- name: "Euro",
39
- symbol: "€"
40
- },
41
- gbp: {
42
- name: "British Pound",
43
- symbol: "£"
44
- },
45
- cad: {
46
- name: "Canadian Dollar",
47
- symbol: "C$"
48
- },
49
- aud: {
50
- name: "Australian Dollar",
51
- symbol: "A$"
52
- },
53
- nzd: {
54
- name: "New Zealand Dollar",
55
- symbol: "NZ$"
56
- },
57
- jpy: {
58
- name: "Japanese Yen",
59
- symbol: "¥"
60
- },
61
- rub: {
62
- name: "Russian Ruble",
63
- symbol: "₽"
64
- },
65
- krw: {
66
- name: "South Korean Won",
67
- symbol: "₩"
68
- },
69
- idr: {
70
- name: "Indonesian Rupiah",
71
- symbol: "Rp"
72
- },
73
- php: {
74
- name: "Philippine Peso",
75
- symbol: "₱"
76
- },
77
- thb: {
78
- name: "Thai Baht",
79
- symbol: "฿"
80
- },
81
- vnd: {
82
- name: "Vietnamese Dong",
83
- symbol: "₫"
84
- },
85
- inr: {
86
- name: "Indian Rupee",
87
- symbol: "₹"
88
- },
89
- try: {
90
- name: "Turkish Lira",
91
- symbol: "₺"
92
- },
93
- // hkd: { name: "Hong Kong Dollar", symbol: "HK$" },
94
- sgd: {
95
- name: "Singapore Dollar",
96
- symbol: "S$"
97
- }
98
- // twd: { name: "Taiwanese Dollar", symbol: "NT$" },
99
- };
100
- const newTokenRates = () => ({
101
- btc: null,
102
- eth: null,
103
- dot: null,
104
- tao: null,
105
- usd: null,
106
- cny: null,
107
- eur: null,
108
- gbp: null,
109
- cad: null,
110
- aud: null,
111
- nzd: null,
112
- jpy: null,
113
- rub: null,
114
- krw: null,
115
- idr: null,
116
- php: null,
117
- thb: null,
118
- vnd: null,
119
- inr: null,
120
- try: null,
121
- // hkd: null,
122
- sgd: null
123
- // twd: null,
124
- });
125
-
126
- class TokenRatesError extends Error {
127
- constructor(message, response) {
128
- super(message);
129
- this.response = response;
130
- }
131
- }
132
- const ALL_CURRENCY_IDS = Object.keys(SUPPORTED_CURRENCIES);
133
- const DEFAULT_COINSAPI_CONFIG = {
134
- apiUrl: "https://coins.talisman.xyz"
135
- };
136
- async function fetchTokenRates(tokens, currencyIds = ALL_CURRENCY_IDS, config = DEFAULT_COINSAPI_CONFIG) {
137
- // create a map from `coingeckoId` -> `tokenId` for each token
138
- const coingeckoIdToTokenIds = Object.values(tokens).flatMap(token => {
139
- // BEGIN: LP tokens have a rate which is calculated later on, using the rates of two other tokens.
140
- //
141
- // This section contains the logic such that: if token is an LP token, then fetch the rates for the two underlying tokens.
142
- if (token.type === "evm-uniswapv2") {
143
- if (token.platform !== "ethereum") return [];
144
- const getToken = (evmNetworkId, tokenAddress, coingeckoId) => ({
145
- id: evmErc20TokenId(evmNetworkId, tokenAddress),
146
- coingeckoId
147
- });
148
- const token0 = token.coingeckoId0 ? [getToken(token.networkId, token.tokenAddress0, token.coingeckoId0)] : [];
149
- const token1 = token.coingeckoId1 ? [getToken(token.networkId, token.tokenAddress1, token.coingeckoId1)] : [];
150
- return [...token0, ...token1];
151
- }
152
- // END: LP tokens have a rate which is calculated later on, using the rates of two other tokens.
153
-
154
- // ignore tokens which don't have a coingeckoId
155
- if (!token.coingeckoId) return [];
156
- return [{
157
- id: token.id,
158
- coingeckoId: token.coingeckoId
159
- }];
160
- })
161
-
162
- // get each token's coingeckoId
163
- .reduce((coingeckoIdToTokenIds, {
164
- id,
165
- coingeckoId
166
- }) => {
167
- if (!coingeckoIdToTokenIds[coingeckoId]) coingeckoIdToTokenIds[coingeckoId] = [];
168
- coingeckoIdToTokenIds[coingeckoId].push(id);
169
- return coingeckoIdToTokenIds;
170
- }, {});
171
-
172
- // create a list of coingeckoIds we want to fetch
173
- const coingeckoIds = Object.keys(coingeckoIdToTokenIds).sort();
174
-
175
- // skip network request if there is nothing for us to fetch
176
- if (coingeckoIds.length < 1) return {};
177
-
178
- // If `currencyIds` includes `tao`, we need to always fetch the `bittensor` coingeckoId and the `usd` currency,
179
- // we can use these to calculate the currency rate for TAO relative to all other tokens.
180
- //
181
- // We support showing balances in TAO just like we support BTC/ETH/DOT, but coingecko doesn't support TAO as a vs currency rate.
182
- // We can macgyver our own TOKEN<>TAO rate by combining the TOKEN<>USD data with the TAO<>USD data.
183
- const hasVsTao = currencyIds.includes("tao");
184
- const [effectiveCoingeckoIds, effectiveCurrencyIds] = hasVsTao ? [[...new Set(coingeckoIds).add("bittensor")], [...new Set(
185
- // don't request `tao` from coingecko (we calculate it from `usd`)
186
- currencyIds.filter(c => c !== "tao"))
187
- // always include `usd` (so we can calculate `tao`)
188
- .add("usd")]] : [coingeckoIds, currencyIds];
189
- const response = await fetch(`${config.apiUrl}/token-rates`, {
190
- method: "POST",
191
- body: JSON.stringify({
192
- coingeckoIds: effectiveCoingeckoIds,
193
- currencyIds: effectiveCurrencyIds
194
- })
195
- });
196
- const rawTokenRates = await response.json();
197
- if (hasVsTao) {
198
- // calculate the TAO<>USD rate
199
- const effectiveTaoIndex = effectiveCoingeckoIds.indexOf("bittensor");
200
- const effectiveUsdIndex = effectiveCurrencyIds.indexOf("usd");
201
- const taoUsdRate = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[0];
202
- const taoUsdChange24h = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[2];
203
-
204
- // insert TOKEN<>TAO rate (calculated based on TAO<>USD rate and TOKEN<>USD rate) into each TOKEN
205
- const taoIndex = currencyIds.indexOf("tao");
206
- rawTokenRates.forEach((rates, i) => {
207
- // hardcoded rate for TAO<>TAO
208
- if (i === effectiveTaoIndex) {
209
- rates?.splice(taoIndex, 0, [1, null, null]);
210
- return;
211
- }
212
-
213
- // get TOKEN<>USD rate
214
- const tokenUsdRate = rates?.[effectiveUsdIndex]?.[0];
215
- // calculate TOKEN<>TAO rate
216
- const tokenTaoRate = typeof tokenUsdRate === "number" && typeof taoUsdRate === "number" && taoUsdRate !== 0 ? tokenUsdRate / taoUsdRate : null;
217
- const tokenUsdChange24h = rates?.[effectiveUsdIndex]?.[2];
218
- const tokenTaoChange24h = typeof taoUsdChange24h === "number" && typeof tokenUsdChange24h === "number" ? (1 + tokenUsdChange24h) / (1 + taoUsdChange24h) - 1 : null;
219
-
220
- // insert at the correct location (based on the index of `tao` in `currencyIds`)
221
- rates?.splice(taoIndex, 0, [tokenTaoRate, null, tokenTaoChange24h]);
222
- });
223
- }
224
- const tokenRates = parseTokenRatesFromApi(rawTokenRates, coingeckoIds, currencyIds);
225
-
226
- // build a TokenRatesList from the token prices result
227
- const ratesList = Object.fromEntries(Object.entries(tokens).map(([tokenId, token]) => [tokenId, token.coingeckoId ? tokenRates[token.coingeckoId] ?? null : null]));
228
- return ratesList;
229
- }
230
-
231
- // To save on bandwidth and work around response size limits, values are returned without json property names
232
- // (e.g. [[[12, 12332, 0.5]]] instead of { dot : {usd: { value: 12, marketCap: 12332, change24h: 0.5 }} })
233
-
234
- const parseTokenRatesFromApi = (rawTokenRates, coingeckoIds, currencyIds) => {
235
- return Object.fromEntries(coingeckoIds.map((coingeckoId, idx) => {
236
- const rates = rawTokenRates[idx];
237
- if (!rates) return [coingeckoId, null];
238
- return [coingeckoId, Object.fromEntries(currencyIds.map((currencyId, idx) => {
239
- const curRate = rates[idx];
240
- if (!curRate) return [currencyId, null];
241
- const [price, marketCap, change24h] = rates[idx];
242
- return [currencyId, {
243
- price,
244
- marketCap,
245
- change24h
246
- }];
247
- }))];
248
- }));
249
- };
250
-
251
- export { ALL_CURRENCY_IDS, DEFAULT_COINSAPI_CONFIG, SUPPORTED_CURRENCIES, TokenRatesError, fetchTokenRates, newTokenRates, tryToDeleteOldTokenRatesDb };