@metamask-previews/assets-controller 20.4.1-preview-e80304db4 → 20.4.1-preview-1d88b8ba5
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 -11
- 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 +18 -11
- 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 +2 -32
- package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
- package/dist/data-sources/PriceDataSource.js +37 -164
- 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 +2 -2
- package/dist/data-sources/MarketStatsPriceStream.d.ts +0 -108
- package/dist/data-sources/MarketStatsPriceStream.d.ts.map +0 -1
- package/dist/data-sources/MarketStatsPriceStream.js +0 -297
- 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,108 +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. Reconcile
|
|
6
|
-
* reads `getSubscriptions`. A subscribe that does not open is retried on the
|
|
7
|
-
* next reconcile, and those assets stay on the poll. Chain health is read
|
|
8
|
-
* from `getChainStatuses`. A chain reported down is polled after a short
|
|
9
|
-
* jitter until it recovers. When MarketStatsService is not wired, every
|
|
10
|
-
* asset is polled.
|
|
11
|
-
*/
|
|
12
|
-
import type { MarketStatsServiceActions, MarketStatsServiceChainStatusChangedEvent, SupportedCurrency } from '@metamask/core-backend';
|
|
13
|
-
import type { Messenger } from '@metamask/messenger';
|
|
14
|
-
import type { Caip19AssetId } from '../types.js';
|
|
15
|
-
export type MarketStatsPriceStreamMessenger = Messenger<string, MarketStatsServiceActions, MarketStatsServiceChainStatusChangedEvent>;
|
|
16
|
-
export type StreamCandidate = {
|
|
17
|
-
assetId: Caip19AssetId;
|
|
18
|
-
wssSupport: boolean;
|
|
19
|
-
};
|
|
20
|
-
export type MarketStatsPriceStreamOptions = {
|
|
21
|
-
messenger: MarketStatsPriceStreamMessenger;
|
|
22
|
-
getSelectedCurrency: () => SupportedCurrency;
|
|
23
|
-
getPollIntervalMs: () => number;
|
|
24
|
-
requestPoll: (delayMs: number, details: {
|
|
25
|
-
chainIds: string[];
|
|
26
|
-
status: 'up' | 'down';
|
|
27
|
-
}) => void;
|
|
28
|
-
/** Defaults to Math.random. Tests inject a fixed value. */
|
|
29
|
-
random?: () => number;
|
|
30
|
-
};
|
|
31
|
-
/**
|
|
32
|
-
* Read `wssSupport` off a spot-price entry.
|
|
33
|
-
*
|
|
34
|
-
* @param data - One asset's `/v3/spot-prices` entry.
|
|
35
|
-
* @returns Whether the asset can stream.
|
|
36
|
-
*/
|
|
37
|
-
export declare function readSpotPriceStreamEligibility(data: object): boolean;
|
|
38
|
-
/**
|
|
39
|
-
* Assets the Price API marks as streamable.
|
|
40
|
-
*
|
|
41
|
-
* @param candidates - Assets learned from the latest spot-price response.
|
|
42
|
-
* @returns Asset ids to subscribe.
|
|
43
|
-
*/
|
|
44
|
-
export declare function selectAssetsToStream(candidates: StreamCandidate[]): Caip19AssetId[];
|
|
45
|
-
/**
|
|
46
|
-
* CAIP-2 chain id from a CAIP-19 asset id, or undefined when the id is invalid.
|
|
47
|
-
*
|
|
48
|
-
* @param assetId - CAIP-19 asset identifier.
|
|
49
|
-
* @returns The chain id.
|
|
50
|
-
*/
|
|
51
|
-
export declare function chainIdFromAssetId(assetId: string): string | undefined;
|
|
52
|
-
/**
|
|
53
|
-
* True when the messenger has no MarketStatsService handler.
|
|
54
|
-
* Price updates then stay on the poll.
|
|
55
|
-
*
|
|
56
|
-
* @param error - Failure from `messenger.call`.
|
|
57
|
-
* @returns Whether streaming cannot be used in this process.
|
|
58
|
-
*/
|
|
59
|
-
export declare function isMarketStatsUnavailable(error: unknown): boolean;
|
|
60
|
-
export declare function fallbackJitterMs(pollIntervalMs: number, random: () => number): number;
|
|
61
|
-
/**
|
|
62
|
-
* Opens market-stats channels for the price-fetch set.
|
|
63
|
-
*/
|
|
64
|
-
export declare class MarketStatsPriceStream {
|
|
65
|
-
#private;
|
|
66
|
-
constructor(options: MarketStatsPriceStreamOptions);
|
|
67
|
-
/**
|
|
68
|
-
* Asset ids with an open market-stats channel for the selected currency.
|
|
69
|
-
*
|
|
70
|
-
* @returns Ids the service currently has open. Empty when streaming is off.
|
|
71
|
-
*/
|
|
72
|
-
subscribedAssetIds(): Promise<ReadonlySet<string>>;
|
|
73
|
-
/**
|
|
74
|
-
* Chain ids `getChainStatuses` currently reports as down.
|
|
75
|
-
* Empty when MarketStatsService is not registered.
|
|
76
|
-
*
|
|
77
|
-
* @returns Down chain ids.
|
|
78
|
-
*/
|
|
79
|
-
downChainIds(): Promise<ReadonlySet<string>>;
|
|
80
|
-
/**
|
|
81
|
-
* Whether this asset should be priced from `/v3/spot-prices` on the poll.
|
|
82
|
-
* Down chains are skipped until their jitter window ends, then polled.
|
|
83
|
-
*
|
|
84
|
-
* @param assetId - CAIP-19 asset id.
|
|
85
|
-
* @param now - Current time in ms.
|
|
86
|
-
* @param subscribed - Asset ids `getSubscriptions` currently has open.
|
|
87
|
-
* @param downChains - Chain ids `getChainStatuses` reports as down.
|
|
88
|
-
* @returns True when the poll should fetch this asset.
|
|
89
|
-
*/
|
|
90
|
-
shouldPoll(assetId: Caip19AssetId, now: number, subscribed: ReadonlySet<string>, downChains: ReadonlySet<string>): boolean;
|
|
91
|
-
/**
|
|
92
|
-
* Subscribe price-fetch assets marked `wssSupport`.
|
|
93
|
-
* Drop channels for assets that left that set.
|
|
94
|
-
*
|
|
95
|
-
* @param candidates - Price-fetch assets in the current subscription scope.
|
|
96
|
-
*/
|
|
97
|
-
reconcile(candidates: StreamCandidate[]): Promise<void>;
|
|
98
|
-
/**
|
|
99
|
-
* Drop one reference on each open channel for a price-fetch asset.
|
|
100
|
-
* Used when the selected currency changes, and when the price subscription ends.
|
|
101
|
-
*/
|
|
102
|
-
releaseSubscriptions(): Promise<void>;
|
|
103
|
-
/**
|
|
104
|
-
* Remove listeners and drop channels this stream opened.
|
|
105
|
-
*/
|
|
106
|
-
destroy(): void;
|
|
107
|
-
}
|
|
108
|
-
//# sourceMappingURL=MarketStatsPriceStream.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarketStatsPriceStream.d.ts","sourceRoot":"","sources":["../../src/data-sources/MarketStatsPriceStream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EACV,yBAAyB,EACzB,yCAAyC,EACzC,iBAAiB,EAClB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAIrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAQjD,MAAM,MAAM,+BAA+B,GAAG,SAAS,C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OASG;IACH,UAAU,CACR,OAAO,EAAE,aAAa,EACtB,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,WAAW,CAAC,MAAM,CAAC,EAC/B,UAAU,EAAE,WAAW,CAAC,MAAM,CAAC,GAC9B,OAAO,CAST;IAED;;;;;OAKG;IACG,SAAS,CAAC,UAAU,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA0C5D;IAED;;;OAGG;IACG,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CAI1C;IAED;;OAEG;IACH,OAAO,IAAI,IAAI,CAQd;CAkGF"}
|
|
@@ -1,297 +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. Reconcile
|
|
6
|
-
* reads `getSubscriptions`. A subscribe that does not open is retried on the
|
|
7
|
-
* next reconcile, and those assets stay on the poll. Chain health is read
|
|
8
|
-
* from `getChainStatuses`. A chain reported down is polled after a short
|
|
9
|
-
* jitter until it recovers. When MarketStatsService is not wired, every
|
|
10
|
-
* asset is polled.
|
|
11
|
-
*/
|
|
12
|
-
import { parseCaipAssetType } from '@metamask/utils';
|
|
13
|
-
import { createModuleLogger, projectLogger } from '../logger.js';
|
|
14
|
-
import { normalizeAssetId } from '../utils/index.js';
|
|
15
|
-
const log = createModuleLogger(projectLogger, 'MarketStatsPriceStream');
|
|
16
|
-
/** Cap on the random delay before a chain-down poll, to avoid a thundering herd. */
|
|
17
|
-
const MAX_FALLBACK_JITTER_MS = 5_000;
|
|
18
|
-
/**
|
|
19
|
-
* Read `wssSupport` off a spot-price entry.
|
|
20
|
-
*
|
|
21
|
-
* @param data - One asset's `/v3/spot-prices` entry.
|
|
22
|
-
* @returns Whether the asset can stream.
|
|
23
|
-
*/
|
|
24
|
-
export function readSpotPriceStreamEligibility(data) {
|
|
25
|
-
return data.wssSupport === true;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Assets the Price API marks as streamable.
|
|
29
|
-
*
|
|
30
|
-
* @param candidates - Assets learned from the latest spot-price response.
|
|
31
|
-
* @returns Asset ids to subscribe.
|
|
32
|
-
*/
|
|
33
|
-
export function selectAssetsToStream(candidates) {
|
|
34
|
-
return candidates
|
|
35
|
-
.filter((candidate) => candidate.wssSupport)
|
|
36
|
-
.map((candidate) => candidate.assetId);
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* CAIP-2 chain id from a CAIP-19 asset id, or undefined when the id is invalid.
|
|
40
|
-
*
|
|
41
|
-
* @param assetId - CAIP-19 asset identifier.
|
|
42
|
-
* @returns The chain id.
|
|
43
|
-
*/
|
|
44
|
-
export function chainIdFromAssetId(assetId) {
|
|
45
|
-
try {
|
|
46
|
-
return parseCaipAssetType(assetId).chainId;
|
|
47
|
-
}
|
|
48
|
-
catch {
|
|
49
|
-
return undefined;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* True when the messenger has no MarketStatsService handler.
|
|
54
|
-
* Price updates then stay on the poll.
|
|
55
|
-
*
|
|
56
|
-
* @param error - Failure from `messenger.call`.
|
|
57
|
-
* @returns Whether streaming cannot be used in this process.
|
|
58
|
-
*/
|
|
59
|
-
export function isMarketStatsUnavailable(error) {
|
|
60
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
61
|
-
return (message.includes('has not been registered') ||
|
|
62
|
-
message.includes('has not been delegated'));
|
|
63
|
-
}
|
|
64
|
-
export function fallbackJitterMs(pollIntervalMs, random) {
|
|
65
|
-
const cap = Math.min(Math.max(pollIntervalMs, 0), MAX_FALLBACK_JITTER_MS);
|
|
66
|
-
if (cap === 0) {
|
|
67
|
-
return 0;
|
|
68
|
-
}
|
|
69
|
-
return Math.floor(random() * cap);
|
|
70
|
-
}
|
|
71
|
-
function canonicalAssetId(assetId) {
|
|
72
|
-
try {
|
|
73
|
-
return normalizeAssetId(assetId);
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
return assetId;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Opens market-stats channels for the price-fetch set.
|
|
81
|
-
*/
|
|
82
|
-
export class MarketStatsPriceStream {
|
|
83
|
-
#messenger;
|
|
84
|
-
#getSelectedCurrency;
|
|
85
|
-
#getPollIntervalMs;
|
|
86
|
-
#requestPoll;
|
|
87
|
-
#random;
|
|
88
|
-
#onChainStatus;
|
|
89
|
-
/**
|
|
90
|
-
* Asset ids from the last reconcile. An id that leaves this set is
|
|
91
|
-
* unsubscribed. Channels opened outside the price-fetch set are left open.
|
|
92
|
-
*/
|
|
93
|
-
#pricedAssetIds = new Set();
|
|
94
|
-
#pollNotBefore = new Map();
|
|
95
|
-
#lock = Promise.resolve();
|
|
96
|
-
constructor(options) {
|
|
97
|
-
this.#messenger = options.messenger;
|
|
98
|
-
this.#getSelectedCurrency = options.getSelectedCurrency;
|
|
99
|
-
this.#getPollIntervalMs = options.getPollIntervalMs;
|
|
100
|
-
this.#requestPoll = options.requestPoll;
|
|
101
|
-
this.#random = options.random ?? Math.random;
|
|
102
|
-
this.#onChainStatus = (payload) => {
|
|
103
|
-
this.#handleChainStatus(payload);
|
|
104
|
-
};
|
|
105
|
-
this.#messenger.subscribe('MarketStatsService:chainStatusChanged', this.#onChainStatus);
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Asset ids with an open market-stats channel for the selected currency.
|
|
109
|
-
*
|
|
110
|
-
* @returns Ids the service currently has open. Empty when streaming is off.
|
|
111
|
-
*/
|
|
112
|
-
async subscribedAssetIds() {
|
|
113
|
-
const currency = this.#getSelectedCurrency().toLowerCase();
|
|
114
|
-
const subscriptions = await this.#readSubscriptions();
|
|
115
|
-
if (!subscriptions) {
|
|
116
|
-
return new Set();
|
|
117
|
-
}
|
|
118
|
-
return new Set(subscriptions
|
|
119
|
-
.filter((subscription) => subscription.currency.toLowerCase() === currency)
|
|
120
|
-
.map((subscription) => canonicalAssetId(subscription.assetId)));
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* Chain ids `getChainStatuses` currently reports as down.
|
|
124
|
-
* Empty when MarketStatsService is not registered.
|
|
125
|
-
*
|
|
126
|
-
* @returns Down chain ids.
|
|
127
|
-
*/
|
|
128
|
-
async downChainIds() {
|
|
129
|
-
const statuses = await this.#readChainStatuses();
|
|
130
|
-
if (!statuses) {
|
|
131
|
-
return new Set();
|
|
132
|
-
}
|
|
133
|
-
return new Set(statuses
|
|
134
|
-
.filter((entry) => entry.status === 'down')
|
|
135
|
-
.map((entry) => entry.chainId));
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Whether this asset should be priced from `/v3/spot-prices` on the poll.
|
|
139
|
-
* Down chains are skipped until their jitter window ends, then polled.
|
|
140
|
-
*
|
|
141
|
-
* @param assetId - CAIP-19 asset id.
|
|
142
|
-
* @param now - Current time in ms.
|
|
143
|
-
* @param subscribed - Asset ids `getSubscriptions` currently has open.
|
|
144
|
-
* @param downChains - Chain ids `getChainStatuses` reports as down.
|
|
145
|
-
* @returns True when the poll should fetch this asset.
|
|
146
|
-
*/
|
|
147
|
-
shouldPoll(assetId, now, subscribed, downChains) {
|
|
148
|
-
const chainId = chainIdFromAssetId(assetId);
|
|
149
|
-
if (chainId && (this.#pollNotBefore.get(chainId) ?? 0) > now) {
|
|
150
|
-
return false;
|
|
151
|
-
}
|
|
152
|
-
if (chainId && downChains.has(chainId)) {
|
|
153
|
-
return true;
|
|
154
|
-
}
|
|
155
|
-
return !subscribed.has(canonicalAssetId(assetId));
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* Subscribe price-fetch assets marked `wssSupport`.
|
|
159
|
-
* Drop channels for assets that left that set.
|
|
160
|
-
*
|
|
161
|
-
* @param candidates - Price-fetch assets in the current subscription scope.
|
|
162
|
-
*/
|
|
163
|
-
async reconcile(candidates) {
|
|
164
|
-
await this.#withLock(async () => {
|
|
165
|
-
const selectedCurrency = this.#getSelectedCurrency();
|
|
166
|
-
const priced = new Set(candidates.map((candidate) => canonicalAssetId(candidate.assetId)));
|
|
167
|
-
const subscribing = selectAssetsToStream(candidates).map((assetId) => ({
|
|
168
|
-
assetId: canonicalAssetId(assetId),
|
|
169
|
-
currency: selectedCurrency,
|
|
170
|
-
}));
|
|
171
|
-
const current = await this.#readSubscriptions();
|
|
172
|
-
if (!current) {
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
const previous = this.#pricedAssetIds;
|
|
176
|
-
this.#pricedAssetIds = priced;
|
|
177
|
-
await this.#unsubscribe(current.filter((subscription) => {
|
|
178
|
-
const assetId = canonicalAssetId(subscription.assetId);
|
|
179
|
-
return previous.has(assetId) && !priced.has(assetId);
|
|
180
|
-
}));
|
|
181
|
-
if (subscribing.length > 0) {
|
|
182
|
-
try {
|
|
183
|
-
await this.#messenger.call('MarketStatsService:subscribe', subscribing);
|
|
184
|
-
}
|
|
185
|
-
catch (error) {
|
|
186
|
-
if (isMarketStatsUnavailable(error)) {
|
|
187
|
-
log('Market stats stream is not available; polling prices');
|
|
188
|
-
}
|
|
189
|
-
else {
|
|
190
|
-
log('Market stats subscribe failed; polling assets the service did not open', { error });
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
});
|
|
195
|
-
}
|
|
196
|
-
/**
|
|
197
|
-
* Drop one reference on each open channel for a price-fetch asset.
|
|
198
|
-
* Used when the selected currency changes, and when the price subscription ends.
|
|
199
|
-
*/
|
|
200
|
-
async releaseSubscriptions() {
|
|
201
|
-
await this.#withLock(async () => {
|
|
202
|
-
await this.#releaseOpened();
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Remove listeners and drop channels this stream opened.
|
|
207
|
-
*/
|
|
208
|
-
destroy() {
|
|
209
|
-
this.#messenger.unsubscribe('MarketStatsService:chainStatusChanged', this.#onChainStatus);
|
|
210
|
-
this.#releaseOpened().catch(() => {
|
|
211
|
-
// destroy is sync; a failed unsubscribe is already logged
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
async #releaseOpened() {
|
|
215
|
-
if (this.#pricedAssetIds.size === 0) {
|
|
216
|
-
return;
|
|
217
|
-
}
|
|
218
|
-
const current = await this.#readSubscriptions();
|
|
219
|
-
if (!current) {
|
|
220
|
-
return;
|
|
221
|
-
}
|
|
222
|
-
await this.#unsubscribe(current.filter((subscription) => this.#pricedAssetIds.has(canonicalAssetId(subscription.assetId))));
|
|
223
|
-
}
|
|
224
|
-
async #readChainStatuses() {
|
|
225
|
-
try {
|
|
226
|
-
return this.#messenger.call('MarketStatsService:getChainStatuses');
|
|
227
|
-
}
|
|
228
|
-
catch (error) {
|
|
229
|
-
if (isMarketStatsUnavailable(error)) {
|
|
230
|
-
return null;
|
|
231
|
-
}
|
|
232
|
-
throw error;
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
async #readSubscriptions() {
|
|
236
|
-
try {
|
|
237
|
-
return this.#messenger.call('MarketStatsService:getSubscriptions');
|
|
238
|
-
}
|
|
239
|
-
catch (error) {
|
|
240
|
-
if (isMarketStatsUnavailable(error)) {
|
|
241
|
-
log('Market stats stream is not available; polling prices');
|
|
242
|
-
return null;
|
|
243
|
-
}
|
|
244
|
-
throw error;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
async #unsubscribe(open) {
|
|
248
|
-
if (open.length === 0) {
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
try {
|
|
252
|
-
await this.#messenger.call('MarketStatsService:unsubscribe', open.map(({ assetId, currency }) => ({
|
|
253
|
-
assetId: canonicalAssetId(assetId),
|
|
254
|
-
currency,
|
|
255
|
-
})));
|
|
256
|
-
}
|
|
257
|
-
catch (error) {
|
|
258
|
-
log('Market stats unsubscribe failed', {
|
|
259
|
-
assetIds: open.map((info) => info.assetId),
|
|
260
|
-
error,
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
#handleChainStatus(payload) {
|
|
265
|
-
if (payload.status === 'down') {
|
|
266
|
-
const jitter = fallbackJitterMs(this.#getPollIntervalMs(), this.#random);
|
|
267
|
-
const notBefore = Date.now() + jitter;
|
|
268
|
-
for (const chainId of payload.chainIds) {
|
|
269
|
-
this.#pollNotBefore.set(chainId, notBefore);
|
|
270
|
-
}
|
|
271
|
-
this.#requestPoll(jitter, {
|
|
272
|
-
chainIds: payload.chainIds,
|
|
273
|
-
status: 'down',
|
|
274
|
-
});
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
for (const chainId of payload.chainIds) {
|
|
278
|
-
this.#pollNotBefore.delete(chainId);
|
|
279
|
-
}
|
|
280
|
-
this.#requestPoll(0, { chainIds: payload.chainIds, status: 'up' });
|
|
281
|
-
}
|
|
282
|
-
async #withLock(fn) {
|
|
283
|
-
const previous = this.#lock;
|
|
284
|
-
let release = () => undefined;
|
|
285
|
-
this.#lock = new Promise((resolve) => {
|
|
286
|
-
release = resolve;
|
|
287
|
-
});
|
|
288
|
-
await previous;
|
|
289
|
-
try {
|
|
290
|
-
await fn();
|
|
291
|
-
}
|
|
292
|
-
finally {
|
|
293
|
-
release();
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
//# sourceMappingURL=MarketStatsPriceStream.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarketStatsPriceStream.js","sourceRoot":"","sources":["../../src/data-sources/MarketStatsPriceStream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAQH,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAEjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,MAAM,GAAG,GAAG,kBAAkB,CAAC,a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OAAO,CAAC,CAAC;YACzE,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC;YACtC,KAAK,MAAM,OAAO,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;gBACvC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;YAC9C,CAAC;YACD,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE;gBACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;gBAC1B,MAAM,EAAE,MAAM;aACf,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QAED,KAAK,MAAM,OAAO,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;YACvC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC;QACD,IAAI,CAAC,YAAY,CAAC,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,EAAuB;QACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC;QAC5B,IAAI,OAAO,GAAe,GAAG,EAAE,CAAC,SAAS,CAAC;QAC1C,IAAI,CAAC,KAAK,GAAG,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. Reconcile\n * reads `getSubscriptions`. A subscribe that does not open is retried on the\n * next reconcile, and those assets stay on the poll. Chain health is read\n * from `getChainStatuses`. A chain reported down is polled after a short\n * jitter until it recovers. When MarketStatsService is not wired, every\n * asset is polled.\n */\n\nimport type {\n MarketStatsServiceActions,\n MarketStatsServiceChainStatusChangedEvent,\n SupportedCurrency,\n} from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\nimport { parseCaipAssetType } from '@metamask/utils';\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\n/** Cap on the random delay before a chain-down poll, to avoid a thundering herd. */\nconst MAX_FALLBACK_JITTER_MS = 5_000;\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 getPollIntervalMs: () => number;\n requestPoll: (\n delayMs: number,\n details: { chainIds: string[]; status: 'up' | 'down' },\n ) => void;\n /** Defaults to Math.random. Tests inject a fixed value. */\n random?: () => number;\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 * CAIP-2 chain id from a CAIP-19 asset id, or undefined when the id is invalid.\n *\n * @param assetId - CAIP-19 asset identifier.\n * @returns The chain id.\n */\nexport function chainIdFromAssetId(assetId: string): string | undefined {\n try {\n return parseCaipAssetType(assetId as Caip19AssetId).chainId;\n } catch {\n return undefined;\n }\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\nexport function fallbackJitterMs(\n pollIntervalMs: number,\n random: () => number,\n): number {\n const cap = Math.min(Math.max(pollIntervalMs, 0), MAX_FALLBACK_JITTER_MS);\n if (cap === 0) {\n return 0;\n }\n return Math.floor(random() * cap);\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 readonly #getPollIntervalMs: () => number;\n\n readonly #requestPoll: MarketStatsPriceStreamOptions['requestPoll'];\n\n readonly #random: () => number;\n\n readonly #onChainStatus: (payload: {\n chainIds: string[];\n status: 'up' | 'down';\n timestamp?: number;\n }) => void;\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 readonly #pollNotBefore = new Map<string, number>();\n\n #lock: Promise<void> = Promise.resolve();\n\n constructor(options: MarketStatsPriceStreamOptions) {\n this.#messenger = options.messenger;\n this.#getSelectedCurrency = options.getSelectedCurrency;\n this.#getPollIntervalMs = options.getPollIntervalMs;\n this.#requestPoll = options.requestPoll;\n this.#random = options.random ?? Math.random;\n\n this.#onChainStatus = (payload): void => {\n this.#handleChainStatus(payload);\n };\n\n this.#messenger.subscribe(\n 'MarketStatsService:chainStatusChanged',\n this.#onChainStatus,\n );\n }\n\n /**\n * Asset ids with an open market-stats channel for the selected currency.\n *\n * @returns Ids the service currently has open. Empty when streaming is off.\n */\n async subscribedAssetIds(): Promise<ReadonlySet<string>> {\n const currency = this.#getSelectedCurrency().toLowerCase();\n const subscriptions = await this.#readSubscriptions();\n if (!subscriptions) {\n return new Set();\n }\n return new Set(\n subscriptions\n .filter(\n (subscription) => subscription.currency.toLowerCase() === currency,\n )\n .map((subscription) => canonicalAssetId(subscription.assetId)),\n );\n }\n\n /**\n * Chain ids `getChainStatuses` currently reports as down.\n * Empty when MarketStatsService is not registered.\n *\n * @returns Down chain ids.\n */\n async downChainIds(): Promise<ReadonlySet<string>> {\n const statuses = await this.#readChainStatuses();\n if (!statuses) {\n return new Set();\n }\n return new Set(\n statuses\n .filter((entry) => entry.status === 'down')\n .map((entry) => entry.chainId),\n );\n }\n\n /**\n * Whether this asset should be priced from `/v3/spot-prices` on the poll.\n * Down chains are skipped until their jitter window ends, then polled.\n *\n * @param assetId - CAIP-19 asset id.\n * @param now - Current time in ms.\n * @param subscribed - Asset ids `getSubscriptions` currently has open.\n * @param downChains - Chain ids `getChainStatuses` reports as down.\n * @returns True when the poll should fetch this asset.\n */\n shouldPoll(\n assetId: Caip19AssetId,\n now: number,\n subscribed: ReadonlySet<string>,\n downChains: ReadonlySet<string>,\n ): boolean {\n const chainId = chainIdFromAssetId(assetId);\n if (chainId && (this.#pollNotBefore.get(chainId) ?? 0) > now) {\n return false;\n }\n if (chainId && downChains.has(chainId)) {\n return true;\n }\n return !subscribed.has(canonicalAssetId(assetId));\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 if (subscribing.length > 0) {\n try {\n await this.#messenger.call(\n 'MarketStatsService:subscribe',\n subscribing,\n );\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.#messenger.unsubscribe(\n 'MarketStatsService:chainStatusChanged',\n this.#onChainStatus,\n );\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 #readChainStatuses(): Promise<\n { chainId: string; status: 'up' | 'down' }[] | null\n > {\n try {\n return this.#messenger.call('MarketStatsService:getChainStatuses');\n } catch (error) {\n if (isMarketStatsUnavailable(error)) {\n return null;\n }\n throw error;\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 #handleChainStatus(payload: {\n chainIds: string[];\n status: 'up' | 'down';\n }): void {\n if (payload.status === 'down') {\n const jitter = fallbackJitterMs(this.#getPollIntervalMs(), this.#random);\n const notBefore = Date.now() + jitter;\n for (const chainId of payload.chainIds) {\n this.#pollNotBefore.set(chainId, notBefore);\n }\n this.#requestPoll(jitter, {\n chainIds: payload.chainIds,\n status: 'down',\n });\n return;\n }\n\n for (const chainId of payload.chainIds) {\n this.#pollNotBefore.delete(chainId);\n }\n this.#requestPoll(0, { chainIds: payload.chainIds, status: 'up' });\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"}
|