@metamask-previews/assets-controller 20.4.1-preview-e9ac9ffe1 → 20.4.1-preview-70269bbdb
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 +14 -0
- package/README.md +3 -0
- package/dist/AssetsController-method-action-types.d.ts +6 -2
- package/dist/AssetsController-method-action-types.d.ts.map +1 -1
- package/dist/AssetsController-method-action-types.js.map +1 -1
- package/dist/AssetsController.d.ts +11 -13
- package/dist/AssetsController.d.ts.map +1 -1
- package/dist/AssetsController.js +27 -17
- package/dist/AssetsController.js.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.d.ts +4 -2
- package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.js +3 -1
- package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
- package/dist/data-sources/MarketStatsPriceStream.d.ts +67 -0
- package/dist/data-sources/MarketStatsPriceStream.d.ts.map +1 -0
- package/dist/data-sources/MarketStatsPriceStream.js +181 -0
- package/dist/data-sources/MarketStatsPriceStream.js.map +1 -0
- package/dist/data-sources/PriceDataSource.d.ts +29 -2
- package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
- package/dist/data-sources/PriceDataSource.js +113 -37
- 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 +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/store/MarketStatsStore.d.ts +72 -0
- package/dist/store/MarketStatsStore.d.ts.map +1 -0
- package/dist/store/MarketStatsStore.js +182 -0
- package/dist/store/MarketStatsStore.js.map +1 -0
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,182 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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,C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CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;YAC5B,OAAO;QACT,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,GAAG,CAClB,QAAQ,CAAC,MAAM,CACb,CAAC,OAAO,EAAqB,EAAE,CAAC,OAAO,OAAO,KAAK,QAAQ,CAC5D,CACF,CAAC;QACF,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;YACjC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC1B,SAAS;YACX,CAAC;YACD,IAAI,IAAI,CAAC,GAAG,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;gBAC9C,OAAO,CAAC,MAAM,CAAC,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"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -200,6 +200,11 @@ export type FungibleAssetPrice = BaseAssetPrice & {
|
|
|
200
200
|
pricePercentChange1y?: number;
|
|
201
201
|
/** Current price in USD */
|
|
202
202
|
usdPrice: number;
|
|
203
|
+
/**
|
|
204
|
+
* True when this asset can stream on `market-stats.v1`.
|
|
205
|
+
* Absent or false keeps the asset on the `/v3/spot-prices` poll.
|
|
206
|
+
*/
|
|
207
|
+
wssSupport?: boolean;
|
|
203
208
|
};
|
|
204
209
|
/**
|
|
205
210
|
* Price data for NFT collections
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAExE;;;;;;;;;GASG;AACH,MAAM,MAAM,aAAa,GAAG,aAAa,CAAC;AAE1C;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;AAE/B;;GAEG;AACH,MAAM,MAAM,OAAO,GAAG,WAAW,CAAC;AAMlC;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,KAAK,GAAG,aAAa,CAAC;AAE3D;;GAEG;AACH,MAAM,MAAM,aAAa,GACrB,QAAQ,GACR,OAAO,GACP,QAAQ,GACR,SAAS,GACT,KAAK,GACL,MAAM,CAAC;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EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { SupportedCurrency } from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { CaipAssetType, CaipChainId, Json } from '@metamask/utils';\n\n/**\n * CAIP-19 compliant asset identifier\n * Format: \"{chainId}/{assetNamespace}:{assetReference}[/tokenId]\"\n *\n * Examples:\n * - Native: \"eip155:1/slip44:60\" (ETH)\n * - ERC20: \"eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\" (USDC)\n * - ERC721: \"eip155:1/erc721:0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D/1234\" (BAYC #1234)\n * - SPL: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"\n */\nexport type Caip19AssetId = CaipAssetType;\n\n/**\n * InternalAccount UUID from AccountsController\n * Not the blockchain address!\n */\nexport type AccountId = string;\n\n/**\n * CAIP-2 chain identifier\n */\nexport type ChainId = CaipChainId;\n\n// ============================================================================\n// ASSET TYPES - Defined by metadata structure\n// ============================================================================\n\n/**\n * Asset types define the metadata structure, not blockchain implementation.\n * - \"fungible\" includes: native, erc20, spl - all share balance, symbol, decimals\n * - \"nft\" includes: erc721, erc1155 - include tokenId, image, attributes\n */\nexport type AssetType = 'fungible' | 'nft' | 'collectible';\n\n/**\n * Token standards - blockchain implementation details\n */\nexport type TokenStandard =\n | 'native'\n | 'erc20'\n | 'erc721'\n | 'erc1155'\n | 'spl'\n | string;\n\n// ============================================================================\n// METADATA TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * UI preferences for an asset (stored in assetPreferences state, not in metadata).\n */\nexport type AssetPreferences = {\n /** Whether the asset is hidden from display */\n hidden?: boolean;\n};\n\n/**\n * Base metadata attributes shared by ALL asset types.\n */\nexport type BaseAssetMetadata = {\n /** Token standard - how it's implemented on the blockchain */\n type: TokenStandard;\n /** Display symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Full name (e.g., \"Ethereum\", \"USD Coin\") */\n name: string;\n /** Token decimals (18 for ETH, 6 for USDC, etc.) */\n decimals: number;\n /** Logo URL or data URI */\n image?: string;\n};\n\n// ============================================================================\n// TOKEN CONTRACT DATA TYPES\n// ============================================================================\n\n/** Fee information for token transfers */\nexport type TokenFees = {\n avgFee: number;\n maxFee: number;\n minFee: number;\n};\n\n/** Honeypot detection status */\nexport type HoneypotStatus = {\n honeypotIs: boolean;\n goPlus?: boolean;\n};\n\n/** Storage slot information for the contract */\nexport type StorageSlots = {\n balance: number;\n approval: number;\n};\n\n/** Localized description */\nexport type LocalizedDescription = {\n en: string;\n};\n\n// ============================================================================\n// ASSET METADATA TYPES\n// ============================================================================\n\n/**\n * Metadata for fungible tokens.\n * Structure mirrors V3AssetResponse from the Tokens API.\n *\n * Differences from V3AssetResponse:\n * - `type` is derived from assetId namespace (not in API response)\n * - `image` maps from API's `iconUrl`\n * - `assetId` is not stored (used as the key)\n */\nexport type FungibleAssetMetadata = {\n /** Token type derived from assetId namespace */\n type: 'native' | 'erc20' | 'spl';\n /** CoinGecko ID for price lookups */\n coingeckoId?: string;\n /** Number of token list occurrences */\n occurrences?: number;\n /** DEX/aggregator integrations */\n aggregators?: string[];\n /** Asset labels/tags (e.g., \"stable_coin\") */\n labels?: string[];\n /** Whether the token supports ERC-20 permit */\n erc20Permit?: boolean;\n /** Fee information for token transfers */\n fees?: TokenFees;\n /** Honeypot detection status */\n honeypotStatus?: HoneypotStatus;\n /** Storage slot information for the contract */\n storage?: StorageSlots;\n /** Whether the contract is verified */\n isContractVerified?: boolean;\n /** Localized description */\n description?: LocalizedDescription;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC721 NFTs\n * Asset Type: \"nft\"\n */\nexport type ERC721AssetMetadata = {\n type: 'erc721';\n decimals: 0;\n /** Collection name */\n collectionName?: string;\n /** Collection size */\n collectionSize?: number;\n /** NFT traits/attributes - must be Json-serializable */\n traits?: Record<string, Json>;\n /** Rarity score */\n rarity?: number;\n /** Verification status */\n verified?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC1155 multi-tokens\n */\nexport type ERC1155AssetMetadata = {\n type: 'erc1155';\n /** Token URI */\n tokenUri?: string;\n /** Token category */\n category?: string;\n /** Spam detection flag */\n isSpam?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Union type representing all possible asset metadata types.\n * All types must be JSON-serializable.\n */\nexport type AssetMetadata =\n | FungibleAssetMetadata\n | ERC721AssetMetadata\n | ERC1155AssetMetadata\n | (BaseAssetMetadata & { [key: string]: Json });\n\n// ============================================================================\n// PRICE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Base price attributes.\n */\nexport type BaseAssetPrice = {\n /** Current price in selected currency */\n price: number;\n /** Timestamp of last price update */\n lastUpdated: number;\n};\n\n/**\n * Price data for fungible tokens (native, ERC20, SPL)\n * Matches V3SpotPricesResponse from the Price API.\n */\nexport type FungibleAssetPrice = BaseAssetPrice & {\n assetPriceType: 'fungible';\n /** CoinGecko ID */\n id?: string;\n /** Market capitalization */\n marketCap?: number;\n /** All-time high price */\n allTimeHigh?: number;\n /** All-time low price */\n allTimeLow?: number;\n /** 24h trading volume */\n totalVolume?: number;\n /** 24h high price */\n high1d?: number;\n /** 24h low price */\n low1d?: number;\n /** Circulating supply */\n circulatingSupply?: number;\n /** Fully diluted market cap */\n dilutedMarketCap?: number;\n /** 24h market cap change percentage */\n marketCapPercentChange1d?: number;\n /** 24h price change in USD */\n priceChange1d?: number;\n /** 5m price change percentage */\n pricePercentChange5m?: number;\n /** 1h price change percentage */\n pricePercentChange1h?: number;\n /** 4h price change percentage */\n pricePercentChange4h?: number;\n /** 24h price change percentage */\n pricePercentChange1d?: number;\n /** 7d price change percentage */\n pricePercentChange7d?: number;\n /** 14d price change percentage */\n pricePercentChange14d?: number;\n /** 30d price change percentage */\n pricePercentChange30d?: number;\n /** 200d price change percentage */\n pricePercentChange200d?: number;\n /** 1y price change percentage */\n pricePercentChange1y?: number;\n /** Current price in USD */\n usdPrice: number;\n};\n\n/**\n * Price data for NFT collections\n */\nexport type NFTAssetPrice = BaseAssetPrice & {\n assetPriceType: 'nft';\n /** Floor price */\n floorPrice?: number;\n /** Last sale price */\n lastSalePrice?: number;\n /** Collection trading volume */\n collectionVolume?: number;\n /** Average price */\n averagePrice?: number;\n /** Number of sales in 24h */\n sales24h?: number;\n};\n\n/**\n * Union type representing all possible asset price types.\n * All types must be JSON-serializable.\n */\nexport type AssetPrice = FungibleAssetPrice | NFTAssetPrice;\n\n// ============================================================================\n// BALANCE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Balance data for fungible tokens (native, ERC20, SPL).\n */\nexport type FungibleAssetBalance = {\n /** Converted balance amount (e.g., \"1000\" for 1000 USDC) */\n amount: string;\n /**\n * Network-specific balance fields, when the source provides them. Stellar\n * native rows carry `spendableBalance` / `minimumReserveBalance`, and\n * trustlines carry `limit` / `authorized` / `sponsored`.\n */\n metadata?: Json;\n};\n\n/**\n * Balance data for ERC721 NFTs.\n * Each tokenId has its own CAIP-19 asset ID, so always \"1\".\n */\nexport type ERC721AssetBalance = {\n /** Always \"1\" for ERC721 (non-fungible) */\n amount: '1';\n};\n\n/**\n * Balance data for ERC1155 multi-tokens.\n */\nexport type ERC1155AssetBalance = {\n /** Quantity owned of this specific tokenId */\n amount: string;\n};\n\n/**\n * Union type representing all possible asset balance types.\n * All types must be JSON-serializable.\n */\nexport type AssetBalance =\n | FungibleAssetBalance\n | ERC721AssetBalance\n | ERC1155AssetBalance\n | { amount: string; [key: string]: Json };\n\n// ============================================================================\n// DATA SOURCE TYPES\n// ============================================================================\n\n/**\n * Data type dimension - what kind of data\n */\nexport type DataType = 'balance' | 'metadata' | 'price';\n\n/**\n * Account with its supported chains (enabled chains ∩ account scope).\n * Pre-computed by the controller so data sources do not need to implement\n * account-scope logic; they iterate over supportedChains for each account.\n */\nexport type AccountWithSupportedChains = {\n account: InternalAccount;\n supportedChains: ChainId[];\n};\n\n/**\n * Request for data from data sources\n */\nexport type DataRequest = {\n /** Accounts with their supported chains (enabled ∩ account scope). Data sources use this instead of computing accountSupportsChain. */\n accountsWithSupportedChains: AccountWithSupportedChains[];\n /** CAIP-2 chain IDs (union of chains in this request) */\n chainIds: ChainId[];\n /** Filter by asset types */\n assetTypes?: AssetType[];\n /** Which data to fetch */\n dataTypes: DataType[];\n /**\n * Optional scoped CAIP-19 asset IDs for this fetch (not the full pin list).\n * v5 force-update and v5 RPC fallback put pins here. v6 omits it: natives,\n * pins, and default tracked assets are read from controller state as\n * `includeAssetIds`; detected ERC-20 balances come back with the chain\n * snapshot. RPC fallback additionally refetches existing balances.\n */\n customAssets?: Caip19AssetId[];\n /** Force fresh fetch, bypass cache */\n forceUpdate?: boolean;\n /**\n * Bypass server-side HTTP caches in addition to the client-side ones that\n * `forceUpdate` already skips. Data sources backed by cached HTTP APIs\n * (e.g. the Accounts API with its 60s cache) append a random `bypassServerCache`\n * query param so the server re-reads instead of replaying a stale snapshot.\n * Use sparingly — e.g. right after a transaction confirms.\n */\n bypassServerCache?: boolean;\n /** Hint for polling interval (ms) - used by data sources that implement polling */\n updateInterval?: number;\n};\n\n/**\n * Response from data sources\n */\nexport type DataResponse = {\n /** Metadata for assets (shared across accounts) */\n assetsInfo?: Record<Caip19AssetId, AssetMetadata>;\n /** Price data for assets (shared across accounts) */\n assetsPrice?: Record<Caip19AssetId, AssetPrice>;\n /** Balance data per account */\n assetsBalance?: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Errors encountered, keyed by chain ID (chain-axis fallback + telemetry) */\n errors?: Record<ChainId, string>;\n /**\n * How to apply this response to state. See {@link AssetsUpdateMode}.\n * Defaults to `'merge'` if omitted.\n */\n updateMode?: AssetsUpdateMode;\n /**\n * When set with `updateMode: 'merge'`, balances on chains present in\n * `assetsBalance` replace the prior chain slice (stale tokens on those chains\n * are dropped). Custom assets on covered chains are preserved. Used for\n * Accounts API v5 `getAssets({ forceUpdate: true })`. Accounts API v6 uses\n * `updateMode: 'full'` instead.\n */\n replaceCoveredChainBalances?: boolean;\n};\n\n/**\n * Type of {@link DataResponse.updateMode}: how the controller applies the response to state.\n *\n * - **full**: Response is the full set for covered chains (those present in\n * `assetsBalance`). Assets in state on those chains but not in the response\n * are cleared, including custom assets (Accounts API v6 returns pins via\n * `includeAssetIds`). A chain the source could not answer in full is reported\n * in `errors` and left out of `assetsBalance` entirely, so it is never\n * covered. Use for Accounts API v6 and RpcDataSource v6 snapshots.\n * - **merge**: Only assets present in the response are updated; nothing is\n * removed, unless {@link DataResponse.replaceCoveredChainBalances} is set\n * (Accounts API v5 force refresh). Metadata and prices from the response\n * are applied. Use for event-driven updates and Accounts API v5.\n */\nexport type AssetsUpdateMode = 'full' | 'merge';\n\nexport type AssetsLoadingStatus = 'loading' | 'loaded';\n\n// ============================================================================\n// DATA SOURCE <-> CONTROLLER (DIRECT CALLS, NO MESSENGER PER SOURCE)\n// ============================================================================\n\n/**\n * Callbacks for data sources to report to AssetsController.\n * Passed to data sources so they report by direct call instead of messenger.\n */\nexport type AssetsControllerReport = {\n onActiveChainsUpdate: (dataSourceId: string, activeChains: ChainId[]) => void;\n onAssetsUpdate: (response: DataResponse, sourceId: string) => Promise<void>;\n};\n\n/** Request passed from controller to data source when subscribing */\nexport type DataSourceSubscriptionRequest = {\n request: DataRequest;\n subscriptionId: string;\n isUpdate: boolean;\n};\n\n/**\n * Interface for balance data sources that the controller calls directly.\n * No messenger is required for controller <-> data source communication.\n */\nexport type BalanceDataSource = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n getName: () => string;\n};\n\n/**\n * Interface for the price data source (subscribe/unsubscribe + middleware).\n * Controller calls these methods directly.\n */\nexport type PriceDataSourceInterface = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n};\n\n/**\n * Middleware-only source (e.g. detection, token enrichment).\n * Controller calls getAssetsMiddleware() directly.\n */\nexport type MiddlewareDataSource = {\n getAssetsMiddleware: () => Middleware;\n};\n\n// ============================================================================\n// CONTROLLER STATE\n// ============================================================================\n\n/**\n * State structure for AssetsController following normalized design.\n *\n * All values must stay JSON-serializable. UI preferences (e.g. hidden) live in\n * assetPreferences, not in metadata.\n *\n * Keys use CAIP identifiers:\n * - assetsInfo keys: CAIP-19 asset IDs (e.g., \"eip155:1/erc20:0x...\")\n * - assetsBalance outer keys: Account IDs (InternalAccount.id UUIDs)\n * - assetsBalance inner keys: CAIP-19 asset IDs\n * - assetsPrice keys: CAIP-19 asset IDs\n * - customAssets outer keys: Account IDs (InternalAccount.id UUIDs)\n * - customAssets inner values: CAIP-19 asset IDs array\n * - assetPreferences keys: CAIP-19 asset IDs\n */\nexport type AssetsControllerState = {\n /** Shared metadata for all assets (stored once per asset) */\n assetsInfo: Record<Caip19AssetId, AssetMetadata>;\n /** Per-account balance data */\n assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Price data for assets */\n assetsPrice: Record<Caip19AssetId, AssetPrice>;\n /** Custom assets added by users per account */\n customAssets: Record<AccountId, Caip19AssetId[]>;\n /** UI preferences per asset (e.g. hidden) - separate from metadata */\n assetPreferences: Record<Caip19AssetId, AssetPreferences>;\n /** Currently-active ISO 4217 currency code */\n selectedCurrency: SupportedCurrency;\n assetsLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n /**\n * Per-account status of the background (Snap + RPC) fetch that runs after\n * the initial balance has resolved. Tracked on every forced fetch.\n */\n assetsBackgroundLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n};\n\n// ============================================================================\n// UNIFIED MIDDLEWARE TYPES\n// ============================================================================\n\n/**\n * Base context for all middleware operations.\n * Contains the common interface shared by fetch and subscribe.\n */\nexport type Context = {\n /** The data request */\n request: DataRequest;\n /** The response data (mutated by middlewares) */\n response: DataResponse;\n /**\n * Optional breakdown of latency (ms) per data source, e.g. from parallel\n * middlewares. Keys are source names (often \"MiddlewareName.SourceName\").\n * Merged into the controller's durationByDataSource for tracing.\n */\n durationByDataSource?: Record<string, number>;\n};\n\n/**\n * Next function for middleware chain\n */\nexport type NextFunction = (context: Context) => Promise<Context>;\n\n/**\n * Middleware function - works for both fetch and subscribe operations.\n */\nexport type Middleware = (\n context: Context,\n next: NextFunction,\n) => Promise<Context>;\n\n/**\n * An assets data source: any object that can participate in the assets\n * middleware chain with a display name (e.g. for tracing). Used by\n * createParallelMiddleware and by the controller when executing the chain.\n */\nexport type AssetsDataSource = {\n getName(): string;\n assetsMiddleware: Middleware;\n};\n\n/**\n * Wraps a middleware to only execute if specific dataTypes are requested.\n *\n * @param dataTypes - DataTypes that must be in the request for middleware to run\n * @param middleware - The middleware to conditionally execute\n * @returns A middleware that skips execution if none of the dataTypes are requested\n *\n * @example\n * ```typescript\n * // Only runs for metadata requests\n * const metadataMiddleware = forDataTypes(['metadata'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Enrich metadata...\n * return result;\n * });\n *\n * // Runs for balance or price requests\n * const balanceOrPriceMiddleware = forDataTypes(['balance', 'price'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Process balances or prices...\n * return result;\n * });\n * ```\n */\nexport function forDataTypes(\n dataTypes: DataType[],\n middleware: Middleware,\n): Middleware {\n return async (ctx, next) => {\n const requestedTypes = ctx.request.dataTypes;\n const shouldRun = dataTypes.some((dt) => requestedTypes.includes(dt));\n\n if (!shouldRun) {\n return next(ctx);\n }\n\n return middleware(ctx, next);\n };\n}\n\n/**\n * Context for fetch operations.\n * Extends base Context - no additional fields needed for fetch.\n */\nexport type FetchContext = Context;\n\n// Legacy aliases for backwards compatibility\nexport type FetchNextFunction = NextFunction;\nexport type FetchMiddleware = Middleware;\n\n/**\n * Subscription response returned when subscribing to asset updates.\n */\nexport type SubscriptionResponse = {\n /** Chains actively subscribed */\n chains: ChainId[];\n /** Account ID being watched */\n accountId: AccountId;\n /** Asset types being watched */\n assetTypes: AssetType[];\n /** Data types being kept fresh */\n dataTypes: DataType[];\n /** Cleanup function */\n unsubscribe: () => void;\n};\n\n// ============================================================================\n// COMBINED ASSET TYPE (for UI)\n// ============================================================================\n\n/**\n * Combined asset type matching state structure: balance, metadata, price\n */\nexport type Asset = {\n /** CAIP-19 asset ID */\n id: Caip19AssetId;\n /** CAIP-2 chain ID (extracted from id) */\n chainId: ChainId;\n /** Balance data */\n balance: AssetBalance;\n /** Metadata (symbol, name, decimals, etc.) */\n metadata: AssetMetadata;\n /** Price data */\n price: AssetPrice;\n /** Computed fiat value (balance × price) */\n fiatValue: number;\n};\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Event emitted when balances change\n */\nexport type BalanceChangeEvent = {\n accountId: AccountId;\n assetId: Caip19AssetId;\n previousAmount: string;\n newAmount: string;\n timestamp: number;\n};\n\n/**\n * Event emitted when prices change\n */\nexport type PriceChangeEvent = {\n assetIds: Caip19AssetId[];\n timestamp: number;\n};\n\n/**\n * Event emitted when metadata changes\n */\nexport type MetadataChangeEvent = {\n assetId: Caip19AssetId;\n changes: Partial<AssetMetadata>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAyiBA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,YAAY,CAC1B,SAAqB,EACrB,UAAsB;IAEtB,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC;QAC7C,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QAEtE,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;QAED,OAAO,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { SupportedCurrency } from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { CaipAssetType, CaipChainId, Json } from '@metamask/utils';\n\n/**\n * CAIP-19 compliant asset identifier\n * Format: \"{chainId}/{assetNamespace}:{assetReference}[/tokenId]\"\n *\n * Examples:\n * - Native: \"eip155:1/slip44:60\" (ETH)\n * - ERC20: \"eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\" (USDC)\n * - ERC721: \"eip155:1/erc721:0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D/1234\" (BAYC #1234)\n * - SPL: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"\n */\nexport type Caip19AssetId = CaipAssetType;\n\n/**\n * InternalAccount UUID from AccountsController\n * Not the blockchain address!\n */\nexport type AccountId = string;\n\n/**\n * CAIP-2 chain identifier\n */\nexport type ChainId = CaipChainId;\n\n// ============================================================================\n// ASSET TYPES - Defined by metadata structure\n// ============================================================================\n\n/**\n * Asset types define the metadata structure, not blockchain implementation.\n * - \"fungible\" includes: native, erc20, spl - all share balance, symbol, decimals\n * - \"nft\" includes: erc721, erc1155 - include tokenId, image, attributes\n */\nexport type AssetType = 'fungible' | 'nft' | 'collectible';\n\n/**\n * Token standards - blockchain implementation details\n */\nexport type TokenStandard =\n | 'native'\n | 'erc20'\n | 'erc721'\n | 'erc1155'\n | 'spl'\n | string;\n\n// ============================================================================\n// METADATA TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * UI preferences for an asset (stored in assetPreferences state, not in metadata).\n */\nexport type AssetPreferences = {\n /** Whether the asset is hidden from display */\n hidden?: boolean;\n};\n\n/**\n * Base metadata attributes shared by ALL asset types.\n */\nexport type BaseAssetMetadata = {\n /** Token standard - how it's implemented on the blockchain */\n type: TokenStandard;\n /** Display symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Full name (e.g., \"Ethereum\", \"USD Coin\") */\n name: string;\n /** Token decimals (18 for ETH, 6 for USDC, etc.) */\n decimals: number;\n /** Logo URL or data URI */\n image?: string;\n};\n\n// ============================================================================\n// TOKEN CONTRACT DATA TYPES\n// ============================================================================\n\n/** Fee information for token transfers */\nexport type TokenFees = {\n avgFee: number;\n maxFee: number;\n minFee: number;\n};\n\n/** Honeypot detection status */\nexport type HoneypotStatus = {\n honeypotIs: boolean;\n goPlus?: boolean;\n};\n\n/** Storage slot information for the contract */\nexport type StorageSlots = {\n balance: number;\n approval: number;\n};\n\n/** Localized description */\nexport type LocalizedDescription = {\n en: string;\n};\n\n// ============================================================================\n// ASSET METADATA TYPES\n// ============================================================================\n\n/**\n * Metadata for fungible tokens.\n * Structure mirrors V3AssetResponse from the Tokens API.\n *\n * Differences from V3AssetResponse:\n * - `type` is derived from assetId namespace (not in API response)\n * - `image` maps from API's `iconUrl`\n * - `assetId` is not stored (used as the key)\n */\nexport type FungibleAssetMetadata = {\n /** Token type derived from assetId namespace */\n type: 'native' | 'erc20' | 'spl';\n /** CoinGecko ID for price lookups */\n coingeckoId?: string;\n /** Number of token list occurrences */\n occurrences?: number;\n /** DEX/aggregator integrations */\n aggregators?: string[];\n /** Asset labels/tags (e.g., \"stable_coin\") */\n labels?: string[];\n /** Whether the token supports ERC-20 permit */\n erc20Permit?: boolean;\n /** Fee information for token transfers */\n fees?: TokenFees;\n /** Honeypot detection status */\n honeypotStatus?: HoneypotStatus;\n /** Storage slot information for the contract */\n storage?: StorageSlots;\n /** Whether the contract is verified */\n isContractVerified?: boolean;\n /** Localized description */\n description?: LocalizedDescription;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC721 NFTs\n * Asset Type: \"nft\"\n */\nexport type ERC721AssetMetadata = {\n type: 'erc721';\n decimals: 0;\n /** Collection name */\n collectionName?: string;\n /** Collection size */\n collectionSize?: number;\n /** NFT traits/attributes - must be Json-serializable */\n traits?: Record<string, Json>;\n /** Rarity score */\n rarity?: number;\n /** Verification status */\n verified?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC1155 multi-tokens\n */\nexport type ERC1155AssetMetadata = {\n type: 'erc1155';\n /** Token URI */\n tokenUri?: string;\n /** Token category */\n category?: string;\n /** Spam detection flag */\n isSpam?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Union type representing all possible asset metadata types.\n * All types must be JSON-serializable.\n */\nexport type AssetMetadata =\n | FungibleAssetMetadata\n | ERC721AssetMetadata\n | ERC1155AssetMetadata\n | (BaseAssetMetadata & { [key: string]: Json });\n\n// ============================================================================\n// PRICE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Base price attributes.\n */\nexport type BaseAssetPrice = {\n /** Current price in selected currency */\n price: number;\n /** Timestamp of last price update */\n lastUpdated: number;\n};\n\n/**\n * Price data for fungible tokens (native, ERC20, SPL)\n * Matches V3SpotPricesResponse from the Price API.\n */\nexport type FungibleAssetPrice = BaseAssetPrice & {\n assetPriceType: 'fungible';\n /** CoinGecko ID */\n id?: string;\n /** Market capitalization */\n marketCap?: number;\n /** All-time high price */\n allTimeHigh?: number;\n /** All-time low price */\n allTimeLow?: number;\n /** 24h trading volume */\n totalVolume?: number;\n /** 24h high price */\n high1d?: number;\n /** 24h low price */\n low1d?: number;\n /** Circulating supply */\n circulatingSupply?: number;\n /** Fully diluted market cap */\n dilutedMarketCap?: number;\n /** 24h market cap change percentage */\n marketCapPercentChange1d?: number;\n /** 24h price change in USD */\n priceChange1d?: number;\n /** 5m price change percentage */\n pricePercentChange5m?: number;\n /** 1h price change percentage */\n pricePercentChange1h?: number;\n /** 4h price change percentage */\n pricePercentChange4h?: number;\n /** 24h price change percentage */\n pricePercentChange1d?: number;\n /** 7d price change percentage */\n pricePercentChange7d?: number;\n /** 14d price change percentage */\n pricePercentChange14d?: number;\n /** 30d price change percentage */\n pricePercentChange30d?: number;\n /** 200d price change percentage */\n pricePercentChange200d?: number;\n /** 1y price change percentage */\n pricePercentChange1y?: number;\n /** Current price in USD */\n usdPrice: number;\n /**\n * True when this asset can stream on `market-stats.v1`.\n * Absent or false keeps the asset on the `/v3/spot-prices` poll.\n */\n wssSupport?: boolean;\n};\n\n/**\n * Price data for NFT collections\n */\nexport type NFTAssetPrice = BaseAssetPrice & {\n assetPriceType: 'nft';\n /** Floor price */\n floorPrice?: number;\n /** Last sale price */\n lastSalePrice?: number;\n /** Collection trading volume */\n collectionVolume?: number;\n /** Average price */\n averagePrice?: number;\n /** Number of sales in 24h */\n sales24h?: number;\n};\n\n/**\n * Union type representing all possible asset price types.\n * All types must be JSON-serializable.\n */\nexport type AssetPrice = FungibleAssetPrice | NFTAssetPrice;\n\n// ============================================================================\n// BALANCE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Balance data for fungible tokens (native, ERC20, SPL).\n */\nexport type FungibleAssetBalance = {\n /** Converted balance amount (e.g., \"1000\" for 1000 USDC) */\n amount: string;\n /**\n * Network-specific balance fields, when the source provides them. Stellar\n * native rows carry `spendableBalance` / `minimumReserveBalance`, and\n * trustlines carry `limit` / `authorized` / `sponsored`.\n */\n metadata?: Json;\n};\n\n/**\n * Balance data for ERC721 NFTs.\n * Each tokenId has its own CAIP-19 asset ID, so always \"1\".\n */\nexport type ERC721AssetBalance = {\n /** Always \"1\" for ERC721 (non-fungible) */\n amount: '1';\n};\n\n/**\n * Balance data for ERC1155 multi-tokens.\n */\nexport type ERC1155AssetBalance = {\n /** Quantity owned of this specific tokenId */\n amount: string;\n};\n\n/**\n * Union type representing all possible asset balance types.\n * All types must be JSON-serializable.\n */\nexport type AssetBalance =\n | FungibleAssetBalance\n | ERC721AssetBalance\n | ERC1155AssetBalance\n | { amount: string; [key: string]: Json };\n\n// ============================================================================\n// DATA SOURCE TYPES\n// ============================================================================\n\n/**\n * Data type dimension - what kind of data\n */\nexport type DataType = 'balance' | 'metadata' | 'price';\n\n/**\n * Account with its supported chains (enabled chains ∩ account scope).\n * Pre-computed by the controller so data sources do not need to implement\n * account-scope logic; they iterate over supportedChains for each account.\n */\nexport type AccountWithSupportedChains = {\n account: InternalAccount;\n supportedChains: ChainId[];\n};\n\n/**\n * Request for data from data sources\n */\nexport type DataRequest = {\n /** Accounts with their supported chains (enabled ∩ account scope). Data sources use this instead of computing accountSupportsChain. */\n accountsWithSupportedChains: AccountWithSupportedChains[];\n /** CAIP-2 chain IDs (union of chains in this request) */\n chainIds: ChainId[];\n /** Filter by asset types */\n assetTypes?: AssetType[];\n /** Which data to fetch */\n dataTypes: DataType[];\n /**\n * Optional scoped CAIP-19 asset IDs for this fetch (not the full pin list).\n * v5 force-update and v5 RPC fallback put pins here. v6 omits it: natives,\n * pins, and default tracked assets are read from controller state as\n * `includeAssetIds`; detected ERC-20 balances come back with the chain\n * snapshot. RPC fallback additionally refetches existing balances.\n */\n customAssets?: Caip19AssetId[];\n /** Force fresh fetch, bypass cache */\n forceUpdate?: boolean;\n /**\n * Bypass server-side HTTP caches in addition to the client-side ones that\n * `forceUpdate` already skips. Data sources backed by cached HTTP APIs\n * (e.g. the Accounts API with its 60s cache) append a random `bypassServerCache`\n * query param so the server re-reads instead of replaying a stale snapshot.\n * Use sparingly — e.g. right after a transaction confirms.\n */\n bypassServerCache?: boolean;\n /** Hint for polling interval (ms) - used by data sources that implement polling */\n updateInterval?: number;\n};\n\n/**\n * Response from data sources\n */\nexport type DataResponse = {\n /** Metadata for assets (shared across accounts) */\n assetsInfo?: Record<Caip19AssetId, AssetMetadata>;\n /** Price data for assets (shared across accounts) */\n assetsPrice?: Record<Caip19AssetId, AssetPrice>;\n /** Balance data per account */\n assetsBalance?: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Errors encountered, keyed by chain ID (chain-axis fallback + telemetry) */\n errors?: Record<ChainId, string>;\n /**\n * How to apply this response to state. See {@link AssetsUpdateMode}.\n * Defaults to `'merge'` if omitted.\n */\n updateMode?: AssetsUpdateMode;\n /**\n * When set with `updateMode: 'merge'`, balances on chains present in\n * `assetsBalance` replace the prior chain slice (stale tokens on those chains\n * are dropped). Custom assets on covered chains are preserved. Used for\n * Accounts API v5 `getAssets({ forceUpdate: true })`. Accounts API v6 uses\n * `updateMode: 'full'` instead.\n */\n replaceCoveredChainBalances?: boolean;\n};\n\n/**\n * Type of {@link DataResponse.updateMode}: how the controller applies the response to state.\n *\n * - **full**: Response is the full set for covered chains (those present in\n * `assetsBalance`). Assets in state on those chains but not in the response\n * are cleared, including custom assets (Accounts API v6 returns pins via\n * `includeAssetIds`). A chain the source could not answer in full is reported\n * in `errors` and left out of `assetsBalance` entirely, so it is never\n * covered. Use for Accounts API v6 and RpcDataSource v6 snapshots.\n * - **merge**: Only assets present in the response are updated; nothing is\n * removed, unless {@link DataResponse.replaceCoveredChainBalances} is set\n * (Accounts API v5 force refresh). Metadata and prices from the response\n * are applied. Use for event-driven updates and Accounts API v5.\n */\nexport type AssetsUpdateMode = 'full' | 'merge';\n\nexport type AssetsLoadingStatus = 'loading' | 'loaded';\n\n// ============================================================================\n// DATA SOURCE <-> CONTROLLER (DIRECT CALLS, NO MESSENGER PER SOURCE)\n// ============================================================================\n\n/**\n * Callbacks for data sources to report to AssetsController.\n * Passed to data sources so they report by direct call instead of messenger.\n */\nexport type AssetsControllerReport = {\n onActiveChainsUpdate: (dataSourceId: string, activeChains: ChainId[]) => void;\n onAssetsUpdate: (response: DataResponse, sourceId: string) => Promise<void>;\n};\n\n/** Request passed from controller to data source when subscribing */\nexport type DataSourceSubscriptionRequest = {\n request: DataRequest;\n subscriptionId: string;\n isUpdate: boolean;\n};\n\n/**\n * Interface for balance data sources that the controller calls directly.\n * No messenger is required for controller <-> data source communication.\n */\nexport type BalanceDataSource = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n getName: () => string;\n};\n\n/**\n * Interface for the price data source (subscribe/unsubscribe + middleware).\n * Controller calls these methods directly.\n */\nexport type PriceDataSourceInterface = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n};\n\n/**\n * Middleware-only source (e.g. detection, token enrichment).\n * Controller calls getAssetsMiddleware() directly.\n */\nexport type MiddlewareDataSource = {\n getAssetsMiddleware: () => Middleware;\n};\n\n// ============================================================================\n// CONTROLLER STATE\n// ============================================================================\n\n/**\n * State structure for AssetsController following normalized design.\n *\n * All values must stay JSON-serializable. UI preferences (e.g. hidden) live in\n * assetPreferences, not in metadata.\n *\n * Keys use CAIP identifiers:\n * - assetsInfo keys: CAIP-19 asset IDs (e.g., \"eip155:1/erc20:0x...\")\n * - assetsBalance outer keys: Account IDs (InternalAccount.id UUIDs)\n * - assetsBalance inner keys: CAIP-19 asset IDs\n * - assetsPrice keys: CAIP-19 asset IDs\n * - customAssets outer keys: Account IDs (InternalAccount.id UUIDs)\n * - customAssets inner values: CAIP-19 asset IDs array\n * - assetPreferences keys: CAIP-19 asset IDs\n */\nexport type AssetsControllerState = {\n /** Shared metadata for all assets (stored once per asset) */\n assetsInfo: Record<Caip19AssetId, AssetMetadata>;\n /** Per-account balance data */\n assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Price data for assets */\n assetsPrice: Record<Caip19AssetId, AssetPrice>;\n /** Custom assets added by users per account */\n customAssets: Record<AccountId, Caip19AssetId[]>;\n /** UI preferences per asset (e.g. hidden) - separate from metadata */\n assetPreferences: Record<Caip19AssetId, AssetPreferences>;\n /** Currently-active ISO 4217 currency code */\n selectedCurrency: SupportedCurrency;\n assetsLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n /**\n * Per-account status of the background (Snap + RPC) fetch that runs after\n * the initial balance has resolved. Tracked on every forced fetch.\n */\n assetsBackgroundLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n};\n\n// ============================================================================\n// UNIFIED MIDDLEWARE TYPES\n// ============================================================================\n\n/**\n * Base context for all middleware operations.\n * Contains the common interface shared by fetch and subscribe.\n */\nexport type Context = {\n /** The data request */\n request: DataRequest;\n /** The response data (mutated by middlewares) */\n response: DataResponse;\n /**\n * Optional breakdown of latency (ms) per data source, e.g. from parallel\n * middlewares. Keys are source names (often \"MiddlewareName.SourceName\").\n * Merged into the controller's durationByDataSource for tracing.\n */\n durationByDataSource?: Record<string, number>;\n};\n\n/**\n * Next function for middleware chain\n */\nexport type NextFunction = (context: Context) => Promise<Context>;\n\n/**\n * Middleware function - works for both fetch and subscribe operations.\n */\nexport type Middleware = (\n context: Context,\n next: NextFunction,\n) => Promise<Context>;\n\n/**\n * An assets data source: any object that can participate in the assets\n * middleware chain with a display name (e.g. for tracing). Used by\n * createParallelMiddleware and by the controller when executing the chain.\n */\nexport type AssetsDataSource = {\n getName(): string;\n assetsMiddleware: Middleware;\n};\n\n/**\n * Wraps a middleware to only execute if specific dataTypes are requested.\n *\n * @param dataTypes - DataTypes that must be in the request for middleware to run\n * @param middleware - The middleware to conditionally execute\n * @returns A middleware that skips execution if none of the dataTypes are requested\n *\n * @example\n * ```typescript\n * // Only runs for metadata requests\n * const metadataMiddleware = forDataTypes(['metadata'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Enrich metadata...\n * return result;\n * });\n *\n * // Runs for balance or price requests\n * const balanceOrPriceMiddleware = forDataTypes(['balance', 'price'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Process balances or prices...\n * return result;\n * });\n * ```\n */\nexport function forDataTypes(\n dataTypes: DataType[],\n middleware: Middleware,\n): Middleware {\n return async (ctx, next) => {\n const requestedTypes = ctx.request.dataTypes;\n const shouldRun = dataTypes.some((dt) => requestedTypes.includes(dt));\n\n if (!shouldRun) {\n return next(ctx);\n }\n\n return middleware(ctx, next);\n };\n}\n\n/**\n * Context for fetch operations.\n * Extends base Context - no additional fields needed for fetch.\n */\nexport type FetchContext = Context;\n\n// Legacy aliases for backwards compatibility\nexport type FetchNextFunction = NextFunction;\nexport type FetchMiddleware = Middleware;\n\n/**\n * Subscription response returned when subscribing to asset updates.\n */\nexport type SubscriptionResponse = {\n /** Chains actively subscribed */\n chains: ChainId[];\n /** Account ID being watched */\n accountId: AccountId;\n /** Asset types being watched */\n assetTypes: AssetType[];\n /** Data types being kept fresh */\n dataTypes: DataType[];\n /** Cleanup function */\n unsubscribe: () => void;\n};\n\n// ============================================================================\n// COMBINED ASSET TYPE (for UI)\n// ============================================================================\n\n/**\n * Combined asset type matching state structure: balance, metadata, price\n */\nexport type Asset = {\n /** CAIP-19 asset ID */\n id: Caip19AssetId;\n /** CAIP-2 chain ID (extracted from id) */\n chainId: ChainId;\n /** Balance data */\n balance: AssetBalance;\n /** Metadata (symbol, name, decimals, etc.) */\n metadata: AssetMetadata;\n /** Price data */\n price: AssetPrice;\n /** Computed fiat value (balance × price) */\n fiatValue: number;\n};\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Event emitted when balances change\n */\nexport type BalanceChangeEvent = {\n accountId: AccountId;\n assetId: Caip19AssetId;\n previousAmount: string;\n newAmount: string;\n timestamp: number;\n};\n\n/**\n * Event emitted when prices change\n */\nexport type PriceChangeEvent = {\n assetIds: Caip19AssetId[];\n timestamp: number;\n};\n\n/**\n * Event emitted when metadata changes\n */\nexport type MetadataChangeEvent = {\n assetId: Caip19AssetId;\n changes: Partial<AssetMetadata>;\n};\n"]}
|
package/package.json
CHANGED