@metamask/assets-controllers 20.0.0 → 22.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 (73) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/dist/AccountTrackerController.d.ts +28 -7
  3. package/dist/AccountTrackerController.d.ts.map +1 -1
  4. package/dist/AccountTrackerController.js +104 -30
  5. package/dist/AccountTrackerController.js.map +1 -1
  6. package/dist/AssetsContractController.d.ts +3 -3
  7. package/dist/AssetsContractController.d.ts.map +1 -1
  8. package/dist/AssetsContractController.js +9 -3
  9. package/dist/AssetsContractController.js.map +1 -1
  10. package/dist/CurrencyRateController.d.ts +2 -2
  11. package/dist/CurrencyRateController.d.ts.map +1 -1
  12. package/dist/CurrencyRateController.js +1 -1
  13. package/dist/CurrencyRateController.js.map +1 -1
  14. package/dist/NftController.d.ts +73 -1
  15. package/dist/NftController.d.ts.map +1 -1
  16. package/dist/NftController.js +26 -9
  17. package/dist/NftController.js.map +1 -1
  18. package/dist/NftDetectionController.d.ts +7 -4
  19. package/dist/NftDetectionController.d.ts.map +1 -1
  20. package/dist/NftDetectionController.js +26 -14
  21. package/dist/NftDetectionController.js.map +1 -1
  22. package/dist/Standards/ERC20Standard.d.ts.map +1 -1
  23. package/dist/Standards/ERC20Standard.js +4 -0
  24. package/dist/Standards/ERC20Standard.js.map +1 -1
  25. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts +11 -10
  26. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -1
  27. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +106 -85
  28. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -1
  29. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -1
  30. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +2 -0
  31. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -1
  32. package/dist/Standards/standards-types.d.ts.map +1 -1
  33. package/dist/Standards/standards-types.js.map +1 -1
  34. package/dist/TokenDetectionController.d.ts +2 -2
  35. package/dist/TokenDetectionController.d.ts.map +1 -1
  36. package/dist/TokenDetectionController.js +1 -1
  37. package/dist/TokenDetectionController.js.map +1 -1
  38. package/dist/TokenListController.d.ts +2 -2
  39. package/dist/TokenListController.d.ts.map +1 -1
  40. package/dist/TokenListController.js +3 -15
  41. package/dist/TokenListController.js.map +1 -1
  42. package/dist/TokenRatesController.d.ts +9 -75
  43. package/dist/TokenRatesController.d.ts.map +1 -1
  44. package/dist/TokenRatesController.js +180 -203
  45. package/dist/TokenRatesController.js.map +1 -1
  46. package/dist/TokensController.d.ts +6 -8
  47. package/dist/TokensController.d.ts.map +1 -1
  48. package/dist/TokensController.js +70 -21
  49. package/dist/TokensController.js.map +1 -1
  50. package/dist/assetsUtil.d.ts +59 -9
  51. package/dist/assetsUtil.d.ts.map +1 -1
  52. package/dist/assetsUtil.js +138 -27
  53. package/dist/assetsUtil.js.map +1 -1
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +3 -1
  57. package/dist/index.js.map +1 -1
  58. package/dist/token-prices-service/abstract-token-prices-service.d.ts +62 -0
  59. package/dist/token-prices-service/abstract-token-prices-service.d.ts.map +1 -0
  60. package/dist/token-prices-service/abstract-token-prices-service.js +3 -0
  61. package/dist/token-prices-service/abstract-token-prices-service.js.map +1 -0
  62. package/dist/token-prices-service/codefi-v2.d.ts +80 -0
  63. package/dist/token-prices-service/codefi-v2.d.ts.map +1 -0
  64. package/dist/token-prices-service/codefi-v2.js +327 -0
  65. package/dist/token-prices-service/codefi-v2.js.map +1 -0
  66. package/dist/token-prices-service/index.d.ts +3 -0
  67. package/dist/token-prices-service/index.d.ts.map +1 -0
  68. package/dist/token-prices-service/index.js +6 -0
  69. package/dist/token-prices-service/index.js.map +1 -0
  70. package/dist/token-service.d.ts.map +1 -1
  71. package/dist/token-service.js +1 -1
  72. package/dist/token-service.js.map +1 -1
  73. package/package.json +6 -3
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.getFormattedIpfsUrl = exports.formatIconUrlWithProxy = exports.isTokenDetectionSupportedForNetwork = void 0;
17
+ exports.CodefiTokenPricesServiceV2 = exports.getFormattedIpfsUrl = exports.formatIconUrlWithProxy = exports.isTokenDetectionSupportedForNetwork = void 0;
18
18
  __exportStar(require("./AccountTrackerController"), exports);
19
19
  __exportStar(require("./AssetsContractController"), exports);
20
20
  __exportStar(require("./CurrencyRateController"), exports);
@@ -29,4 +29,6 @@ var assetsUtil_1 = require("./assetsUtil");
29
29
  Object.defineProperty(exports, "isTokenDetectionSupportedForNetwork", { enumerable: true, get: function () { return assetsUtil_1.isTokenDetectionSupportedForNetwork; } });
30
30
  Object.defineProperty(exports, "formatIconUrlWithProxy", { enumerable: true, get: function () { return assetsUtil_1.formatIconUrlWithProxy; } });
31
31
  Object.defineProperty(exports, "getFormattedIpfsUrl", { enumerable: true, get: function () { return assetsUtil_1.getFormattedIpfsUrl; } });
32
+ var token_prices_service_1 = require("./token-prices-service");
33
+ Object.defineProperty(exports, "CodefiTokenPricesServiceV2", { enumerable: true, get: function () { return token_prices_service_1.CodefiTokenPricesServiceV2; } });
32
34
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +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,2CAIsB;AAHpB,iIAAA,mCAAmC,OAAA;AACnC,oHAAA,sBAAsB,OAAA;AACtB,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 {\n isTokenDetectionSupportedForNetwork,\n formatIconUrlWithProxy,\n getFormattedIpfsUrl,\n} from './assetsUtil';\n"]}
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,2CAIsB;AAHpB,iIAAA,mCAAmC,OAAA;AACnC,oHAAA,sBAAsB,OAAA;AACtB,iHAAA,mBAAmB,OAAA;AAErB,+DAAoE;AAA3D,kIAAA,0BAA0B,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 {\n isTokenDetectionSupportedForNetwork,\n formatIconUrlWithProxy,\n getFormattedIpfsUrl,\n} from './assetsUtil';\nexport { CodefiTokenPricesServiceV2 } from './token-prices-service';\n"]}
@@ -0,0 +1,62 @@
1
+ import type { Hex } from '@metamask/utils';
2
+ /**
3
+ * Represents the price of a token in a currency.
4
+ */
5
+ export declare type TokenPrice<TokenAddress extends Hex, Currency extends string> = {
6
+ tokenAddress: TokenAddress;
7
+ value: number;
8
+ currency: Currency;
9
+ };
10
+ /**
11
+ * A map of token address to its price.
12
+ */
13
+ export declare type TokenPricesByTokenAddress<TokenAddress extends Hex, Currency extends string> = {
14
+ [A in TokenAddress]: TokenPrice<A, Currency>;
15
+ };
16
+ /**
17
+ * An ideal token prices service. All implementations must confirm to this
18
+ * interface.
19
+ *
20
+ * @template ChainId - A type union of valid arguments for the `chainId`
21
+ * argument to `fetchTokenPrices`.
22
+ * @template TokenAddress - A type union of all token addresses. The reason this
23
+ * type parameter exists is so that we can guarantee that same addresses that
24
+ * `fetchTokenPrices` receives are the same addresses that shown up in the
25
+ * return value.
26
+ * @template Currency - A type union of valid arguments for the `currency`
27
+ * argument to `fetchTokenPrices`.
28
+ */
29
+ export declare type AbstractTokenPricesService<ChainId extends Hex = Hex, TokenAddress extends Hex = Hex, Currency extends string = string> = {
30
+ /**
31
+ * Retrieves prices in the given currency for the tokens identified by the
32
+ * given addresses which are expected to live on the given chain.
33
+ *
34
+ * @param args - The arguments to this function.
35
+ * @param args.chainId - An EIP-155 chain ID.
36
+ * @param args.tokenAddresses - Addresses for tokens that live on the chain.
37
+ * @param args.currency - The desired currency of the token prices.
38
+ * @returns The prices for the requested tokens.
39
+ */
40
+ fetchTokenPrices({ chainId, tokenAddresses, currency, }: {
41
+ chainId: ChainId;
42
+ tokenAddresses: TokenAddress[];
43
+ currency: Currency;
44
+ }): Promise<TokenPricesByTokenAddress<TokenAddress, Currency>>;
45
+ /**
46
+ * Type guard for whether the API can return token prices for the given chain
47
+ * ID.
48
+ *
49
+ * @param chainId - The chain ID to check.
50
+ * @returns True if the API supports the chain ID, false otherwise.
51
+ */
52
+ validateChainIdSupported(chainId: unknown): chainId is ChainId;
53
+ /**
54
+ * Type guard for whether the API can return token prices in the given
55
+ * currency.
56
+ *
57
+ * @param currency - The currency to check.
58
+ * @returns True if the API supports the currency, false otherwise.
59
+ */
60
+ validateCurrencySupported(currency: unknown): currency is Currency;
61
+ };
62
+ //# sourceMappingURL=abstract-token-prices-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abstract-token-prices-service.d.ts","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C;;GAEG;AACH,oBAAY,UAAU,CAAC,YAAY,SAAS,GAAG,EAAE,QAAQ,SAAS,MAAM,IAAI;IAC1E,YAAY,EAAE,YAAY,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,QAAQ,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,oBAAY,yBAAyB,CACnC,YAAY,SAAS,GAAG,EACxB,QAAQ,SAAS,MAAM,IACrB;KACD,CAAC,IAAI,YAAY,GAAG,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,oBAAY,0BAA0B,CACpC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,YAAY,SAAS,GAAG,GAAG,GAAG,EAC9B,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B;IACF;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EACf,OAAO,EACP,cAAc,EACd,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,OAAO,CAAC;QACjB,cAAc,EAAE,YAAY,EAAE,CAAC;QAC/B,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,yBAAyB,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC;IAE/D;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=abstract-token-prices-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abstract-token-prices-service.js","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"","sourcesContent":["import type { Hex } from '@metamask/utils';\n\n/**\n * Represents the price of a token in a currency.\n */\nexport type TokenPrice<TokenAddress extends Hex, Currency extends string> = {\n tokenAddress: TokenAddress;\n value: number;\n currency: Currency;\n};\n\n/**\n * A map of token address to its price.\n */\nexport type TokenPricesByTokenAddress<\n TokenAddress extends Hex,\n Currency extends string,\n> = {\n [A in TokenAddress]: TokenPrice<A, Currency>;\n};\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template TokenAddress - A type union of all token addresses. The reason this\n * type parameter exists is so that we can guarantee that same addresses that\n * `fetchTokenPrices` receives are the same addresses that shown up in the\n * return value.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n TokenAddress extends Hex = Hex,\n Currency extends string = string,\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 this 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 fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: ChainId;\n tokenAddresses: TokenAddress[];\n currency: Currency;\n }): Promise<TokenPricesByTokenAddress<TokenAddress, Currency>>;\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 ChainId;\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.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
@@ -0,0 +1,80 @@
1
+ import type { Hex } from '@metamask/utils';
2
+ import type { AbstractTokenPricesService, TokenPricesByTokenAddress } from './abstract-token-prices-service';
3
+ /**
4
+ * The list of currencies that can be supplied as the `vsCurrency` parameter to
5
+ * the `/spot-prices` endpoint, in lowercase form.
6
+ */
7
+ export declare const SUPPORTED_CURRENCIES: readonly ["btc", "eth", "ltc", "bch", "bnb", "eos", "xrp", "xlm", "link", "dot", "yfi", "usd", "aed", "ars", "aud", "bdt", "bhd", "bmd", "brl", "cad", "chf", "clp", "cny", "czk", "dkk", "eur", "gbp", "hkd", "huf", "idr", "ils", "inr", "jpy", "krw", "kwd", "lkr", "mmk", "mxn", "myr", "ngn", "nok", "nzd", "php", "pkr", "pln", "rub", "sar", "sek", "sgd", "thb", "try", "twd", "uah", "vef", "vnd", "zar", "xdr", "xag", "xau", "bits", "sats"];
8
+ /**
9
+ * A currency that can be supplied as the `vsCurrency` parameter to
10
+ * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.
11
+ */
12
+ declare type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number] | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;
13
+ /**
14
+ * The list of chain IDs that can be supplied in the URL for the `/spot-prices`
15
+ * endpoint, but in hexadecimal form (for consistency with how we represent
16
+ * chain IDs in other places).
17
+ */
18
+ export declare const SUPPORTED_CHAIN_IDS: readonly ["0x1", "0xa", "0x19", "0x38", "0x39", "0x42", "0x46", "0x52", "0x58", "0x64", "0x6a", "0x7a", "0x80", "0x89", "0xfa", "0x120", "0x141", "0x144", "0x169", "0x440", "0x504", "0x505", "0x2105", "0x2107", "0x2710", "0xa4b1", "0xa4ec", "0xa516", "0xa86a", "0x518af", "0x4e454152", "0x63564c40"];
19
+ /**
20
+ * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,
21
+ * but in hexadecimal form (for consistency with how we represent chain IDs in
22
+ * other places).
23
+ */
24
+ declare type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
25
+ /**
26
+ * This version of the token prices service uses V2 of the Codefi Price API to
27
+ * fetch token prices.
28
+ */
29
+ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency> {
30
+ #private;
31
+ /**
32
+ * Construct a Codefi Token Price Service.
33
+ *
34
+ * @param options - Constructor options
35
+ * @param options.retries - Number of retry attempts for each token price update.
36
+ * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures
37
+ * allowed before breaking the circuit and pausing further updates.
38
+ * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks
39
+ * from too many consecutive failures.
40
+ */
41
+ constructor({ retries, maximumConsecutiveFailures, circuitBreakDuration, }?: {
42
+ retries?: number;
43
+ maximumConsecutiveFailures?: number;
44
+ circuitBreakDuration?: number;
45
+ });
46
+ /**
47
+ * Retrieves prices in the given currency for the tokens identified by the
48
+ * given addresses which are expected to live on the given chain.
49
+ *
50
+ * @param args - The arguments to function.
51
+ * @param args.chainId - An EIP-155 chain ID.
52
+ * @param args.tokenAddresses - Addresses for tokens that live on the chain.
53
+ * @param args.currency - The desired currency of the token prices.
54
+ * @returns The prices for the requested tokens.
55
+ */
56
+ fetchTokenPrices({ chainId, tokenAddresses, currency, }: {
57
+ chainId: SupportedChainId;
58
+ tokenAddresses: Hex[];
59
+ currency: SupportedCurrency;
60
+ }): Promise<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;
61
+ /**
62
+ * Type guard for whether the API can return token prices for the given chain
63
+ * ID.
64
+ *
65
+ * @param chainId - The chain ID to check.
66
+ * @returns True if the API supports the chain ID, false otherwise.
67
+ */
68
+ validateChainIdSupported(chainId: unknown): chainId is SupportedChainId;
69
+ /**
70
+ * Type guard for whether the API can return token prices in the given
71
+ * currency.
72
+ *
73
+ * @param currency - The currency to check. If a string, can be either
74
+ * lowercase or uppercase.
75
+ * @returns True if the API supports the currency, false otherwise.
76
+ */
77
+ validateCurrencySupported(currency: unknown): currency is SupportedCurrency;
78
+ }
79
+ export {};
80
+ //# sourceMappingURL=codefi-v2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codefi-v2.d.ts","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAY3C,OAAO,KAAK,EACV,0BAA0B,EAE1B,yBAAyB,EAC1B,MAAM,iCAAiC,CAAC;AAUzC;;;GAGG;AACH,eAAO,MAAM,oBAAoB,ybA2HvB,CAAC;AAEX;;;GAGG;AACH,aAAK,iBAAiB,GAClB,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,GACrC,SAAS,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AAErD;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,6SAkEtB,CAAC;AAEX;;;;GAIG;AACH,aAAK,gBAAgB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAY7D;;;GAGG;AACH,qBAAa,0BACX,YACE,0BAA0B,CAAC,gBAAgB,EAAE,GAAG,EAAE,iBAAiB,CAAC;;IAItE;;;;;;;;;OASG;gBACS,EACV,OAAqC,EACrC,0BAAyE,EACzE,oBAAqC,GACtC,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,0BAA0B,CAAC,EAAE,MAAM,CAAC;QACpC,oBAAoB,CAAC,EAAE,MAAM,CAAC;KAC1B;IAcN;;;;;;;;;OASG;IACG,gBAAgB,CAAC,EACrB,OAAO,EACP,cAAc,EACd,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,gBAAgB,CAAC;QAC1B,cAAc,EAAE,GAAG,EAAE,CAAC;QACtB,QAAQ,EAAE,iBAAiB,CAAC;KAC7B,GAAG,OAAO,CAAC,yBAAyB,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC;IAiD9D;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,gBAAgB;IAKvE;;;;;;;OAOG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,iBAAiB;CAO5E"}
@@ -0,0 +1,327 @@
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
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var _CodefiTokenPricesServiceV2_tokenPricePolicy;
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.CodefiTokenPricesServiceV2 = exports.SUPPORTED_CHAIN_IDS = exports.SUPPORTED_CURRENCIES = void 0;
25
+ const controller_utils_1 = require("@metamask/controller-utils");
26
+ const utils_1 = require("@metamask/utils");
27
+ const cockatiel_1 = require("cockatiel");
28
+ /**
29
+ * The list of currencies that can be supplied as the `vsCurrency` parameter to
30
+ * the `/spot-prices` endpoint, in lowercase form.
31
+ */
32
+ exports.SUPPORTED_CURRENCIES = [
33
+ // Bitcoin
34
+ 'btc',
35
+ // Ether
36
+ 'eth',
37
+ // Litecoin
38
+ 'ltc',
39
+ // Bitcoin Cash
40
+ 'bch',
41
+ // Binance Coin
42
+ 'bnb',
43
+ // EOS
44
+ 'eos',
45
+ // XRP
46
+ 'xrp',
47
+ // Lumens
48
+ 'xlm',
49
+ // Chainlink
50
+ 'link',
51
+ // Polkadot
52
+ 'dot',
53
+ // Yearn.finance
54
+ 'yfi',
55
+ // US Dollar
56
+ 'usd',
57
+ // United Arab Emirates Dirham
58
+ 'aed',
59
+ // Argentine Peso
60
+ 'ars',
61
+ // Australian Dollar
62
+ 'aud',
63
+ // Bangladeshi Taka
64
+ 'bdt',
65
+ // Bahraini Dinar
66
+ 'bhd',
67
+ // Bermudian Dollar
68
+ 'bmd',
69
+ // Brazil Real
70
+ 'brl',
71
+ // Canadian Dollar
72
+ 'cad',
73
+ // Swiss Franc
74
+ 'chf',
75
+ // Chilean Peso
76
+ 'clp',
77
+ // Chinese Yuan
78
+ 'cny',
79
+ // Czech Koruna
80
+ 'czk',
81
+ // Danish Krone
82
+ 'dkk',
83
+ // Euro
84
+ 'eur',
85
+ // British Pound Sterling
86
+ 'gbp',
87
+ // Hong Kong Dollar
88
+ 'hkd',
89
+ // Hungarian Forint
90
+ 'huf',
91
+ // Indonesian Rupiah
92
+ 'idr',
93
+ // Israeli New Shekel
94
+ 'ils',
95
+ // Indian Rupee
96
+ 'inr',
97
+ // Japanese Yen
98
+ 'jpy',
99
+ // South Korean Won
100
+ 'krw',
101
+ // Kuwaiti Dinar
102
+ 'kwd',
103
+ // Sri Lankan Rupee
104
+ 'lkr',
105
+ // Burmese Kyat
106
+ 'mmk',
107
+ // Mexican Peso
108
+ 'mxn',
109
+ // Malaysian Ringgit
110
+ 'myr',
111
+ // Nigerian Naira
112
+ 'ngn',
113
+ // Norwegian Krone
114
+ 'nok',
115
+ // New Zealand Dollar
116
+ 'nzd',
117
+ // Philippine Peso
118
+ 'php',
119
+ // Pakistani Rupee
120
+ 'pkr',
121
+ // Polish Zloty
122
+ 'pln',
123
+ // Russian Ruble
124
+ 'rub',
125
+ // Saudi Riyal
126
+ 'sar',
127
+ // Swedish Krona
128
+ 'sek',
129
+ // Singapore Dollar
130
+ 'sgd',
131
+ // Thai Baht
132
+ 'thb',
133
+ // Turkish Lira
134
+ 'try',
135
+ // New Taiwan Dollar
136
+ 'twd',
137
+ // Ukrainian hryvnia
138
+ 'uah',
139
+ // Venezuelan bolívar fuerte
140
+ 'vef',
141
+ // Vietnamese đồng
142
+ 'vnd',
143
+ // South African Rand
144
+ 'zar',
145
+ // IMF Special Drawing Rights
146
+ 'xdr',
147
+ // Silver - Troy Ounce
148
+ 'xag',
149
+ // Gold - Troy Ounce
150
+ 'xau',
151
+ // Bits
152
+ 'bits',
153
+ // Satoshi
154
+ 'sats',
155
+ ];
156
+ /**
157
+ * The list of chain IDs that can be supplied in the URL for the `/spot-prices`
158
+ * endpoint, but in hexadecimal form (for consistency with how we represent
159
+ * chain IDs in other places).
160
+ */
161
+ exports.SUPPORTED_CHAIN_IDS = [
162
+ // Ethereum Mainnet
163
+ '0x1',
164
+ // OP Mainnet
165
+ '0xa',
166
+ // Cronos Mainnet
167
+ '0x19',
168
+ // BNB Smart Chain Mainnet
169
+ '0x38',
170
+ // Syscoin Mainnet
171
+ '0x39',
172
+ // OKXChain Mainnet
173
+ '0x42',
174
+ // Hoo Smart Chain
175
+ '0x46',
176
+ // Meter Mainnet
177
+ '0x52',
178
+ // TomoChain
179
+ '0x58',
180
+ // Gnosis
181
+ '0x64',
182
+ // Velas EVM Mainnet
183
+ '0x6a',
184
+ // Fuse Mainnet
185
+ '0x7a',
186
+ // Huobi ECO Chain Mainnet
187
+ '0x80',
188
+ // Polygon Mainnet
189
+ '0x89',
190
+ // Fantom Opera
191
+ '0xfa',
192
+ // Boba Network
193
+ '0x120',
194
+ // KCC Mainnet
195
+ '0x141',
196
+ // zkSync Era Mainnet
197
+ '0x144',
198
+ // Theta Mainnet
199
+ '0x169',
200
+ // Metis Andromeda Mainnet
201
+ '0x440',
202
+ // Moonbeam
203
+ '0x504',
204
+ // Moonriver
205
+ '0x505',
206
+ // Base
207
+ '0x2105',
208
+ // Shiden
209
+ // NOTE: This is the wrong chain ID, this should be 0x150
210
+ '0x2107',
211
+ // Smart Bitcoin Cash
212
+ '0x2710',
213
+ // Arbitrum One
214
+ '0xa4b1',
215
+ // Celo Mainnet
216
+ '0xa4ec',
217
+ // Oasis Emerald
218
+ '0xa516',
219
+ // Avalanche C-Chain
220
+ '0xa86a',
221
+ // Polis Mainnet
222
+ '0x518af',
223
+ // Aurora Mainnet
224
+ '0x4e454152',
225
+ // Harmony Mainnet Shard 0
226
+ '0x63564c40',
227
+ ];
228
+ /**
229
+ * All requests to V2 of the Price API start with this.
230
+ */
231
+ const BASE_URL = 'https://price-api.metafi.codefi.network/v2';
232
+ const DEFAULT_TOKEN_PRICE_RETRIES = 3;
233
+ // Each update attempt will result (1 + retries) calls if the server is down
234
+ const DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;
235
+ /**
236
+ * This version of the token prices service uses V2 of the Codefi Price API to
237
+ * fetch token prices.
238
+ */
239
+ class CodefiTokenPricesServiceV2 {
240
+ /**
241
+ * Construct a Codefi Token Price Service.
242
+ *
243
+ * @param options - Constructor options
244
+ * @param options.retries - Number of retry attempts for each token price update.
245
+ * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures
246
+ * allowed before breaking the circuit and pausing further updates.
247
+ * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks
248
+ * from too many consecutive failures.
249
+ */
250
+ constructor({ retries = DEFAULT_TOKEN_PRICE_RETRIES, maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES, circuitBreakDuration = 30 * 60 * 1000, } = {}) {
251
+ _CodefiTokenPricesServiceV2_tokenPricePolicy.set(this, void 0);
252
+ // Construct a policy that will retry each update, and halt further updates
253
+ // for a certain period after too many consecutive failures.
254
+ const retryPolicy = (0, cockatiel_1.retry)(cockatiel_1.handleAll, {
255
+ maxAttempts: retries,
256
+ backoff: new cockatiel_1.ExponentialBackoff(),
257
+ });
258
+ const circuitBreakerPolicy = (0, cockatiel_1.circuitBreaker)(cockatiel_1.handleAll, {
259
+ halfOpenAfter: circuitBreakDuration,
260
+ breaker: new cockatiel_1.ConsecutiveBreaker(maximumConsecutiveFailures),
261
+ });
262
+ __classPrivateFieldSet(this, _CodefiTokenPricesServiceV2_tokenPricePolicy, (0, cockatiel_1.wrap)(retryPolicy, circuitBreakerPolicy), "f");
263
+ }
264
+ /**
265
+ * Retrieves prices in the given currency for the tokens identified by the
266
+ * given addresses which are expected to live on the given chain.
267
+ *
268
+ * @param args - The arguments to function.
269
+ * @param args.chainId - An EIP-155 chain ID.
270
+ * @param args.tokenAddresses - Addresses for tokens that live on the chain.
271
+ * @param args.currency - The desired currency of the token prices.
272
+ * @returns The prices for the requested tokens.
273
+ */
274
+ fetchTokenPrices({ chainId, tokenAddresses, currency, }) {
275
+ return __awaiter(this, void 0, void 0, function* () {
276
+ const chainIdAsNumber = (0, utils_1.hexToNumber)(chainId);
277
+ const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);
278
+ url.searchParams.append('tokenAddresses', tokenAddresses.join(','));
279
+ url.searchParams.append('vsCurrency', currency);
280
+ const pricesByCurrencyByTokenAddress = yield __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_tokenPricePolicy, "f").execute(() => (0, controller_utils_1.handleFetch)(url));
281
+ return tokenAddresses.reduce((obj, tokenAddress) => {
282
+ var _a;
283
+ // The Price API lowercases both currency and token addresses, so we have
284
+ // to keep track of them and make sure we return the original versions.
285
+ const lowercasedTokenAddress = tokenAddress.toLowerCase();
286
+ const lowercasedCurrency = currency.toLowerCase();
287
+ const price = (_a = pricesByCurrencyByTokenAddress[lowercasedTokenAddress]) === null || _a === void 0 ? void 0 : _a[lowercasedCurrency];
288
+ if (!price) {
289
+ throw new Error(`Could not find price for "${tokenAddress}" in "${currency}"`);
290
+ }
291
+ const tokenPrice = {
292
+ tokenAddress,
293
+ value: price,
294
+ currency,
295
+ };
296
+ return Object.assign(Object.assign({}, obj), { [tokenAddress]: tokenPrice });
297
+ }, {});
298
+ });
299
+ }
300
+ /**
301
+ * Type guard for whether the API can return token prices for the given chain
302
+ * ID.
303
+ *
304
+ * @param chainId - The chain ID to check.
305
+ * @returns True if the API supports the chain ID, false otherwise.
306
+ */
307
+ validateChainIdSupported(chainId) {
308
+ const supportedChainIds = exports.SUPPORTED_CHAIN_IDS;
309
+ return typeof chainId === 'string' && supportedChainIds.includes(chainId);
310
+ }
311
+ /**
312
+ * Type guard for whether the API can return token prices in the given
313
+ * currency.
314
+ *
315
+ * @param currency - The currency to check. If a string, can be either
316
+ * lowercase or uppercase.
317
+ * @returns True if the API supports the currency, false otherwise.
318
+ */
319
+ validateCurrencySupported(currency) {
320
+ const supportedCurrencies = exports.SUPPORTED_CURRENCIES;
321
+ return (typeof currency === 'string' &&
322
+ supportedCurrencies.includes(currency.toLowerCase()));
323
+ }
324
+ }
325
+ exports.CodefiTokenPricesServiceV2 = CodefiTokenPricesServiceV2;
326
+ _CodefiTokenPricesServiceV2_tokenPricePolicy = new WeakMap();
327
+ //# sourceMappingURL=codefi-v2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codefi-v2.js","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,iEAAyD;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,EAAC,GAAG,CAAC,CAAC,CAAC;YAEjE,OAAO,cAAc,CAAC,MAAM,CAC1B,CACE,GAA+D,EAC/D,YAAY,EACZ,EAAE;;gBACF,yEAAyE;gBACzE,uEAAuE;gBACvE,MAAM,sBAAsB,GAC1B,YAAY,CAAC,WAAW,EAAoB,CAAC;gBAC/C,MAAM,kBAAkB,GACtB,QAAQ,CAAC,WAAW,EAAkC,CAAC;gBAEzD,MAAM,KAAK,GACT,MAAA,8BAA8B,CAAC,sBAAsB,CAAC,0CACpD,kBAAkB,CACnB,CAAC;gBAEJ,IAAI,CAAC,KAAK,EAAE;oBACV,MAAM,IAAI,KAAK,CACb,6BAA6B,YAAY,SAAS,QAAQ,GAAG,CAC9D,CAAC;iBACH;gBAED,MAAM,UAAU,GAAuC;oBACrD,YAAY;oBACZ,KAAK,EAAE,KAAK;oBACZ,QAAQ;iBACT,CAAC;gBACF,uCACK,GAAG,KACN,CAAC,YAAY,CAAC,EAAE,UAAU,IAC1B;YACJ,CAAC,EACD,EAAE,CACkD,CAAC;QACzD,CAAC;KAAA;IAED;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAgB;QACvC,MAAM,iBAAiB,GAAsB,2BAAmB,CAAC;QACjE,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,iBAAiB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC5E,CAAC;IAED;;;;;;;OAOG;IACH,yBAAyB,CAAC,QAAiB;QACzC,MAAM,mBAAmB,GAAsB,4BAAoB,CAAC;QACpE,OAAO,CACL,OAAO,QAAQ,KAAK,QAAQ;YAC5B,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF;AApID,gEAoIC","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} from 'cockatiel';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype SpotPricesEndpointData<\n TokenAddress extends Hex,\n Currency extends string,\n> = Record<TokenAddress, Record<Currency, number>>;\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 * 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 */\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 // Base\n '0x2105',\n // Shiden\n // NOTE: This is the wrong chain ID, this should be 0x150\n '0x2107',\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] 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.metafi.codefi.network/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\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.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.circuitBreakDuration - The amount of time to wait when the circuit breaks\n * from too many consecutive failures.\n */\n constructor({\n retries = DEFAULT_TOKEN_PRICE_RETRIES,\n maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = 30 * 60 * 1000,\n }: {\n retries?: number;\n maximumConsecutiveFailures?: number;\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 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<TokenPricesByTokenAddress<Hex, SupportedCurrency>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append('tokenAddresses', tokenAddresses.join(','));\n url.searchParams.append('vsCurrency', currency);\n\n const pricesByCurrencyByTokenAddress: SpotPricesEndpointData<\n Lowercase<Hex>,\n Lowercase<SupportedCurrency>\n > = await this.#tokenPricePolicy.execute(() => handleFetch(url));\n\n return 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 const lowercasedCurrency =\n currency.toLowerCase() as Lowercase<SupportedCurrency>;\n\n const price =\n pricesByCurrencyByTokenAddress[lowercasedTokenAddress]?.[\n lowercasedCurrency\n ];\n\n if (!price) {\n throw new Error(\n `Could not find price for \"${tokenAddress}\" in \"${currency}\"`,\n );\n }\n\n const tokenPrice: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n value: price,\n currency,\n };\n return {\n ...obj,\n [tokenAddress]: tokenPrice,\n };\n },\n {},\n ) as 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"]}
@@ -0,0 +1,3 @@
1
+ export type { AbstractTokenPricesService } from './abstract-token-prices-service';
2
+ export { CodefiTokenPricesServiceV2 } from './codefi-v2';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/token-prices-service/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CodefiTokenPricesServiceV2 = void 0;
4
+ var codefi_v2_1 = require("./codefi-v2");
5
+ Object.defineProperty(exports, "CodefiTokenPricesServiceV2", { enumerable: true, get: function () { return codefi_v2_1.CodefiTokenPricesServiceV2; } });
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/token-prices-service/index.ts"],"names":[],"mappings":";;;AACA,yCAAyD;AAAhD,uHAAA,0BAA0B,OAAA","sourcesContent":["export type { AbstractTokenPricesService } from './abstract-token-prices-service';\nexport { CodefiTokenPricesServiceV2 } from './codefi-v2';\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"token-service.d.ts","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAI3C,eAAO,MAAM,mBAAmB,8CAA8C,CAAC;AAC/E,eAAO,MAAM,+BAA+B,oEACuB,CAAC;AA+BpE;;;;;;;;;GASG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,GAAG,EACZ,WAAW,EAAE,WAAW,EACxB,EAAE,OAAwB,EAAE;;CAAK,GAChC,OAAO,CAAC,OAAO,CAAC,CAOlB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EACxC,OAAO,EAAE,GAAG,EACZ,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,WAAW,EACxB,EAAE,OAAwB,EAAE;;CAAK,GAChC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAUxB"}
1
+ {"version":3,"file":"token-service.d.ts","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAI3C,eAAO,MAAM,mBAAmB,8CAA8C,CAAC;AAC/E,eAAO,MAAM,+BAA+B,oEACuB,CAAC;AAiCpE;;;;;;;;;GASG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,GAAG,EACZ,WAAW,EAAE,WAAW,EACxB,EAAE,OAAwB,EAAE;;CAAK,GAChC,OAAO,CAAC,OAAO,CAAC,CAOlB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EACxC,OAAO,EAAE,GAAG,EACZ,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,WAAW,EACxB,EAAE,OAAwB,EAAE;;CAAK,GAChC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAUxB"}
@@ -21,7 +21,7 @@ exports.TOKEN_METADATA_NO_SUPPORT_ERROR = 'TokenService Error: Network does not
21
21
  * @returns The tokens URL.
22
22
  */
23
23
  function getTokensURL(chainId) {
24
- return `${exports.TOKEN_END_POINT_API}/tokens/${(0, controller_utils_1.convertHexToDecimal)(chainId)}`;
24
+ return `${exports.TOKEN_END_POINT_API}/tokens/${(0, controller_utils_1.convertHexToDecimal)(chainId)}?occurrenceFloor=3&includeNativeAssets=false&includeDuplicateSymbolAssets=false&includeTokenFees=false&includeAssetType=false`;
25
25
  }
26
26
  /**
27
27
  * Get the token metadata URL for the given network and token.
@@ -1 +1 @@
1
- {"version":3,"file":"token-service.js","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAA+E;AAG/E,6CAA8D;AAEjD,QAAA,mBAAmB,GAAG,2CAA2C,CAAC;AAClE,QAAA,+BAA+B,GAC1C,iEAAiE,CAAC;AAEpE;;;;;GAKG;AACH,SAAS,YAAY,CAAC,OAAY;IAChC,OAAO,GAAG,2BAAmB,WAAW,IAAA,sCAAmB,EAAC,OAAO,CAAC,EAAE,CAAC;AACzE,CAAC;AAED;;;;;;GAMG;AACH,SAAS,mBAAmB,CAAC,OAAY,EAAE,YAAoB;IAC7D,OAAO,GAAG,2BAAmB,UAAU,IAAA,sCAAmB,EACxD,OAAO,CACR,YAAY,YAAY,EAAE,CAAC;AAC9B,CAAC;AAED,MAAM,wBAAwB,GAAG,KAAM,CAAC;AAExC,qCAAqC;AACrC,yGAAyG;AACzG,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEhD;;;;;;;;;GASG;AACH,SAAsB,uBAAuB,CAC3C,OAAY,EACZ,WAAwB,EACxB,EAAE,OAAO,GAAG,cAAc,EAAE,GAAG,EAAE;;QAEjC,MAAM,QAAQ,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,EAAC,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;SAC1D;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE;gBACzD,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;aACnC;SACF;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CAAA;AAED;;;;;;GAMG;AACH,SAAe,iBAAiB,CAAC,WAAqB;;QACpD,MAAM,WAAW,GAAG,MAAM,WAAW,CAAC,IAAI,EAAE,CAAC;QAC7C,0EAA0E;QAC1E,IAAI,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,KAAK,EAAE;YACtB,MAAM,IAAI,KAAK,CAAC,uBAAuB,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;SAC7D;QACD,OAAO,WAAW,CAAC;IACrB,CAAC;CAAA","sourcesContent":["import { convertHexToDecimal, timeoutFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { isTokenListSupportedForNetwork } from './assetsUtil';\n\nexport const TOKEN_END_POINT_API = 'https://token-api.metaswap.codefi.network';\nexport const TOKEN_METADATA_NO_SUPPORT_ERROR =\n 'TokenService Error: Network does not support fetchTokenMetadata';\n\n/**\n * Get the tokens URL for a specific network.\n *\n * @param chainId - The chain ID of the network the tokens requested are on.\n * @returns The tokens URL.\n */\nfunction getTokensURL(chainId: Hex) {\n return `${TOKEN_END_POINT_API}/tokens/${convertHexToDecimal(chainId)}`;\n}\n\n/**\n * Get the token metadata URL for the given network and token.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The token address.\n * @returns The token metadata URL.\n */\nfunction getTokenMetadataURL(chainId: Hex, tokenAddress: string) {\n return `${TOKEN_END_POINT_API}/token/${convertHexToDecimal(\n chainId,\n )}?address=${tokenAddress}`;\n}\n\nconst tenSecondsInMilliseconds = 10_000;\n\n// Token list averages 1.6 MB in size\n// timeoutFetch by default has a 500ms timeout, which will almost always timeout given the response size.\nconst defaultTimeout = tenSecondsInMilliseconds;\n\n/**\n * Fetch the list of token metadata for a given network. This request is cancellable using the\n * abort signal passed in.\n *\n * @param chainId - The chain ID of the network the requested tokens are on.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token list, or `undefined` if the request was cancelled.\n */\nexport async function fetchTokenListByChainId(\n chainId: Hex,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<unknown> {\n const tokenURL = getTokensURL(chainId);\n const response = await queryApi(tokenURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response);\n }\n return undefined;\n}\n\n/**\n * Fetch metadata for the token address provided for a given network. This request is cancellable\n * using the abort signal passed in.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The address of the token to fetch metadata for.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token metadata, or `undefined` if the request was either aborted or failed.\n */\nexport async function fetchTokenMetadata<T>(\n chainId: Hex,\n tokenAddress: string,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<T | undefined> {\n if (!isTokenListSupportedForNetwork(chainId)) {\n throw new Error(TOKEN_METADATA_NO_SUPPORT_ERROR);\n }\n const tokenMetadataURL = getTokenMetadataURL(chainId, tokenAddress);\n const response = await queryApi(tokenMetadataURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response) as Promise<T>;\n }\n return undefined;\n}\n\n/**\n * Perform fetch request against the api.\n *\n * @param apiURL - The URL of the API to fetch.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param timeout - The fetch timeout.\n * @returns Promise resolving request response.\n */\nasync function queryApi(\n apiURL: string,\n abortSignal: AbortSignal,\n timeout: number,\n): Promise<Response | undefined> {\n const fetchOptions: RequestInit = {\n referrer: apiURL,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n signal: abortSignal,\n cache: 'default',\n };\n fetchOptions.headers = new window.Headers();\n fetchOptions.headers.set('Content-Type', 'application/json');\n try {\n return await timeoutFetch(apiURL, fetchOptions, timeout);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n console.log('Request is aborted');\n }\n }\n return undefined;\n}\n\n/**\n * Parse an API response and return the response JSON data.\n *\n * @param apiResponse - The API response to parse.\n * @returns The response JSON data.\n * @throws Will throw if the response includes an error.\n */\nasync function parseJsonResponse(apiResponse: Response): Promise<unknown> {\n const responseObj = await apiResponse.json();\n // api may return errors as json without setting an error http status code\n if (responseObj?.error) {\n throw new Error(`TokenService Error: ${responseObj.error}`);\n }\n return responseObj;\n}\n"]}
1
+ {"version":3,"file":"token-service.js","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAA+E;AAG/E,6CAA8D;AAEjD,QAAA,mBAAmB,GAAG,2CAA2C,CAAC;AAClE,QAAA,+BAA+B,GAC1C,iEAAiE,CAAC;AAEpE;;;;;GAKG;AACH,SAAS,YAAY,CAAC,OAAY;IAChC,OAAO,GAAG,2BAAmB,WAAW,IAAA,sCAAmB,EACzD,OAAO,CACR,+HAA+H,CAAC;AACnI,CAAC;AAED;;;;;;GAMG;AACH,SAAS,mBAAmB,CAAC,OAAY,EAAE,YAAoB;IAC7D,OAAO,GAAG,2BAAmB,UAAU,IAAA,sCAAmB,EACxD,OAAO,CACR,YAAY,YAAY,EAAE,CAAC;AAC9B,CAAC;AAED,MAAM,wBAAwB,GAAG,KAAM,CAAC;AAExC,qCAAqC;AACrC,yGAAyG;AACzG,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEhD;;;;;;;;;GASG;AACH,SAAsB,uBAAuB,CAC3C,OAAY,EACZ,WAAwB,EACxB,EAAE,OAAO,GAAG,cAAc,EAAE,GAAG,EAAE;;QAEjC,MAAM,QAAQ,GAAG,YAAY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M,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;SAC1D;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE;gBACzD,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;aACnC;SACF;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CAAA;AAED;;;;;;GAMG;AACH,SAAe,iBAAiB,CAAC,WAAqB;;QACpD,MAAM,WAAW,GAAG,MAAM,WAAW,CAAC,IAAI,EAAE,CAAC;QAC7C,0EAA0E;QAC1E,IAAI,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,KAAK,EAAE;YACtB,MAAM,IAAI,KAAK,CAAC,uBAAuB,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;SAC7D;QACD,OAAO,WAAW,CAAC;IACrB,CAAC;CAAA","sourcesContent":["import { convertHexToDecimal, timeoutFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { isTokenListSupportedForNetwork } from './assetsUtil';\n\nexport const TOKEN_END_POINT_API = 'https://token-api.metaswap.codefi.network';\nexport const TOKEN_METADATA_NO_SUPPORT_ERROR =\n 'TokenService Error: Network does not support fetchTokenMetadata';\n\n/**\n * Get the tokens URL for a specific network.\n *\n * @param chainId - The chain ID of the network the tokens requested are on.\n * @returns The tokens URL.\n */\nfunction getTokensURL(chainId: Hex) {\n return `${TOKEN_END_POINT_API}/tokens/${convertHexToDecimal(\n chainId,\n )}?occurrenceFloor=3&includeNativeAssets=false&includeDuplicateSymbolAssets=false&includeTokenFees=false&includeAssetType=false`;\n}\n\n/**\n * Get the token metadata URL for the given network and token.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The token address.\n * @returns The token metadata URL.\n */\nfunction getTokenMetadataURL(chainId: Hex, tokenAddress: string) {\n return `${TOKEN_END_POINT_API}/token/${convertHexToDecimal(\n chainId,\n )}?address=${tokenAddress}`;\n}\n\nconst tenSecondsInMilliseconds = 10_000;\n\n// Token list averages 1.6 MB in size\n// timeoutFetch by default has a 500ms timeout, which will almost always timeout given the response size.\nconst defaultTimeout = tenSecondsInMilliseconds;\n\n/**\n * Fetch the list of token metadata for a given network. This request is cancellable using the\n * abort signal passed in.\n *\n * @param chainId - The chain ID of the network the requested tokens are on.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token list, or `undefined` if the request was cancelled.\n */\nexport async function fetchTokenListByChainId(\n chainId: Hex,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<unknown> {\n const tokenURL = getTokensURL(chainId);\n const response = await queryApi(tokenURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response);\n }\n return undefined;\n}\n\n/**\n * Fetch metadata for the token address provided for a given network. This request is cancellable\n * using the abort signal passed in.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The address of the token to fetch metadata for.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token metadata, or `undefined` if the request was either aborted or failed.\n */\nexport async function fetchTokenMetadata<T>(\n chainId: Hex,\n tokenAddress: string,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<T | undefined> {\n if (!isTokenListSupportedForNetwork(chainId)) {\n throw new Error(TOKEN_METADATA_NO_SUPPORT_ERROR);\n }\n const tokenMetadataURL = getTokenMetadataURL(chainId, tokenAddress);\n const response = await queryApi(tokenMetadataURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response) as Promise<T>;\n }\n return undefined;\n}\n\n/**\n * Perform fetch request against the api.\n *\n * @param apiURL - The URL of the API to fetch.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param timeout - The fetch timeout.\n * @returns Promise resolving request response.\n */\nasync function queryApi(\n apiURL: string,\n abortSignal: AbortSignal,\n timeout: number,\n): Promise<Response | undefined> {\n const fetchOptions: RequestInit = {\n referrer: apiURL,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n signal: abortSignal,\n cache: 'default',\n };\n fetchOptions.headers = new window.Headers();\n fetchOptions.headers.set('Content-Type', 'application/json');\n try {\n return await timeoutFetch(apiURL, fetchOptions, timeout);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n console.log('Request is aborted');\n }\n }\n return undefined;\n}\n\n/**\n * Parse an API response and return the response JSON data.\n *\n * @param apiResponse - The API response to parse.\n * @returns The response JSON data.\n * @throws Will throw if the response includes an error.\n */\nasync function parseJsonResponse(apiResponse: Response): Promise<unknown> {\n const responseObj = await apiResponse.json();\n // api may return errors as json without setting an error http status code\n if (responseObj?.error) {\n throw new Error(`TokenService Error: ${responseObj.error}`);\n }\n return responseObj;\n}\n"]}