@metamask-previews/assets-controllers 45.1.0-preview-57e6ab5d → 45.1.0-preview-e58ce4ab
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -9
- package/dist/AccountTrackerController.d.cts +4 -4
- package/dist/AccountTrackerController.d.mts +4 -4
- package/dist/CurrencyRateController.d.cts +4 -4
- package/dist/CurrencyRateController.d.mts +4 -4
- package/dist/Standards/ERC20Standard.mjs +4 -2
- package/dist/Standards/ERC20Standard.mjs.map +1 -1
- package/dist/TokenBalancesController.d.cts +4 -4
- package/dist/TokenBalancesController.d.mts +4 -4
- package/dist/TokenDetectionController.d.cts +4 -4
- package/dist/TokenDetectionController.d.mts +4 -4
- package/dist/TokenListController.d.cts +4 -4
- package/dist/TokenListController.d.mts +4 -4
- package/dist/TokenRatesController.d.cts +4 -4
- package/dist/TokenRatesController.d.mts +4 -4
- package/dist/token-prices-service/codefi-v2.mjs +2 -1
- package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
- package/package.json +3 -8
package/CHANGELOG.md
CHANGED
|
@@ -7,15 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
-
### Fixed
|
|
11
|
-
|
|
12
|
-
- Make implicit peer dependencies explicit ([#4974](https://github.com/MetaMask/core/pull/4974))
|
|
13
|
-
- Add the following packages as peer dependencies of this package to satisfy peer dependency requirements from other dependencies:
|
|
14
|
-
- `@metamask/providers` `^18.1.0` (required by `@metamask/keyring-api`)
|
|
15
|
-
- `webextension-polyfill` `^0.10.0 || ^0.11.0 || ^0.12.0` (required by `@metamask/providers`)
|
|
16
|
-
- These dependencies really should be present in projects that consume this package (e.g. MetaMask clients), and this change ensures that they now are.
|
|
17
|
-
- Furthermore, we are assuming that clients already use these dependencies, since otherwise it would be impossible to consume this package in its entirety or even create a working build. Hence, the addition of these peer dependencies is really a formality and should not be breaking.
|
|
18
|
-
|
|
19
10
|
## [45.1.0]
|
|
20
11
|
|
|
21
12
|
### Added
|
|
@@ -65,14 +65,14 @@ type AccountTrackerPollingInput = {
|
|
|
65
65
|
networkClientId: NetworkClientId;
|
|
66
66
|
};
|
|
67
67
|
declare const AccountTrackerController_base: (abstract new (...args: any[]) => {
|
|
68
|
-
readonly "__#
|
|
69
|
-
"__#
|
|
68
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
69
|
+
"__#787811@#intervalLength": number | undefined;
|
|
70
70
|
setIntervalLength(intervalLength: number): void;
|
|
71
71
|
getIntervalLength(): number | undefined;
|
|
72
72
|
_startPolling(input: AccountTrackerPollingInput): void;
|
|
73
73
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
74
|
-
readonly "__#
|
|
75
|
-
"__#
|
|
74
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
75
|
+
"__#787803@#callbacks": Map<string, Set<(input: AccountTrackerPollingInput) => void>>;
|
|
76
76
|
_executePoll(input: AccountTrackerPollingInput): Promise<void>;
|
|
77
77
|
startPolling(input: AccountTrackerPollingInput): string;
|
|
78
78
|
stopAllPolling(): void;
|
|
@@ -65,14 +65,14 @@ type AccountTrackerPollingInput = {
|
|
|
65
65
|
networkClientId: NetworkClientId;
|
|
66
66
|
};
|
|
67
67
|
declare const AccountTrackerController_base: (abstract new (...args: any[]) => {
|
|
68
|
-
readonly "__#
|
|
69
|
-
"__#
|
|
68
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
69
|
+
"__#787811@#intervalLength": number | undefined;
|
|
70
70
|
setIntervalLength(intervalLength: number): void;
|
|
71
71
|
getIntervalLength(): number | undefined;
|
|
72
72
|
_startPolling(input: AccountTrackerPollingInput): void;
|
|
73
73
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
74
|
-
readonly "__#
|
|
75
|
-
"__#
|
|
74
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
75
|
+
"__#787803@#callbacks": Map<string, Set<(input: AccountTrackerPollingInput) => void>>;
|
|
76
76
|
_executePoll(input: AccountTrackerPollingInput): Promise<void>;
|
|
77
77
|
startPolling(input: AccountTrackerPollingInput): string;
|
|
78
78
|
stopAllPolling(): void;
|
|
@@ -29,14 +29,14 @@ type CurrencyRatePollingInput = {
|
|
|
29
29
|
nativeCurrencies: string[];
|
|
30
30
|
};
|
|
31
31
|
declare const CurrencyRateController_base: (abstract new (...args: any[]) => {
|
|
32
|
-
readonly "__#
|
|
33
|
-
"__#
|
|
32
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
33
|
+
"__#787811@#intervalLength": number | undefined;
|
|
34
34
|
setIntervalLength(intervalLength: number): void;
|
|
35
35
|
getIntervalLength(): number | undefined;
|
|
36
36
|
_startPolling(input: CurrencyRatePollingInput): void;
|
|
37
37
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
38
|
-
readonly "__#
|
|
39
|
-
"__#
|
|
38
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
39
|
+
"__#787803@#callbacks": Map<string, Set<(input: CurrencyRatePollingInput) => void>>;
|
|
40
40
|
_executePoll(input: CurrencyRatePollingInput): Promise<void>;
|
|
41
41
|
startPolling(input: CurrencyRatePollingInput): string;
|
|
42
42
|
stopAllPolling(): void;
|
|
@@ -29,14 +29,14 @@ type CurrencyRatePollingInput = {
|
|
|
29
29
|
nativeCurrencies: string[];
|
|
30
30
|
};
|
|
31
31
|
declare const CurrencyRateController_base: (abstract new (...args: any[]) => {
|
|
32
|
-
readonly "__#
|
|
33
|
-
"__#
|
|
32
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
33
|
+
"__#787811@#intervalLength": number | undefined;
|
|
34
34
|
setIntervalLength(intervalLength: number): void;
|
|
35
35
|
getIntervalLength(): number | undefined;
|
|
36
36
|
_startPolling(input: CurrencyRatePollingInput): void;
|
|
37
37
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
38
|
-
readonly "__#
|
|
39
|
-
"__#
|
|
38
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
39
|
+
"__#787803@#callbacks": Map<string, Set<(input: CurrencyRatePollingInput) => void>>;
|
|
40
40
|
_executePoll(input: CurrencyRatePollingInput): Promise<void>;
|
|
41
41
|
startPolling(input: CurrencyRatePollingInput): string;
|
|
42
42
|
stopAllPolling(): void;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import $ethereumjsutil from "@ethereumjs/util";
|
|
2
|
+
const { toUtf8 } = $ethereumjsutil;
|
|
2
3
|
import { Contract } from "@ethersproject/contracts";
|
|
3
|
-
import
|
|
4
|
+
import $metamaskabiutils from "@metamask/abi-utils";
|
|
5
|
+
const { decodeSingle } = $metamaskabiutils;
|
|
4
6
|
import { ERC20 } from "@metamask/controller-utils";
|
|
5
7
|
import { abiERC20 } from "@metamask/metamask-eth-abis";
|
|
6
8
|
import { assertIsStrictHexString } from "@metamask/utils";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ERC20Standard.mjs","sourceRoot":"","sources":["../../src/Standards/ERC20Standard.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ERC20Standard.mjs","sourceRoot":"","sources":["../../src/Standards/ERC20Standard.ts"],"names":[],"mappings":";;AACA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;;;AAGpD,OAAO,EAAE,KAAK,EAAE,mCAAmC;AACnD,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AACvD,OAAO,EAAE,uBAAuB,EAAE,wBAAwB;AAG1D,OAAO,EAAE,mBAAmB,EAAE,0BAAsB;AAEpD,MAAM,OAAO,aAAa;IAGxB,YAAY,QAAsB;QAChC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED;;;;;;OAMG;IACH,KAA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ACJ,CAAC;CACF","sourcesContent":["import { toUtf8 } from '@ethereumjs/util';\nimport { Contract } from '@ethersproject/contracts';\nimport type { Web3Provider } from '@ethersproject/providers';\nimport { decodeSingle } from '@metamask/abi-utils';\nimport { ERC20 } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { assertIsStrictHexString } from '@metamask/utils';\nimport type BN from 'bn.js';\n\nimport { ethersBigNumberToBN } from '../assetsUtil';\n\nexport class ERC20Standard {\n private readonly provider: Web3Provider;\n\n constructor(provider: Web3Provider) {\n this.provider = provider;\n }\n\n /**\n * Get balance or count for current account on specific asset contract.\n *\n * @param address - Asset ERC20 contract address.\n * @param selectedAddress - Current account public address.\n * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getBalanceOf(address: string, selectedAddress: string): Promise<BN> {\n const contract = new Contract(address, abiERC20, this.provider);\n const balance = await contract.balanceOf(selectedAddress);\n return ethersBigNumberToBN(balance);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract string.\n * @returns Promise resolving to the 'decimals'.\n */\n async getTokenDecimals(address: string): Promise<string> {\n const contract = new Contract(address, abiERC20, this.provider);\n try {\n const decimals = await contract.decimals();\n return decimals.toString();\n } catch (err) {\n // Mirror previous implementation\n if (\n err instanceof Error &&\n err.message.includes('call revert exception')\n ) {\n throw new Error('Failed to parse token decimals');\n }\n throw err;\n }\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract string.\n * @returns Promise resolving to the 'name'.\n */\n async getTokenName(address: string): Promise<string> {\n const contract = new Contract(address, abiERC20, this.provider);\n try {\n const name = await contract.name();\n return name.toString();\n } catch (err) {\n // Mirror previous implementation\n if (\n err instanceof Error &&\n err.message.includes('call revert exception')\n ) {\n throw new Error('Failed to parse token name');\n }\n throw err;\n }\n }\n\n /**\n * Query for symbol for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @returns Promise resolving to the 'symbol'.\n */\n async getTokenSymbol(address: string): Promise<string> {\n // Signature for calling `symbol()`\n const payload = { to: address, data: '0x95d89b41' };\n const result = await this.provider.call(payload);\n assertIsStrictHexString(result);\n // Parse as string - treat empty string as failure\n try {\n const decoded = decodeSingle('string', result);\n if (decoded?.length > 0) {\n return decoded;\n }\n } catch {\n // Ignore error\n }\n\n // Parse as bytes - treat empty string as failure\n try {\n const utf8 = toUtf8(result);\n if (utf8.length > 0) {\n return utf8;\n }\n } catch {\n // Ignore error\n }\n\n throw new Error('Failed to parse token symbol');\n }\n\n /**\n * Query if a contract implements an interface.\n *\n * @param address - Asset contract address.\n * @param userAddress - The public address for the currently active user's account.\n * @returns Promise resolving an object containing the standard, decimals, symbol and balance of the given contract/userAddress pair.\n */\n async getDetails(\n address: string,\n userAddress?: string,\n ): Promise<{\n standard: string;\n symbol: string | undefined;\n decimals: string | undefined;\n balance: BN | undefined;\n }> {\n const [decimals, symbol, balance] = await Promise.all([\n this.getTokenDecimals(address),\n this.getTokenSymbol(address),\n userAddress ? this.getBalanceOf(address, userAddress) : undefined,\n ]);\n return {\n decimals,\n symbol,\n balance,\n standard: ERC20,\n };\n }\n}\n"]}
|
|
@@ -45,14 +45,14 @@ export type TokenBalancesPollingInput = {
|
|
|
45
45
|
chainId: Hex;
|
|
46
46
|
};
|
|
47
47
|
declare const TokenBalancesController_base: (abstract new (...args: any[]) => {
|
|
48
|
-
readonly "__#
|
|
49
|
-
"__#
|
|
48
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
49
|
+
"__#787811@#intervalLength": number | undefined;
|
|
50
50
|
setIntervalLength(intervalLength: number): void;
|
|
51
51
|
getIntervalLength(): number | undefined;
|
|
52
52
|
_startPolling(input: TokenBalancesPollingInput): void;
|
|
53
53
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
54
|
-
readonly "__#
|
|
55
|
-
"__#
|
|
54
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
55
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenBalancesPollingInput) => void>>;
|
|
56
56
|
_executePoll(input: TokenBalancesPollingInput): Promise<void>;
|
|
57
57
|
startPolling(input: TokenBalancesPollingInput): string;
|
|
58
58
|
stopAllPolling(): void;
|
|
@@ -45,14 +45,14 @@ export type TokenBalancesPollingInput = {
|
|
|
45
45
|
chainId: Hex;
|
|
46
46
|
};
|
|
47
47
|
declare const TokenBalancesController_base: (abstract new (...args: any[]) => {
|
|
48
|
-
readonly "__#
|
|
49
|
-
"__#
|
|
48
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
49
|
+
"__#787811@#intervalLength": number | undefined;
|
|
50
50
|
setIntervalLength(intervalLength: number): void;
|
|
51
51
|
getIntervalLength(): number | undefined;
|
|
52
52
|
_startPolling(input: TokenBalancesPollingInput): void;
|
|
53
53
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
54
|
-
readonly "__#
|
|
55
|
-
"__#
|
|
54
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
55
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenBalancesPollingInput) => void>>;
|
|
56
56
|
_executePoll(input: TokenBalancesPollingInput): Promise<void>;
|
|
57
57
|
startPolling(input: TokenBalancesPollingInput): string;
|
|
58
58
|
stopAllPolling(): void;
|
|
@@ -34,14 +34,14 @@ type TokenDetectionPollingInput = {
|
|
|
34
34
|
address: string;
|
|
35
35
|
};
|
|
36
36
|
declare const TokenDetectionController_base: (abstract new (...args: any[]) => {
|
|
37
|
-
readonly "__#
|
|
38
|
-
"__#
|
|
37
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
38
|
+
"__#787811@#intervalLength": number | undefined;
|
|
39
39
|
setIntervalLength(intervalLength: number): void;
|
|
40
40
|
getIntervalLength(): number | undefined;
|
|
41
41
|
_startPolling(input: TokenDetectionPollingInput): void;
|
|
42
42
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
43
|
-
readonly "__#
|
|
44
|
-
"__#
|
|
43
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
44
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenDetectionPollingInput) => void>>;
|
|
45
45
|
_executePoll(input: TokenDetectionPollingInput): Promise<void>;
|
|
46
46
|
startPolling(input: TokenDetectionPollingInput): string;
|
|
47
47
|
stopAllPolling(): void;
|
|
@@ -34,14 +34,14 @@ type TokenDetectionPollingInput = {
|
|
|
34
34
|
address: string;
|
|
35
35
|
};
|
|
36
36
|
declare const TokenDetectionController_base: (abstract new (...args: any[]) => {
|
|
37
|
-
readonly "__#
|
|
38
|
-
"__#
|
|
37
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
38
|
+
"__#787811@#intervalLength": number | undefined;
|
|
39
39
|
setIntervalLength(intervalLength: number): void;
|
|
40
40
|
getIntervalLength(): number | undefined;
|
|
41
41
|
_startPolling(input: TokenDetectionPollingInput): void;
|
|
42
42
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
43
|
-
readonly "__#
|
|
44
|
-
"__#
|
|
43
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
44
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenDetectionPollingInput) => void>>;
|
|
45
45
|
_executePoll(input: TokenDetectionPollingInput): Promise<void>;
|
|
46
46
|
startPolling(input: TokenDetectionPollingInput): string;
|
|
47
47
|
stopAllPolling(): void;
|
|
@@ -37,14 +37,14 @@ type TokenListPollingInput = {
|
|
|
37
37
|
chainId: Hex;
|
|
38
38
|
};
|
|
39
39
|
declare const TokenListController_base: (abstract new (...args: any[]) => {
|
|
40
|
-
readonly "__#
|
|
41
|
-
"__#
|
|
40
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
41
|
+
"__#787811@#intervalLength": number | undefined;
|
|
42
42
|
setIntervalLength(intervalLength: number): void;
|
|
43
43
|
getIntervalLength(): number | undefined;
|
|
44
44
|
_startPolling(input: TokenListPollingInput): void;
|
|
45
45
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
46
|
-
readonly "__#
|
|
47
|
-
"__#
|
|
46
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
47
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenListPollingInput) => void>>;
|
|
48
48
|
_executePoll(input: TokenListPollingInput): Promise<void>;
|
|
49
49
|
startPolling(input: TokenListPollingInput): string;
|
|
50
50
|
stopAllPolling(): void;
|
|
@@ -37,14 +37,14 @@ type TokenListPollingInput = {
|
|
|
37
37
|
chainId: Hex;
|
|
38
38
|
};
|
|
39
39
|
declare const TokenListController_base: (abstract new (...args: any[]) => {
|
|
40
|
-
readonly "__#
|
|
41
|
-
"__#
|
|
40
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
41
|
+
"__#787811@#intervalLength": number | undefined;
|
|
42
42
|
setIntervalLength(intervalLength: number): void;
|
|
43
43
|
getIntervalLength(): number | undefined;
|
|
44
44
|
_startPolling(input: TokenListPollingInput): void;
|
|
45
45
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
46
|
-
readonly "__#
|
|
47
|
-
"__#
|
|
46
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
47
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenListPollingInput) => void>>;
|
|
48
48
|
_executePoll(input: TokenListPollingInput): Promise<void>;
|
|
49
49
|
startPolling(input: TokenListPollingInput): string;
|
|
50
50
|
stopAllPolling(): void;
|
|
@@ -108,14 +108,14 @@ export type TokenRatesPollingInput = {
|
|
|
108
108
|
chainId: Hex;
|
|
109
109
|
};
|
|
110
110
|
declare const TokenRatesController_base: (abstract new (...args: any[]) => {
|
|
111
|
-
readonly "__#
|
|
112
|
-
"__#
|
|
111
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
112
|
+
"__#787811@#intervalLength": number | undefined;
|
|
113
113
|
setIntervalLength(intervalLength: number): void;
|
|
114
114
|
getIntervalLength(): number | undefined;
|
|
115
115
|
_startPolling(input: TokenRatesPollingInput): void;
|
|
116
116
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
117
|
-
readonly "__#
|
|
118
|
-
"__#
|
|
117
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
118
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenRatesPollingInput) => void>>;
|
|
119
119
|
_executePoll(input: TokenRatesPollingInput): Promise<void>;
|
|
120
120
|
startPolling(input: TokenRatesPollingInput): string;
|
|
121
121
|
stopAllPolling(): void;
|
|
@@ -108,14 +108,14 @@ export type TokenRatesPollingInput = {
|
|
|
108
108
|
chainId: Hex;
|
|
109
109
|
};
|
|
110
110
|
declare const TokenRatesController_base: (abstract new (...args: any[]) => {
|
|
111
|
-
readonly "__#
|
|
112
|
-
"__#
|
|
111
|
+
readonly "__#787811@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
112
|
+
"__#787811@#intervalLength": number | undefined;
|
|
113
113
|
setIntervalLength(intervalLength: number): void;
|
|
114
114
|
getIntervalLength(): number | undefined;
|
|
115
115
|
_startPolling(input: TokenRatesPollingInput): void;
|
|
116
116
|
_stopPollingByPollingTokenSetId(key: string): void;
|
|
117
|
-
readonly "__#
|
|
118
|
-
"__#
|
|
117
|
+
readonly "__#787803@#pollingTokenSets": Map<string, Set<string>>;
|
|
118
|
+
"__#787803@#callbacks": Map<string, Set<(input: TokenRatesPollingInput) => void>>;
|
|
119
119
|
_executePoll(input: TokenRatesPollingInput): Promise<void>;
|
|
120
120
|
startPolling(input: TokenRatesPollingInput): string;
|
|
121
121
|
stopAllPolling(): void;
|
|
@@ -12,7 +12,8 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
12
12
|
var _CodefiTokenPricesServiceV2_tokenPricePolicy;
|
|
13
13
|
import { handleFetch } from "@metamask/controller-utils";
|
|
14
14
|
import { hexToNumber } from "@metamask/utils";
|
|
15
|
-
import
|
|
15
|
+
import $cockatiel from "cockatiel";
|
|
16
|
+
const { circuitBreaker, ConsecutiveBreaker, ExponentialBackoff, handleAll, retry, wrap, CircuitState } = $cockatiel;
|
|
16
17
|
/**
|
|
17
18
|
* The list of currencies that can be supplied as the `vsCurrency` parameter to
|
|
18
19
|
* the `/spot-prices` endpoint, in lowercase form.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codefi-v2.mjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,mCAAmC;AAEzD,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAC9C,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,kBAAkB,EAClB,SAAS,EAET,KAAK,EACL,IAAI,EACJ,YAAY,EACb,kBAAkB;AAQnB;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,UAAU;IACV,KAAK;IACL,QAAQ;IACR,KAAK;IACL,WAAW;IACX,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,SAAS;IACT,KAAK;IACL,YAAY;IACZ,MAAM;IACN,WAAW;IACX,KAAK;IACL,gBAAgB;IAChB,KAAK;IACL,YAAY;IACZ,KAAK;IACL,8BAA8B;IAC9B,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,oBAAoB;IACpB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,cAAc;IACd,KAAK;IACL,kBAAkB;IAClB,KAAK;IACL,cAAc;IACd,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,OA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mB,GAAsB,oBAAoB,CAAC;QACpE,OAAO,CACL,OAAO,QAAQ,KAAK,QAAQ;YAC5B,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\nimport {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n type IPolicy,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Mantle\n '0x1388',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\nconst DEFAULT_TOKEN_PRICE_RETRIES = 3;\n// Each update attempt will result (1 + retries) calls if the server is down\nconst DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES =\n (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;\n\nconst DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n #tokenPricePolicy: IPolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param options - Constructor options\n * @param options.degradedThreshold - The threshold between \"normal\" and \"degrated\" service,\n * in milliseconds.\n * @param options.retries - Number of retry attempts for each token price update.\n * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures\n * allowed before breaking the circuit and pausing further updates.\n * @param options.onBreak - An event handler for when the circuit breaks, useful for capturing\n * metrics about network failures.\n * @param options.onDegraded - An event handler for when the circuit remains closed, but requests\n * are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).\n * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks\n * from too many consecutive failures.\n */\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_TOKEN_PRICE_RETRIES,\n maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = 30 * 60 * 1000,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n // Construct a policy that will retry each update, and halt further updates\n // for a certain period after too many consecutive failures.\n const retryPolicy = retry(handleAll, {\n maxAttempts: retries,\n backoff: new ExponentialBackoff(),\n });\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maximumConsecutiveFailures),\n });\n if (onBreak) {\n circuitBreakerPolicy.onBreak(onBreak);\n }\n if (onDegraded) {\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegraded();\n }\n });\n }\n this.#tokenPricePolicy = wrap(retryPolicy, circuitBreakerPolicy);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [getNativeTokenAddress(chainId), ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#tokenPricePolicy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [getNativeTokenAddress(chainId), ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (!marketData) {\n return obj;\n }\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"codefi-v2.mjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,mCAAmC;AAEzD,OAAO,EAAE,WAAW,EAAE,wBAAwB;;;AAkB9C;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,UAAU;IACV,KAAK;IACL,QAAQ;IACR,KAAK;IACL,WAAW;IACX,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,SAAS;IACT,KAAK;IACL,YAAY;IACZ,MAAM;IACN,WAAW;IACX,KAAK;IACL,gBAAgB;IAChB,KAAK;IACL,YAAY;IACZ,KAAK;IACL,8BAA8B;IAC9B,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,oBAAoB;IACpB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,cAAc;IACd,KAAK;IACL,kBAAkB;IAClB,KAAK;IACL,cAAc;IACd,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,OAAO;IACP,KAAK;IACL,yBAAyB;IACzB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,mBAAmB;I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AmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\nimport {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n type IPolicy,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Mantle\n '0x1388',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\nconst DEFAULT_TOKEN_PRICE_RETRIES = 3;\n// Each update attempt will result (1 + retries) calls if the server is down\nconst DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES =\n (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;\n\nconst DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n #tokenPricePolicy: IPolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param options - Constructor options\n * @param options.degradedThreshold - The threshold between \"normal\" and \"degrated\" service,\n * in milliseconds.\n * @param options.retries - Number of retry attempts for each token price update.\n * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures\n * allowed before breaking the circuit and pausing further updates.\n * @param options.onBreak - An event handler for when the circuit breaks, useful for capturing\n * metrics about network failures.\n * @param options.onDegraded - An event handler for when the circuit remains closed, but requests\n * are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).\n * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks\n * from too many consecutive failures.\n */\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_TOKEN_PRICE_RETRIES,\n maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = 30 * 60 * 1000,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n // Construct a policy that will retry each update, and halt further updates\n // for a certain period after too many consecutive failures.\n const retryPolicy = retry(handleAll, {\n maxAttempts: retries,\n backoff: new ExponentialBackoff(),\n });\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maximumConsecutiveFailures),\n });\n if (onBreak) {\n circuitBreakerPolicy.onBreak(onBreak);\n }\n if (onDegraded) {\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegraded();\n }\n });\n }\n this.#tokenPricePolicy = wrap(retryPolicy, circuitBreakerPolicy);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [getNativeTokenAddress(chainId), ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#tokenPricePolicy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [getNativeTokenAddress(chainId), ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (!marketData) {\n return obj;\n }\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/assets-controllers",
|
|
3
|
-
"version": "45.1.0-preview-
|
|
3
|
+
"version": "45.1.0-preview-e58ce4ab",
|
|
4
4
|
"description": "Controllers which manage interactions involving ERC-20, ERC-721, and ERC-1155 tokens (including NFTs)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -74,7 +74,6 @@
|
|
|
74
74
|
"uuid": "^8.3.2"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@babel/runtime": "^7.23.9",
|
|
78
77
|
"@metamask/accounts-controller": "^20.0.0",
|
|
79
78
|
"@metamask/approval-controller": "^7.1.1",
|
|
80
79
|
"@metamask/auto-changelog": "^3.4.4",
|
|
@@ -83,7 +82,6 @@
|
|
|
83
82
|
"@metamask/keyring-controller": "^19.0.0",
|
|
84
83
|
"@metamask/network-controller": "^22.0.2",
|
|
85
84
|
"@metamask/preferences-controller": "^15.0.0",
|
|
86
|
-
"@metamask/providers": "^18.1.1",
|
|
87
85
|
"@types/jest": "^27.4.1",
|
|
88
86
|
"@types/lodash": "^4.14.191",
|
|
89
87
|
"@types/node": "^16.18.54",
|
|
@@ -95,17 +93,14 @@
|
|
|
95
93
|
"ts-jest": "^27.1.4",
|
|
96
94
|
"typedoc": "^0.24.8",
|
|
97
95
|
"typedoc-plugin-missing-exports": "^2.0.0",
|
|
98
|
-
"typescript": "~5.2.2"
|
|
99
|
-
"webextension-polyfill": "^0.12.0"
|
|
96
|
+
"typescript": "~5.2.2"
|
|
100
97
|
},
|
|
101
98
|
"peerDependencies": {
|
|
102
99
|
"@metamask/accounts-controller": "^20.0.0",
|
|
103
100
|
"@metamask/approval-controller": "^7.0.0",
|
|
104
101
|
"@metamask/keyring-controller": "^19.0.0",
|
|
105
102
|
"@metamask/network-controller": "^22.0.0",
|
|
106
|
-
"@metamask/preferences-controller": "^15.0.0"
|
|
107
|
-
"@metamask/providers": "^18.1.0",
|
|
108
|
-
"webextension-polyfill": "^0.10.0 || ^0.11.0 || ^0.12.0"
|
|
103
|
+
"@metamask/preferences-controller": "^15.0.0"
|
|
109
104
|
},
|
|
110
105
|
"engines": {
|
|
111
106
|
"node": "^18.18 || >=20"
|