@metamask/assets-controllers 1.0.0

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +20 -0
  3. package/README.md +30 -0
  4. package/dist/AccountTrackerController.d.ts +88 -0
  5. package/dist/AccountTrackerController.js +138 -0
  6. package/dist/AccountTrackerController.js.map +1 -0
  7. package/dist/AssetsContractController.d.ts +176 -0
  8. package/dist/AssetsContractController.js +314 -0
  9. package/dist/AssetsContractController.js.map +1 -0
  10. package/dist/CurrencyRateController.d.ts +98 -0
  11. package/dist/CurrencyRateController.js +193 -0
  12. package/dist/CurrencyRateController.js.map +1 -0
  13. package/dist/NftController.d.ts +409 -0
  14. package/dist/NftController.js +835 -0
  15. package/dist/NftController.js.map +1 -0
  16. package/dist/NftDetectionController.d.ts +179 -0
  17. package/dist/NftDetectionController.js +204 -0
  18. package/dist/NftDetectionController.js.map +1 -0
  19. package/dist/Standards/ERC20Standard.d.ts +42 -0
  20. package/dist/Standards/ERC20Standard.js +121 -0
  21. package/dist/Standards/ERC20Standard.js.map +1 -0
  22. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts +78 -0
  23. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +148 -0
  24. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -0
  25. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts +88 -0
  26. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +182 -0
  27. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -0
  28. package/dist/Standards/standards-types.d.ts +14 -0
  29. package/dist/Standards/standards-types.js +3 -0
  30. package/dist/Standards/standards-types.js.map +1 -0
  31. package/dist/TokenBalancesController.d.ts +69 -0
  32. package/dist/TokenBalancesController.js +94 -0
  33. package/dist/TokenBalancesController.js.map +1 -0
  34. package/dist/TokenDetectionController.d.ts +84 -0
  35. package/dist/TokenDetectionController.js +185 -0
  36. package/dist/TokenDetectionController.js.map +1 -0
  37. package/dist/TokenListController.d.ts +114 -0
  38. package/dist/TokenListController.js +256 -0
  39. package/dist/TokenListController.js.map +1 -0
  40. package/dist/TokenRatesController.d.ts +167 -0
  41. package/dist/TokenRatesController.js +284 -0
  42. package/dist/TokenRatesController.js.map +1 -0
  43. package/dist/TokensController.d.ts +238 -0
  44. package/dist/TokensController.js +530 -0
  45. package/dist/TokensController.js.map +1 -0
  46. package/dist/assetsUtil.d.ts +106 -0
  47. package/dist/assetsUtil.js +228 -0
  48. package/dist/assetsUtil.js.map +1 -0
  49. package/dist/crypto-compare.d.ts +12 -0
  50. package/dist/crypto-compare.js +67 -0
  51. package/dist/crypto-compare.js.map +1 -0
  52. package/dist/index.d.ts +11 -0
  53. package/dist/index.js +31 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/token-service.d.ts +29 -0
  56. package/dist/token-service.js +134 -0
  57. package/dist/token-service.js.map +1 -0
  58. package/package.json +75 -0
@@ -0,0 +1,106 @@
1
+ /// <reference types="bn.js" />
2
+ import { BigNumber } from '@ethersproject/bignumber';
3
+ import { BN } from 'ethereumjs-util';
4
+ import { Nft, NftMetadata } from './NftController';
5
+ import { Token } from './TokenRatesController';
6
+ /**
7
+ * Compares nft metadata entries to any nft entry.
8
+ * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,
9
+ * there's a need to update the nft in state.
10
+ *
11
+ * @param newNftMetadata - Nft metadata object.
12
+ * @param nft - Nft object to compare with.
13
+ * @returns Whether there are differences.
14
+ */
15
+ export declare function compareNftMetadata(newNftMetadata: NftMetadata, nft: Nft): boolean;
16
+ /**
17
+ * Formats aggregator names to presentable format.
18
+ *
19
+ * @param aggregators - List of token list names in camelcase.
20
+ * @returns Formatted aggregator names.
21
+ */
22
+ export declare const formatAggregatorNames: (aggregators: string[]) => string[];
23
+ /**
24
+ * Format token list assets to use image proxy from Codefi.
25
+ *
26
+ * @param params - Object that contains chainID and tokenAddress.
27
+ * @param params.chainId - ChainID of network in decimal or hexadecimal format.
28
+ * @param params.tokenAddress - Address of token in mixed or lowercase.
29
+ * @returns Formatted image url
30
+ */
31
+ export declare const formatIconUrlWithProxy: ({ chainId, tokenAddress, }: {
32
+ chainId: string;
33
+ tokenAddress: string;
34
+ }) => string;
35
+ /**
36
+ * Validates a ERC20 token to be added with EIP747.
37
+ *
38
+ * @param token - Token object to validate.
39
+ */
40
+ export declare function validateTokenToWatch(token: Token): void;
41
+ /**
42
+ * Networks where token detection is supported - Values are in decimal format
43
+ */
44
+ export declare enum SupportedTokenDetectionNetworks {
45
+ mainnet = "1",
46
+ bsc = "56",
47
+ polygon = "137",
48
+ avax = "43114"
49
+ }
50
+ /**
51
+ * Check if token detection is enabled for certain networks.
52
+ *
53
+ * @param chainId - ChainID of network
54
+ * @returns Whether the current network supports token detection
55
+ */
56
+ export declare function isTokenDetectionSupportedForNetwork(chainId: string): boolean;
57
+ /**
58
+ * Check if token list polling is enabled for a given network.
59
+ * Currently this method is used to support e2e testing for consumers of this package.
60
+ *
61
+ * @param chainId - ChainID of network
62
+ * @returns Whether the current network supports tokenlists
63
+ */
64
+ export declare function isTokenListSupportedForNetwork(chainId: string): boolean;
65
+ /**
66
+ * Removes IPFS protocol prefix from input string.
67
+ *
68
+ * @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})
69
+ * @returns IPFS content identifier and (possibly) path in a string
70
+ * @throws Will throw if the url passed is not IPFS.
71
+ */
72
+ export declare function removeIpfsProtocolPrefix(ipfsUrl: string): string;
73
+ /**
74
+ * Extracts content identifier and path from an input string.
75
+ *
76
+ * @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix
77
+ * @returns IFPS content identifier (cid) and sub path as string.
78
+ * @throws Will throw if the url passed is not ipfs.
79
+ */
80
+ export declare function getIpfsCIDv1AndPath(ipfsUrl: string): {
81
+ cid: string;
82
+ path?: string;
83
+ };
84
+ /**
85
+ * Formats URL correctly for use retrieving assets hosted on IPFS.
86
+ *
87
+ * @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).
88
+ * @param ipfsUrl - The IFPS URL pointed at the asset.
89
+ * @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.
90
+ * @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.
91
+ */
92
+ export declare function getFormattedIpfsUrl(ipfsGateway: string, ipfsUrl: string, subdomainSupported: boolean): string;
93
+ /**
94
+ * Adds URL protocol prefix to input URL string if missing.
95
+ *
96
+ * @param urlString - An IPFS URL.
97
+ * @returns A URL with a https:// prepended.
98
+ */
99
+ export declare function addUrlProtocolPrefix(urlString: string): string;
100
+ /**
101
+ * Converts an Ethers BigNumber to a BN.
102
+ *
103
+ * @param bigNumber - An Ethers BigNumber instance.
104
+ * @returns A BN object.
105
+ */
106
+ export declare function ethersBigNumberToBN(bigNumber: BigNumber): BN;
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ethersBigNumberToBN = exports.addUrlProtocolPrefix = exports.getFormattedIpfsUrl = exports.getIpfsCIDv1AndPath = exports.removeIpfsProtocolPrefix = exports.isTokenListSupportedForNetwork = exports.isTokenDetectionSupportedForNetwork = exports.SupportedTokenDetectionNetworks = exports.validateTokenToWatch = exports.formatIconUrlWithProxy = exports.formatAggregatorNames = exports.compareNftMetadata = void 0;
4
+ const eth_rpc_errors_1 = require("eth-rpc-errors");
5
+ const cid_1 = require("multiformats/cid");
6
+ const controller_utils_1 = require("@metamask/controller-utils");
7
+ const ethereumjs_util_1 = require("ethereumjs-util");
8
+ /**
9
+ * Compares nft metadata entries to any nft entry.
10
+ * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,
11
+ * there's a need to update the nft in state.
12
+ *
13
+ * @param newNftMetadata - Nft metadata object.
14
+ * @param nft - Nft object to compare with.
15
+ * @returns Whether there are differences.
16
+ */
17
+ function compareNftMetadata(newNftMetadata, nft) {
18
+ const keys = [
19
+ 'image',
20
+ 'backgroundColor',
21
+ 'imagePreview',
22
+ 'imageThumbnail',
23
+ 'imageOriginal',
24
+ 'animation',
25
+ 'animationOriginal',
26
+ 'externalLink',
27
+ ];
28
+ const differentValues = keys.reduce((value, key) => {
29
+ if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {
30
+ return value + 1;
31
+ }
32
+ return value;
33
+ }, 0);
34
+ return differentValues > 0;
35
+ }
36
+ exports.compareNftMetadata = compareNftMetadata;
37
+ const aggregatorNameByKey = {
38
+ aave: 'Aave',
39
+ bancor: 'Bancor',
40
+ cmc: 'CMC',
41
+ cryptocom: 'Crypto.com',
42
+ coinGecko: 'CoinGecko',
43
+ oneInch: '1inch',
44
+ paraswap: 'Paraswap',
45
+ pmm: 'PMM',
46
+ zapper: 'Zapper',
47
+ zerion: 'Zerion',
48
+ zeroEx: '0x',
49
+ synthetix: 'Synthetix',
50
+ yearn: 'Yearn',
51
+ apeswap: 'ApeSwap',
52
+ binanceDex: 'BinanceDex',
53
+ pancakeTop100: 'PancakeTop100',
54
+ pancakeExtended: 'PancakeExtended',
55
+ balancer: 'Balancer',
56
+ quickswap: 'QuickSwap',
57
+ matcha: 'Matcha',
58
+ pangolinDex: 'PangolinDex',
59
+ pangolinDexStableCoin: 'PangolinDexStableCoin',
60
+ pangolinDexAvaxBridge: 'PangolinDexAvaxBridge',
61
+ traderJoe: 'TraderJoe',
62
+ airswapLight: 'AirswapLight',
63
+ kleros: 'Kleros',
64
+ };
65
+ /**
66
+ * Formats aggregator names to presentable format.
67
+ *
68
+ * @param aggregators - List of token list names in camelcase.
69
+ * @returns Formatted aggregator names.
70
+ */
71
+ const formatAggregatorNames = (aggregators) => {
72
+ return aggregators.map((key) => aggregatorNameByKey[key] ||
73
+ `${key[0].toUpperCase()}${key.substring(1, key.length)}`);
74
+ };
75
+ exports.formatAggregatorNames = formatAggregatorNames;
76
+ /**
77
+ * Format token list assets to use image proxy from Codefi.
78
+ *
79
+ * @param params - Object that contains chainID and tokenAddress.
80
+ * @param params.chainId - ChainID of network in decimal or hexadecimal format.
81
+ * @param params.tokenAddress - Address of token in mixed or lowercase.
82
+ * @returns Formatted image url
83
+ */
84
+ const formatIconUrlWithProxy = ({ chainId, tokenAddress, }) => {
85
+ const chainIdDecimal = (0, controller_utils_1.convertHexToDecimal)(chainId).toString();
86
+ return `https://static.metaswap.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;
87
+ };
88
+ exports.formatIconUrlWithProxy = formatIconUrlWithProxy;
89
+ /**
90
+ * Validates a ERC20 token to be added with EIP747.
91
+ *
92
+ * @param token - Token object to validate.
93
+ */
94
+ function validateTokenToWatch(token) {
95
+ const { address, symbol, decimals } = token;
96
+ if (!address || !symbol || typeof decimals === 'undefined') {
97
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams(`Must specify address, symbol, and decimals.`);
98
+ }
99
+ if (typeof symbol !== 'string') {
100
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams(`Invalid symbol: not a string.`);
101
+ }
102
+ if (symbol.length > 11) {
103
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams(`Invalid symbol "${symbol}": longer than 11 characters.`);
104
+ }
105
+ const numDecimals = parseInt(decimals, 10);
106
+ if (isNaN(numDecimals) || numDecimals > 36 || numDecimals < 0) {
107
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams(`Invalid decimals "${decimals}": must be 0 <= 36.`);
108
+ }
109
+ if (!(0, controller_utils_1.isValidHexAddress)(address)) {
110
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams(`Invalid address "${address}".`);
111
+ }
112
+ }
113
+ exports.validateTokenToWatch = validateTokenToWatch;
114
+ /**
115
+ * Networks where token detection is supported - Values are in decimal format
116
+ */
117
+ var SupportedTokenDetectionNetworks;
118
+ (function (SupportedTokenDetectionNetworks) {
119
+ SupportedTokenDetectionNetworks["mainnet"] = "1";
120
+ SupportedTokenDetectionNetworks["bsc"] = "56";
121
+ SupportedTokenDetectionNetworks["polygon"] = "137";
122
+ SupportedTokenDetectionNetworks["avax"] = "43114";
123
+ })(SupportedTokenDetectionNetworks = exports.SupportedTokenDetectionNetworks || (exports.SupportedTokenDetectionNetworks = {}));
124
+ /**
125
+ * Check if token detection is enabled for certain networks.
126
+ *
127
+ * @param chainId - ChainID of network
128
+ * @returns Whether the current network supports token detection
129
+ */
130
+ function isTokenDetectionSupportedForNetwork(chainId) {
131
+ return Object.values(SupportedTokenDetectionNetworks).includes(chainId);
132
+ }
133
+ exports.isTokenDetectionSupportedForNetwork = isTokenDetectionSupportedForNetwork;
134
+ /**
135
+ * Check if token list polling is enabled for a given network.
136
+ * Currently this method is used to support e2e testing for consumers of this package.
137
+ *
138
+ * @param chainId - ChainID of network
139
+ * @returns Whether the current network supports tokenlists
140
+ */
141
+ function isTokenListSupportedForNetwork(chainId) {
142
+ const chainIdDecimal = (0, controller_utils_1.convertHexToDecimal)(chainId).toString();
143
+ return (isTokenDetectionSupportedForNetwork(chainIdDecimal) ||
144
+ chainIdDecimal === controller_utils_1.GANACHE_CHAIN_ID);
145
+ }
146
+ exports.isTokenListSupportedForNetwork = isTokenListSupportedForNetwork;
147
+ /**
148
+ * Removes IPFS protocol prefix from input string.
149
+ *
150
+ * @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})
151
+ * @returns IPFS content identifier and (possibly) path in a string
152
+ * @throws Will throw if the url passed is not IPFS.
153
+ */
154
+ function removeIpfsProtocolPrefix(ipfsUrl) {
155
+ if (ipfsUrl.startsWith('ipfs://ipfs/')) {
156
+ return ipfsUrl.replace('ipfs://ipfs/', '');
157
+ }
158
+ else if (ipfsUrl.startsWith('ipfs://')) {
159
+ return ipfsUrl.replace('ipfs://', '');
160
+ }
161
+ // this method should not be used with non-ipfs urls (i.e. startsWith('ipfs://') === true)
162
+ throw new Error('this method should not be used with non ipfs urls');
163
+ }
164
+ exports.removeIpfsProtocolPrefix = removeIpfsProtocolPrefix;
165
+ /**
166
+ * Extracts content identifier and path from an input string.
167
+ *
168
+ * @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix
169
+ * @returns IFPS content identifier (cid) and sub path as string.
170
+ * @throws Will throw if the url passed is not ipfs.
171
+ */
172
+ function getIpfsCIDv1AndPath(ipfsUrl) {
173
+ const url = removeIpfsProtocolPrefix(ipfsUrl);
174
+ // check if there is a path
175
+ // (CID is everything preceding first forward slash, path is everything after)
176
+ const index = url.indexOf('/');
177
+ const cid = index !== -1 ? url.substring(0, index) : url;
178
+ const path = index !== -1 ? url.substring(index) : undefined;
179
+ // We want to ensure that the CID is v1 (https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)
180
+ // because most cid v0s appear to be incompatible with IPFS subdomains
181
+ return {
182
+ cid: cid_1.CID.parse(cid).toV1().toString(),
183
+ path,
184
+ };
185
+ }
186
+ exports.getIpfsCIDv1AndPath = getIpfsCIDv1AndPath;
187
+ /**
188
+ * Formats URL correctly for use retrieving assets hosted on IPFS.
189
+ *
190
+ * @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).
191
+ * @param ipfsUrl - The IFPS URL pointed at the asset.
192
+ * @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.
193
+ * @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.
194
+ */
195
+ function getFormattedIpfsUrl(ipfsGateway, ipfsUrl, subdomainSupported) {
196
+ const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));
197
+ if (subdomainSupported) {
198
+ const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);
199
+ return `${protocol}//${cid}.ipfs.${host}${path !== null && path !== void 0 ? path : ''}`;
200
+ }
201
+ const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);
202
+ return `${origin}/ipfs/${cidAndPath}`;
203
+ }
204
+ exports.getFormattedIpfsUrl = getFormattedIpfsUrl;
205
+ /**
206
+ * Adds URL protocol prefix to input URL string if missing.
207
+ *
208
+ * @param urlString - An IPFS URL.
209
+ * @returns A URL with a https:// prepended.
210
+ */
211
+ function addUrlProtocolPrefix(urlString) {
212
+ if (!urlString.match(/(^http:\/\/)|(^https:\/\/)/u)) {
213
+ return `https://${urlString}`;
214
+ }
215
+ return urlString;
216
+ }
217
+ exports.addUrlProtocolPrefix = addUrlProtocolPrefix;
218
+ /**
219
+ * Converts an Ethers BigNumber to a BN.
220
+ *
221
+ * @param bigNumber - An Ethers BigNumber instance.
222
+ * @returns A BN object.
223
+ */
224
+ function ethersBigNumberToBN(bigNumber) {
225
+ return new ethereumjs_util_1.BN((0, ethereumjs_util_1.stripHexPrefix)(bigNumber.toHexString()), 'hex');
226
+ }
227
+ exports.ethersBigNumberToBN = ethersBigNumberToBN;
228
+ //# sourceMappingURL=assetsUtil.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assetsUtil.js","sourceRoot":"","sources":["../src/assetsUtil.ts"],"names":[],"mappings":";;;AAAA,mDAA2C;AAC3C,0CAAuC;AACvC,iEAIoC;AAEpC,qDAAqD;AAIrD;;;;;;;;GAQG;AACH,SAAgB,kBAAkB,CAAC,cAA2B,EAAE,GAAQ;IACtE,MAAM,IAAI,GAA0B;QAClC,OAAO;QACP,iBAAiB;QACjB,cAAc;QACd,gBAAgB;QAChB,eAAe;QACf,WAAW;QACX,mBAAmB;QACnB,cAAc;KACf,CAAC;IACF,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACjD,IAAI,cAAc,CAAC,GAAG,CAAC,IAAI,cAAc,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,EAAE;YAC3D,OAAO,KAAK,GAAG,CAAC,CAAC;SAClB;QACD,OAAO,KAAK,CAAC;IACf,CAAC,EAAE,CAAC,CAAC,CAAC;IACN,OAAO,eAAe,GAAG,CAAC,CAAC;AAC7B,CAAC;AAlBD,gDAkBC;AAED,MAAM,mB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exAddress,\n GANACHE_CHAIN_ID,\n} from '@metamask/controller-utils';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { BN, stripHexPrefix } from 'ethereumjs-util';\nimport { Nft, NftMetadata } from './NftController';\nimport { Token } from './TokenRatesController';\n\n/**\n * Compares nft metadata entries to any nft entry.\n * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,\n * there's a need to update the nft in state.\n *\n * @param newNftMetadata - Nft metadata object.\n * @param nft - Nft object to compare with.\n * @returns Whether there are differences.\n */\nexport function compareNftMetadata(newNftMetadata: NftMetadata, nft: Nft) {\n const keys: (keyof NftMetadata)[] = [\n 'image',\n 'backgroundColor',\n 'imagePreview',\n 'imageThumbnail',\n 'imageOriginal',\n 'animation',\n 'animationOriginal',\n 'externalLink',\n ];\n const differentValues = keys.reduce((value, key) => {\n if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {\n return value + 1;\n }\n return value;\n }, 0);\n return differentValues > 0;\n}\n\nconst aggregatorNameByKey: Record<string, string> = {\n aave: 'Aave',\n bancor: 'Bancor',\n cmc: 'CMC',\n cryptocom: 'Crypto.com',\n coinGecko: 'CoinGecko',\n oneInch: '1inch',\n paraswap: 'Paraswap',\n pmm: 'PMM',\n zapper: 'Zapper',\n zerion: 'Zerion',\n zeroEx: '0x',\n synthetix: 'Synthetix',\n yearn: 'Yearn',\n apeswap: 'ApeSwap',\n binanceDex: 'BinanceDex',\n pancakeTop100: 'PancakeTop100',\n pancakeExtended: 'PancakeExtended',\n balancer: 'Balancer',\n quickswap: 'QuickSwap',\n matcha: 'Matcha',\n pangolinDex: 'PangolinDex',\n pangolinDexStableCoin: 'PangolinDexStableCoin',\n pangolinDexAvaxBridge: 'PangolinDexAvaxBridge',\n traderJoe: 'TraderJoe',\n airswapLight: 'AirswapLight',\n kleros: 'Kleros',\n};\n\n/**\n * Formats aggregator names to presentable format.\n *\n * @param aggregators - List of token list names in camelcase.\n * @returns Formatted aggregator names.\n */\nexport const formatAggregatorNames = (aggregators: string[]) => {\n return aggregators.map(\n (key) =>\n aggregatorNameByKey[key] ||\n `${key[0].toUpperCase()}${key.substring(1, key.length)}`,\n );\n};\n\n/**\n * Format token list assets to use image proxy from Codefi.\n *\n * @param params - Object that contains chainID and tokenAddress.\n * @param params.chainId - ChainID of network in decimal or hexadecimal format.\n * @param params.tokenAddress - Address of token in mixed or lowercase.\n * @returns Formatted image url\n */\nexport const formatIconUrlWithProxy = ({\n chainId,\n tokenAddress,\n}: {\n chainId: string;\n tokenAddress: string;\n}) => {\n const chainIdDecimal = convertHexToDecimal(chainId).toString();\n return `https://static.metaswap.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;\n};\n\n/**\n * Validates a ERC20 token to be added with EIP747.\n *\n * @param token - Token object to validate.\n */\nexport function validateTokenToWatch(token: Token) {\n const { address, symbol, decimals } = token;\n if (!address || !symbol || typeof decimals === 'undefined') {\n throw ethErrors.rpc.invalidParams(\n `Must specify address, symbol, and decimals.`,\n );\n }\n\n if (typeof symbol !== 'string') {\n throw ethErrors.rpc.invalidParams(`Invalid symbol: not a string.`);\n }\n\n if (symbol.length > 11) {\n throw ethErrors.rpc.invalidParams(\n `Invalid symbol \"${symbol}\": longer than 11 characters.`,\n );\n }\n const numDecimals = parseInt(decimals as unknown as string, 10);\n if (isNaN(numDecimals) || numDecimals > 36 || numDecimals < 0) {\n throw ethErrors.rpc.invalidParams(\n `Invalid decimals \"${decimals}\": must be 0 <= 36.`,\n );\n }\n\n if (!isValidHexAddress(address)) {\n throw ethErrors.rpc.invalidParams(`Invalid address \"${address}\".`);\n }\n}\n\n/**\n * Networks where token detection is supported - Values are in decimal format\n */\nexport enum SupportedTokenDetectionNetworks {\n mainnet = '1',\n bsc = '56',\n polygon = '137',\n avax = '43114',\n}\n\n/**\n * Check if token detection is enabled for certain networks.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport function isTokenDetectionSupportedForNetwork(chainId: string): boolean {\n return Object.values<string>(SupportedTokenDetectionNetworks).includes(\n chainId,\n );\n}\n\n/**\n * Check if token list polling is enabled for a given network.\n * Currently this method is used to support e2e testing for consumers of this package.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports tokenlists\n */\nexport function isTokenListSupportedForNetwork(chainId: string): boolean {\n const chainIdDecimal = convertHexToDecimal(chainId).toString();\n return (\n isTokenDetectionSupportedForNetwork(chainIdDecimal) ||\n chainIdDecimal === GANACHE_CHAIN_ID\n );\n}\n\n/**\n * Removes IPFS protocol prefix from input string.\n *\n * @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})\n * @returns IPFS content identifier and (possibly) path in a string\n * @throws Will throw if the url passed is not IPFS.\n */\nexport function removeIpfsProtocolPrefix(ipfsUrl: string) {\n if (ipfsUrl.startsWith('ipfs://ipfs/')) {\n return ipfsUrl.replace('ipfs://ipfs/', '');\n } else if (ipfsUrl.startsWith('ipfs://')) {\n return ipfsUrl.replace('ipfs://', '');\n }\n // this method should not be used with non-ipfs urls (i.e. startsWith('ipfs://') === true)\n throw new Error('this method should not be used with non ipfs urls');\n}\n\n/**\n * Extracts content identifier and path from an input string.\n *\n * @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix\n * @returns IFPS content identifier (cid) and sub path as string.\n * @throws Will throw if the url passed is not ipfs.\n */\nexport function getIpfsCIDv1AndPath(ipfsUrl: string): {\n cid: string;\n path?: string;\n} {\n const url = removeIpfsProtocolPrefix(ipfsUrl);\n\n // check if there is a path\n // (CID is everything preceding first forward slash, path is everything after)\n const index = url.indexOf('/');\n const cid = index !== -1 ? url.substring(0, index) : url;\n const path = index !== -1 ? url.substring(index) : undefined;\n\n // We want to ensure that the CID is v1 (https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)\n // because most cid v0s appear to be incompatible with IPFS subdomains\n return {\n cid: CID.parse(cid).toV1().toString(),\n path,\n };\n}\n\n/**\n * Formats URL correctly for use retrieving assets hosted on IPFS.\n *\n * @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).\n * @param ipfsUrl - The IFPS URL pointed at the asset.\n * @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.\n * @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.\n */\nexport function getFormattedIpfsUrl(\n ipfsGateway: string,\n ipfsUrl: string,\n subdomainSupported: boolean,\n): string {\n const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));\n if (subdomainSupported) {\n const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);\n return `${protocol}//${cid}.ipfs.${host}${path ?? ''}`;\n }\n const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);\n return `${origin}/ipfs/${cidAndPath}`;\n}\n\n/**\n * Adds URL protocol prefix to input URL string if missing.\n *\n * @param urlString - An IPFS URL.\n * @returns A URL with a https:// prepended.\n */\nexport function addUrlProtocolPrefix(urlString: string): string {\n if (!urlString.match(/(^http:\\/\\/)|(^https:\\/\\/)/u)) {\n return `https://${urlString}`;\n }\n return urlString;\n}\n\n/**\n * Converts an Ethers BigNumber to a BN.\n *\n * @param bigNumber - An Ethers BigNumber instance.\n * @returns A BN object.\n */\nexport function ethersBigNumberToBN(bigNumber: BigNumber): BN {\n return new BN(stripHexPrefix(bigNumber.toHexString()), 'hex');\n}\n"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Fetches the exchange rate for a given currency.
3
+ *
4
+ * @param currency - ISO 4217 currency code.
5
+ * @param nativeCurrency - Symbol for base asset.
6
+ * @param includeUSDRate - Whether to add the USD rate to the fetch.
7
+ * @returns Promise resolving to exchange rate for given currency.
8
+ */
9
+ export declare function fetchExchangeRate(currency: string, nativeCurrency: string, includeUSDRate?: boolean): Promise<{
10
+ conversionRate: number;
11
+ usdConversionRate: number;
12
+ }>;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.fetchExchangeRate = void 0;
13
+ const controller_utils_1 = require("@metamask/controller-utils");
14
+ /**
15
+ * Get the CryptoCompare API URL for getting the conversion rate from the given native currency to
16
+ * the given currency. Optionally, the conversion rate from the native currency to USD can also be
17
+ * included in the response.
18
+ *
19
+ * @param currentCurrency - The currency to get a conversion rate for.
20
+ * @param nativeCurrency - The native currency to convert from.
21
+ * @param includeUSDRate - Whether or not the native currency to USD conversion rate should be
22
+ * included in the response as well.
23
+ * @returns The API URL for getting the conversion rate.
24
+ */
25
+ function getPricingURL(currentCurrency, nativeCurrency, includeUSDRate) {
26
+ return (`https://min-api.cryptocompare.com/data/price?fsym=` +
27
+ `${nativeCurrency.toUpperCase()}&tsyms=${currentCurrency.toUpperCase()}` +
28
+ `${includeUSDRate && currentCurrency.toUpperCase() !== 'USD' ? ',USD' : ''}`);
29
+ }
30
+ /**
31
+ * Fetches the exchange rate for a given currency.
32
+ *
33
+ * @param currency - ISO 4217 currency code.
34
+ * @param nativeCurrency - Symbol for base asset.
35
+ * @param includeUSDRate - Whether to add the USD rate to the fetch.
36
+ * @returns Promise resolving to exchange rate for given currency.
37
+ */
38
+ function fetchExchangeRate(currency, nativeCurrency, includeUSDRate) {
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ const json = yield (0, controller_utils_1.handleFetch)(getPricingURL(currency, nativeCurrency, includeUSDRate));
41
+ /*
42
+ Example expected error response (if pair is not found)
43
+ {
44
+ Response: "Error",
45
+ Message: "cccagg_or_exchange market does not exist for this coin pair (ETH-<NON_EXISTENT_TOKEN>)",
46
+ HasWarning: false,
47
+ }
48
+ */
49
+ if (json.Response === 'Error') {
50
+ throw new Error(json.Message);
51
+ }
52
+ const conversionRate = Number(json[currency.toUpperCase()]);
53
+ const usdConversionRate = Number(json.USD);
54
+ if (!Number.isFinite(conversionRate)) {
55
+ throw new Error(`Invalid response for ${currency.toUpperCase()}: ${json[currency.toUpperCase()]}`);
56
+ }
57
+ if (includeUSDRate && !Number.isFinite(usdConversionRate)) {
58
+ throw new Error(`Invalid response for usdConversionRate: ${json.USD}`);
59
+ }
60
+ return {
61
+ conversionRate,
62
+ usdConversionRate,
63
+ };
64
+ });
65
+ }
66
+ exports.fetchExchangeRate = fetchExchangeRate;
67
+ //# sourceMappingURL=crypto-compare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto-compare.js","sourceRoot":"","sources":["../src/crypto-compare.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAAyD;AAEzD;;;;;;;;;;GAUG;AACH,SAAS,aAAa,CACpB,eAAuB,EACvB,cAAsB,EACtB,cAAwB;IAExB,OAAO,CACL,oDAAoD;QACpD,GAAG,cAAc,CAAC,WAAW,EAAE,UAAU,eAAe,CAAC,WAAW,EAAE,EAAE;QACxE,GAAG,cAAc,IAAI,eAAe,CAAC,WAAW,EAAE,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAC7E,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAsB,iBAAiB,CACrC,QAAgB,EAChB,cAAsB,EACtB,cAAwB;;QAKxB,MAAM,IAAI,GAAG,MAAM,IAAA,8BAAW,EAC5B,aAAa,CAAC,QAAQ,EAAE,cAAc,EAAE,cAAc,CAAC,CACxD,CAAC;QAEF;;;;;;;UAOE;QACF,IAAI,IAAI,CAAC,QAAQ,KAAK,OAAO,EAAE;YAC7B,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;SAC/B;QAED,MAAM,cAAc,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;QAE5D,MAAM,iBAAiB,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC3C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE;YACpC,MAAM,IAAI,KAAK,CACb,wBAAwB,QAAQ,CAAC,WAAW,EAAE,KAC5C,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAC7B,EAAE,CACH,CAAC;SACH;QAED,IAAI,cAAc,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE;YACzD,MAAM,IAAI,KAAK,CAAC,2CAA2C,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;SACxE;QAED,OAAO;YACL,cAAc;YACd,iBAAiB;SAClB,CAAC;IACJ,CAAC;CAAA;AA3CD,8CA2CC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\n/**\n * Get the CryptoCompare API URL for getting the conversion rate from the given native currency to\n * the given currency. Optionally, the conversion rate from the native currency to USD can also be\n * included in the response.\n *\n * @param currentCurrency - The currency to get a conversion rate for.\n * @param nativeCurrency - The native currency to convert from.\n * @param includeUSDRate - Whether or not the native currency to USD conversion rate should be\n * included in the response as well.\n * @returns The API URL for getting the conversion rate.\n */\nfunction getPricingURL(\n currentCurrency: string,\n nativeCurrency: string,\n includeUSDRate?: boolean,\n) {\n return (\n `https://min-api.cryptocompare.com/data/price?fsym=` +\n `${nativeCurrency.toUpperCase()}&tsyms=${currentCurrency.toUpperCase()}` +\n `${includeUSDRate && currentCurrency.toUpperCase() !== 'USD' ? ',USD' : ''}`\n );\n}\n\n/**\n * Fetches the exchange rate for a given currency.\n *\n * @param currency - ISO 4217 currency code.\n * @param nativeCurrency - Symbol for base asset.\n * @param includeUSDRate - Whether to add the USD rate to the fetch.\n * @returns Promise resolving to exchange rate for given currency.\n */\nexport async function fetchExchangeRate(\n currency: string,\n nativeCurrency: string,\n includeUSDRate?: boolean,\n): Promise<{\n conversionRate: number;\n usdConversionRate: number;\n}> {\n const json = await handleFetch(\n getPricingURL(currency, nativeCurrency, includeUSDRate),\n );\n\n /*\n Example expected error response (if pair is not found)\n {\n Response: \"Error\",\n Message: \"cccagg_or_exchange market does not exist for this coin pair (ETH-<NON_EXISTENT_TOKEN>)\",\n HasWarning: false,\n }\n */\n if (json.Response === 'Error') {\n throw new Error(json.Message);\n }\n\n const conversionRate = Number(json[currency.toUpperCase()]);\n\n const usdConversionRate = Number(json.USD);\n if (!Number.isFinite(conversionRate)) {\n throw new Error(\n `Invalid response for ${currency.toUpperCase()}: ${\n json[currency.toUpperCase()]\n }`,\n );\n }\n\n if (includeUSDRate && !Number.isFinite(usdConversionRate)) {\n throw new Error(`Invalid response for usdConversionRate: ${json.USD}`);\n }\n\n return {\n conversionRate,\n usdConversionRate,\n };\n}\n"]}
@@ -0,0 +1,11 @@
1
+ export * from './AccountTrackerController';
2
+ export * from './AssetsContractController';
3
+ export * from './CurrencyRateController';
4
+ export * from './NftController';
5
+ export * from './NftDetectionController';
6
+ export * from './TokenBalancesController';
7
+ export * from './TokenDetectionController';
8
+ export * from './TokenListController';
9
+ export * from './TokenRatesController';
10
+ export * from './TokensController';
11
+ export { formatIconUrlWithProxy, getFormattedIpfsUrl } from './assetsUtil';
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.getFormattedIpfsUrl = exports.formatIconUrlWithProxy = void 0;
18
+ __exportStar(require("./AccountTrackerController"), exports);
19
+ __exportStar(require("./AssetsContractController"), exports);
20
+ __exportStar(require("./CurrencyRateController"), exports);
21
+ __exportStar(require("./NftController"), exports);
22
+ __exportStar(require("./NftDetectionController"), exports);
23
+ __exportStar(require("./TokenBalancesController"), exports);
24
+ __exportStar(require("./TokenDetectionController"), exports);
25
+ __exportStar(require("./TokenListController"), exports);
26
+ __exportStar(require("./TokenRatesController"), exports);
27
+ __exportStar(require("./TokensController"), exports);
28
+ var assetsUtil_1 = require("./assetsUtil");
29
+ Object.defineProperty(exports, "formatIconUrlWithProxy", { enumerable: true, get: function () { return assetsUtil_1.formatIconUrlWithProxy; } });
30
+ Object.defineProperty(exports, "getFormattedIpfsUrl", { enumerable: true, get: function () { return assetsUtil_1.getFormattedIpfsUrl; } });
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,6DAA2C;AAC3C,6DAA2C;AAC3C,2DAAyC;AACzC,kDAAgC;AAChC,2DAAyC;AACzC,4DAA0C;AAC1C,6DAA2C;AAC3C,wDAAsC;AACtC,yDAAuC;AACvC,qDAAmC;AACnC,2CAA2E;AAAlE,oHAAA,sBAAsB,OAAA;AAAE,iHAAA,mBAAmB,OAAA","sourcesContent":["export * from './AccountTrackerController';\nexport * from './AssetsContractController';\nexport * from './CurrencyRateController';\nexport * from './NftController';\nexport * from './NftDetectionController';\nexport * from './TokenBalancesController';\nexport * from './TokenDetectionController';\nexport * from './TokenListController';\nexport * from './TokenRatesController';\nexport * from './TokensController';\nexport { formatIconUrlWithProxy, getFormattedIpfsUrl } from './assetsUtil';\n"]}
@@ -0,0 +1,29 @@
1
+ export declare const TOKEN_END_POINT_API = "https://token-api.metaswap.codefi.network";
2
+ export declare const TOKEN_METADATA_NO_SUPPORT_ERROR = "TokenService Error: Network does not support fetchTokenMetadata";
3
+ /**
4
+ * Fetch the list of token metadata for a given network. This request is cancellable using the
5
+ * abort signal passed in.
6
+ *
7
+ * @param chainId - The chain ID of the network the requested tokens are on.
8
+ * @param abortSignal - The abort signal used to cancel the request if necessary.
9
+ * @param options - Additional fetch options.
10
+ * @param options.timeout - The fetch timeout.
11
+ * @returns The token list, or `undefined` if the request was cancelled.
12
+ */
13
+ export declare function fetchTokenList(chainId: string, abortSignal: AbortSignal, { timeout }?: {
14
+ timeout?: number | undefined;
15
+ }): Promise<unknown>;
16
+ /**
17
+ * Fetch metadata for the token address provided for a given network. This request is cancellable
18
+ * using the abort signal passed in.
19
+ *
20
+ * @param chainId - The chain ID of the network the token is on.
21
+ * @param tokenAddress - The address of the token to fetch metadata for.
22
+ * @param abortSignal - The abort signal used to cancel the request if necessary.
23
+ * @param options - Additional fetch options.
24
+ * @param options.timeout - The fetch timeout.
25
+ * @returns The token metadata, or `undefined` if the request was either aborted or failed.
26
+ */
27
+ export declare function fetchTokenMetadata<T>(chainId: string, tokenAddress: string, abortSignal: AbortSignal, { timeout }?: {
28
+ timeout?: number | undefined;
29
+ }): Promise<T | undefined>;