@talismn/token-rates 4.0.8 → 4.0.10
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.
- package/dist/index.d.mts +0 -10
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +0 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -15
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -13
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { NetworkId, SubDTaoToken, Token, TokenId, TokenList } from "@talismn/chaindata-provider";
|
|
2
2
|
import { IChainConnectorDot } from "@talismn/chain-connectors";
|
|
3
|
-
//#region src/types.d.ts
|
|
4
3
|
export declare const SUPPORTED_CURRENCIES: {
|
|
5
4
|
readonly btc: {
|
|
6
5
|
readonly name: "Bitcoin";
|
|
@@ -99,8 +98,6 @@ export type TokenRateData = {
|
|
|
99
98
|
};
|
|
100
99
|
export type TokenRateCurrency = keyof typeof SUPPORTED_CURRENCIES;
|
|
101
100
|
export declare const newTokenRates: () => TokenRates;
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/fetchDTaoTokenRates.d.ts
|
|
104
101
|
export type FetchDTaoTokenRatesOptions = {
|
|
105
102
|
/** substrate chain connector of the host (only its `send` method is used, for one state_call per invocation) */
|
|
106
103
|
connector: IChainConnectorDot;
|
|
@@ -129,8 +126,6 @@ export type FetchDTaoTokenRatesOptions = {
|
|
|
129
126
|
* and for merging the result into their rates list/store.
|
|
130
127
|
*/
|
|
131
128
|
export declare const fetchDTaoTokenRates: ({ connector, networkId, tokens, tokenRates, previousRates, customFetch, taoDataApiUrl, timeoutMs }: FetchDTaoTokenRatesOptions) => Promise<TokenRatesList>;
|
|
132
|
-
//#endregion
|
|
133
|
-
//#region src/getDTaoTokenRates.d.ts
|
|
134
129
|
/**
|
|
135
130
|
* Rates of a bittensor dtao (subnet alpha) token, derived from its network's native TAO rates
|
|
136
131
|
* scaled by the subnet pool price. To be used for tokens that don't have a coingecko id.
|
|
@@ -141,11 +136,7 @@ export declare const fetchDTaoTokenRates: ({ connector, networkId, tokens, token
|
|
|
141
136
|
* @param alphaPriceChange24h 24h change of the pool price (alpha vs TAO) in percent, when known
|
|
142
137
|
*/
|
|
143
138
|
export declare const getDTaoTokenRates: (token: SubDTaoToken, tokenRates: TokenRatesList, scaledAlphaPrice: string | bigint, alphaPriceChange24h?: number | null) => TokenRates | null;
|
|
144
|
-
//#endregion
|
|
145
|
-
//#region src/TalismanTokenRatesDatabase.d.ts
|
|
146
139
|
export declare const tryToDeleteOldTokenRatesDb: () => void;
|
|
147
|
-
//#endregion
|
|
148
|
-
//#region src/TokenRates.d.ts
|
|
149
140
|
export declare class TokenRatesError extends Error {
|
|
150
141
|
response?: Response;
|
|
151
142
|
constructor(message: string, response?: Response);
|
|
@@ -156,5 +147,4 @@ export type CoinsApiConfig = {
|
|
|
156
147
|
};
|
|
157
148
|
export declare const DEFAULT_COINSAPI_CONFIG: CoinsApiConfig;
|
|
158
149
|
export declare function fetchTokenRates(tokens: Record<TokenId, Token>, currencyIds?: TokenRateCurrency[], config?: CoinsApiConfig): Promise<TokenRatesList>;
|
|
159
|
-
//#endregion
|
|
160
150
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/fetchDTaoTokenRates.ts","../src/getDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["_$__types0.TokenRates"],"sources":["../src/types.ts","../src/fetchDTaoTokenRates.ts","../src/getDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"mappings":";;qBAEa;WACX;aAAO;aAAiB;;WACxB;aAAO;aAAkB;;WACzB;aAAO;aAAkB;;WACzB;aAAO;aAAmB;;WAE1B;aAAO;aAAmB;;WAC1B;aAAO;aAAsB;;WAC7B;aAAO;aAAc;;WACrB;aAAO;aAAuB;;WAC9B;aAAO;aAAyB;;WAChC;aAAO;aAA2B;;WAClC;aAAO;aAA4B;;WACnC;aAAO;aAAsB;;WAC7B;aAAO;aAAuB;;WAC9B;aAAO;aAA0B;;WACjC;aAAO;aAA2B;;WAClC;aAAO;aAAyB;;WAChC;aAAO;aAAmB;;WAC1B;aAAO;aAAyB;;WAChC;aAAO;aAAsB;;WAC7B;aAAO;aAAsB;;WAE7B;aAAO;aAA0B;;;YAIvB;EAAsB,YAAY;;YAElC,iBAAiB,OAAO,SAAS;YACjC,aAAa,OAAO,mBAAmB;YAEvC;EAAkB;EAAe;EAAoB;;YACrD,iCAAiC;qBAEhC,qBAAoB;YCkCrB;;EAEV,WAAW;;EAEX,YAAY;;EAEZ,QAAQ;;EAER,YAAY;;EAEZ,eAAe;;EAEf,qBAAqB;;EAErB;;EAEA;;;;;;;;;;;qBAYW,wBAAmB,WAAA,WAAA,QAAA,YAAA,eAAA,aAAA,eAAA,aAS7B,+BAA6B,QAAQ;;;;;;;;;;qBCnE3B,oBAAiB,OACrB,cAAY,YACP,gBAAc,mCACO,wCADrBA;qBC3CD;qBCUA,wBAAwB;EACnC,WAAW;EACX,YAAY,iBAAiB,WAAW;;qBAM7B,kBAAwD;YACzD;EACV;;qBAGW,yBAAyB;wBAGhB,gBACpB,QAAQ,OAAO,SAAS,QACxB,cAAa,qBACb,SAAQ,iBACP,QAAQ"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { IChainConnectorDot } from "@talismn/chain-connectors";
|
|
2
2
|
import { NetworkId, SubDTaoToken, Token, TokenId, TokenList } from "@talismn/chaindata-provider";
|
|
3
|
-
//#region src/types.d.ts
|
|
4
3
|
export declare const SUPPORTED_CURRENCIES: {
|
|
5
4
|
readonly btc: {
|
|
6
5
|
readonly name: "Bitcoin";
|
|
@@ -99,8 +98,6 @@ export type TokenRateData = {
|
|
|
99
98
|
};
|
|
100
99
|
export type TokenRateCurrency = keyof typeof SUPPORTED_CURRENCIES;
|
|
101
100
|
export declare const newTokenRates: () => TokenRates;
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/fetchDTaoTokenRates.d.ts
|
|
104
101
|
export type FetchDTaoTokenRatesOptions = {
|
|
105
102
|
/** substrate chain connector of the host (only its `send` method is used, for one state_call per invocation) */
|
|
106
103
|
connector: IChainConnectorDot;
|
|
@@ -129,8 +126,6 @@ export type FetchDTaoTokenRatesOptions = {
|
|
|
129
126
|
* and for merging the result into their rates list/store.
|
|
130
127
|
*/
|
|
131
128
|
export declare const fetchDTaoTokenRates: ({ connector, networkId, tokens, tokenRates, previousRates, customFetch, taoDataApiUrl, timeoutMs }: FetchDTaoTokenRatesOptions) => Promise<TokenRatesList>;
|
|
132
|
-
//#endregion
|
|
133
|
-
//#region src/getDTaoTokenRates.d.ts
|
|
134
129
|
/**
|
|
135
130
|
* Rates of a bittensor dtao (subnet alpha) token, derived from its network's native TAO rates
|
|
136
131
|
* scaled by the subnet pool price. To be used for tokens that don't have a coingecko id.
|
|
@@ -141,11 +136,7 @@ export declare const fetchDTaoTokenRates: ({ connector, networkId, tokens, token
|
|
|
141
136
|
* @param alphaPriceChange24h 24h change of the pool price (alpha vs TAO) in percent, when known
|
|
142
137
|
*/
|
|
143
138
|
export declare const getDTaoTokenRates: (token: SubDTaoToken, tokenRates: TokenRatesList, scaledAlphaPrice: string | bigint, alphaPriceChange24h?: number | null) => TokenRates | null;
|
|
144
|
-
//#endregion
|
|
145
|
-
//#region src/TalismanTokenRatesDatabase.d.ts
|
|
146
139
|
export declare const tryToDeleteOldTokenRatesDb: () => void;
|
|
147
|
-
//#endregion
|
|
148
|
-
//#region src/TokenRates.d.ts
|
|
149
140
|
export declare class TokenRatesError extends Error {
|
|
150
141
|
response?: Response;
|
|
151
142
|
constructor(message: string, response?: Response);
|
|
@@ -156,5 +147,4 @@ export type CoinsApiConfig = {
|
|
|
156
147
|
};
|
|
157
148
|
export declare const DEFAULT_COINSAPI_CONFIG: CoinsApiConfig;
|
|
158
149
|
export declare function fetchTokenRates(tokens: Record<TokenId, Token>, currencyIds?: TokenRateCurrency[], config?: CoinsApiConfig): Promise<TokenRatesList>;
|
|
159
|
-
//#endregion
|
|
160
150
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/fetchDTaoTokenRates.ts","../src/getDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["_$__types0.TokenRates"],"sources":["../src/types.ts","../src/fetchDTaoTokenRates.ts","../src/getDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"mappings":";;qBAEa;WACX;aAAO;aAAiB;;WACxB;aAAO;aAAkB;;WACzB;aAAO;aAAkB;;WACzB;aAAO;aAAmB;;WAE1B;aAAO;aAAmB;;WAC1B;aAAO;aAAsB;;WAC7B;aAAO;aAAc;;WACrB;aAAO;aAAuB;;WAC9B;aAAO;aAAyB;;WAChC;aAAO;aAA2B;;WAClC;aAAO;aAA4B;;WACnC;aAAO;aAAsB;;WAC7B;aAAO;aAAuB;;WAC9B;aAAO;aAA0B;;WACjC;aAAO;aAA2B;;WAClC;aAAO;aAAyB;;WAChC;aAAO;aAAmB;;WAC1B;aAAO;aAAyB;;WAChC;aAAO;aAAsB;;WAC7B;aAAO;aAAsB;;WAE7B;aAAO;aAA0B;;;YAIvB;EAAsB,YAAY;;YAElC,iBAAiB,OAAO,SAAS;YACjC,aAAa,OAAO,mBAAmB;YAEvC;EAAkB;EAAe;EAAoB;;YACrD,iCAAiC;qBAEhC,qBAAoB;YCkCrB;;EAEV,WAAW;;EAEX,YAAY;;EAEZ,QAAQ;;EAER,YAAY;;EAEZ,eAAe;;EAEf,qBAAqB;;EAErB;;EAEA;;;;;;;;;;;qBAYW,wBAAmB,WAAA,WAAA,QAAA,YAAA,eAAA,aAAA,eAAA,aAS7B,+BAA6B,QAAQ;;;;;;;;;;qBCnE3B,oBAAiB,OACrB,cAAY,YACP,gBAAc,mCACO,wCADrBA;qBC3CD;qBCUA,wBAAwB;EACnC,WAAW;EACX,YAAY,iBAAiB,WAAW;;qBAM7B,kBAAwD;YACzD;EACV;;qBAGW,yBAAyB;wBAGhB,gBACpB,QAAQ,OAAO,SAAS,QACxB,cAAa,qBACb,SAAQ,iBACP,QAAQ"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
|
|
2
|
+
// \0rolldown/runtime.js
|
|
3
3
|
var __create = Object.create;
|
|
4
4
|
var __defProp = Object.defineProperty;
|
|
5
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -20,17 +20,14 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
|
-
//#endregion
|
|
24
23
|
let _talismn_chaindata_provider = require("@talismn/chaindata-provider");
|
|
25
24
|
let _talismn_util = require("@talismn/util");
|
|
26
25
|
let scale_ts = require("scale-ts");
|
|
27
26
|
let anylogger = require("anylogger");
|
|
28
27
|
anylogger = __toESM(anylogger);
|
|
29
|
-
|
|
30
|
-
//#region src/log.ts
|
|
28
|
+
// src/log.ts
|
|
31
29
|
var log_default = (0, anylogger.default)("@talismn/token-rates");
|
|
32
|
-
|
|
33
|
-
//#region src/types.ts
|
|
30
|
+
// src/types.ts
|
|
34
31
|
const SUPPORTED_CURRENCIES = {
|
|
35
32
|
btc: {
|
|
36
33
|
name: "Bitcoin",
|
|
@@ -140,8 +137,7 @@ const newTokenRates = () => ({
|
|
|
140
137
|
try: null,
|
|
141
138
|
sgd: null
|
|
142
139
|
});
|
|
143
|
-
|
|
144
|
-
//#region src/getDTaoTokenRates.ts
|
|
140
|
+
// src/getDTaoTokenRates.ts
|
|
145
141
|
/** TAO-per-alpha pool price fixed-point scale: 10^9 (TAO decimals) */
|
|
146
142
|
const SCALED_ALPHA_PRICE_SCALE = 10 ** 9;
|
|
147
143
|
/**
|
|
@@ -182,8 +178,7 @@ const getDTaoTokenRates = (token, tokenRates, scaledAlphaPrice, alphaPriceChange
|
|
|
182
178
|
return null;
|
|
183
179
|
}
|
|
184
180
|
};
|
|
185
|
-
|
|
186
|
-
//#region src/fetchDTaoTokenRates.ts
|
|
181
|
+
// src/fetchDTaoTokenRates.ts
|
|
187
182
|
const DEFAULT_BITTENSOR_NETWORK_ID = "bittensor";
|
|
188
183
|
const DEFAULT_TAO_DATA_API_URL = "https://tda.talisman.xyz";
|
|
189
184
|
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
@@ -245,15 +240,13 @@ const fetchDTaoTokenRates = async ({ connector, networkId = DEFAULT_BITTENSOR_NE
|
|
|
245
240
|
return [token.id, rates ?? previousRates[token.id]];
|
|
246
241
|
}).filter(([, rates]) => !!rates));
|
|
247
242
|
};
|
|
248
|
-
|
|
249
|
-
//#region src/TalismanTokenRatesDatabase.ts
|
|
243
|
+
// src/TalismanTokenRatesDatabase.ts
|
|
250
244
|
const tryToDeleteOldTokenRatesDb = () => {
|
|
251
245
|
try {
|
|
252
246
|
indexedDB.deleteDatabase("TalismanTokenRates");
|
|
253
247
|
} catch {}
|
|
254
248
|
};
|
|
255
|
-
|
|
256
|
-
//#region src/TokenRates.ts
|
|
249
|
+
// src/TokenRates.ts
|
|
257
250
|
var TokenRatesError = class extends Error {
|
|
258
251
|
response;
|
|
259
252
|
constructor(message, response) {
|
|
@@ -340,7 +333,6 @@ const parseTokenRatesFromApi = (rawTokenRates, coingeckoIds, currencyIds) => {
|
|
|
340
333
|
}))];
|
|
341
334
|
}));
|
|
342
335
|
};
|
|
343
|
-
//#endregion
|
|
344
336
|
exports.ALL_CURRENCY_IDS = ALL_CURRENCY_IDS;
|
|
345
337
|
exports.DEFAULT_COINSAPI_CONFIG = DEFAULT_COINSAPI_CONFIG;
|
|
346
338
|
exports.SUPPORTED_CURRENCIES = SUPPORTED_CURRENCIES;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["packageJson.name","subNativeTokenId","Vector","Struct","u16","u64","subNativeTokenId","throwAfter","evmErc20TokenId"],"sources":["../package.json","../src/log.ts","../src/types.ts","../src/getDTaoTokenRates.ts","../src/fetchDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"sourcesContent":["","import anylogger from \"anylogger\"\n\nimport packageJson from \"../package.json\"\n\nexport default anylogger(packageJson.name)\n","import type { TokenId } from \"@talismn/chaindata-provider\"\n\nexport const SUPPORTED_CURRENCIES = {\n btc: { name: \"Bitcoin\", symbol: \"₿\" },\n eth: { name: \"Ethereum\", symbol: \"Ξ\" },\n dot: { name: \"Polkadot\", symbol: \"D\" },\n tao: { name: \"Bittensor\", symbol: \"τ\" },\n\n usd: { name: \"US Dollar\", symbol: \"$\" },\n cny: { name: \"Chinese Yuan\", symbol: \"¥\" },\n eur: { name: \"Euro\", symbol: \"€\" },\n gbp: { name: \"British Pound\", symbol: \"£\" },\n cad: { name: \"Canadian Dollar\", symbol: \"C$\" },\n aud: { name: \"Australian Dollar\", symbol: \"A$\" },\n nzd: { name: \"New Zealand Dollar\", symbol: \"NZ$\" },\n jpy: { name: \"Japanese Yen\", symbol: \"¥\" },\n rub: { name: \"Russian Ruble\", symbol: \"₽\" },\n krw: { name: \"South Korean Won\", symbol: \"₩\" },\n idr: { name: \"Indonesian Rupiah\", symbol: \"Rp\" },\n php: { name: \"Philippine Peso\", symbol: \"₱\" },\n thb: { name: \"Thai Baht\", symbol: \"฿\" },\n vnd: { name: \"Vietnamese Dong\", symbol: \"₫\" },\n inr: { name: \"Indian Rupee\", symbol: \"₹\" },\n try: { name: \"Turkish Lira\", symbol: \"₺\" },\n // hkd: { name: \"Hong Kong Dollar\", symbol: \"HK$\" },\n sgd: { name: \"Singapore Dollar\", symbol: \"S$\" },\n // twd: { name: \"Taiwanese Dollar\", symbol: \"NT$\" },\n} as const\n\nexport type TokenRatesStorage = { tokenRates: TokenRatesList }\n\nexport type TokenRatesList = Record<TokenId, TokenRates>\nexport type TokenRates = Record<TokenRateCurrency, TokenRateData | null>\n\nexport type TokenRateData = { price: number; marketCap?: number; change24h?: number }\nexport type TokenRateCurrency = keyof typeof SUPPORTED_CURRENCIES\n\nexport const newTokenRates = (): TokenRates => ({\n btc: null,\n eth: null,\n dot: null,\n tao: null,\n\n usd: null,\n cny: null,\n eur: null,\n gbp: null,\n cad: null,\n aud: null,\n nzd: null,\n jpy: null,\n rub: null,\n krw: null,\n idr: null,\n php: null,\n thb: null,\n vnd: null,\n inr: null,\n try: null,\n // hkd: null,\n sgd: null,\n // twd: null,\n})\n","import { type SubDTaoToken, subNativeTokenId } from \"@talismn/chaindata-provider\"\n\nimport log from \"./log\"\nimport {\n newTokenRates,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRatesList,\n} from \"./types\"\n\n/** TAO-per-alpha pool price fixed-point scale: 10^9 (TAO decimals) */\nconst SCALED_ALPHA_PRICE_SCALE = 10 ** 9\n\n/**\n * 24h change of an alpha token in a given currency, in percent: the pool price change (alpha vs\n * TAO) compounded with the TAO change in that currency. Unknown without the pool change.\n */\nconst getAlphaChange24h = (\n currency: TokenRateCurrency,\n taoChange24h: number | null | undefined,\n alphaPriceChange24h: number | null | undefined\n): number | undefined => {\n if (typeof alphaPriceChange24h !== \"number\" || !Number.isFinite(alphaPriceChange24h))\n return undefined\n\n // TAO itself doesn't move against the tao currency: the alpha change is the pool change\n if (currency === \"tao\") return alphaPriceChange24h\n\n if (typeof taoChange24h !== \"number\" || !Number.isFinite(taoChange24h)) return undefined\n return ((1 + alphaPriceChange24h / 100) * (1 + taoChange24h / 100) - 1) * 100\n}\n\n/**\n * Rates of a bittensor dtao (subnet alpha) token, derived from its network's native TAO rates\n * scaled by the subnet pool price. To be used for tokens that don't have a coingecko id.\n *\n * @param token\n * @param tokenRates must contain the rates of the network's native (TAO) token\n * @param scaledAlphaPrice current TAO-per-alpha pool price, fixed-point scaled by 10^9 (rao)\n * @param alphaPriceChange24h 24h change of the pool price (alpha vs TAO) in percent, when known\n */\nexport const getDTaoTokenRates = (\n token: SubDTaoToken,\n tokenRates: TokenRatesList,\n scaledAlphaPrice: string | bigint,\n alphaPriceChange24h?: number | null\n) => {\n try {\n const taoTokenId = subNativeTokenId(token.networkId)\n const taoTokenRates = tokenRates[taoTokenId]\n if (!taoTokenRates) return null\n\n // for root subnet, same rates as TAO\n if (token.netuid === 0) return structuredClone(taoTokenRates)\n\n const priceRatio = Number(BigInt(scaledAlphaPrice)) / SCALED_ALPHA_PRICE_SCALE\n\n const alphaRates = newTokenRates()\n for (const [currency, taoRate] of Object.entries(taoTokenRates) as [\n TokenRateCurrency,\n TokenRateData | null,\n ][]) {\n if (!taoRate) {\n alphaRates[currency] = null\n } else {\n alphaRates[currency] = {\n price: taoRate.price * priceRatio,\n marketCap: taoRate.marketCap ? taoRate.marketCap * priceRatio : undefined,\n change24h: getAlphaChange24h(currency, taoRate.change24h, alphaPriceChange24h),\n }\n }\n }\n\n return alphaRates\n } catch (err) {\n log.error(\"Failed to compute dtao token rates\", err)\n return null\n }\n}\n","import type { IChainConnectorDot } from \"@talismn/chain-connectors\"\nimport type { NetworkId, SubDTaoToken, TokenList } from \"@talismn/chaindata-provider\"\nimport { subNativeTokenId } from \"@talismn/chaindata-provider\"\nimport { throwAfter } from \"@talismn/util\"\nimport { Struct, u16, u64, Vector } from \"scale-ts\"\n\nimport { getDTaoTokenRates } from \"./getDTaoTokenRates\"\nimport log from \"./log\"\nimport type { TokenRatesList } from \"./types\"\n\nconst DEFAULT_BITTENSOR_NETWORK_ID = \"bittensor\"\nconst DEFAULT_TAO_DATA_API_URL = \"https://tda.talisman.xyz\"\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n// decoded shape of the SwapRuntimeApi_current_alpha_price_all result\nconst alphaPricesCodec = Vector(Struct({ netuid: u16, price: u64 }))\n\n/** Current TAO-per-alpha pool price of every subnet, keyed by netuid, in the scaledAlphaPrice fixed-point format (rao) */\nconst fetchScaledAlphaPricesByNetuid = async (\n connector: IChainConnectorDot,\n networkId: NetworkId\n): Promise<Map<number, bigint>> => {\n const result = await connector.send<string>(networkId, \"state_call\", [\n \"SwapRuntimeApi_current_alpha_price_all\",\n \"0x\",\n ])\n return new Map(alphaPricesCodec.dec(result).map(({ netuid, price }) => [netuid, price]))\n}\n\nconst ALPHA_PRICE_CHANGES_TTL = 5 * 60_000\nconst alphaPriceChangesCache = new Map<\n string,\n { fetchedAt: number; changes: Map<number, number> }\n>()\n\n/**\n * 24h percent change of every subnet pool price (alpha vs TAO) from the tao-data api — the\n * chain knows the current pool prices but not yesterday's. 5-min in-memory cache; failure is\n * non-fatal (stale cache when available, else no change24h on the computed rates).\n */\nconst getAlphaPriceChangesByNetuid = async (\n apiUrl: string,\n customFetch: typeof fetch,\n timeoutMs: number\n): Promise<Map<number, number> | null> => {\n const cached = alphaPriceChangesCache.get(apiUrl)\n if (cached && performance.now() - cached.fetchedAt < ALPHA_PRICE_CHANGES_TTL)\n return cached.changes\n\n try {\n const response = await customFetch(`${apiUrl}/pools`, {\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`)\n const pools = (await response.json()) as {\n netuid: number\n price_change_1_day: number | string\n }[]\n const changes = new Map(\n pools\n .map((pool): [number, number] => [pool.netuid, Number(pool.price_change_1_day)])\n .filter(([, change]) => Number.isFinite(change))\n )\n alphaPriceChangesCache.set(apiUrl, { fetchedAt: performance.now(), changes })\n return changes\n } catch (err) {\n log.warn(\"Failed to fetch alpha price 24h changes\", err)\n return cached?.changes ?? null\n }\n}\n\nexport type FetchDTaoTokenRatesOptions = {\n /** substrate chain connector of the host (only its `send` method is used, for one state_call per invocation) */\n connector: IChainConnectorDot\n /** the bittensor network id, defaults to \"bittensor\" (mainnet) */\n networkId?: NetworkId\n /** token list to price — non-dtao tokens (and dtao tokens with a coingeckoId) are ignored */\n tokens: TokenList\n /** freshly fetched rates list — dtao rates derive from the network's native TAO token rates in it */\n tokenRates: TokenRatesList\n /** previous rates list, used as keep-last fallback when fetching fails */\n previousRates: TokenRatesList\n /** custom fetch for the tao-data api (eg with auth headers), defaults to global fetch */\n customFetch?: typeof fetch\n /** tao-data api url, defaults to https://tda.talisman.xyz — pass null to skip the 24h-change fetch (eg testnets, which the api has no data for) */\n taoDataApiUrl?: string | null\n /** per-request timeout for the chain call and the tao-data api call, defaults to 10s */\n timeoutMs?: number\n}\n\n/**\n * Rates entries for the bittensor dtao (subnet alpha) tokens of `tokens`, priced from their\n * subnet pool combined with the TAO rates in `tokenRates`. On chain-fetch failure, falls\n * back to the token's entry in `previousRates` (keep-last). Never throws — a dtao pricing\n * failure must not discard the rates list it gets merged into.\n *\n * Hosts remain responsible for WHEN to call this (network enabled state, refresh cadence)\n * and for merging the result into their rates list/store.\n */\nexport const fetchDTaoTokenRates = async ({\n connector,\n networkId = DEFAULT_BITTENSOR_NETWORK_ID,\n tokens,\n tokenRates,\n previousRates,\n customFetch = fetch,\n taoDataApiUrl = DEFAULT_TAO_DATA_API_URL,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n}: FetchDTaoTokenRatesOptions): Promise<TokenRatesList> => {\n const dtaoTokens = Object.values(tokens).filter(\n (token): token is SubDTaoToken =>\n token.type === \"substrate-dtao\" && token.networkId === networkId && !token.coingeckoId\n )\n if (!dtaoTokens.length) return {}\n\n // alpha rates derive from the network's native TAO rates: without them there is nothing to\n // price against, and keep-last must not apply (stale entries would display as current)\n if (!tokenRates[subNativeTokenId(networkId)]) return {}\n\n // the two fetches are independent: run them concurrently\n const [prices, changes] = await Promise.all([\n Promise.race([\n fetchScaledAlphaPricesByNetuid(connector, networkId),\n throwAfter(timeoutMs, `Timed out after ${timeoutMs}ms`),\n ]).catch((err) => {\n log.warn(\"Failed to fetch alpha prices, keeping previous dtao rates\", err)\n return null\n }),\n taoDataApiUrl === null\n ? null\n : getAlphaPriceChangesByNetuid(taoDataApiUrl, customFetch, timeoutMs),\n ])\n\n if (!prices)\n return Object.fromEntries(\n dtaoTokens\n .filter((token) => previousRates[token.id])\n .map((token) => [token.id, previousRates[token.id]])\n )\n\n return Object.fromEntries(\n dtaoTokens\n .map((token) => {\n // never fabricate a zero price: a missing or zero pool price keeps the last rates\n const price = prices.get(token.netuid)\n const rates = price\n ? getDTaoTokenRates(token, tokenRates, price, changes?.get(token.netuid))\n : null\n return [token.id, rates ?? previousRates[token.id]] as const\n })\n .filter(([, rates]) => !!rates)\n )\n}\n","export const tryToDeleteOldTokenRatesDb = () => {\n try {\n // try and delete it if it's still there\n indexedDB.deleteDatabase(\"TalismanTokenRates\")\n } catch {\n // dont care if it fails\n }\n}\n","import { evmErc20TokenId, type Token, type TokenId } from \"@talismn/chaindata-provider\"\n\nimport {\n SUPPORTED_CURRENCIES,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRates,\n type TokenRatesList,\n} from \"./types\"\n\nexport class TokenRatesError extends Error {\n response?: Response\n constructor(message: string, response?: Response) {\n super(message)\n this.response = response\n }\n}\n\nexport const ALL_CURRENCY_IDS = Object.keys(SUPPORTED_CURRENCIES) as TokenRateCurrency[]\nexport type CoinsApiConfig = {\n apiUrl: string\n}\n\nexport const DEFAULT_COINSAPI_CONFIG: CoinsApiConfig = {\n apiUrl: \"https://coins.talisman.xyz\",\n}\nexport async function fetchTokenRates(\n tokens: Record<TokenId, Token>,\n currencyIds: TokenRateCurrency[] = ALL_CURRENCY_IDS,\n config: CoinsApiConfig = DEFAULT_COINSAPI_CONFIG\n): Promise<TokenRatesList> {\n // create a map from `coingeckoId` -> `tokenId` for each token\n const coingeckoIdToTokenIds = Object.values(tokens)\n .flatMap((token) => {\n // BEGIN: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n //\n // This section contains the logic such that: if token is an LP token, then fetch the rates for the two underlying tokens.\n if (token.type === \"evm-uniswapv2\") {\n if (token.platform !== \"ethereum\") return []\n\n const getToken = (\n evmNetworkId: string,\n tokenAddress: `0x${string}`,\n coingeckoId: string\n ) => ({\n id: evmErc20TokenId(evmNetworkId, tokenAddress),\n coingeckoId,\n })\n\n const token0 = token.coingeckoId0\n ? [getToken(token.networkId, token.tokenAddress0, token.coingeckoId0)]\n : []\n const token1 = token.coingeckoId1\n ? [getToken(token.networkId, token.tokenAddress1, token.coingeckoId1)]\n : []\n\n return [...token0, ...token1]\n }\n // END: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n\n // ignore tokens which don't have a coingeckoId\n if (!token.coingeckoId) return []\n\n return [{ id: token.id, coingeckoId: token.coingeckoId }]\n })\n\n // get each token's coingeckoId\n .reduce(\n (coingeckoIdToTokenIds, { id, coingeckoId }) => {\n if (!coingeckoIdToTokenIds[coingeckoId]) coingeckoIdToTokenIds[coingeckoId] = []\n coingeckoIdToTokenIds[coingeckoId].push(id)\n return coingeckoIdToTokenIds\n },\n {} as Record<string, string[]>\n )\n\n // create a list of coingeckoIds we want to fetch\n const coingeckoIds = Object.keys(coingeckoIdToTokenIds).sort()\n\n // skip network request if there is nothing for us to fetch\n if (coingeckoIds.length < 1) return {}\n\n // If `currencyIds` includes `tao`, we need to always fetch the `bittensor` coingeckoId and the `usd` currency,\n // we can use these to calculate the currency rate for TAO relative to all other tokens.\n //\n // We support showing balances in TAO just like we support BTC/ETH/DOT, but coingecko doesn't support TAO as a vs currency rate.\n // We can macgyver our own TOKEN<>TAO rate by combining the TOKEN<>USD data with the TAO<>USD data.\n const hasVsTao = currencyIds.includes(\"tao\")\n const [effectiveCoingeckoIds, effectiveCurrencyIds] = hasVsTao\n ? [\n [...new Set(coingeckoIds).add(\"bittensor\")],\n [\n ...new Set(\n // don't request `tao` from coingecko (we calculate it from `usd`)\n currencyIds.filter((c) => c !== \"tao\")\n )\n // always include `usd` (so we can calculate `tao`)\n .add(\"usd\"),\n ],\n ]\n : [coingeckoIds, currencyIds]\n\n const response = await fetch(`${config.apiUrl}/token-rates`, {\n method: \"POST\",\n body: JSON.stringify({\n coingeckoIds: effectiveCoingeckoIds,\n currencyIds: effectiveCurrencyIds,\n }),\n })\n\n const rawTokenRates = (await response.json()) as RawTokenRates\n\n if (hasVsTao) {\n // calculate the TAO<>USD rate\n const effectiveTaoIndex = effectiveCoingeckoIds.indexOf(\"bittensor\")\n const effectiveUsdIndex = effectiveCurrencyIds.indexOf(\"usd\")\n const taoUsdRate = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[0]\n const taoUsdChange24h = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[2]\n\n // insert TOKEN<>TAO rate (calculated based on TAO<>USD rate and TOKEN<>USD rate) into each TOKEN\n const taoIndex = currencyIds.indexOf(\"tao\")\n rawTokenRates.forEach((rates, i) => {\n // hardcoded rate for TAO<>TAO\n if (i === effectiveTaoIndex) {\n rates?.splice(taoIndex, 0, [1, null, null])\n return\n }\n\n // get TOKEN<>USD rate\n const tokenUsdRate = rates?.[effectiveUsdIndex]?.[0]\n // calculate TOKEN<>TAO rate\n const tokenTaoRate =\n typeof tokenUsdRate === \"number\" && typeof taoUsdRate === \"number\" && taoUsdRate !== 0\n ? tokenUsdRate / taoUsdRate\n : null\n\n // the 24h changes are percents: the token's change against TAO is its USD price\n // ratio now over 24h ago, divided by TAO's\n const tokenUsdChange24h = rates?.[effectiveUsdIndex]?.[2]\n const tokenTaoChange24h =\n typeof taoUsdChange24h === \"number\" &&\n typeof tokenUsdChange24h === \"number\" &&\n taoUsdChange24h > -100\n ? ((1 + tokenUsdChange24h / 100) / (1 + taoUsdChange24h / 100) - 1) * 100\n : null\n\n // insert at the correct location (based on the index of `tao` in `currencyIds`)\n rates?.splice(taoIndex, 0, [tokenTaoRate, null, tokenTaoChange24h])\n })\n }\n\n const tokenRates = parseTokenRatesFromApi(rawTokenRates, coingeckoIds, currencyIds)\n\n // build a TokenRatesList from the token prices result\n const ratesList: TokenRatesList = Object.fromEntries(\n Object.entries(tokens).map(([tokenId, token]) => [\n tokenId,\n token.coingeckoId ? (tokenRates[token.coingeckoId] ?? null) : null,\n ])\n ) as TokenRatesList\n\n return ratesList\n}\n\n// To save on bandwidth and work around response size limits, values are returned without json property names\n// (e.g. [[[12, 12332, 0.5]]] instead of { dot : {usd: { value: 12, marketCap: 12332, change24h: 0.5 }} })\ntype RawTokenRates = [number | null, number | null, number | null][][]\n\nconst parseTokenRatesFromApi = (\n rawTokenRates: RawTokenRates,\n coingeckoIds: string[],\n currencyIds: TokenRateCurrency[]\n): TokenRatesList => {\n return Object.fromEntries(\n coingeckoIds.map((coingeckoId, idx) => {\n const rates = rawTokenRates[idx]\n if (!rates) return [coingeckoId, null]\n\n return [\n coingeckoId,\n Object.fromEntries(\n currencyIds.map((currencyId, idx) => {\n const curRate = rates[idx]\n if (!curRate) return [currencyId, null]\n\n const [price, marketCap, change24h] = rates[idx]\n return [currencyId, { price, marketCap, change24h } as TokenRateData]\n })\n ) as TokenRates,\n ]\n })\n ) as TokenRatesList\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACIA,IAAA,eAAA,GAAe,UAAA,QAAA,CAAUA,sBAAgB;;;ACFzC,MAAa,uBAAuB;CAClC,KAAK;EAAE,MAAM;EAAW,QAAQ;CAAI;CACpC,KAAK;EAAE,MAAM;EAAY,QAAQ;CAAI;CACrC,KAAK;EAAE,MAAM;EAAY,QAAQ;CAAI;CACrC,KAAK;EAAE,MAAM;EAAa,QAAQ;CAAI;CAEtC,KAAK;EAAE,MAAM;EAAa,QAAQ;CAAI;CACtC,KAAK;EAAE,MAAM;E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BAAmB;IAC3B,OAAO,OAAO,UAAU,GAAG;KAAC;KAAG;KAAM;IAAI,CAAC;IAC1C;GACF;GAGA,MAAM,eAAe,QAAQ,kBAAkB,GAAG;GAElD,MAAM,eACJ,OAAO,iBAAiB,YAAY,OAAO,eAAe,YAAY,eAAe,IACjF,eAAe,aACf;GAIN,MAAM,oBAAoB,QAAQ,kBAAkB,GAAG;GACvD,MAAM,oBACJ,OAAO,oBAAoB,YAC3B,OAAO,sBAAsB,YAC7B,kBAAkB,SACZ,IAAI,oBAAoB,QAAQ,IAAI,kBAAkB,OAAO,KAAK,MACpE;GAGN,OAAO,OAAO,UAAU,GAAG;IAAC;IAAc;IAAM;GAAiB,CAAC;EACpE,CAAC;CACH;CAEA,MAAM,aAAa,uBAAuB,eAAe,cAAc,WAAW;CAUlF,OAPkC,OAAO,YACvC,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,SAAS,WAAW,CAC/C,SACA,MAAM,cAAe,WAAW,MAAM,gBAAgB,OAAQ,IAChE,CAAC,CAGY;AACjB;AAMA,MAAM,0BACJ,eACA,cACA,gBACmB;CACnB,OAAO,OAAO,YACZ,aAAa,KAAK,aAAa,QAAQ;EACrC,MAAM,QAAQ,cAAc;EAC5B,IAAI,CAAC,OAAO,OAAO,CAAC,aAAa,IAAI;EAErC,OAAO,CACL,aACA,OAAO,YACL,YAAY,KAAK,YAAY,QAAQ;GAEnC,IAAI,CADY,MAAM,MACR,OAAO,CAAC,YAAY,IAAI;GAEtC,MAAM,CAAC,OAAO,WAAW,aAAa,MAAM;GAC5C,OAAO,CAAC,YAAY;IAAE;IAAO;IAAW;GAAU,CAAkB;EACtE,CAAC,CACH,CACF;CACF,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["packageJson.name","subNativeTokenId","Vector","Struct","u16","u64","subNativeTokenId","throwAfter","evmErc20TokenId"],"sources":["../package.json","../src/log.ts","../src/types.ts","../src/getDTaoTokenRates.ts","../src/fetchDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"sourcesContent":["","import anylogger from \"anylogger\"\n\nimport packageJson from \"../package.json\"\n\nexport default anylogger(packageJson.name)\n","import type { TokenId } from \"@talismn/chaindata-provider\"\n\nexport const SUPPORTED_CURRENCIES = {\n btc: { name: \"Bitcoin\", symbol: \"₿\" },\n eth: { name: \"Ethereum\", symbol: \"Ξ\" },\n dot: { name: \"Polkadot\", symbol: \"D\" },\n tao: { name: \"Bittensor\", symbol: \"τ\" },\n\n usd: { name: \"US Dollar\", symbol: \"$\" },\n cny: { name: \"Chinese Yuan\", symbol: \"¥\" },\n eur: { name: \"Euro\", symbol: \"€\" },\n gbp: { name: \"British Pound\", symbol: \"£\" },\n cad: { name: \"Canadian Dollar\", symbol: \"C$\" },\n aud: { name: \"Australian Dollar\", symbol: \"A$\" },\n nzd: { name: \"New Zealand Dollar\", symbol: \"NZ$\" },\n jpy: { name: \"Japanese Yen\", symbol: \"¥\" },\n rub: { name: \"Russian Ruble\", symbol: \"₽\" },\n krw: { name: \"South Korean Won\", symbol: \"₩\" },\n idr: { name: \"Indonesian Rupiah\", symbol: \"Rp\" },\n php: { name: \"Philippine Peso\", symbol: \"₱\" },\n thb: { name: \"Thai Baht\", symbol: \"฿\" },\n vnd: { name: \"Vietnamese Dong\", symbol: \"₫\" },\n inr: { name: \"Indian Rupee\", symbol: \"₹\" },\n try: { name: \"Turkish Lira\", symbol: \"₺\" },\n // hkd: { name: \"Hong Kong Dollar\", symbol: \"HK$\" },\n sgd: { name: \"Singapore Dollar\", symbol: \"S$\" },\n // twd: { name: \"Taiwanese Dollar\", symbol: \"NT$\" },\n} as const\n\nexport type TokenRatesStorage = { tokenRates: TokenRatesList }\n\nexport type TokenRatesList = Record<TokenId, TokenRates>\nexport type TokenRates = Record<TokenRateCurrency, TokenRateData | null>\n\nexport type TokenRateData = { price: number; marketCap?: number; change24h?: number }\nexport type TokenRateCurrency = keyof typeof SUPPORTED_CURRENCIES\n\nexport const newTokenRates = (): TokenRates => ({\n btc: null,\n eth: null,\n dot: null,\n tao: null,\n\n usd: null,\n cny: null,\n eur: null,\n gbp: null,\n cad: null,\n aud: null,\n nzd: null,\n jpy: null,\n rub: null,\n krw: null,\n idr: null,\n php: null,\n thb: null,\n vnd: null,\n inr: null,\n try: null,\n // hkd: null,\n sgd: null,\n // twd: null,\n})\n","import { type SubDTaoToken, subNativeTokenId } from \"@talismn/chaindata-provider\"\n\nimport log from \"./log\"\nimport {\n newTokenRates,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRatesList,\n} from \"./types\"\n\n/** TAO-per-alpha pool price fixed-point scale: 10^9 (TAO decimals) */\nconst SCALED_ALPHA_PRICE_SCALE = 10 ** 9\n\n/**\n * 24h change of an alpha token in a given currency, in percent: the pool price change (alpha vs\n * TAO) compounded with the TAO change in that currency. Unknown without the pool change.\n */\nconst getAlphaChange24h = (\n currency: TokenRateCurrency,\n taoChange24h: number | null | undefined,\n alphaPriceChange24h: number | null | undefined\n): number | undefined => {\n if (typeof alphaPriceChange24h !== \"number\" || !Number.isFinite(alphaPriceChange24h))\n return undefined\n\n // TAO itself doesn't move against the tao currency: the alpha change is the pool change\n if (currency === \"tao\") return alphaPriceChange24h\n\n if (typeof taoChange24h !== \"number\" || !Number.isFinite(taoChange24h)) return undefined\n return ((1 + alphaPriceChange24h / 100) * (1 + taoChange24h / 100) - 1) * 100\n}\n\n/**\n * Rates of a bittensor dtao (subnet alpha) token, derived from its network's native TAO rates\n * scaled by the subnet pool price. To be used for tokens that don't have a coingecko id.\n *\n * @param token\n * @param tokenRates must contain the rates of the network's native (TAO) token\n * @param scaledAlphaPrice current TAO-per-alpha pool price, fixed-point scaled by 10^9 (rao)\n * @param alphaPriceChange24h 24h change of the pool price (alpha vs TAO) in percent, when known\n */\nexport const getDTaoTokenRates = (\n token: SubDTaoToken,\n tokenRates: TokenRatesList,\n scaledAlphaPrice: string | bigint,\n alphaPriceChange24h?: number | null\n) => {\n try {\n const taoTokenId = subNativeTokenId(token.networkId)\n const taoTokenRates = tokenRates[taoTokenId]\n if (!taoTokenRates) return null\n\n // for root subnet, same rates as TAO\n if (token.netuid === 0) return structuredClone(taoTokenRates)\n\n const priceRatio = Number(BigInt(scaledAlphaPrice)) / SCALED_ALPHA_PRICE_SCALE\n\n const alphaRates = newTokenRates()\n for (const [currency, taoRate] of Object.entries(taoTokenRates) as [\n TokenRateCurrency,\n TokenRateData | null,\n ][]) {\n if (!taoRate) {\n alphaRates[currency] = null\n } else {\n alphaRates[currency] = {\n price: taoRate.price * priceRatio,\n marketCap: taoRate.marketCap ? taoRate.marketCap * priceRatio : undefined,\n change24h: getAlphaChange24h(currency, taoRate.change24h, alphaPriceChange24h),\n }\n }\n }\n\n return alphaRates\n } catch (err) {\n log.error(\"Failed to compute dtao token rates\", err)\n return null\n }\n}\n","import type { IChainConnectorDot } from \"@talismn/chain-connectors\"\nimport type { NetworkId, SubDTaoToken, TokenList } from \"@talismn/chaindata-provider\"\nimport { subNativeTokenId } from \"@talismn/chaindata-provider\"\nimport { throwAfter } from \"@talismn/util\"\nimport { Struct, u16, u64, Vector } from \"scale-ts\"\n\nimport { getDTaoTokenRates } from \"./getDTaoTokenRates\"\nimport log from \"./log\"\nimport type { TokenRatesList } from \"./types\"\n\nconst DEFAULT_BITTENSOR_NETWORK_ID = \"bittensor\"\nconst DEFAULT_TAO_DATA_API_URL = \"https://tda.talisman.xyz\"\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n// decoded shape of the SwapRuntimeApi_current_alpha_price_all result\nconst alphaPricesCodec = Vector(Struct({ netuid: u16, price: u64 }))\n\n/** Current TAO-per-alpha pool price of every subnet, keyed by netuid, in the scaledAlphaPrice fixed-point format (rao) */\nconst fetchScaledAlphaPricesByNetuid = async (\n connector: IChainConnectorDot,\n networkId: NetworkId\n): Promise<Map<number, bigint>> => {\n const result = await connector.send<string>(networkId, \"state_call\", [\n \"SwapRuntimeApi_current_alpha_price_all\",\n \"0x\",\n ])\n return new Map(alphaPricesCodec.dec(result).map(({ netuid, price }) => [netuid, price]))\n}\n\nconst ALPHA_PRICE_CHANGES_TTL = 5 * 60_000\nconst alphaPriceChangesCache = new Map<\n string,\n { fetchedAt: number; changes: Map<number, number> }\n>()\n\n/**\n * 24h percent change of every subnet pool price (alpha vs TAO) from the tao-data api — the\n * chain knows the current pool prices but not yesterday's. 5-min in-memory cache; failure is\n * non-fatal (stale cache when available, else no change24h on the computed rates).\n */\nconst getAlphaPriceChangesByNetuid = async (\n apiUrl: string,\n customFetch: typeof fetch,\n timeoutMs: number\n): Promise<Map<number, number> | null> => {\n const cached = alphaPriceChangesCache.get(apiUrl)\n if (cached && performance.now() - cached.fetchedAt < ALPHA_PRICE_CHANGES_TTL)\n return cached.changes\n\n try {\n const response = await customFetch(`${apiUrl}/pools`, {\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`)\n const pools = (await response.json()) as {\n netuid: number\n price_change_1_day: number | string\n }[]\n const changes = new Map(\n pools\n .map((pool): [number, number] => [pool.netuid, Number(pool.price_change_1_day)])\n .filter(([, change]) => Number.isFinite(change))\n )\n alphaPriceChangesCache.set(apiUrl, { fetchedAt: performance.now(), changes })\n return changes\n } catch (err) {\n log.warn(\"Failed to fetch alpha price 24h changes\", err)\n return cached?.changes ?? null\n }\n}\n\nexport type FetchDTaoTokenRatesOptions = {\n /** substrate chain connector of the host (only its `send` method is used, for one state_call per invocation) */\n connector: IChainConnectorDot\n /** the bittensor network id, defaults to \"bittensor\" (mainnet) */\n networkId?: NetworkId\n /** token list to price — non-dtao tokens (and dtao tokens with a coingeckoId) are ignored */\n tokens: TokenList\n /** freshly fetched rates list — dtao rates derive from the network's native TAO token rates in it */\n tokenRates: TokenRatesList\n /** previous rates list, used as keep-last fallback when fetching fails */\n previousRates: TokenRatesList\n /** custom fetch for the tao-data api (eg with auth headers), defaults to global fetch */\n customFetch?: typeof fetch\n /** tao-data api url, defaults to https://tda.talisman.xyz — pass null to skip the 24h-change fetch (eg testnets, which the api has no data for) */\n taoDataApiUrl?: string | null\n /** per-request timeout for the chain call and the tao-data api call, defaults to 10s */\n timeoutMs?: number\n}\n\n/**\n * Rates entries for the bittensor dtao (subnet alpha) tokens of `tokens`, priced from their\n * subnet pool combined with the TAO rates in `tokenRates`. On chain-fetch failure, falls\n * back to the token's entry in `previousRates` (keep-last). Never throws — a dtao pricing\n * failure must not discard the rates list it gets merged into.\n *\n * Hosts remain responsible for WHEN to call this (network enabled state, refresh cadence)\n * and for merging the result into their rates list/store.\n */\nexport const fetchDTaoTokenRates = async ({\n connector,\n networkId = DEFAULT_BITTENSOR_NETWORK_ID,\n tokens,\n tokenRates,\n previousRates,\n customFetch = fetch,\n taoDataApiUrl = DEFAULT_TAO_DATA_API_URL,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n}: FetchDTaoTokenRatesOptions): Promise<TokenRatesList> => {\n const dtaoTokens = Object.values(tokens).filter(\n (token): token is SubDTaoToken =>\n token.type === \"substrate-dtao\" && token.networkId === networkId && !token.coingeckoId\n )\n if (!dtaoTokens.length) return {}\n\n // alpha rates derive from the network's native TAO rates: without them there is nothing to\n // price against, and keep-last must not apply (stale entries would display as current)\n if (!tokenRates[subNativeTokenId(networkId)]) return {}\n\n // the two fetches are independent: run them concurrently\n const [prices, changes] = await Promise.all([\n Promise.race([\n fetchScaledAlphaPricesByNetuid(connector, networkId),\n throwAfter(timeoutMs, `Timed out after ${timeoutMs}ms`),\n ]).catch((err) => {\n log.warn(\"Failed to fetch alpha prices, keeping previous dtao rates\", err)\n return null\n }),\n taoDataApiUrl === null\n ? null\n : getAlphaPriceChangesByNetuid(taoDataApiUrl, customFetch, timeoutMs),\n ])\n\n if (!prices)\n return Object.fromEntries(\n dtaoTokens\n .filter((token) => previousRates[token.id])\n .map((token) => [token.id, previousRates[token.id]])\n )\n\n return Object.fromEntries(\n dtaoTokens\n .map((token) => {\n // never fabricate a zero price: a missing or zero pool price keeps the last rates\n const price = prices.get(token.netuid)\n const rates = price\n ? getDTaoTokenRates(token, tokenRates, price, changes?.get(token.netuid))\n : null\n return [token.id, rates ?? previousRates[token.id]] as const\n })\n .filter(([, rates]) => !!rates)\n )\n}\n","export const tryToDeleteOldTokenRatesDb = () => {\n try {\n // try and delete it if it's still there\n indexedDB.deleteDatabase(\"TalismanTokenRates\")\n } catch {\n // dont care if it fails\n }\n}\n","import { evmErc20TokenId, type Token, type TokenId } from \"@talismn/chaindata-provider\"\n\nimport {\n SUPPORTED_CURRENCIES,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRates,\n type TokenRatesList,\n} from \"./types\"\n\nexport class TokenRatesError extends Error {\n response?: Response\n constructor(message: string, response?: Response) {\n super(message)\n this.response = response\n }\n}\n\nexport const ALL_CURRENCY_IDS = Object.keys(SUPPORTED_CURRENCIES) as TokenRateCurrency[]\nexport type CoinsApiConfig = {\n apiUrl: string\n}\n\nexport const DEFAULT_COINSAPI_CONFIG: CoinsApiConfig = {\n apiUrl: \"https://coins.talisman.xyz\",\n}\nexport async function fetchTokenRates(\n tokens: Record<TokenId, Token>,\n currencyIds: TokenRateCurrency[] = ALL_CURRENCY_IDS,\n config: CoinsApiConfig = DEFAULT_COINSAPI_CONFIG\n): Promise<TokenRatesList> {\n // create a map from `coingeckoId` -> `tokenId` for each token\n const coingeckoIdToTokenIds = Object.values(tokens)\n .flatMap((token) => {\n // BEGIN: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n //\n // This section contains the logic such that: if token is an LP token, then fetch the rates for the two underlying tokens.\n if (token.type === \"evm-uniswapv2\") {\n if (token.platform !== \"ethereum\") return []\n\n const getToken = (\n evmNetworkId: string,\n tokenAddress: `0x${string}`,\n coingeckoId: string\n ) => ({\n id: evmErc20TokenId(evmNetworkId, tokenAddress),\n coingeckoId,\n })\n\n const token0 = token.coingeckoId0\n ? [getToken(token.networkId, token.tokenAddress0, token.coingeckoId0)]\n : []\n const token1 = token.coingeckoId1\n ? [getToken(token.networkId, token.tokenAddress1, token.coingeckoId1)]\n : []\n\n return [...token0, ...token1]\n }\n // END: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n\n // ignore tokens which don't have a coingeckoId\n if (!token.coingeckoId) return []\n\n return [{ id: token.id, coingeckoId: token.coingeckoId }]\n })\n\n // get each token's coingeckoId\n .reduce(\n (coingeckoIdToTokenIds, { id, coingeckoId }) => {\n if (!coingeckoIdToTokenIds[coingeckoId]) coingeckoIdToTokenIds[coingeckoId] = []\n coingeckoIdToTokenIds[coingeckoId].push(id)\n return coingeckoIdToTokenIds\n },\n {} as Record<string, string[]>\n )\n\n // create a list of coingeckoIds we want to fetch\n const coingeckoIds = Object.keys(coingeckoIdToTokenIds).sort()\n\n // skip network request if there is nothing for us to fetch\n if (coingeckoIds.length < 1) return {}\n\n // If `currencyIds` includes `tao`, we need to always fetch the `bittensor` coingeckoId and the `usd` currency,\n // we can use these to calculate the currency rate for TAO relative to all other tokens.\n //\n // We support showing balances in TAO just like we support BTC/ETH/DOT, but coingecko doesn't support TAO as a vs currency rate.\n // We can macgyver our own TOKEN<>TAO rate by combining the TOKEN<>USD data with the TAO<>USD data.\n const hasVsTao = currencyIds.includes(\"tao\")\n const [effectiveCoingeckoIds, effectiveCurrencyIds] = hasVsTao\n ? [\n [...new Set(coingeckoIds).add(\"bittensor\")],\n [\n ...new Set(\n // don't request `tao` from coingecko (we calculate it from `usd`)\n currencyIds.filter((c) => c !== \"tao\")\n )\n // always include `usd` (so we can calculate `tao`)\n .add(\"usd\"),\n ],\n ]\n : [coingeckoIds, currencyIds]\n\n const response = await fetch(`${config.apiUrl}/token-rates`, {\n method: \"POST\",\n body: JSON.stringify({\n coingeckoIds: effectiveCoingeckoIds,\n currencyIds: effectiveCurrencyIds,\n }),\n })\n\n const rawTokenRates = (await response.json()) as RawTokenRates\n\n if (hasVsTao) {\n // calculate the TAO<>USD rate\n const effectiveTaoIndex = effectiveCoingeckoIds.indexOf(\"bittensor\")\n const effectiveUsdIndex = effectiveCurrencyIds.indexOf(\"usd\")\n const taoUsdRate = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[0]\n const taoUsdChange24h = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[2]\n\n // insert TOKEN<>TAO rate (calculated based on TAO<>USD rate and TOKEN<>USD rate) into each TOKEN\n const taoIndex = currencyIds.indexOf(\"tao\")\n rawTokenRates.forEach((rates, i) => {\n // hardcoded rate for TAO<>TAO\n if (i === effectiveTaoIndex) {\n rates?.splice(taoIndex, 0, [1, null, null])\n return\n }\n\n // get TOKEN<>USD rate\n const tokenUsdRate = rates?.[effectiveUsdIndex]?.[0]\n // calculate TOKEN<>TAO rate\n const tokenTaoRate =\n typeof tokenUsdRate === \"number\" && typeof taoUsdRate === \"number\" && taoUsdRate !== 0\n ? tokenUsdRate / taoUsdRate\n : null\n\n // the 24h changes are percents: the token's change against TAO is its USD price\n // ratio now over 24h ago, divided by TAO's\n const tokenUsdChange24h = rates?.[effectiveUsdIndex]?.[2]\n const tokenTaoChange24h =\n typeof taoUsdChange24h === \"number\" &&\n typeof tokenUsdChange24h === \"number\" &&\n taoUsdChange24h > -100\n ? ((1 + tokenUsdChange24h / 100) / (1 + taoUsdChange24h / 100) - 1) * 100\n : null\n\n // insert at the correct location (based on the index of `tao` in `currencyIds`)\n rates?.splice(taoIndex, 0, [tokenTaoRate, null, tokenTaoChange24h])\n })\n }\n\n const tokenRates = parseTokenRatesFromApi(rawTokenRates, coingeckoIds, currencyIds)\n\n // build a TokenRatesList from the token prices result\n const ratesList: TokenRatesList = Object.fromEntries(\n Object.entries(tokens).map(([tokenId, token]) => [\n tokenId,\n token.coingeckoId ? (tokenRates[token.coingeckoId] ?? null) : null,\n ])\n ) as TokenRatesList\n\n return ratesList\n}\n\n// To save on bandwidth and work around response size limits, values are returned without json property names\n// (e.g. [[[12, 12332, 0.5]]] instead of { dot : {usd: { value: 12, marketCap: 12332, change24h: 0.5 }} })\ntype RawTokenRates = [number | null, number | null, number | null][][]\n\nconst parseTokenRatesFromApi = (\n rawTokenRates: RawTokenRates,\n coingeckoIds: string[],\n currencyIds: TokenRateCurrency[]\n): TokenRatesList => {\n return Object.fromEntries(\n coingeckoIds.map((coingeckoId, idx) => {\n const rates = rawTokenRates[idx]\n if (!rates) return [coingeckoId, null]\n\n return [\n coingeckoId,\n Object.fromEntries(\n currencyIds.map((currencyId, idx) => {\n const curRate = rates[idx]\n if (!curRate) return [currencyId, null]\n\n const [price, marketCap, change24h] = rates[idx]\n return [currencyId, { price, marketCap, change24h } as TokenRateData]\n })\n ) as TokenRates,\n ]\n })\n ) as TokenRatesList\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;ACIA,IAAA,eAAA,GAAe,UAAA,QAAA,CAAUA,sBAAgB;;ACFzC,MAAa,uBAAuB;CAClC,KAAK;EAAE,MAAM;EAAW,QAAQ;CAAI;CACpC,KAAK;EAAE,MAAM;EAAY,QAAQ;CAAI;CACrC,KAAK;EAAE,MAAM;EAAY,QAAQ;CAAI;CACrC,KAAK;EAAE,MAAM;EAAa,QAAQ;CAAI;CAEtC,KAAK;EAAE,MAAM;EAAa,QAAQ;CAAI;CACtC,KAAK;EAAE,MAAM;EAAgB,QAAQ;CAAI;CACzC,KAAK;EAAE,MAAM;EAAQ,QAAQ;CAAI;CACjC,KAAK;EAAE,MAAM;EAAiB,QAAQ;CAAI;CAC1C,KAAK;EAAE,MAAM;EAAmB,QAAQ;CAAK;CAC7C,KAAK;EAAE,MAAM;EAAqB,QAAQ;CAAK;CAC/C,KAAK;EAAE,MAAM;EAAsB,QAAQ;CAAM;CACjD,KAAK;EAAE,MAAM;EAAgB,QAAQ;CAAI;CACzC,KAAK;EAAE,MAAM;EAAiB,QAAQ;CAAI;CAC1C,KAAK;EAAE,MAAM;EAAoB,QAAQ;CAAI;CAC7C,KAAK;EAAE,MAAM;EAAqB,QAAQ;CAAK;CAC/C,KAAK;EAAE,MAAM;EAAmB,QAAQ;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BAAuB,eAAe,cAAc,WAAW;CAUlF,OAPkC,OAAO,YACvC,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,SAAS,WAAW,CAC/C,SACA,MAAM,cAAe,WAAW,MAAM,gBAAgB,OAAQ,IAChE,CAAC,CAGY;AACjB;AAMA,MAAM,0BACJ,eACA,cACA,gBACmB;CACnB,OAAO,OAAO,YACZ,aAAa,KAAK,aAAa,QAAQ;EACrC,MAAM,QAAQ,cAAc;EAC5B,IAAI,CAAC,OAAO,OAAO,CAAC,aAAa,IAAI;EAErC,OAAO,CACL,aACA,OAAO,YACL,YAAY,KAAK,YAAY,QAAQ;GAEnC,IAAI,CADY,MAAM,MACR,OAAO,CAAC,YAAY,IAAI;GAEtC,MAAM,CAAC,OAAO,WAAW,aAAa,MAAM;GAC5C,OAAO,CAAC,YAAY;IAAE;IAAO;IAAW;GAAU,CAAkB;EACtE,CAAC,CACH,CACF;CACF,CAAC,CACH;AACF"}
|
package/dist/index.mjs
CHANGED
|
@@ -2,11 +2,9 @@ import { evmErc20TokenId, subNativeTokenId } from "@talismn/chaindata-provider";
|
|
|
2
2
|
import { throwAfter } from "@talismn/util";
|
|
3
3
|
import { Struct, Vector, u16, u64 } from "scale-ts";
|
|
4
4
|
import anylogger from "anylogger";
|
|
5
|
-
|
|
6
|
-
//#region src/log.ts
|
|
5
|
+
// src/log.ts
|
|
7
6
|
var log_default = anylogger("@talismn/token-rates");
|
|
8
|
-
|
|
9
|
-
//#region src/types.ts
|
|
7
|
+
// src/types.ts
|
|
10
8
|
const SUPPORTED_CURRENCIES = {
|
|
11
9
|
btc: {
|
|
12
10
|
name: "Bitcoin",
|
|
@@ -116,8 +114,7 @@ const newTokenRates = () => ({
|
|
|
116
114
|
try: null,
|
|
117
115
|
sgd: null
|
|
118
116
|
});
|
|
119
|
-
|
|
120
|
-
//#region src/getDTaoTokenRates.ts
|
|
117
|
+
// src/getDTaoTokenRates.ts
|
|
121
118
|
/** TAO-per-alpha pool price fixed-point scale: 10^9 (TAO decimals) */
|
|
122
119
|
const SCALED_ALPHA_PRICE_SCALE = 10 ** 9;
|
|
123
120
|
/**
|
|
@@ -158,8 +155,7 @@ const getDTaoTokenRates = (token, tokenRates, scaledAlphaPrice, alphaPriceChange
|
|
|
158
155
|
return null;
|
|
159
156
|
}
|
|
160
157
|
};
|
|
161
|
-
|
|
162
|
-
//#region src/fetchDTaoTokenRates.ts
|
|
158
|
+
// src/fetchDTaoTokenRates.ts
|
|
163
159
|
const DEFAULT_BITTENSOR_NETWORK_ID = "bittensor";
|
|
164
160
|
const DEFAULT_TAO_DATA_API_URL = "https://tda.talisman.xyz";
|
|
165
161
|
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
@@ -221,15 +217,13 @@ const fetchDTaoTokenRates = async ({ connector, networkId = DEFAULT_BITTENSOR_NE
|
|
|
221
217
|
return [token.id, rates ?? previousRates[token.id]];
|
|
222
218
|
}).filter(([, rates]) => !!rates));
|
|
223
219
|
};
|
|
224
|
-
|
|
225
|
-
//#region src/TalismanTokenRatesDatabase.ts
|
|
220
|
+
// src/TalismanTokenRatesDatabase.ts
|
|
226
221
|
const tryToDeleteOldTokenRatesDb = () => {
|
|
227
222
|
try {
|
|
228
223
|
indexedDB.deleteDatabase("TalismanTokenRates");
|
|
229
224
|
} catch {}
|
|
230
225
|
};
|
|
231
|
-
|
|
232
|
-
//#region src/TokenRates.ts
|
|
226
|
+
// src/TokenRates.ts
|
|
233
227
|
var TokenRatesError = class extends Error {
|
|
234
228
|
response;
|
|
235
229
|
constructor(message, response) {
|
|
@@ -316,7 +310,6 @@ const parseTokenRatesFromApi = (rawTokenRates, coingeckoIds, currencyIds) => {
|
|
|
316
310
|
}))];
|
|
317
311
|
}));
|
|
318
312
|
};
|
|
319
|
-
//#endregion
|
|
320
313
|
export { ALL_CURRENCY_IDS, DEFAULT_COINSAPI_CONFIG, SUPPORTED_CURRENCIES, TokenRatesError, fetchDTaoTokenRates, fetchTokenRates, getDTaoTokenRates, newTokenRates, tryToDeleteOldTokenRatesDb };
|
|
321
314
|
|
|
322
315
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["packageJson.name"],"sources":["../package.json","../src/log.ts","../src/types.ts","../src/getDTaoTokenRates.ts","../src/fetchDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"sourcesContent":["","import anylogger from \"anylogger\"\n\nimport packageJson from \"../package.json\"\n\nexport default anylogger(packageJson.name)\n","import type { TokenId } from \"@talismn/chaindata-provider\"\n\nexport const SUPPORTED_CURRENCIES = {\n btc: { name: \"Bitcoin\", symbol: \"₿\" },\n eth: { name: \"Ethereum\", symbol: \"Ξ\" },\n dot: { name: \"Polkadot\", symbol: \"D\" },\n tao: { name: \"Bittensor\", symbol: \"τ\" },\n\n usd: { name: \"US Dollar\", symbol: \"$\" },\n cny: { name: \"Chinese Yuan\", symbol: \"¥\" },\n eur: { name: \"Euro\", symbol: \"€\" },\n gbp: { name: \"British Pound\", symbol: \"£\" },\n cad: { name: \"Canadian Dollar\", symbol: \"C$\" },\n aud: { name: \"Australian Dollar\", symbol: \"A$\" },\n nzd: { name: \"New Zealand Dollar\", symbol: \"NZ$\" },\n jpy: { name: \"Japanese Yen\", symbol: \"¥\" },\n rub: { name: \"Russian Ruble\", symbol: \"₽\" },\n krw: { name: \"South Korean Won\", symbol: \"₩\" },\n idr: { name: \"Indonesian Rupiah\", symbol: \"Rp\" },\n php: { name: \"Philippine Peso\", symbol: \"₱\" },\n thb: { name: \"Thai Baht\", symbol: \"฿\" },\n vnd: { name: \"Vietnamese Dong\", symbol: \"₫\" },\n inr: { name: \"Indian Rupee\", symbol: \"₹\" },\n try: { name: \"Turkish Lira\", symbol: \"₺\" },\n // hkd: { name: \"Hong Kong Dollar\", symbol: \"HK$\" },\n sgd: { name: \"Singapore Dollar\", symbol: \"S$\" },\n // twd: { name: \"Taiwanese Dollar\", symbol: \"NT$\" },\n} as const\n\nexport type TokenRatesStorage = { tokenRates: TokenRatesList }\n\nexport type TokenRatesList = Record<TokenId, TokenRates>\nexport type TokenRates = Record<TokenRateCurrency, TokenRateData | null>\n\nexport type TokenRateData = { price: number; marketCap?: number; change24h?: number }\nexport type TokenRateCurrency = keyof typeof SUPPORTED_CURRENCIES\n\nexport const newTokenRates = (): TokenRates => ({\n btc: null,\n eth: null,\n dot: null,\n tao: null,\n\n usd: null,\n cny: null,\n eur: null,\n gbp: null,\n cad: null,\n aud: null,\n nzd: null,\n jpy: null,\n rub: null,\n krw: null,\n idr: null,\n php: null,\n thb: null,\n vnd: null,\n inr: null,\n try: null,\n // hkd: null,\n sgd: null,\n // twd: null,\n})\n","import { type SubDTaoToken, subNativeTokenId } from \"@talismn/chaindata-provider\"\n\nimport log from \"./log\"\nimport {\n newTokenRates,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRatesList,\n} from \"./types\"\n\n/** TAO-per-alpha pool price fixed-point scale: 10^9 (TAO decimals) */\nconst SCALED_ALPHA_PRICE_SCALE = 10 ** 9\n\n/**\n * 24h change of an alpha token in a given currency, in percent: the pool price change (alpha vs\n * TAO) compounded with the TAO change in that currency. Unknown without the pool change.\n */\nconst getAlphaChange24h = (\n currency: TokenRateCurrency,\n taoChange24h: number | null | undefined,\n alphaPriceChange24h: number | null | undefined\n): number | undefined => {\n if (typeof alphaPriceChange24h !== \"number\" || !Number.isFinite(alphaPriceChange24h))\n return undefined\n\n // TAO itself doesn't move against the tao currency: the alpha change is the pool change\n if (currency === \"tao\") return alphaPriceChange24h\n\n if (typeof taoChange24h !== \"number\" || !Number.isFinite(taoChange24h)) return undefined\n return ((1 + alphaPriceChange24h / 100) * (1 + taoChange24h / 100) - 1) * 100\n}\n\n/**\n * Rates of a bittensor dtao (subnet alpha) token, derived from its network's native TAO rates\n * scaled by the subnet pool price. To be used for tokens that don't have a coingecko id.\n *\n * @param token\n * @param tokenRates must contain the rates of the network's native (TAO) token\n * @param scaledAlphaPrice current TAO-per-alpha pool price, fixed-point scaled by 10^9 (rao)\n * @param alphaPriceChange24h 24h change of the pool price (alpha vs TAO) in percent, when known\n */\nexport const getDTaoTokenRates = (\n token: SubDTaoToken,\n tokenRates: TokenRatesList,\n scaledAlphaPrice: string | bigint,\n alphaPriceChange24h?: number | null\n) => {\n try {\n const taoTokenId = subNativeTokenId(token.networkId)\n const taoTokenRates = tokenRates[taoTokenId]\n if (!taoTokenRates) return null\n\n // for root subnet, same rates as TAO\n if (token.netuid === 0) return structuredClone(taoTokenRates)\n\n const priceRatio = Number(BigInt(scaledAlphaPrice)) / SCALED_ALPHA_PRICE_SCALE\n\n const alphaRates = newTokenRates()\n for (const [currency, taoRate] of Object.entries(taoTokenRates) as [\n TokenRateCurrency,\n TokenRateData | null,\n ][]) {\n if (!taoRate) {\n alphaRates[currency] = null\n } else {\n alphaRates[currency] = {\n price: taoRate.price * priceRatio,\n marketCap: taoRate.marketCap ? taoRate.marketCap * priceRatio : undefined,\n change24h: getAlphaChange24h(currency, taoRate.change24h, alphaPriceChange24h),\n }\n }\n }\n\n return alphaRates\n } catch (err) {\n log.error(\"Failed to compute dtao token rates\", err)\n return null\n }\n}\n","import type { IChainConnectorDot } from \"@talismn/chain-connectors\"\nimport type { NetworkId, SubDTaoToken, TokenList } from \"@talismn/chaindata-provider\"\nimport { subNativeTokenId } from \"@talismn/chaindata-provider\"\nimport { throwAfter } from \"@talismn/util\"\nimport { Struct, u16, u64, Vector } from \"scale-ts\"\n\nimport { getDTaoTokenRates } from \"./getDTaoTokenRates\"\nimport log from \"./log\"\nimport type { TokenRatesList } from \"./types\"\n\nconst DEFAULT_BITTENSOR_NETWORK_ID = \"bittensor\"\nconst DEFAULT_TAO_DATA_API_URL = \"https://tda.talisman.xyz\"\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n// decoded shape of the SwapRuntimeApi_current_alpha_price_all result\nconst alphaPricesCodec = Vector(Struct({ netuid: u16, price: u64 }))\n\n/** Current TAO-per-alpha pool price of every subnet, keyed by netuid, in the scaledAlphaPrice fixed-point format (rao) */\nconst fetchScaledAlphaPricesByNetuid = async (\n connector: IChainConnectorDot,\n networkId: NetworkId\n): Promise<Map<number, bigint>> => {\n const result = await connector.send<string>(networkId, \"state_call\", [\n \"SwapRuntimeApi_current_alpha_price_all\",\n \"0x\",\n ])\n return new Map(alphaPricesCodec.dec(result).map(({ netuid, price }) => [netuid, price]))\n}\n\nconst ALPHA_PRICE_CHANGES_TTL = 5 * 60_000\nconst alphaPriceChangesCache = new Map<\n string,\n { fetchedAt: number; changes: Map<number, number> }\n>()\n\n/**\n * 24h percent change of every subnet pool price (alpha vs TAO) from the tao-data api — the\n * chain knows the current pool prices but not yesterday's. 5-min in-memory cache; failure is\n * non-fatal (stale cache when available, else no change24h on the computed rates).\n */\nconst getAlphaPriceChangesByNetuid = async (\n apiUrl: string,\n customFetch: typeof fetch,\n timeoutMs: number\n): Promise<Map<number, number> | null> => {\n const cached = alphaPriceChangesCache.get(apiUrl)\n if (cached && performance.now() - cached.fetchedAt < ALPHA_PRICE_CHANGES_TTL)\n return cached.changes\n\n try {\n const response = await customFetch(`${apiUrl}/pools`, {\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`)\n const pools = (await response.json()) as {\n netuid: number\n price_change_1_day: number | string\n }[]\n const changes = new Map(\n pools\n .map((pool): [number, number] => [pool.netuid, Number(pool.price_change_1_day)])\n .filter(([, change]) => Number.isFinite(change))\n )\n alphaPriceChangesCache.set(apiUrl, { fetchedAt: performance.now(), changes })\n return changes\n } catch (err) {\n log.warn(\"Failed to fetch alpha price 24h changes\", err)\n return cached?.changes ?? null\n }\n}\n\nexport type FetchDTaoTokenRatesOptions = {\n /** substrate chain connector of the host (only its `send` method is used, for one state_call per invocation) */\n connector: IChainConnectorDot\n /** the bittensor network id, defaults to \"bittensor\" (mainnet) */\n networkId?: NetworkId\n /** token list to price — non-dtao tokens (and dtao tokens with a coingeckoId) are ignored */\n tokens: TokenList\n /** freshly fetched rates list — dtao rates derive from the network's native TAO token rates in it */\n tokenRates: TokenRatesList\n /** previous rates list, used as keep-last fallback when fetching fails */\n previousRates: TokenRatesList\n /** custom fetch for the tao-data api (eg with auth headers), defaults to global fetch */\n customFetch?: typeof fetch\n /** tao-data api url, defaults to https://tda.talisman.xyz — pass null to skip the 24h-change fetch (eg testnets, which the api has no data for) */\n taoDataApiUrl?: string | null\n /** per-request timeout for the chain call and the tao-data api call, defaults to 10s */\n timeoutMs?: number\n}\n\n/**\n * Rates entries for the bittensor dtao (subnet alpha) tokens of `tokens`, priced from their\n * subnet pool combined with the TAO rates in `tokenRates`. On chain-fetch failure, falls\n * back to the token's entry in `previousRates` (keep-last). Never throws — a dtao pricing\n * failure must not discard the rates list it gets merged into.\n *\n * Hosts remain responsible for WHEN to call this (network enabled state, refresh cadence)\n * and for merging the result into their rates list/store.\n */\nexport const fetchDTaoTokenRates = async ({\n connector,\n networkId = DEFAULT_BITTENSOR_NETWORK_ID,\n tokens,\n tokenRates,\n previousRates,\n customFetch = fetch,\n taoDataApiUrl = DEFAULT_TAO_DATA_API_URL,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n}: FetchDTaoTokenRatesOptions): Promise<TokenRatesList> => {\n const dtaoTokens = Object.values(tokens).filter(\n (token): token is SubDTaoToken =>\n token.type === \"substrate-dtao\" && token.networkId === networkId && !token.coingeckoId\n )\n if (!dtaoTokens.length) return {}\n\n // alpha rates derive from the network's native TAO rates: without them there is nothing to\n // price against, and keep-last must not apply (stale entries would display as current)\n if (!tokenRates[subNativeTokenId(networkId)]) return {}\n\n // the two fetches are independent: run them concurrently\n const [prices, changes] = await Promise.all([\n Promise.race([\n fetchScaledAlphaPricesByNetuid(connector, networkId),\n throwAfter(timeoutMs, `Timed out after ${timeoutMs}ms`),\n ]).catch((err) => {\n log.warn(\"Failed to fetch alpha prices, keeping previous dtao rates\", err)\n return null\n }),\n taoDataApiUrl === null\n ? null\n : getAlphaPriceChangesByNetuid(taoDataApiUrl, customFetch, timeoutMs),\n ])\n\n if (!prices)\n return Object.fromEntries(\n dtaoTokens\n .filter((token) => previousRates[token.id])\n .map((token) => [token.id, previousRates[token.id]])\n )\n\n return Object.fromEntries(\n dtaoTokens\n .map((token) => {\n // never fabricate a zero price: a missing or zero pool price keeps the last rates\n const price = prices.get(token.netuid)\n const rates = price\n ? getDTaoTokenRates(token, tokenRates, price, changes?.get(token.netuid))\n : null\n return [token.id, rates ?? previousRates[token.id]] as const\n })\n .filter(([, rates]) => !!rates)\n )\n}\n","export const tryToDeleteOldTokenRatesDb = () => {\n try {\n // try and delete it if it's still there\n indexedDB.deleteDatabase(\"TalismanTokenRates\")\n } catch {\n // dont care if it fails\n }\n}\n","import { evmErc20TokenId, type Token, type TokenId } from \"@talismn/chaindata-provider\"\n\nimport {\n SUPPORTED_CURRENCIES,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRates,\n type TokenRatesList,\n} from \"./types\"\n\nexport class TokenRatesError extends Error {\n response?: Response\n constructor(message: string, response?: Response) {\n super(message)\n this.response = response\n }\n}\n\nexport const ALL_CURRENCY_IDS = Object.keys(SUPPORTED_CURRENCIES) as TokenRateCurrency[]\nexport type CoinsApiConfig = {\n apiUrl: string\n}\n\nexport const DEFAULT_COINSAPI_CONFIG: CoinsApiConfig = {\n apiUrl: \"https://coins.talisman.xyz\",\n}\nexport async function fetchTokenRates(\n tokens: Record<TokenId, Token>,\n currencyIds: TokenRateCurrency[] = ALL_CURRENCY_IDS,\n config: CoinsApiConfig = DEFAULT_COINSAPI_CONFIG\n): Promise<TokenRatesList> {\n // create a map from `coingeckoId` -> `tokenId` for each token\n const coingeckoIdToTokenIds = Object.values(tokens)\n .flatMap((token) => {\n // BEGIN: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n //\n // This section contains the logic such that: if token is an LP token, then fetch the rates for the two underlying tokens.\n if (token.type === \"evm-uniswapv2\") {\n if (token.platform !== \"ethereum\") return []\n\n const getToken = (\n evmNetworkId: string,\n tokenAddress: `0x${string}`,\n coingeckoId: string\n ) => ({\n id: evmErc20TokenId(evmNetworkId, tokenAddress),\n coingeckoId,\n })\n\n const token0 = token.coingeckoId0\n ? [getToken(token.networkId, token.tokenAddress0, token.coingeckoId0)]\n : []\n const token1 = token.coingeckoId1\n ? [getToken(token.networkId, token.tokenAddress1, token.coingeckoId1)]\n : []\n\n return [...token0, ...token1]\n }\n // END: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n\n // ignore tokens which don't have a coingeckoId\n if (!token.coingeckoId) return []\n\n return [{ id: token.id, coingeckoId: token.coingeckoId }]\n })\n\n // get each token's coingeckoId\n .reduce(\n (coingeckoIdToTokenIds, { id, coingeckoId }) => {\n if (!coingeckoIdToTokenIds[coingeckoId]) coingeckoIdToTokenIds[coingeckoId] = []\n coingeckoIdToTokenIds[coingeckoId].push(id)\n return coingeckoIdToTokenIds\n },\n {} as Record<string, string[]>\n )\n\n // create a list of coingeckoIds we want to fetch\n const coingeckoIds = Object.keys(coingeckoIdToTokenIds).sort()\n\n // skip network request if there is nothing for us to fetch\n if (coingeckoIds.length < 1) return {}\n\n // If `currencyIds` includes `tao`, we need to always fetch the `bittensor` coingeckoId and the `usd` currency,\n // we can use these to calculate the currency rate for TAO relative to all other tokens.\n //\n // We support showing balances in TAO just like we support BTC/ETH/DOT, but coingecko doesn't support TAO as a vs currency rate.\n // We can macgyver our own TOKEN<>TAO rate by combining the TOKEN<>USD data with the TAO<>USD data.\n const hasVsTao = currencyIds.includes(\"tao\")\n const [effectiveCoingeckoIds, effectiveCurrencyIds] = hasVsTao\n ? [\n [...new Set(coingeckoIds).add(\"bittensor\")],\n [\n ...new Set(\n // don't request `tao` from coingecko (we calculate it from `usd`)\n currencyIds.filter((c) => c !== \"tao\")\n )\n // always include `usd` (so we can calculate `tao`)\n .add(\"usd\"),\n ],\n ]\n : [coingeckoIds, currencyIds]\n\n const response = await fetch(`${config.apiUrl}/token-rates`, {\n method: \"POST\",\n body: JSON.stringify({\n coingeckoIds: effectiveCoingeckoIds,\n currencyIds: effectiveCurrencyIds,\n }),\n })\n\n const rawTokenRates = (await response.json()) as RawTokenRates\n\n if (hasVsTao) {\n // calculate the TAO<>USD rate\n const effectiveTaoIndex = effectiveCoingeckoIds.indexOf(\"bittensor\")\n const effectiveUsdIndex = effectiveCurrencyIds.indexOf(\"usd\")\n const taoUsdRate = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[0]\n const taoUsdChange24h = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[2]\n\n // insert TOKEN<>TAO rate (calculated based on TAO<>USD rate and TOKEN<>USD rate) into each TOKEN\n const taoIndex = currencyIds.indexOf(\"tao\")\n rawTokenRates.forEach((rates, i) => {\n // hardcoded rate for TAO<>TAO\n if (i === effectiveTaoIndex) {\n rates?.splice(taoIndex, 0, [1, null, null])\n return\n }\n\n // get TOKEN<>USD rate\n const tokenUsdRate = rates?.[effectiveUsdIndex]?.[0]\n // calculate TOKEN<>TAO rate\n const tokenTaoRate =\n typeof tokenUsdRate === \"number\" && typeof taoUsdRate === \"number\" && taoUsdRate !== 0\n ? tokenUsdRate / taoUsdRate\n : null\n\n // the 24h changes are percents: the token's change against TAO is its USD price\n // ratio now over 24h ago, divided by TAO's\n const tokenUsdChange24h = rates?.[effectiveUsdIndex]?.[2]\n const tokenTaoChange24h =\n typeof taoUsdChange24h === \"number\" &&\n typeof tokenUsdChange24h === \"number\" &&\n taoUsdChange24h > -100\n ? ((1 + tokenUsdChange24h / 100) / (1 + taoUsdChange24h / 100) - 1) * 100\n : null\n\n // insert at the correct location (based on the index of `tao` in `currencyIds`)\n rates?.splice(taoIndex, 0, [tokenTaoRate, null, tokenTaoChange24h])\n })\n }\n\n const tokenRates = parseTokenRatesFromApi(rawTokenRates, coingeckoIds, currencyIds)\n\n // build a TokenRatesList from the token prices result\n const ratesList: TokenRatesList = Object.fromEntries(\n Object.entries(tokens).map(([tokenId, token]) => [\n tokenId,\n token.coingeckoId ? (tokenRates[token.coingeckoId] ?? null) : null,\n ])\n ) as TokenRatesList\n\n return ratesList\n}\n\n// To save on bandwidth and work around response size limits, values are returned without json property names\n// (e.g. [[[12, 12332, 0.5]]] instead of { dot : {usd: { value: 12, marketCap: 12332, change24h: 0.5 }} })\ntype RawTokenRates = [number | null, number | null, number | null][][]\n\nconst parseTokenRatesFromApi = (\n rawTokenRates: RawTokenRates,\n coingeckoIds: string[],\n currencyIds: TokenRateCurrency[]\n): TokenRatesList => {\n return Object.fromEntries(\n coingeckoIds.map((coingeckoId, idx) => {\n const rates = rawTokenRates[idx]\n if (!rates) return [coingeckoId, null]\n\n return [\n coingeckoId,\n Object.fromEntries(\n currencyIds.map((currencyId, idx) => {\n const curRate = rates[idx]\n if (!curRate) return [currencyId, null]\n\n const [price, marketCap, change24h] = rates[idx]\n return [currencyId, { price, marketCap, change24h } as TokenRateData]\n })\n ) as TokenRates,\n ]\n })\n ) as TokenRatesList\n}\n"],"mappings":";;;;;;ACIA,IAAA,cAAe,UAAUA,sBAAgB;;;ACFzC,MAAa,uBAAuB;CAClC,KAAK;EAAE,MAAM;EAAW,QAAQ;CAAI;CACpC,KAAK;EAAE,MAAM;EAAY,QAAQ;CAAI;CACrC,KAAK;EAAE,MAAM;EAAY,QAAQ;CAAI;CACrC,KAAK;EAAE,MAAM;EAAa,QAAQ;CAAI;CAEtC,KAAK;EAAE,MAAM;EAAa,QAAQ;CAAI;CACtC,KAAK;EAAE,MAAM;EAAgB,QAAQ;CAAI;CACzC,KAAK;EAAE,MAAM;EAAQ,QAAQ;CAAI;CACjC,KAAK;EAAE,MAAM;EAAiB,QAAQ;CAAI;CAC1C,KAAK;EAAE,MAAM;EAAmB,QAAQ;CAAK;CAC7C,KAAK;EAAE,MAAM;EAAqB,QAAQ;CAAK;CAC/C,KAAK;EAAE,MAAM;EAAsB,QAAQ;CAAM;CACjD,KAAK;EAAE,MAAM;EAAgB,QA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AAC;EACpE,CAAC;CACH;CAEA,MAAM,aAAa,uBAAuB,eAAe,cAAc,WAAW;CAUlF,OAPkC,OAAO,YACvC,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,SAAS,WAAW,CAC/C,SACA,MAAM,cAAe,WAAW,MAAM,gBAAgB,OAAQ,IAChE,CAAC,CAGY;AACjB;AAMA,MAAM,0BACJ,eACA,cACA,gBACmB;CACnB,OAAO,OAAO,YACZ,aAAa,KAAK,aAAa,QAAQ;EACrC,MAAM,QAAQ,cAAc;EAC5B,IAAI,CAAC,OAAO,OAAO,CAAC,aAAa,IAAI;EAErC,OAAO,CACL,aACA,OAAO,YACL,YAAY,KAAK,YAAY,QAAQ;GAEnC,IAAI,CADY,MAAM,MACR,OAAO,CAAC,YAAY,IAAI;GAEtC,MAAM,CAAC,OAAO,WAAW,aAAa,MAAM;GAC5C,OAAO,CAAC,YAAY;IAAE;IAAO;IAAW;GAAU,CAAkB;EACtE,CAAC,CACH,CACF;CACF,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["packageJson.name"],"sources":["../package.json","../src/log.ts","../src/types.ts","../src/getDTaoTokenRates.ts","../src/fetchDTaoTokenRates.ts","../src/TalismanTokenRatesDatabase.ts","../src/TokenRates.ts"],"sourcesContent":["","import anylogger from \"anylogger\"\n\nimport packageJson from \"../package.json\"\n\nexport default anylogger(packageJson.name)\n","import type { TokenId } from \"@talismn/chaindata-provider\"\n\nexport const SUPPORTED_CURRENCIES = {\n btc: { name: \"Bitcoin\", symbol: \"₿\" },\n eth: { name: \"Ethereum\", symbol: \"Ξ\" },\n dot: { name: \"Polkadot\", symbol: \"D\" },\n tao: { name: \"Bittensor\", symbol: \"τ\" },\n\n usd: { name: \"US Dollar\", symbol: \"$\" },\n cny: { name: \"Chinese Yuan\", symbol: \"¥\" },\n eur: { name: \"Euro\", symbol: \"€\" },\n gbp: { name: \"British Pound\", symbol: \"£\" },\n cad: { name: \"Canadian Dollar\", symbol: \"C$\" },\n aud: { name: \"Australian Dollar\", symbol: \"A$\" },\n nzd: { name: \"New Zealand Dollar\", symbol: \"NZ$\" },\n jpy: { name: \"Japanese Yen\", symbol: \"¥\" },\n rub: { name: \"Russian Ruble\", symbol: \"₽\" },\n krw: { name: \"South Korean Won\", symbol: \"₩\" },\n idr: { name: \"Indonesian Rupiah\", symbol: \"Rp\" },\n php: { name: \"Philippine Peso\", symbol: \"₱\" },\n thb: { name: \"Thai Baht\", symbol: \"฿\" },\n vnd: { name: \"Vietnamese Dong\", symbol: \"₫\" },\n inr: { name: \"Indian Rupee\", symbol: \"₹\" },\n try: { name: \"Turkish Lira\", symbol: \"₺\" },\n // hkd: { name: \"Hong Kong Dollar\", symbol: \"HK$\" },\n sgd: { name: \"Singapore Dollar\", symbol: \"S$\" },\n // twd: { name: \"Taiwanese Dollar\", symbol: \"NT$\" },\n} as const\n\nexport type TokenRatesStorage = { tokenRates: TokenRatesList }\n\nexport type TokenRatesList = Record<TokenId, TokenRates>\nexport type TokenRates = Record<TokenRateCurrency, TokenRateData | null>\n\nexport type TokenRateData = { price: number; marketCap?: number; change24h?: number }\nexport type TokenRateCurrency = keyof typeof SUPPORTED_CURRENCIES\n\nexport const newTokenRates = (): TokenRates => ({\n btc: null,\n eth: null,\n dot: null,\n tao: null,\n\n usd: null,\n cny: null,\n eur: null,\n gbp: null,\n cad: null,\n aud: null,\n nzd: null,\n jpy: null,\n rub: null,\n krw: null,\n idr: null,\n php: null,\n thb: null,\n vnd: null,\n inr: null,\n try: null,\n // hkd: null,\n sgd: null,\n // twd: null,\n})\n","import { type SubDTaoToken, subNativeTokenId } from \"@talismn/chaindata-provider\"\n\nimport log from \"./log\"\nimport {\n newTokenRates,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRatesList,\n} from \"./types\"\n\n/** TAO-per-alpha pool price fixed-point scale: 10^9 (TAO decimals) */\nconst SCALED_ALPHA_PRICE_SCALE = 10 ** 9\n\n/**\n * 24h change of an alpha token in a given currency, in percent: the pool price change (alpha vs\n * TAO) compounded with the TAO change in that currency. Unknown without the pool change.\n */\nconst getAlphaChange24h = (\n currency: TokenRateCurrency,\n taoChange24h: number | null | undefined,\n alphaPriceChange24h: number | null | undefined\n): number | undefined => {\n if (typeof alphaPriceChange24h !== \"number\" || !Number.isFinite(alphaPriceChange24h))\n return undefined\n\n // TAO itself doesn't move against the tao currency: the alpha change is the pool change\n if (currency === \"tao\") return alphaPriceChange24h\n\n if (typeof taoChange24h !== \"number\" || !Number.isFinite(taoChange24h)) return undefined\n return ((1 + alphaPriceChange24h / 100) * (1 + taoChange24h / 100) - 1) * 100\n}\n\n/**\n * Rates of a bittensor dtao (subnet alpha) token, derived from its network's native TAO rates\n * scaled by the subnet pool price. To be used for tokens that don't have a coingecko id.\n *\n * @param token\n * @param tokenRates must contain the rates of the network's native (TAO) token\n * @param scaledAlphaPrice current TAO-per-alpha pool price, fixed-point scaled by 10^9 (rao)\n * @param alphaPriceChange24h 24h change of the pool price (alpha vs TAO) in percent, when known\n */\nexport const getDTaoTokenRates = (\n token: SubDTaoToken,\n tokenRates: TokenRatesList,\n scaledAlphaPrice: string | bigint,\n alphaPriceChange24h?: number | null\n) => {\n try {\n const taoTokenId = subNativeTokenId(token.networkId)\n const taoTokenRates = tokenRates[taoTokenId]\n if (!taoTokenRates) return null\n\n // for root subnet, same rates as TAO\n if (token.netuid === 0) return structuredClone(taoTokenRates)\n\n const priceRatio = Number(BigInt(scaledAlphaPrice)) / SCALED_ALPHA_PRICE_SCALE\n\n const alphaRates = newTokenRates()\n for (const [currency, taoRate] of Object.entries(taoTokenRates) as [\n TokenRateCurrency,\n TokenRateData | null,\n ][]) {\n if (!taoRate) {\n alphaRates[currency] = null\n } else {\n alphaRates[currency] = {\n price: taoRate.price * priceRatio,\n marketCap: taoRate.marketCap ? taoRate.marketCap * priceRatio : undefined,\n change24h: getAlphaChange24h(currency, taoRate.change24h, alphaPriceChange24h),\n }\n }\n }\n\n return alphaRates\n } catch (err) {\n log.error(\"Failed to compute dtao token rates\", err)\n return null\n }\n}\n","import type { IChainConnectorDot } from \"@talismn/chain-connectors\"\nimport type { NetworkId, SubDTaoToken, TokenList } from \"@talismn/chaindata-provider\"\nimport { subNativeTokenId } from \"@talismn/chaindata-provider\"\nimport { throwAfter } from \"@talismn/util\"\nimport { Struct, u16, u64, Vector } from \"scale-ts\"\n\nimport { getDTaoTokenRates } from \"./getDTaoTokenRates\"\nimport log from \"./log\"\nimport type { TokenRatesList } from \"./types\"\n\nconst DEFAULT_BITTENSOR_NETWORK_ID = \"bittensor\"\nconst DEFAULT_TAO_DATA_API_URL = \"https://tda.talisman.xyz\"\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n// decoded shape of the SwapRuntimeApi_current_alpha_price_all result\nconst alphaPricesCodec = Vector(Struct({ netuid: u16, price: u64 }))\n\n/** Current TAO-per-alpha pool price of every subnet, keyed by netuid, in the scaledAlphaPrice fixed-point format (rao) */\nconst fetchScaledAlphaPricesByNetuid = async (\n connector: IChainConnectorDot,\n networkId: NetworkId\n): Promise<Map<number, bigint>> => {\n const result = await connector.send<string>(networkId, \"state_call\", [\n \"SwapRuntimeApi_current_alpha_price_all\",\n \"0x\",\n ])\n return new Map(alphaPricesCodec.dec(result).map(({ netuid, price }) => [netuid, price]))\n}\n\nconst ALPHA_PRICE_CHANGES_TTL = 5 * 60_000\nconst alphaPriceChangesCache = new Map<\n string,\n { fetchedAt: number; changes: Map<number, number> }\n>()\n\n/**\n * 24h percent change of every subnet pool price (alpha vs TAO) from the tao-data api — the\n * chain knows the current pool prices but not yesterday's. 5-min in-memory cache; failure is\n * non-fatal (stale cache when available, else no change24h on the computed rates).\n */\nconst getAlphaPriceChangesByNetuid = async (\n apiUrl: string,\n customFetch: typeof fetch,\n timeoutMs: number\n): Promise<Map<number, number> | null> => {\n const cached = alphaPriceChangesCache.get(apiUrl)\n if (cached && performance.now() - cached.fetchedAt < ALPHA_PRICE_CHANGES_TTL)\n return cached.changes\n\n try {\n const response = await customFetch(`${apiUrl}/pools`, {\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`)\n const pools = (await response.json()) as {\n netuid: number\n price_change_1_day: number | string\n }[]\n const changes = new Map(\n pools\n .map((pool): [number, number] => [pool.netuid, Number(pool.price_change_1_day)])\n .filter(([, change]) => Number.isFinite(change))\n )\n alphaPriceChangesCache.set(apiUrl, { fetchedAt: performance.now(), changes })\n return changes\n } catch (err) {\n log.warn(\"Failed to fetch alpha price 24h changes\", err)\n return cached?.changes ?? null\n }\n}\n\nexport type FetchDTaoTokenRatesOptions = {\n /** substrate chain connector of the host (only its `send` method is used, for one state_call per invocation) */\n connector: IChainConnectorDot\n /** the bittensor network id, defaults to \"bittensor\" (mainnet) */\n networkId?: NetworkId\n /** token list to price — non-dtao tokens (and dtao tokens with a coingeckoId) are ignored */\n tokens: TokenList\n /** freshly fetched rates list — dtao rates derive from the network's native TAO token rates in it */\n tokenRates: TokenRatesList\n /** previous rates list, used as keep-last fallback when fetching fails */\n previousRates: TokenRatesList\n /** custom fetch for the tao-data api (eg with auth headers), defaults to global fetch */\n customFetch?: typeof fetch\n /** tao-data api url, defaults to https://tda.talisman.xyz — pass null to skip the 24h-change fetch (eg testnets, which the api has no data for) */\n taoDataApiUrl?: string | null\n /** per-request timeout for the chain call and the tao-data api call, defaults to 10s */\n timeoutMs?: number\n}\n\n/**\n * Rates entries for the bittensor dtao (subnet alpha) tokens of `tokens`, priced from their\n * subnet pool combined with the TAO rates in `tokenRates`. On chain-fetch failure, falls\n * back to the token's entry in `previousRates` (keep-last). Never throws — a dtao pricing\n * failure must not discard the rates list it gets merged into.\n *\n * Hosts remain responsible for WHEN to call this (network enabled state, refresh cadence)\n * and for merging the result into their rates list/store.\n */\nexport const fetchDTaoTokenRates = async ({\n connector,\n networkId = DEFAULT_BITTENSOR_NETWORK_ID,\n tokens,\n tokenRates,\n previousRates,\n customFetch = fetch,\n taoDataApiUrl = DEFAULT_TAO_DATA_API_URL,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n}: FetchDTaoTokenRatesOptions): Promise<TokenRatesList> => {\n const dtaoTokens = Object.values(tokens).filter(\n (token): token is SubDTaoToken =>\n token.type === \"substrate-dtao\" && token.networkId === networkId && !token.coingeckoId\n )\n if (!dtaoTokens.length) return {}\n\n // alpha rates derive from the network's native TAO rates: without them there is nothing to\n // price against, and keep-last must not apply (stale entries would display as current)\n if (!tokenRates[subNativeTokenId(networkId)]) return {}\n\n // the two fetches are independent: run them concurrently\n const [prices, changes] = await Promise.all([\n Promise.race([\n fetchScaledAlphaPricesByNetuid(connector, networkId),\n throwAfter(timeoutMs, `Timed out after ${timeoutMs}ms`),\n ]).catch((err) => {\n log.warn(\"Failed to fetch alpha prices, keeping previous dtao rates\", err)\n return null\n }),\n taoDataApiUrl === null\n ? null\n : getAlphaPriceChangesByNetuid(taoDataApiUrl, customFetch, timeoutMs),\n ])\n\n if (!prices)\n return Object.fromEntries(\n dtaoTokens\n .filter((token) => previousRates[token.id])\n .map((token) => [token.id, previousRates[token.id]])\n )\n\n return Object.fromEntries(\n dtaoTokens\n .map((token) => {\n // never fabricate a zero price: a missing or zero pool price keeps the last rates\n const price = prices.get(token.netuid)\n const rates = price\n ? getDTaoTokenRates(token, tokenRates, price, changes?.get(token.netuid))\n : null\n return [token.id, rates ?? previousRates[token.id]] as const\n })\n .filter(([, rates]) => !!rates)\n )\n}\n","export const tryToDeleteOldTokenRatesDb = () => {\n try {\n // try and delete it if it's still there\n indexedDB.deleteDatabase(\"TalismanTokenRates\")\n } catch {\n // dont care if it fails\n }\n}\n","import { evmErc20TokenId, type Token, type TokenId } from \"@talismn/chaindata-provider\"\n\nimport {\n SUPPORTED_CURRENCIES,\n type TokenRateCurrency,\n type TokenRateData,\n type TokenRates,\n type TokenRatesList,\n} from \"./types\"\n\nexport class TokenRatesError extends Error {\n response?: Response\n constructor(message: string, response?: Response) {\n super(message)\n this.response = response\n }\n}\n\nexport const ALL_CURRENCY_IDS = Object.keys(SUPPORTED_CURRENCIES) as TokenRateCurrency[]\nexport type CoinsApiConfig = {\n apiUrl: string\n}\n\nexport const DEFAULT_COINSAPI_CONFIG: CoinsApiConfig = {\n apiUrl: \"https://coins.talisman.xyz\",\n}\nexport async function fetchTokenRates(\n tokens: Record<TokenId, Token>,\n currencyIds: TokenRateCurrency[] = ALL_CURRENCY_IDS,\n config: CoinsApiConfig = DEFAULT_COINSAPI_CONFIG\n): Promise<TokenRatesList> {\n // create a map from `coingeckoId` -> `tokenId` for each token\n const coingeckoIdToTokenIds = Object.values(tokens)\n .flatMap((token) => {\n // BEGIN: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n //\n // This section contains the logic such that: if token is an LP token, then fetch the rates for the two underlying tokens.\n if (token.type === \"evm-uniswapv2\") {\n if (token.platform !== \"ethereum\") return []\n\n const getToken = (\n evmNetworkId: string,\n tokenAddress: `0x${string}`,\n coingeckoId: string\n ) => ({\n id: evmErc20TokenId(evmNetworkId, tokenAddress),\n coingeckoId,\n })\n\n const token0 = token.coingeckoId0\n ? [getToken(token.networkId, token.tokenAddress0, token.coingeckoId0)]\n : []\n const token1 = token.coingeckoId1\n ? [getToken(token.networkId, token.tokenAddress1, token.coingeckoId1)]\n : []\n\n return [...token0, ...token1]\n }\n // END: LP tokens have a rate which is calculated later on, using the rates of two other tokens.\n\n // ignore tokens which don't have a coingeckoId\n if (!token.coingeckoId) return []\n\n return [{ id: token.id, coingeckoId: token.coingeckoId }]\n })\n\n // get each token's coingeckoId\n .reduce(\n (coingeckoIdToTokenIds, { id, coingeckoId }) => {\n if (!coingeckoIdToTokenIds[coingeckoId]) coingeckoIdToTokenIds[coingeckoId] = []\n coingeckoIdToTokenIds[coingeckoId].push(id)\n return coingeckoIdToTokenIds\n },\n {} as Record<string, string[]>\n )\n\n // create a list of coingeckoIds we want to fetch\n const coingeckoIds = Object.keys(coingeckoIdToTokenIds).sort()\n\n // skip network request if there is nothing for us to fetch\n if (coingeckoIds.length < 1) return {}\n\n // If `currencyIds` includes `tao`, we need to always fetch the `bittensor` coingeckoId and the `usd` currency,\n // we can use these to calculate the currency rate for TAO relative to all other tokens.\n //\n // We support showing balances in TAO just like we support BTC/ETH/DOT, but coingecko doesn't support TAO as a vs currency rate.\n // We can macgyver our own TOKEN<>TAO rate by combining the TOKEN<>USD data with the TAO<>USD data.\n const hasVsTao = currencyIds.includes(\"tao\")\n const [effectiveCoingeckoIds, effectiveCurrencyIds] = hasVsTao\n ? [\n [...new Set(coingeckoIds).add(\"bittensor\")],\n [\n ...new Set(\n // don't request `tao` from coingecko (we calculate it from `usd`)\n currencyIds.filter((c) => c !== \"tao\")\n )\n // always include `usd` (so we can calculate `tao`)\n .add(\"usd\"),\n ],\n ]\n : [coingeckoIds, currencyIds]\n\n const response = await fetch(`${config.apiUrl}/token-rates`, {\n method: \"POST\",\n body: JSON.stringify({\n coingeckoIds: effectiveCoingeckoIds,\n currencyIds: effectiveCurrencyIds,\n }),\n })\n\n const rawTokenRates = (await response.json()) as RawTokenRates\n\n if (hasVsTao) {\n // calculate the TAO<>USD rate\n const effectiveTaoIndex = effectiveCoingeckoIds.indexOf(\"bittensor\")\n const effectiveUsdIndex = effectiveCurrencyIds.indexOf(\"usd\")\n const taoUsdRate = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[0]\n const taoUsdChange24h = rawTokenRates[effectiveTaoIndex]?.[effectiveUsdIndex]?.[2]\n\n // insert TOKEN<>TAO rate (calculated based on TAO<>USD rate and TOKEN<>USD rate) into each TOKEN\n const taoIndex = currencyIds.indexOf(\"tao\")\n rawTokenRates.forEach((rates, i) => {\n // hardcoded rate for TAO<>TAO\n if (i === effectiveTaoIndex) {\n rates?.splice(taoIndex, 0, [1, null, null])\n return\n }\n\n // get TOKEN<>USD rate\n const tokenUsdRate = rates?.[effectiveUsdIndex]?.[0]\n // calculate TOKEN<>TAO rate\n const tokenTaoRate =\n typeof tokenUsdRate === \"number\" && typeof taoUsdRate === \"number\" && taoUsdRate !== 0\n ? tokenUsdRate / taoUsdRate\n : null\n\n // the 24h changes are percents: the token's change against TAO is its USD price\n // ratio now over 24h ago, divided by TAO's\n const tokenUsdChange24h = rates?.[effectiveUsdIndex]?.[2]\n const tokenTaoChange24h =\n typeof taoUsdChange24h === \"number\" &&\n typeof tokenUsdChange24h === \"number\" &&\n taoUsdChange24h > -100\n ? ((1 + tokenUsdChange24h / 100) / (1 + taoUsdChange24h / 100) - 1) * 100\n : null\n\n // insert at the correct location (based on the index of `tao` in `currencyIds`)\n rates?.splice(taoIndex, 0, [tokenTaoRate, null, tokenTaoChange24h])\n })\n }\n\n const tokenRates = parseTokenRatesFromApi(rawTokenRates, coingeckoIds, currencyIds)\n\n // build a TokenRatesList from the token prices result\n const ratesList: TokenRatesList = Object.fromEntries(\n Object.entries(tokens).map(([tokenId, token]) => [\n tokenId,\n token.coingeckoId ? (tokenRates[token.coingeckoId] ?? null) : null,\n ])\n ) as TokenRatesList\n\n return ratesList\n}\n\n// To save on bandwidth and work around response size limits, values are returned without json property names\n// (e.g. [[[12, 12332, 0.5]]] instead of { dot : {usd: { value: 12, marketCap: 12332, change24h: 0.5 }} })\ntype RawTokenRates = [number | null, number | null, number | null][][]\n\nconst parseTokenRatesFromApi = (\n rawTokenRates: RawTokenRates,\n coingeckoIds: string[],\n currencyIds: TokenRateCurrency[]\n): TokenRatesList => {\n return Object.fromEntries(\n coingeckoIds.map((coingeckoId, idx) => {\n const rates = rawTokenRates[idx]\n if (!rates) return [coingeckoId, null]\n\n return [\n coingeckoId,\n Object.fromEntries(\n currencyIds.map((currencyId, idx) => {\n const curRate = rates[idx]\n if (!curRate) return [currencyId, null]\n\n const [price, marketCap, change24h] = rates[idx]\n return [currencyId, { price, marketCap, change24h } as TokenRateData]\n })\n ) as TokenRates,\n ]\n })\n ) as TokenRatesList\n}\n"],"mappings":";;;;;ACIA,IAAA,cAAe,UAAUA,sBAAgB;;ACFzC,MAAa,uBAAuB;CAClC,K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",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.10",
|
|
4
4
|
"description": "Fiat and crypto prices for tokens, from the Talisman coins API",
|
|
5
5
|
"author": "Talisman",
|
|
6
6
|
"homepage": "https://talisman.xyz",
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
"node": ">=20"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@talismn/chain-connectors": "1.1.
|
|
26
|
-
"@talismn/chaindata-provider": "2.
|
|
27
|
-
"@talismn/util": "2.
|
|
25
|
+
"@talismn/chain-connectors": "1.1.3",
|
|
26
|
+
"@talismn/chaindata-provider": "2.4.0",
|
|
27
|
+
"@talismn/util": "2.2.0",
|
|
28
28
|
"anylogger": "^1.0.11",
|
|
29
29
|
"scale-ts": "^1.6.1"
|
|
30
30
|
},
|