@metamask-previews/assets-controller 20.4.1-preview-c552582c8 → 20.4.1-preview-2da314d6d
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/CHANGELOG.md +0 -9
- package/README.md +0 -3
- package/dist/AssetsController-method-action-types.d.ts +2 -2
- package/dist/AssetsController-method-action-types.js.map +1 -1
- package/dist/AssetsController.d.ts +12 -6
- package/dist/AssetsController.d.ts.map +1 -1
- package/dist/AssetsController.js +16 -21
- package/dist/AssetsController.js.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.d.ts +2 -4
- package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.js +1 -3
- package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
- package/dist/data-sources/PriceDataSource.d.ts +5 -32
- package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
- package/dist/data-sources/PriceDataSource.js +91 -133
- package/dist/data-sources/PriceDataSource.js.map +1 -1
- package/dist/data-sources/index.d.ts +1 -1
- package/dist/data-sources/index.d.ts.map +1 -1
- package/dist/data-sources/index.js.map +1 -1
- package/dist/index.d.ts +2 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +0 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/dist/data-sources/MarketStatsPriceStream.d.ts +0 -67
- package/dist/data-sources/MarketStatsPriceStream.d.ts.map +0 -1
- package/dist/data-sources/MarketStatsPriceStream.js +0 -181
- package/dist/data-sources/MarketStatsPriceStream.js.map +0 -1
- package/dist/store/MarketStatsStore.d.ts +0 -72
- package/dist/store/MarketStatsStore.d.ts.map +0 -1
- package/dist/store/MarketStatsStore.js +0 -182
- package/dist/store/MarketStatsStore.js.map +0 -1
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Subscribes the price-fetch set when the Price API marks it `wssSupport`.
|
|
3
|
-
*
|
|
4
|
-
* That set is balances and custom assets on the selected accounts and chains,
|
|
5
|
-
* minus hidden assets. Open channels live on MarketStatsService. The price
|
|
6
|
-
* poll is unchanged: it still fetches every tracked asset. This stream only
|
|
7
|
-
* adds the socket subscription. When MarketStatsService is not wired, the
|
|
8
|
-
* poll is the only price source.
|
|
9
|
-
*/
|
|
10
|
-
import { createModuleLogger, projectLogger } from '../logger.js';
|
|
11
|
-
import { normalizeAssetId } from '../utils/index.js';
|
|
12
|
-
const log = createModuleLogger(projectLogger, 'MarketStatsPriceStream');
|
|
13
|
-
/**
|
|
14
|
-
* Read `wssSupport` off a spot-price entry.
|
|
15
|
-
*
|
|
16
|
-
* @param data - One asset's `/v3/spot-prices` entry.
|
|
17
|
-
* @returns Whether the asset can stream.
|
|
18
|
-
*/
|
|
19
|
-
export function readSpotPriceStreamEligibility(data) {
|
|
20
|
-
return data.wssSupport === true;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Assets the Price API marks as streamable.
|
|
24
|
-
*
|
|
25
|
-
* @param candidates - Assets learned from the latest spot-price response.
|
|
26
|
-
* @returns Asset ids to subscribe.
|
|
27
|
-
*/
|
|
28
|
-
export function selectAssetsToStream(candidates) {
|
|
29
|
-
return candidates
|
|
30
|
-
.filter((candidate) => candidate.wssSupport)
|
|
31
|
-
.map((candidate) => candidate.assetId);
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* True when the messenger has no MarketStatsService handler.
|
|
35
|
-
* Price updates then stay on the poll.
|
|
36
|
-
*
|
|
37
|
-
* @param error - Failure from `messenger.call`.
|
|
38
|
-
* @returns Whether streaming cannot be used in this process.
|
|
39
|
-
*/
|
|
40
|
-
export function isMarketStatsUnavailable(error) {
|
|
41
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
42
|
-
return (message.includes('has not been registered') ||
|
|
43
|
-
message.includes('has not been delegated'));
|
|
44
|
-
}
|
|
45
|
-
function canonicalAssetId(assetId) {
|
|
46
|
-
try {
|
|
47
|
-
return normalizeAssetId(assetId);
|
|
48
|
-
}
|
|
49
|
-
catch {
|
|
50
|
-
return assetId;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Opens market-stats channels for the price-fetch set.
|
|
55
|
-
*/
|
|
56
|
-
export class MarketStatsPriceStream {
|
|
57
|
-
#messenger;
|
|
58
|
-
#getSelectedCurrency;
|
|
59
|
-
/**
|
|
60
|
-
* Asset ids from the last reconcile. An id that leaves this set is
|
|
61
|
-
* unsubscribed. Channels opened outside the price-fetch set are left open.
|
|
62
|
-
*/
|
|
63
|
-
#pricedAssetIds = new Set();
|
|
64
|
-
#lock = Promise.resolve();
|
|
65
|
-
constructor(options) {
|
|
66
|
-
this.#messenger = options.messenger;
|
|
67
|
-
this.#getSelectedCurrency = options.getSelectedCurrency;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Subscribe price-fetch assets marked `wssSupport`.
|
|
71
|
-
* Drop channels for assets that left that set.
|
|
72
|
-
*
|
|
73
|
-
* @param candidates - Price-fetch assets in the current subscription scope.
|
|
74
|
-
*/
|
|
75
|
-
async reconcile(candidates) {
|
|
76
|
-
await this.#withLock(async () => {
|
|
77
|
-
const selectedCurrency = this.#getSelectedCurrency();
|
|
78
|
-
const priced = new Set(candidates.map((candidate) => canonicalAssetId(candidate.assetId)));
|
|
79
|
-
const subscribing = selectAssetsToStream(candidates).map((assetId) => ({
|
|
80
|
-
assetId: canonicalAssetId(assetId),
|
|
81
|
-
currency: selectedCurrency,
|
|
82
|
-
}));
|
|
83
|
-
const current = await this.#readSubscriptions();
|
|
84
|
-
if (!current) {
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
const previous = this.#pricedAssetIds;
|
|
88
|
-
this.#pricedAssetIds = priced;
|
|
89
|
-
await this.#unsubscribe(current.filter((subscription) => {
|
|
90
|
-
const assetId = canonicalAssetId(subscription.assetId);
|
|
91
|
-
return previous.has(assetId) && !priced.has(assetId);
|
|
92
|
-
}));
|
|
93
|
-
const open = new Set(current.map((subscription) => `${canonicalAssetId(subscription.assetId)}::${subscription.currency.toLowerCase()}`));
|
|
94
|
-
const opening = subscribing.filter((subscription) => !open.has(`${subscription.assetId}::${subscription.currency.toLowerCase()}`));
|
|
95
|
-
if (opening.length > 0) {
|
|
96
|
-
try {
|
|
97
|
-
await this.#messenger.call('MarketStatsService:subscribe', opening);
|
|
98
|
-
}
|
|
99
|
-
catch (error) {
|
|
100
|
-
if (isMarketStatsUnavailable(error)) {
|
|
101
|
-
log('Market stats stream is not available; polling prices');
|
|
102
|
-
}
|
|
103
|
-
else {
|
|
104
|
-
log('Market stats subscribe failed; polling assets the service did not open', { error });
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Drop one reference on each open channel for a price-fetch asset.
|
|
112
|
-
* Used when the selected currency changes, and when the price subscription ends.
|
|
113
|
-
*/
|
|
114
|
-
async releaseSubscriptions() {
|
|
115
|
-
await this.#withLock(async () => {
|
|
116
|
-
await this.#releaseOpened();
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Remove listeners and drop channels this stream opened.
|
|
121
|
-
*/
|
|
122
|
-
destroy() {
|
|
123
|
-
this.#releaseOpened().catch(() => {
|
|
124
|
-
// destroy is sync; a failed unsubscribe is already logged
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
|
-
async #releaseOpened() {
|
|
128
|
-
if (this.#pricedAssetIds.size === 0) {
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
const current = await this.#readSubscriptions();
|
|
132
|
-
if (!current) {
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
await this.#unsubscribe(current.filter((subscription) => this.#pricedAssetIds.has(canonicalAssetId(subscription.assetId))));
|
|
136
|
-
}
|
|
137
|
-
async #readSubscriptions() {
|
|
138
|
-
try {
|
|
139
|
-
return this.#messenger.call('MarketStatsService:getSubscriptions');
|
|
140
|
-
}
|
|
141
|
-
catch (error) {
|
|
142
|
-
if (isMarketStatsUnavailable(error)) {
|
|
143
|
-
log('Market stats stream is not available; polling prices');
|
|
144
|
-
return null;
|
|
145
|
-
}
|
|
146
|
-
throw error;
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
async #unsubscribe(open) {
|
|
150
|
-
if (open.length === 0) {
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
|
-
try {
|
|
154
|
-
await this.#messenger.call('MarketStatsService:unsubscribe', open.map(({ assetId, currency }) => ({
|
|
155
|
-
assetId: canonicalAssetId(assetId),
|
|
156
|
-
currency,
|
|
157
|
-
})));
|
|
158
|
-
}
|
|
159
|
-
catch (error) {
|
|
160
|
-
log('Market stats unsubscribe failed', {
|
|
161
|
-
assetIds: open.map((info) => info.assetId),
|
|
162
|
-
error,
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
async #withLock(fn) {
|
|
167
|
-
const previous = this.#lock;
|
|
168
|
-
let release = () => undefined;
|
|
169
|
-
this.#lock = new Promise((resolve) => {
|
|
170
|
-
release = resolve;
|
|
171
|
-
});
|
|
172
|
-
await previous;
|
|
173
|
-
try {
|
|
174
|
-
await fn();
|
|
175
|
-
}
|
|
176
|
-
finally {
|
|
177
|
-
release();
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
//# sourceMappingURL=MarketStatsPriceStream.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarketStatsPriceStream.js","sourceRoot":"","sources":["../../src/data-sources/MarketStatsPriceStream.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AASH,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAEjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;A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AAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YACzC,OAAO,GAAG,OAAO,CAAC;QACpB,CAAC,CAAC,CAAC;QACH,MAAM,QAAQ,CAAC;QACf,IAAI,CAAC;YACH,MAAM,EAAE,EAAE,CAAC;QACb,CAAC;gBAAS,CAAC;YACT,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Subscribes the price-fetch set when the Price API marks it `wssSupport`.\n *\n * That set is balances and custom assets on the selected accounts and chains,\n * minus hidden assets. Open channels live on MarketStatsService. The price\n * poll is unchanged: it still fetches every tracked asset. This stream only\n * adds the socket subscription. When MarketStatsService is not wired, the\n * poll is the only price source.\n */\n\nimport type {\n MarketStatsServiceActions,\n MarketStatsServiceChainStatusChangedEvent,\n SupportedCurrency,\n} from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\n\nimport { createModuleLogger, projectLogger } from '../logger.js';\nimport type { Caip19AssetId } from '../types.js';\nimport { normalizeAssetId } from '../utils/index.js';\n\nconst log = createModuleLogger(projectLogger, 'MarketStatsPriceStream');\n\nexport type MarketStatsPriceStreamMessenger = Messenger<\n string,\n MarketStatsServiceActions,\n MarketStatsServiceChainStatusChangedEvent\n>;\n\nexport type StreamCandidate = {\n assetId: Caip19AssetId;\n wssSupport: boolean;\n};\n\ntype MarketStatsSubscription = {\n assetId: string;\n currency: string;\n};\n\nexport type MarketStatsPriceStreamOptions = {\n messenger: MarketStatsPriceStreamMessenger;\n getSelectedCurrency: () => SupportedCurrency;\n};\n\n/**\n * Read `wssSupport` off a spot-price entry.\n *\n * @param data - One asset's `/v3/spot-prices` entry.\n * @returns Whether the asset can stream.\n */\nexport function readSpotPriceStreamEligibility(data: object): boolean {\n return (data as { wssSupport?: unknown }).wssSupport === true;\n}\n\n/**\n * Assets the Price API marks as streamable.\n *\n * @param candidates - Assets learned from the latest spot-price response.\n * @returns Asset ids to subscribe.\n */\nexport function selectAssetsToStream(\n candidates: StreamCandidate[],\n): Caip19AssetId[] {\n return candidates\n .filter((candidate) => candidate.wssSupport)\n .map((candidate) => candidate.assetId);\n}\n\n/**\n * True when the messenger has no MarketStatsService handler.\n * Price updates then stay on the poll.\n *\n * @param error - Failure from `messenger.call`.\n * @returns Whether streaming cannot be used in this process.\n */\nexport function isMarketStatsUnavailable(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return (\n message.includes('has not been registered') ||\n message.includes('has not been delegated')\n );\n}\n\nfunction canonicalAssetId(assetId: string): string {\n try {\n return normalizeAssetId(assetId as Caip19AssetId);\n } catch {\n return assetId;\n }\n}\n\n/**\n * Opens market-stats channels for the price-fetch set.\n */\nexport class MarketStatsPriceStream {\n readonly #messenger: MarketStatsPriceStreamMessenger;\n\n readonly #getSelectedCurrency: () => SupportedCurrency;\n\n /**\n * Asset ids from the last reconcile. An id that leaves this set is\n * unsubscribed. Channels opened outside the price-fetch set are left open.\n */\n #pricedAssetIds = new Set<string>();\n\n #lock: Promise<void> = Promise.resolve();\n\n constructor(options: MarketStatsPriceStreamOptions) {\n this.#messenger = options.messenger;\n this.#getSelectedCurrency = options.getSelectedCurrency;\n }\n\n /**\n * Subscribe price-fetch assets marked `wssSupport`.\n * Drop channels for assets that left that set.\n *\n * @param candidates - Price-fetch assets in the current subscription scope.\n */\n async reconcile(candidates: StreamCandidate[]): Promise<void> {\n await this.#withLock(async () => {\n const selectedCurrency = this.#getSelectedCurrency();\n const priced = new Set(\n candidates.map((candidate) => canonicalAssetId(candidate.assetId)),\n );\n const subscribing = selectAssetsToStream(candidates).map((assetId) => ({\n assetId: canonicalAssetId(assetId) as Caip19AssetId,\n currency: selectedCurrency,\n }));\n\n const current = await this.#readSubscriptions();\n if (!current) {\n return;\n }\n\n const previous = this.#pricedAssetIds;\n this.#pricedAssetIds = priced;\n await this.#unsubscribe(\n current.filter((subscription) => {\n const assetId = canonicalAssetId(subscription.assetId);\n return previous.has(assetId) && !priced.has(assetId);\n }),\n );\n const open = new Set(\n current.map(\n (subscription) =>\n `${canonicalAssetId(subscription.assetId)}::${subscription.currency.toLowerCase()}`,\n ),\n );\n const opening = subscribing.filter(\n (subscription) =>\n !open.has(\n `${subscription.assetId}::${subscription.currency.toLowerCase()}`,\n ),\n );\n if (opening.length > 0) {\n try {\n await this.#messenger.call('MarketStatsService:subscribe', opening);\n } catch (error) {\n if (isMarketStatsUnavailable(error)) {\n log('Market stats stream is not available; polling prices');\n } else {\n log(\n 'Market stats subscribe failed; polling assets the service did not open',\n { error },\n );\n }\n }\n }\n });\n }\n\n /**\n * Drop one reference on each open channel for a price-fetch asset.\n * Used when the selected currency changes, and when the price subscription ends.\n */\n async releaseSubscriptions(): Promise<void> {\n await this.#withLock(async () => {\n await this.#releaseOpened();\n });\n }\n\n /**\n * Remove listeners and drop channels this stream opened.\n */\n destroy(): void {\n this.#releaseOpened().catch(() => {\n // destroy is sync; a failed unsubscribe is already logged\n });\n }\n\n async #releaseOpened(): Promise<void> {\n if (this.#pricedAssetIds.size === 0) {\n return;\n }\n const current = await this.#readSubscriptions();\n if (!current) {\n return;\n }\n await this.#unsubscribe(\n current.filter((subscription) =>\n this.#pricedAssetIds.has(canonicalAssetId(subscription.assetId)),\n ),\n );\n }\n\n async #readSubscriptions(): Promise<MarketStatsSubscription[] | null> {\n try {\n return this.#messenger.call('MarketStatsService:getSubscriptions');\n } catch (error) {\n if (isMarketStatsUnavailable(error)) {\n log('Market stats stream is not available; polling prices');\n return null;\n }\n throw error;\n }\n }\n\n async #unsubscribe(open: readonly MarketStatsSubscription[]): Promise<void> {\n if (open.length === 0) {\n return;\n }\n try {\n await this.#messenger.call(\n 'MarketStatsService:unsubscribe',\n open.map(({ assetId, currency }) => ({\n assetId: canonicalAssetId(assetId),\n currency,\n })),\n );\n } catch (error) {\n log('Market stats unsubscribe failed', {\n assetIds: open.map((info) => info.assetId),\n error,\n });\n }\n }\n\n async #withLock(fn: () => Promise<void>): Promise<void> {\n const previous = this.#lock;\n let release: () => void = () => undefined;\n this.#lock = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n try {\n await fn();\n } finally {\n release();\n }\n }\n}\n"]}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Quote cache for `MarketStatsService:pricesUpdated`.
|
|
3
|
-
*
|
|
4
|
-
* The UI holds one instance. A tick updates this object and does not write
|
|
5
|
-
* `AssetsController` state, so it does not persist and does not notify the
|
|
6
|
-
* controller. Polled prices stay in `assetsPrice` and show when this map has
|
|
7
|
-
* no quote.
|
|
8
|
-
*/
|
|
9
|
-
export type LiveQuote = {
|
|
10
|
-
price: number;
|
|
11
|
-
pricePercentChange1d?: number;
|
|
12
|
-
};
|
|
13
|
-
export type LivePriceMap = ReadonlyMap<string, LiveQuote>;
|
|
14
|
-
/**
|
|
15
|
-
* Key a market-stats asset id the same way on the tick and on the lookup.
|
|
16
|
-
* EVM ERC-20 addresses are checksummed. Anything else is kept as given.
|
|
17
|
-
*
|
|
18
|
-
* @param assetId - CAIP-19 asset id, or any other string the caller uses as a key.
|
|
19
|
-
* @returns The map key.
|
|
20
|
-
*/
|
|
21
|
-
export declare function marketStatsAssetKey(assetId: string): string;
|
|
22
|
-
/**
|
|
23
|
-
* Quote for one asset. The id is keyed with {@link marketStatsAssetKey}.
|
|
24
|
-
*
|
|
25
|
-
* @param quotes - Current quote map.
|
|
26
|
-
* @param assetId - CAIP-19 asset id.
|
|
27
|
-
* @returns The streamed quote, or undefined.
|
|
28
|
-
*/
|
|
29
|
-
export declare function readLiveQuote(quotes: LivePriceMap, assetId: string | undefined): LiveQuote | undefined;
|
|
30
|
-
/**
|
|
31
|
-
* Latest market-stats quotes for one currency.
|
|
32
|
-
*/
|
|
33
|
-
export declare class MarketStatsStore {
|
|
34
|
-
#private;
|
|
35
|
-
/**
|
|
36
|
-
* Stable reference so `useSyncExternalStore` can take it directly.
|
|
37
|
-
*
|
|
38
|
-
* @returns The current quote map. The same reference until a tick changes it.
|
|
39
|
-
*/
|
|
40
|
-
readonly getSnapshot: () => LivePriceMap;
|
|
41
|
-
/**
|
|
42
|
-
* @param listener - Called after the quote map changes.
|
|
43
|
-
* @returns Unsubscribe.
|
|
44
|
-
*/
|
|
45
|
-
readonly subscribe: (listener: () => void) => (() => void);
|
|
46
|
-
/**
|
|
47
|
-
* Remember the selected currency and drop quotes from the previous one.
|
|
48
|
-
* Does not notify. Callers invoke this during render, and the currency
|
|
49
|
-
* selector is what re-renders every reader. That render already reads the
|
|
50
|
-
* empty map.
|
|
51
|
-
*
|
|
52
|
-
* @param currency - Selected currency. Case is ignored.
|
|
53
|
-
*/
|
|
54
|
-
setCurrency(currency: string): void;
|
|
55
|
-
/**
|
|
56
|
-
* Merge one `MarketStatsService:pricesUpdated` payload.
|
|
57
|
-
* Entries in another currency are ignored. The argument is the object
|
|
58
|
-
* passed to `publish`. The extension unwraps its forwarded argument list
|
|
59
|
-
* before calling this.
|
|
60
|
-
*
|
|
61
|
-
* @param payload - Published `{ updates }` object.
|
|
62
|
-
*/
|
|
63
|
-
ingestPrices(payload: unknown): void;
|
|
64
|
-
/**
|
|
65
|
-
* A chain reported down leaves the map so the polled price shows until the
|
|
66
|
-
* next tick for that chain.
|
|
67
|
-
*
|
|
68
|
-
* @param payload - Published `MarketStatsService:chainStatusChanged` object.
|
|
69
|
-
*/
|
|
70
|
-
ingestChainStatus(payload: unknown): void;
|
|
71
|
-
}
|
|
72
|
-
//# sourceMappingURL=MarketStatsStore.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarketStatsStore.d.ts","sourceRoot":"","sources":["../../src/store/MarketStatsStore.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,MAAM,MAAM,SAAS,GAAG;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,WAAW,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAE1D;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAK3D;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,MAAM,GAAG,SAAS,GAC1B,SAAS,GAAG,SAAS,CAKvB;AAqBD;;GAEG;AACH,qBAAa,gBAAgB;;IAO3B;;;;OAIG;IACH,QAAQ,CAAC,WAAW,QAAO,YAAY,CAAiB;IAExD;;;OAGG;IACH,QAAQ,CAAC,SAAS,aAAc,MAAM,IAAI,KAAG,CAAC,MAAM,IAAI,CAAC,CAKvD;IAEF;;;;;;;OAOG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAUlC;IAED;;;;;;;OAOG;IACH,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CA6CnC;IAED;;;;;OAKG;IACH,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAgCxC;CAQF"}
|
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Quote cache for `MarketStatsService:pricesUpdated`.
|
|
3
|
-
*
|
|
4
|
-
* The UI holds one instance. A tick updates this object and does not write
|
|
5
|
-
* `AssetsController` state, so it does not persist and does not notify the
|
|
6
|
-
* controller. Polled prices stay in `assetsPrice` and show when this map has
|
|
7
|
-
* no quote.
|
|
8
|
-
*/
|
|
9
|
-
import { isCaipAssetType, parseCaipAssetType } from '@metamask/utils';
|
|
10
|
-
import { safeNormalizeAssetId } from '../utils/index.js';
|
|
11
|
-
/**
|
|
12
|
-
* Key a market-stats asset id the same way on the tick and on the lookup.
|
|
13
|
-
* EVM ERC-20 addresses are checksummed. Anything else is kept as given.
|
|
14
|
-
*
|
|
15
|
-
* @param assetId - CAIP-19 asset id, or any other string the caller uses as a key.
|
|
16
|
-
* @returns The map key.
|
|
17
|
-
*/
|
|
18
|
-
export function marketStatsAssetKey(assetId) {
|
|
19
|
-
if (!isCaipAssetType(assetId)) {
|
|
20
|
-
return assetId;
|
|
21
|
-
}
|
|
22
|
-
return safeNormalizeAssetId(assetId);
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Quote for one asset. The id is keyed with {@link marketStatsAssetKey}.
|
|
26
|
-
*
|
|
27
|
-
* @param quotes - Current quote map.
|
|
28
|
-
* @param assetId - CAIP-19 asset id.
|
|
29
|
-
* @returns The streamed quote, or undefined.
|
|
30
|
-
*/
|
|
31
|
-
export function readLiveQuote(quotes, assetId) {
|
|
32
|
-
if (!assetId) {
|
|
33
|
-
return undefined;
|
|
34
|
-
}
|
|
35
|
-
return quotes.get(marketStatsAssetKey(assetId));
|
|
36
|
-
}
|
|
37
|
-
function readFiniteNumber(value) {
|
|
38
|
-
if (typeof value === 'number') {
|
|
39
|
-
return Number.isFinite(value) ? value : undefined;
|
|
40
|
-
}
|
|
41
|
-
if (typeof value !== 'string' || value.trim() === '') {
|
|
42
|
-
return undefined;
|
|
43
|
-
}
|
|
44
|
-
const numeric = Number(value);
|
|
45
|
-
return Number.isFinite(numeric) ? numeric : undefined;
|
|
46
|
-
}
|
|
47
|
-
function isUnknownArray(value) {
|
|
48
|
-
return Array.isArray(value);
|
|
49
|
-
}
|
|
50
|
-
function isRecord(value) {
|
|
51
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Latest market-stats quotes for one currency.
|
|
55
|
-
*/
|
|
56
|
-
export class MarketStatsStore {
|
|
57
|
-
#currency = 'usd';
|
|
58
|
-
#quotes = new Map();
|
|
59
|
-
#listeners = new Set();
|
|
60
|
-
/**
|
|
61
|
-
* Stable reference so `useSyncExternalStore` can take it directly.
|
|
62
|
-
*
|
|
63
|
-
* @returns The current quote map. The same reference until a tick changes it.
|
|
64
|
-
*/
|
|
65
|
-
getSnapshot = () => this.#quotes;
|
|
66
|
-
/**
|
|
67
|
-
* @param listener - Called after the quote map changes.
|
|
68
|
-
* @returns Unsubscribe.
|
|
69
|
-
*/
|
|
70
|
-
subscribe = (listener) => {
|
|
71
|
-
this.#listeners.add(listener);
|
|
72
|
-
return () => {
|
|
73
|
-
this.#listeners.delete(listener);
|
|
74
|
-
};
|
|
75
|
-
};
|
|
76
|
-
/**
|
|
77
|
-
* Remember the selected currency and drop quotes from the previous one.
|
|
78
|
-
* Does not notify. Callers invoke this during render, and the currency
|
|
79
|
-
* selector is what re-renders every reader. That render already reads the
|
|
80
|
-
* empty map.
|
|
81
|
-
*
|
|
82
|
-
* @param currency - Selected currency. Case is ignored.
|
|
83
|
-
*/
|
|
84
|
-
setCurrency(currency) {
|
|
85
|
-
const next = currency.toLowerCase();
|
|
86
|
-
if (this.#currency === next) {
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
this.#currency = next;
|
|
90
|
-
if (this.#quotes.size === 0) {
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
this.#quotes = new Map();
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Merge one `MarketStatsService:pricesUpdated` payload.
|
|
97
|
-
* Entries in another currency are ignored. The argument is the object
|
|
98
|
-
* passed to `publish`. The extension unwraps its forwarded argument list
|
|
99
|
-
* before calling this.
|
|
100
|
-
*
|
|
101
|
-
* @param payload - Published `{ updates }` object.
|
|
102
|
-
*/
|
|
103
|
-
ingestPrices(payload) {
|
|
104
|
-
if (!isRecord(payload) || !isUnknownArray(payload.updates)) {
|
|
105
|
-
return;
|
|
106
|
-
}
|
|
107
|
-
let changed = false;
|
|
108
|
-
const updated = new Map(this.#quotes);
|
|
109
|
-
for (const entry of payload.updates) {
|
|
110
|
-
if (!isRecord(entry)) {
|
|
111
|
-
continue;
|
|
112
|
-
}
|
|
113
|
-
const { assetId, currency } = entry;
|
|
114
|
-
if (typeof assetId !== 'string' ||
|
|
115
|
-
assetId.length === 0 ||
|
|
116
|
-
typeof currency !== 'string' ||
|
|
117
|
-
currency.toLowerCase() !== this.#currency) {
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
const price = readFiniteNumber(entry.price);
|
|
121
|
-
if (price === undefined) {
|
|
122
|
-
continue;
|
|
123
|
-
}
|
|
124
|
-
const pricePercentChange1d = readFiniteNumber(entry.pricePercentChange1d);
|
|
125
|
-
const key = marketStatsAssetKey(assetId);
|
|
126
|
-
const previous = updated.get(key);
|
|
127
|
-
if (previous?.price === price &&
|
|
128
|
-
previous.pricePercentChange1d === pricePercentChange1d) {
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
updated.set(key, pricePercentChange1d === undefined
|
|
132
|
-
? { price }
|
|
133
|
-
: { price, pricePercentChange1d });
|
|
134
|
-
changed = true;
|
|
135
|
-
}
|
|
136
|
-
if (!changed) {
|
|
137
|
-
return;
|
|
138
|
-
}
|
|
139
|
-
this.#replace(updated);
|
|
140
|
-
}
|
|
141
|
-
/**
|
|
142
|
-
* A chain reported down leaves the map so the polled price shows until the
|
|
143
|
-
* next tick for that chain.
|
|
144
|
-
*
|
|
145
|
-
* @param payload - Published `MarketStatsService:chainStatusChanged` object.
|
|
146
|
-
*/
|
|
147
|
-
ingestChainStatus(payload) {
|
|
148
|
-
if (!isRecord(payload)) {
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
151
|
-
const { chainIds } = payload;
|
|
152
|
-
if (payload.status !== 'down' || !isUnknownArray(chainIds)) {
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
if (this.#quotes.size === 0) {
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
const down = new Set(chainIds.filter((chainId) => typeof chainId === 'string'));
|
|
159
|
-
let changed = false;
|
|
160
|
-
const updated = new Map(this.#quotes);
|
|
161
|
-
for (const key of updated.keys()) {
|
|
162
|
-
if (!isCaipAssetType(key)) {
|
|
163
|
-
continue;
|
|
164
|
-
}
|
|
165
|
-
if (down.has(parseCaipAssetType(key).chainId)) {
|
|
166
|
-
updated.delete(key);
|
|
167
|
-
changed = true;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
if (!changed) {
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
this.#replace(updated);
|
|
174
|
-
}
|
|
175
|
-
#replace(quotes) {
|
|
176
|
-
this.#quotes = quotes;
|
|
177
|
-
for (const listener of this.#listeners) {
|
|
178
|
-
listener();
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
//# sourceMappingURL=MarketStatsStore.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarketStatsStore.js","sourceRoot":"","sources":["../../src/store/MarketStatsStore.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAEtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AASzD;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAe;IACjD,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9B,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,oBAAoB,CAAC,OAAO,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAC3B,MAAoB,EACpB,OAA2B;IAE3B,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,MAAM,CAAC,GAAG,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACpD,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,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C,GAAG,CAAC,CAAC;gBACpB,OAAO,GAAG,IAAI,CAAC;YACjB,CAAC;QACH,CAAC;QACD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO;QACT,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzB,CAAC;IAED,QAAQ,CAAC,MAA8B;QACrC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACvC,QAAQ,EAAE,CAAC;QACb,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Quote cache for `MarketStatsService:pricesUpdated`.\n *\n * The UI holds one instance. A tick updates this object and does not write\n * `AssetsController` state, so it does not persist and does not notify the\n * controller. Polled prices stay in `assetsPrice` and show when this map has\n * no quote.\n */\n\nimport { isCaipAssetType, parseCaipAssetType } from '@metamask/utils';\n\nimport { safeNormalizeAssetId } from '../utils/index.js';\n\nexport type LiveQuote = {\n price: number;\n pricePercentChange1d?: number;\n};\n\nexport type LivePriceMap = ReadonlyMap<string, LiveQuote>;\n\n/**\n * Key a market-stats asset id the same way on the tick and on the lookup.\n * EVM ERC-20 addresses are checksummed. Anything else is kept as given.\n *\n * @param assetId - CAIP-19 asset id, or any other string the caller uses as a key.\n * @returns The map key.\n */\nexport function marketStatsAssetKey(assetId: string): string {\n if (!isCaipAssetType(assetId)) {\n return assetId;\n }\n return safeNormalizeAssetId(assetId);\n}\n\n/**\n * Quote for one asset. The id is keyed with {@link marketStatsAssetKey}.\n *\n * @param quotes - Current quote map.\n * @param assetId - CAIP-19 asset id.\n * @returns The streamed quote, or undefined.\n */\nexport function readLiveQuote(\n quotes: LivePriceMap,\n assetId: string | undefined,\n): LiveQuote | undefined {\n if (!assetId) {\n return undefined;\n }\n return quotes.get(marketStatsAssetKey(assetId));\n}\n\nfunction readFiniteNumber(value: unknown): number | undefined {\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : undefined;\n }\n if (typeof value !== 'string' || value.trim() === '') {\n return undefined;\n }\n const numeric = Number(value);\n return Number.isFinite(numeric) ? numeric : undefined;\n}\n\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Latest market-stats quotes for one currency.\n */\nexport class MarketStatsStore {\n #currency = 'usd';\n\n #quotes: LivePriceMap = new Map<string, LiveQuote>();\n\n readonly #listeners = new Set<() => void>();\n\n /**\n * Stable reference so `useSyncExternalStore` can take it directly.\n *\n * @returns The current quote map. The same reference until a tick changes it.\n */\n readonly getSnapshot = (): LivePriceMap => this.#quotes;\n\n /**\n * @param listener - Called after the quote map changes.\n * @returns Unsubscribe.\n */\n readonly subscribe = (listener: () => void): (() => void) => {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n };\n\n /**\n * Remember the selected currency and drop quotes from the previous one.\n * Does not notify. Callers invoke this during render, and the currency\n * selector is what re-renders every reader. That render already reads the\n * empty map.\n *\n * @param currency - Selected currency. Case is ignored.\n */\n setCurrency(currency: string): void {\n const next = currency.toLowerCase();\n if (this.#currency === next) {\n return;\n }\n this.#currency = next;\n if (this.#quotes.size === 0) {\n return;\n }\n this.#quotes = new Map();\n }\n\n /**\n * Merge one `MarketStatsService:pricesUpdated` payload.\n * Entries in another currency are ignored. The argument is the object\n * passed to `publish`. The extension unwraps its forwarded argument list\n * before calling this.\n *\n * @param payload - Published `{ updates }` object.\n */\n ingestPrices(payload: unknown): void {\n if (!isRecord(payload) || !isUnknownArray(payload.updates)) {\n return;\n }\n\n let changed = false;\n const updated = new Map(this.#quotes);\n for (const entry of payload.updates) {\n if (!isRecord(entry)) {\n continue;\n }\n const { assetId, currency } = entry;\n if (\n typeof assetId !== 'string' ||\n assetId.length === 0 ||\n typeof currency !== 'string' ||\n currency.toLowerCase() !== this.#currency\n ) {\n continue;\n }\n const price = readFiniteNumber(entry.price);\n if (price === undefined) {\n continue;\n }\n const pricePercentChange1d = readFiniteNumber(entry.pricePercentChange1d);\n const key = marketStatsAssetKey(assetId);\n const previous = updated.get(key);\n if (\n previous?.price === price &&\n previous.pricePercentChange1d === pricePercentChange1d\n ) {\n continue;\n }\n updated.set(\n key,\n pricePercentChange1d === undefined\n ? { price }\n : { price, pricePercentChange1d },\n );\n changed = true;\n }\n if (!changed) {\n return;\n }\n this.#replace(updated);\n }\n\n /**\n * A chain reported down leaves the map so the polled price shows until the\n * next tick for that chain.\n *\n * @param payload - Published `MarketStatsService:chainStatusChanged` object.\n */\n ingestChainStatus(payload: unknown): void {\n if (!isRecord(payload)) {\n return;\n }\n const { chainIds } = payload;\n if (payload.status !== 'down' || !isUnknownArray(chainIds)) {\n return;\n }\n if (this.#quotes.size === 0) {\n return;\n }\n\n const down = new Set(\n chainIds.filter(\n (chainId): chainId is string => typeof chainId === 'string',\n ),\n );\n let changed = false;\n const updated = new Map(this.#quotes);\n for (const key of updated.keys()) {\n if (!isCaipAssetType(key)) {\n continue;\n }\n if (down.has(parseCaipAssetType(key).chainId)) {\n updated.delete(key);\n changed = true;\n }\n }\n if (!changed) {\n return;\n }\n this.#replace(updated);\n }\n\n #replace(quotes: Map<string, LiveQuote>): void {\n this.#quotes = quotes;\n for (const listener of this.#listeners) {\n listener();\n }\n }\n}\n"]}
|