@metamask-previews/assets-controllers 11.0.1-preview.3dbf14f

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 (80) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +20 -0
  3. package/README.md +30 -0
  4. package/dist/AccountTrackerController.d.ts +106 -0
  5. package/dist/AccountTrackerController.d.ts.map +1 -0
  6. package/dist/AccountTrackerController.js +163 -0
  7. package/dist/AccountTrackerController.js.map +1 -0
  8. package/dist/AssetsContractController.d.ts +188 -0
  9. package/dist/AssetsContractController.d.ts.map +1 -0
  10. package/dist/AssetsContractController.js +330 -0
  11. package/dist/AssetsContractController.js.map +1 -0
  12. package/dist/CurrencyRateController.d.ts +101 -0
  13. package/dist/CurrencyRateController.d.ts.map +1 -0
  14. package/dist/CurrencyRateController.js +219 -0
  15. package/dist/CurrencyRateController.js.map +1 -0
  16. package/dist/NftController.d.ts +466 -0
  17. package/dist/NftController.d.ts.map +1 -0
  18. package/dist/NftController.js +943 -0
  19. package/dist/NftController.js.map +1 -0
  20. package/dist/NftDetectionController.d.ts +182 -0
  21. package/dist/NftDetectionController.d.ts.map +1 -0
  22. package/dist/NftDetectionController.js +188 -0
  23. package/dist/NftDetectionController.js.map +1 -0
  24. package/dist/Standards/ERC20Standard.d.ts +50 -0
  25. package/dist/Standards/ERC20Standard.d.ts.map +1 -0
  26. package/dist/Standards/ERC20Standard.js +144 -0
  27. package/dist/Standards/ERC20Standard.js.map +1 -0
  28. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts +79 -0
  29. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -0
  30. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +148 -0
  31. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -0
  32. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts +89 -0
  33. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -0
  34. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +182 -0
  35. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -0
  36. package/dist/Standards/standards-types.d.ts +15 -0
  37. package/dist/Standards/standards-types.d.ts.map +1 -0
  38. package/dist/Standards/standards-types.js +3 -0
  39. package/dist/Standards/standards-types.js.map +1 -0
  40. package/dist/TokenBalancesController.d.ts +71 -0
  41. package/dist/TokenBalancesController.d.ts.map +1 -0
  42. package/dist/TokenBalancesController.js +94 -0
  43. package/dist/TokenBalancesController.js.map +1 -0
  44. package/dist/TokenDetectionController.d.ts +87 -0
  45. package/dist/TokenDetectionController.d.ts.map +1 -0
  46. package/dist/TokenDetectionController.js +189 -0
  47. package/dist/TokenDetectionController.js.map +1 -0
  48. package/dist/TokenListController.d.ts +117 -0
  49. package/dist/TokenListController.d.ts.map +1 -0
  50. package/dist/TokenListController.js +248 -0
  51. package/dist/TokenListController.js.map +1 -0
  52. package/dist/TokenRatesController.d.ts +172 -0
  53. package/dist/TokenRatesController.d.ts.map +1 -0
  54. package/dist/TokenRatesController.js +327 -0
  55. package/dist/TokenRatesController.js.map +1 -0
  56. package/dist/TokensController.d.ts +250 -0
  57. package/dist/TokensController.d.ts.map +1 -0
  58. package/dist/TokensController.js +550 -0
  59. package/dist/TokensController.js.map +1 -0
  60. package/dist/assetsUtil.d.ts +109 -0
  61. package/dist/assetsUtil.d.ts.map +1 -0
  62. package/dist/assetsUtil.js +227 -0
  63. package/dist/assetsUtil.js.map +1 -0
  64. package/dist/constants.d.ts +6 -0
  65. package/dist/constants.d.ts.map +1 -0
  66. package/dist/constants.js +10 -0
  67. package/dist/constants.js.map +1 -0
  68. package/dist/crypto-compare.d.ts +13 -0
  69. package/dist/crypto-compare.d.ts.map +1 -0
  70. package/dist/crypto-compare.js +67 -0
  71. package/dist/crypto-compare.js.map +1 -0
  72. package/dist/index.d.ts +12 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +32 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/token-service.d.ts +31 -0
  77. package/dist/token-service.d.ts.map +1 -0
  78. package/dist/token-service.js +134 -0
  79. package/dist/token-service.js.map +1 -0
  80. package/package.json +82 -0
@@ -0,0 +1,188 @@
1
+ /// <reference types="bn.js" />
2
+ import type { BaseConfig, BaseState } from '@metamask/base-controller';
3
+ import { BaseController } from '@metamask/base-controller';
4
+ import type { NetworkState } from '@metamask/network-controller';
5
+ import type { PreferencesState } from '@metamask/preferences-controller';
6
+ import type { Hex } from '@metamask/utils';
7
+ import type { BN } from 'ethereumjs-util';
8
+ /**
9
+ * Check if token detection is enabled for certain networks
10
+ *
11
+ * @param chainId - ChainID of network
12
+ * @returns Whether the current network supports token detection
13
+ */
14
+ export declare const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID: Record<Hex, string>;
15
+ export declare const MISSING_PROVIDER_ERROR = "AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available";
16
+ /**
17
+ * @type AssetsContractConfig
18
+ *
19
+ * Assets Contract controller configuration
20
+ * @property provider - Provider used to create a new web3 instance
21
+ */
22
+ export interface AssetsContractConfig extends BaseConfig {
23
+ provider: any;
24
+ ipfsGateway: string;
25
+ chainId: Hex;
26
+ }
27
+ /**
28
+ * @type BalanceMap
29
+ *
30
+ * Key value object containing the balance for each tokenAddress
31
+ * @property [tokenAddress] - Address of the token
32
+ */
33
+ export interface BalanceMap {
34
+ [tokenAddress: string]: BN;
35
+ }
36
+ /**
37
+ * Controller that interacts with contracts on mainnet through web3
38
+ */
39
+ export declare class AssetsContractController extends BaseController<AssetsContractConfig, BaseState> {
40
+ private _provider?;
41
+ private erc721Standard?;
42
+ private erc1155Standard?;
43
+ private erc20Standard?;
44
+ /**
45
+ * Name of this controller used during composition
46
+ */
47
+ name: string;
48
+ /**
49
+ * Creates a AssetsContractController instance.
50
+ *
51
+ * @param options - The controller options.
52
+ * @param options.chainId - The chain ID of the current network.
53
+ * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
54
+ * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
55
+ * @param config - Initial options used to configure this controller.
56
+ * @param state - Initial state to set on this controller.
57
+ */
58
+ constructor({ chainId: initialChainId, onPreferencesStateChange, onNetworkStateChange, }: {
59
+ chainId: Hex;
60
+ onPreferencesStateChange: (listener: (preferencesState: PreferencesState) => void) => void;
61
+ onNetworkStateChange: (listener: (networkState: NetworkState) => void) => void;
62
+ }, config?: Partial<AssetsContractConfig>, state?: Partial<BaseState>);
63
+ /**
64
+ * Sets a new provider.
65
+ *
66
+ * TODO: Replace this wth a method.
67
+ *
68
+ * @property provider - Provider used to create a new underlying Web3 instance
69
+ */
70
+ set provider(provider: any);
71
+ get provider(): any;
72
+ /**
73
+ * Get balance or count for current account on specific asset contract.
74
+ *
75
+ * @param address - Asset ERC20 contract address.
76
+ * @param selectedAddress - Current account public address.
77
+ * @returns Promise resolving to BN object containing balance for current account on specific asset contract.
78
+ */
79
+ getERC20BalanceOf(address: string, selectedAddress: string): Promise<BN>;
80
+ /**
81
+ * Query for the decimals for a given ERC20 asset.
82
+ *
83
+ * @param address - ERC20 asset contract address.
84
+ * @returns Promise resolving to the 'decimals'.
85
+ */
86
+ getERC20TokenDecimals(address: string): Promise<string>;
87
+ /**
88
+ * Query for the name for a given ERC20 asset.
89
+ *
90
+ * @param address - ERC20 asset contract address.
91
+ * @returns Promise resolving to the 'decimals'.
92
+ */
93
+ getERC20TokenName(address: string): Promise<string>;
94
+ /**
95
+ * Enumerate assets assigned to an owner.
96
+ *
97
+ * @param address - ERC721 asset contract address.
98
+ * @param selectedAddress - Current account public address.
99
+ * @param index - An NFT counter less than `balanceOf(selectedAddress)`.
100
+ * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.
101
+ */
102
+ getERC721NftTokenId(address: string, selectedAddress: string, index: number): Promise<string>;
103
+ /**
104
+ * Enumerate assets assigned to an owner.
105
+ *
106
+ * @param tokenAddress - ERC721 asset contract address.
107
+ * @param userAddress - Current account public address.
108
+ * @param tokenId - ERC721 asset identifier.
109
+ * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.
110
+ */
111
+ getTokenStandardAndDetails(tokenAddress: string, userAddress?: string, tokenId?: string): Promise<{
112
+ standard: string;
113
+ tokenURI?: string | undefined;
114
+ symbol?: string | undefined;
115
+ name?: string | undefined;
116
+ decimals?: string | undefined;
117
+ balance?: BN | undefined;
118
+ }>;
119
+ /**
120
+ * Query for tokenURI for a given ERC721 asset.
121
+ *
122
+ * @param address - ERC721 asset contract address.
123
+ * @param tokenId - ERC721 asset identifier.
124
+ * @returns Promise resolving to the 'tokenURI'.
125
+ */
126
+ getERC721TokenURI(address: string, tokenId: string): Promise<string>;
127
+ /**
128
+ * Query for name for a given asset.
129
+ *
130
+ * @param address - ERC721 or ERC20 asset contract address.
131
+ * @returns Promise resolving to the 'name'.
132
+ */
133
+ getERC721AssetName(address: string): Promise<string>;
134
+ /**
135
+ * Query for symbol for a given asset.
136
+ *
137
+ * @param address - ERC721 or ERC20 asset contract address.
138
+ * @returns Promise resolving to the 'symbol'.
139
+ */
140
+ getERC721AssetSymbol(address: string): Promise<string>;
141
+ /**
142
+ * Query for owner for a given ERC721 asset.
143
+ *
144
+ * @param address - ERC721 asset contract address.
145
+ * @param tokenId - ERC721 asset identifier.
146
+ * @returns Promise resolving to the owner address.
147
+ */
148
+ getERC721OwnerOf(address: string, tokenId: string): Promise<string>;
149
+ /**
150
+ * Query for tokenURI for a given asset.
151
+ *
152
+ * @param address - ERC1155 asset contract address.
153
+ * @param tokenId - ERC1155 asset identifier.
154
+ * @returns Promise resolving to the 'tokenURI'.
155
+ */
156
+ getERC1155TokenURI(address: string, tokenId: string): Promise<string>;
157
+ /**
158
+ * Query for balance of a given ERC 1155 token.
159
+ *
160
+ * @param userAddress - Wallet public address.
161
+ * @param nftAddress - ERC1155 asset contract address.
162
+ * @param nftId - ERC1155 asset identifier.
163
+ * @returns Promise resolving to the 'balanceOf'.
164
+ */
165
+ getERC1155BalanceOf(userAddress: string, nftAddress: string, nftId: string): Promise<BN>;
166
+ /**
167
+ * Transfer single ERC1155 token.
168
+ *
169
+ * @param nftAddress - ERC1155 token address.
170
+ * @param senderAddress - ERC1155 token sender.
171
+ * @param recipientAddress - ERC1155 token recipient.
172
+ * @param nftId - ERC1155 token id.
173
+ * @param qty - Quantity of tokens to be sent.
174
+ * @returns Promise resolving to the 'transferSingle' ERC1155 token.
175
+ */
176
+ transferSingleERC1155(nftAddress: string, senderAddress: string, recipientAddress: string, nftId: string, qty: string): Promise<void>;
177
+ /**
178
+ * Get the token balance for a list of token addresses in a single call. Only non-zero balances
179
+ * are returned.
180
+ *
181
+ * @param selectedAddress - The address to check token balances for.
182
+ * @param tokensToDetect - The token addresses to detect balances for.
183
+ * @returns The list of non-zero token balances.
184
+ */
185
+ getBalancesInSingleCall(selectedAddress: string, tokensToDetect: string[]): Promise<BalanceMap>;
186
+ }
187
+ export default AssetsContractController;
188
+ //# sourceMappingURL=AssetsContractController.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AssetsContractController.d.ts","sourceRoot":"","sources":["../src/AssetsContractController.ts"],"names":[],"mappings":";AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;AAQ1C;;;;;GAKG;AACH,eAAO,MAAM,uCAAuC,EAAE,MAAM,CAAC,GAAG,EAAE,MAAM,CAWvE,CAAC;AAEF,eAAO,MAAM,sBAAsB,0HACsF,CAA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EAAE,MAAM,GACZ,OAAO,CAAC,EAAE,CAAC;IAWd;;;;;;;;;OASG;IACG,qBAAqB,CACzB,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,MAAM,EACrB,gBAAgB,EAAE,MAAM,EACxB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,IAAI,CAAC;IAahB;;;;;;;OAOG;IACG,uBAAuB,CAC3B,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,EAAE;CA4B3B;AAED,eAAe,wBAAwB,CAAC"}
@@ -0,0 +1,330 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AssetsContractController = exports.MISSING_PROVIDER_ERROR = exports.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID = void 0;
16
+ const contracts_1 = require("@ethersproject/contracts");
17
+ const providers_1 = require("@ethersproject/providers");
18
+ const base_controller_1 = require("@metamask/base-controller");
19
+ const controller_utils_1 = require("@metamask/controller-utils");
20
+ const single_call_balance_checker_abi_1 = __importDefault(require("single-call-balance-checker-abi"));
21
+ const assetsUtil_1 = require("./assetsUtil");
22
+ const ERC20Standard_1 = require("./Standards/ERC20Standard");
23
+ const ERC1155Standard_1 = require("./Standards/NftStandards/ERC1155/ERC1155Standard");
24
+ const ERC721Standard_1 = require("./Standards/NftStandards/ERC721/ERC721Standard");
25
+ /**
26
+ * Check if token detection is enabled for certain networks
27
+ *
28
+ * @param chainId - ChainID of network
29
+ * @returns Whether the current network supports token detection
30
+ */
31
+ exports.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID = {
32
+ [assetsUtil_1.SupportedTokenDetectionNetworks.mainnet]: '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',
33
+ [assetsUtil_1.SupportedTokenDetectionNetworks.bsc]: '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',
34
+ [assetsUtil_1.SupportedTokenDetectionNetworks.polygon]: '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',
35
+ [assetsUtil_1.SupportedTokenDetectionNetworks.avax]: '0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',
36
+ [assetsUtil_1.SupportedTokenDetectionNetworks.aurora]: '0x1286415D333855237f89Df27D388127181448538',
37
+ };
38
+ exports.MISSING_PROVIDER_ERROR = 'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';
39
+ /**
40
+ * Controller that interacts with contracts on mainnet through web3
41
+ */
42
+ class AssetsContractController extends base_controller_1.BaseController {
43
+ /**
44
+ * Creates a AssetsContractController instance.
45
+ *
46
+ * @param options - The controller options.
47
+ * @param options.chainId - The chain ID of the current network.
48
+ * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
49
+ * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
50
+ * @param config - Initial options used to configure this controller.
51
+ * @param state - Initial state to set on this controller.
52
+ */
53
+ constructor({ chainId: initialChainId, onPreferencesStateChange, onNetworkStateChange, }, config, state) {
54
+ super(config, state);
55
+ /**
56
+ * Name of this controller used during composition
57
+ */
58
+ this.name = 'AssetsContractController';
59
+ this.defaultConfig = {
60
+ provider: undefined,
61
+ ipfsGateway: controller_utils_1.IPFS_DEFAULT_GATEWAY_URL,
62
+ chainId: initialChainId,
63
+ };
64
+ this.initialize();
65
+ onPreferencesStateChange(({ ipfsGateway }) => {
66
+ this.configure({ ipfsGateway });
67
+ });
68
+ onNetworkStateChange((networkState) => {
69
+ if (this.config.chainId !== networkState.providerConfig.chainId) {
70
+ this.configure({
71
+ chainId: networkState.providerConfig.chainId,
72
+ });
73
+ }
74
+ });
75
+ }
76
+ /**
77
+ * Sets a new provider.
78
+ *
79
+ * TODO: Replace this wth a method.
80
+ *
81
+ * @property provider - Provider used to create a new underlying Web3 instance
82
+ */
83
+ set provider(provider) {
84
+ this._provider = new providers_1.Web3Provider(provider);
85
+ this.erc721Standard = new ERC721Standard_1.ERC721Standard(this._provider);
86
+ this.erc1155Standard = new ERC1155Standard_1.ERC1155Standard(this._provider);
87
+ this.erc20Standard = new ERC20Standard_1.ERC20Standard(this._provider);
88
+ }
89
+ get provider() {
90
+ throw new Error('Property only used for setting');
91
+ }
92
+ /**
93
+ * Get balance or count for current account on specific asset contract.
94
+ *
95
+ * @param address - Asset ERC20 contract address.
96
+ * @param selectedAddress - Current account public address.
97
+ * @returns Promise resolving to BN object containing balance for current account on specific asset contract.
98
+ */
99
+ getERC20BalanceOf(address, selectedAddress) {
100
+ return __awaiter(this, void 0, void 0, function* () {
101
+ if (!this.erc20Standard) {
102
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
103
+ }
104
+ return this.erc20Standard.getBalanceOf(address, selectedAddress);
105
+ });
106
+ }
107
+ /**
108
+ * Query for the decimals for a given ERC20 asset.
109
+ *
110
+ * @param address - ERC20 asset contract address.
111
+ * @returns Promise resolving to the 'decimals'.
112
+ */
113
+ getERC20TokenDecimals(address) {
114
+ return __awaiter(this, void 0, void 0, function* () {
115
+ if (this.erc20Standard === undefined) {
116
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
117
+ }
118
+ return yield this.erc20Standard.getTokenDecimals(address);
119
+ });
120
+ }
121
+ /**
122
+ * Query for the name for a given ERC20 asset.
123
+ *
124
+ * @param address - ERC20 asset contract address.
125
+ * @returns Promise resolving to the 'decimals'.
126
+ */
127
+ getERC20TokenName(address) {
128
+ return __awaiter(this, void 0, void 0, function* () {
129
+ if (this.erc20Standard === undefined) {
130
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
131
+ }
132
+ return yield this.erc20Standard.getTokenName(address);
133
+ });
134
+ }
135
+ /**
136
+ * Enumerate assets assigned to an owner.
137
+ *
138
+ * @param address - ERC721 asset contract address.
139
+ * @param selectedAddress - Current account public address.
140
+ * @param index - An NFT counter less than `balanceOf(selectedAddress)`.
141
+ * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.
142
+ */
143
+ getERC721NftTokenId(address, selectedAddress, index) {
144
+ if (this.erc721Standard === undefined) {
145
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
146
+ }
147
+ return this.erc721Standard.getNftTokenId(address, selectedAddress, index);
148
+ }
149
+ /**
150
+ * Enumerate assets assigned to an owner.
151
+ *
152
+ * @param tokenAddress - ERC721 asset contract address.
153
+ * @param userAddress - Current account public address.
154
+ * @param tokenId - ERC721 asset identifier.
155
+ * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.
156
+ */
157
+ getTokenStandardAndDetails(tokenAddress, userAddress, tokenId) {
158
+ return __awaiter(this, void 0, void 0, function* () {
159
+ if (this.erc721Standard === undefined ||
160
+ this.erc1155Standard === undefined ||
161
+ this.erc20Standard === undefined) {
162
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
163
+ }
164
+ const { ipfsGateway } = this.config;
165
+ // ERC721
166
+ try {
167
+ return Object.assign({}, (yield this.erc721Standard.getDetails(tokenAddress, ipfsGateway, tokenId)));
168
+ }
169
+ catch (_a) {
170
+ // Ignore
171
+ }
172
+ // ERC1155
173
+ try {
174
+ return Object.assign({}, (yield this.erc1155Standard.getDetails(tokenAddress, ipfsGateway, tokenId)));
175
+ }
176
+ catch (_b) {
177
+ // Ignore
178
+ }
179
+ // ERC20
180
+ try {
181
+ return Object.assign({}, (yield this.erc20Standard.getDetails(tokenAddress, userAddress)));
182
+ }
183
+ catch (_c) {
184
+ // Ignore
185
+ }
186
+ throw new Error('Unable to determine contract standard');
187
+ });
188
+ }
189
+ /**
190
+ * Query for tokenURI for a given ERC721 asset.
191
+ *
192
+ * @param address - ERC721 asset contract address.
193
+ * @param tokenId - ERC721 asset identifier.
194
+ * @returns Promise resolving to the 'tokenURI'.
195
+ */
196
+ getERC721TokenURI(address, tokenId) {
197
+ return __awaiter(this, void 0, void 0, function* () {
198
+ if (this.erc721Standard === undefined) {
199
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
200
+ }
201
+ return this.erc721Standard.getTokenURI(address, tokenId);
202
+ });
203
+ }
204
+ /**
205
+ * Query for name for a given asset.
206
+ *
207
+ * @param address - ERC721 or ERC20 asset contract address.
208
+ * @returns Promise resolving to the 'name'.
209
+ */
210
+ getERC721AssetName(address) {
211
+ return __awaiter(this, void 0, void 0, function* () {
212
+ if (this.erc721Standard === undefined) {
213
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
214
+ }
215
+ return this.erc721Standard.getAssetName(address);
216
+ });
217
+ }
218
+ /**
219
+ * Query for symbol for a given asset.
220
+ *
221
+ * @param address - ERC721 or ERC20 asset contract address.
222
+ * @returns Promise resolving to the 'symbol'.
223
+ */
224
+ getERC721AssetSymbol(address) {
225
+ return __awaiter(this, void 0, void 0, function* () {
226
+ if (this.erc721Standard === undefined) {
227
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
228
+ }
229
+ return this.erc721Standard.getAssetSymbol(address);
230
+ });
231
+ }
232
+ /**
233
+ * Query for owner for a given ERC721 asset.
234
+ *
235
+ * @param address - ERC721 asset contract address.
236
+ * @param tokenId - ERC721 asset identifier.
237
+ * @returns Promise resolving to the owner address.
238
+ */
239
+ getERC721OwnerOf(address, tokenId) {
240
+ return __awaiter(this, void 0, void 0, function* () {
241
+ if (this.erc721Standard === undefined) {
242
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
243
+ }
244
+ return this.erc721Standard.getOwnerOf(address, tokenId);
245
+ });
246
+ }
247
+ /**
248
+ * Query for tokenURI for a given asset.
249
+ *
250
+ * @param address - ERC1155 asset contract address.
251
+ * @param tokenId - ERC1155 asset identifier.
252
+ * @returns Promise resolving to the 'tokenURI'.
253
+ */
254
+ getERC1155TokenURI(address, tokenId) {
255
+ return __awaiter(this, void 0, void 0, function* () {
256
+ if (this.erc1155Standard === undefined) {
257
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
258
+ }
259
+ return this.erc1155Standard.getTokenURI(address, tokenId);
260
+ });
261
+ }
262
+ /**
263
+ * Query for balance of a given ERC 1155 token.
264
+ *
265
+ * @param userAddress - Wallet public address.
266
+ * @param nftAddress - ERC1155 asset contract address.
267
+ * @param nftId - ERC1155 asset identifier.
268
+ * @returns Promise resolving to the 'balanceOf'.
269
+ */
270
+ getERC1155BalanceOf(userAddress, nftAddress, nftId) {
271
+ return __awaiter(this, void 0, void 0, function* () {
272
+ if (this.erc1155Standard === undefined) {
273
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
274
+ }
275
+ return yield this.erc1155Standard.getBalanceOf(nftAddress, userAddress, nftId);
276
+ });
277
+ }
278
+ /**
279
+ * Transfer single ERC1155 token.
280
+ *
281
+ * @param nftAddress - ERC1155 token address.
282
+ * @param senderAddress - ERC1155 token sender.
283
+ * @param recipientAddress - ERC1155 token recipient.
284
+ * @param nftId - ERC1155 token id.
285
+ * @param qty - Quantity of tokens to be sent.
286
+ * @returns Promise resolving to the 'transferSingle' ERC1155 token.
287
+ */
288
+ transferSingleERC1155(nftAddress, senderAddress, recipientAddress, nftId, qty) {
289
+ return __awaiter(this, void 0, void 0, function* () {
290
+ if (this.erc1155Standard === undefined) {
291
+ throw new Error(exports.MISSING_PROVIDER_ERROR);
292
+ }
293
+ return yield this.erc1155Standard.transferSingle(nftAddress, senderAddress, recipientAddress, nftId, qty);
294
+ });
295
+ }
296
+ /**
297
+ * Get the token balance for a list of token addresses in a single call. Only non-zero balances
298
+ * are returned.
299
+ *
300
+ * @param selectedAddress - The address to check token balances for.
301
+ * @param tokensToDetect - The token addresses to detect balances for.
302
+ * @returns The list of non-zero token balances.
303
+ */
304
+ getBalancesInSingleCall(selectedAddress, tokensToDetect) {
305
+ return __awaiter(this, void 0, void 0, function* () {
306
+ if (!(this.config.chainId in exports.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)) {
307
+ // Only fetch balance if contract address exists
308
+ return {};
309
+ }
310
+ const contractAddress = exports.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[this.config.chainId];
311
+ const contract = new contracts_1.Contract(contractAddress, single_call_balance_checker_abi_1.default, this._provider);
312
+ const result = yield contract.balances([selectedAddress], tokensToDetect);
313
+ const nonZeroBalances = {};
314
+ /* istanbul ignore else */
315
+ if (result.length > 0) {
316
+ tokensToDetect.forEach((tokenAddress, index) => {
317
+ const balance = result[index];
318
+ /* istanbul ignore else */
319
+ if (String(balance) !== '0') {
320
+ nonZeroBalances[tokenAddress] = balance;
321
+ }
322
+ });
323
+ }
324
+ return nonZeroBalances;
325
+ });
326
+ }
327
+ }
328
+ exports.AssetsContractController = AssetsContractController;
329
+ exports.default = AssetsContractController;
330
+ //# sourceMappingURL=AssetsContractController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AssetsContractController.js","sourceRoot":"","sources":["../src/AssetsContractController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wDAAoD;AACpD,wDAAwD;AAExD,+DAA2D;AAC3D,iEAAsE;AAKtE,sGAA4E;AAE5E,6CAA+D;AAC/D,6DAA0D;AAC1D,sFAAmF;AACnF,mFAAgF;AAEhF;;;;;GAKG;AACU,QAAA,uCAAuC,GAAwB;IAC1E,CAAC,4CAA+B,CAAC,OAAO,CAAC,EACvC,4CAA4C;IAC9C,CAAC,4CAA+B,CAAC,GAAG,CAAC,EACnC,4CAA4C;IAC9C,CAAC,4CAA+B,CAAC,OAAO,CAAC,EACvC,4CAA4C;IAC9C,CAAC,4CAA+B,CAAC,IAAI,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gBACtC,MAAM,IAAI,KAAK,CAAC,8BAAsB,CAAC,CAAC;aACzC;YACD,OAAO,MAAM,IAAI,CAAC,eAAe,CAAC,cAAc,CAC9C,UAAU,EACV,aAAa,EACb,gBAAgB,EAChB,KAAK,EACL,GAAG,CACJ,CAAC;QACJ,CAAC;KAAA;IAED;;;;;;;OAOG;IACG,uBAAuB,CAC3B,eAAuB,EACvB,cAAwB;;YAExB,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,+CAAuC,CAAC,EAAE;gBACrE,gDAAgD;gBAChD,OAAO,EAAE,CAAC;aACX;YACD,MAAM,eAAe,GACnB,+CAAuC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAE/D,MAAM,QAAQ,GAAG,IAAI,oBAAQ,CAC3B,eAAe,EACf,yCAA6B,EAC7B,IAAI,CAAC,SAAS,CACf,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,QAAQ,CAAC,CAAC,eAAe,CAAC,EAAE,cAAc,CAAC,CAAC;YAC1E,MAAM,eAAe,GAAe,EAAE,CAAC;YACvC,0BAA0B;YAC1B,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,cAAc,CAAC,OAAO,CAAC,CAAC,YAAY,EAAE,KAAK,EAAE,EAAE;oBAC7C,MAAM,OAAO,GAAO,MAAM,CAAC,KAAK,CAAC,CAAC;oBAClC,0BAA0B;oBAC1B,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,GAAG,EAAE;wBAC3B,eAAe,CAAC,YAAY,CAAC,GAAG,OAAO,CAAC;qBACzC;gBACH,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,eAAe,CAAC;QACzB,CAAC;KAAA;CACF;AAnXD,4DAmXC;AAED,kBAAe,wBAAwB,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';\nimport type { NetworkState } from '@metamask/network-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type { BN } from 'ethereumjs-util';\nimport abiSingleCallBalancesContract from 'single-call-balance-checker-abi';\n\nimport { SupportedTokenDetectionNetworks } from './assetsUtil';\nimport { ERC20Standard } from './Standards/ERC20Standard';\nimport { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';\nimport { ERC721Standard } from './Standards/NftStandards/ERC721/ERC721Standard';\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 const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID: Record<Hex, string> = {\n [SupportedTokenDetectionNetworks.mainnet]:\n '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',\n [SupportedTokenDetectionNetworks.bsc]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.polygon]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.avax]:\n '0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',\n [SupportedTokenDetectionNetworks.aurora]:\n '0x1286415D333855237f89Df27D388127181448538',\n};\n\nexport const MISSING_PROVIDER_ERROR =\n 'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';\n\n/**\n * @type AssetsContractConfig\n *\n * Assets Contract controller configuration\n * @property provider - Provider used to create a new web3 instance\n */\nexport interface AssetsContractConfig extends BaseConfig {\n provider: any;\n ipfsGateway: string;\n chainId: Hex;\n}\n\n/**\n * @type BalanceMap\n *\n * Key value object containing the balance for each tokenAddress\n * @property [tokenAddress] - Address of the token\n */\nexport interface BalanceMap {\n [tokenAddress: string]: BN;\n}\n\n/**\n * Controller that interacts with contracts on mainnet through web3\n */\nexport class AssetsContractController extends BaseController<\n AssetsContractConfig,\n BaseState\n> {\n private _provider?: Web3Provider;\n\n private erc721Standard?: ERC721Standard;\n\n private erc1155Standard?: ERC1155Standard;\n\n private erc20Standard?: ERC20Standard;\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AssetsContractController';\n\n /**\n * Creates a AssetsContractController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n chainId: initialChainId,\n onPreferencesStateChange,\n onNetworkStateChange,\n }: {\n chainId: Hex;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n },\n config?: Partial<AssetsContractConfig>,\n state?: Partial<BaseState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n provider: undefined,\n ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,\n chainId: initialChainId,\n };\n this.initialize();\n\n onPreferencesStateChange(({ ipfsGateway }) => {\n this.configure({ ipfsGateway });\n });\n\n onNetworkStateChange((networkState) => {\n if (this.config.chainId !== networkState.providerConfig.chainId) {\n this.configure({\n chainId: networkState.providerConfig.chainId,\n });\n }\n });\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @property provider - Provider used to create a new underlying Web3 instance\n */\n set provider(provider: any) {\n this._provider = new Web3Provider(provider);\n this.erc721Standard = new ERC721Standard(this._provider);\n this.erc1155Standard = new ERC1155Standard(this._provider);\n this.erc20Standard = new ERC20Standard(this._provider);\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Get balance or count for current account on specific asset contract.\n *\n * @param address - Asset ERC20 contract address.\n * @param selectedAddress - Current account public address.\n * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getERC20BalanceOf(\n address: string,\n selectedAddress: string,\n ): Promise<BN> {\n if (!this.erc20Standard) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return this.erc20Standard.getBalanceOf(address, selectedAddress);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenDecimals(address: string): Promise<string> {\n if (this.erc20Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return await this.erc20Standard.getTokenDecimals(address);\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenName(address: string): Promise<string> {\n if (this.erc20Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return await this.erc20Standard.getTokenName(address);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param address - ERC721 asset contract address.\n * @param selectedAddress - Current account public address.\n * @param index - An NFT counter less than `balanceOf(selectedAddress)`.\n * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.\n */\n getERC721NftTokenId(\n address: string,\n selectedAddress: string,\n index: number,\n ): Promise<string> {\n if (this.erc721Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return this.erc721Standard.getNftTokenId(address, selectedAddress, index);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param tokenAddress - ERC721 asset contract address.\n * @param userAddress - Current account public address.\n * @param tokenId - ERC721 asset identifier.\n * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.\n */\n async getTokenStandardAndDetails(\n tokenAddress: string,\n userAddress?: string,\n tokenId?: string,\n ): Promise<{\n standard: string;\n tokenURI?: string | undefined;\n symbol?: string | undefined;\n name?: string | undefined;\n decimals?: string | undefined;\n balance?: BN | undefined;\n }> {\n if (\n this.erc721Standard === undefined ||\n this.erc1155Standard === undefined ||\n this.erc20Standard === undefined\n ) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n\n const { ipfsGateway } = this.config;\n\n // ERC721\n try {\n return {\n ...(await this.erc721Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC1155\n try {\n return {\n ...(await this.erc1155Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC20\n try {\n return {\n ...(await this.erc20Standard.getDetails(tokenAddress, userAddress)),\n };\n } catch {\n // Ignore\n }\n\n throw new Error('Unable to determine contract standard');\n }\n\n /**\n * Query for tokenURI for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC721TokenURI(address: string, tokenId: string): Promise<string> {\n if (this.erc721Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return this.erc721Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @returns Promise resolving to the 'name'.\n */\n async getERC721AssetName(address: string): Promise<string> {\n if (this.erc721Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return this.erc721Standard.getAssetName(address);\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @returns Promise resolving to the 'symbol'.\n */\n async getERC721AssetSymbol(address: string): Promise<string> {\n if (this.erc721Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return this.erc721Standard.getAssetSymbol(address);\n }\n\n /**\n * Query for owner for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @returns Promise resolving to the owner address.\n */\n async getERC721OwnerOf(address: string, tokenId: string): Promise<string> {\n if (this.erc721Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return this.erc721Standard.getOwnerOf(address, tokenId);\n }\n\n /**\n * Query for tokenURI for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @param tokenId - ERC1155 asset identifier.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC1155TokenURI(address: string, tokenId: string): Promise<string> {\n if (this.erc1155Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return this.erc1155Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for balance of a given ERC 1155 token.\n *\n * @param userAddress - Wallet public address.\n * @param nftAddress - ERC1155 asset contract address.\n * @param nftId - ERC1155 asset identifier.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getERC1155BalanceOf(\n userAddress: string,\n nftAddress: string,\n nftId: string,\n ): Promise<BN> {\n if (this.erc1155Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return await this.erc1155Standard.getBalanceOf(\n nftAddress,\n userAddress,\n nftId,\n );\n }\n\n /**\n * Transfer single ERC1155 token.\n *\n * @param nftAddress - ERC1155 token address.\n * @param senderAddress - ERC1155 token sender.\n * @param recipientAddress - ERC1155 token recipient.\n * @param nftId - ERC1155 token id.\n * @param qty - Quantity of tokens to be sent.\n * @returns Promise resolving to the 'transferSingle' ERC1155 token.\n */\n async transferSingleERC1155(\n nftAddress: string,\n senderAddress: string,\n recipientAddress: string,\n nftId: string,\n qty: string,\n ): Promise<void> {\n if (this.erc1155Standard === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n return await this.erc1155Standard.transferSingle(\n nftAddress,\n senderAddress,\n recipientAddress,\n nftId,\n qty,\n );\n }\n\n /**\n * Get the token balance for a list of token addresses in a single call. Only non-zero balances\n * are returned.\n *\n * @param selectedAddress - The address to check token balances for.\n * @param tokensToDetect - The token addresses to detect balances for.\n * @returns The list of non-zero token balances.\n */\n async getBalancesInSingleCall(\n selectedAddress: string,\n tokensToDetect: string[],\n ) {\n if (!(this.config.chainId in SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)) {\n // Only fetch balance if contract address exists\n return {};\n }\n const contractAddress =\n SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[this.config.chainId];\n\n const contract = new Contract(\n contractAddress,\n abiSingleCallBalancesContract,\n this._provider,\n );\n const result = await contract.balances([selectedAddress], tokensToDetect);\n const nonZeroBalances: BalanceMap = {};\n /* istanbul ignore else */\n if (result.length > 0) {\n tokensToDetect.forEach((tokenAddress, index) => {\n const balance: BN = result[index];\n /* istanbul ignore else */\n if (String(balance) !== '0') {\n nonZeroBalances[tokenAddress] = balance;\n }\n });\n }\n return nonZeroBalances;\n }\n}\n\nexport default AssetsContractController;\n"]}
@@ -0,0 +1,101 @@
1
+ import type { RestrictedControllerMessenger } from '@metamask/base-controller';
2
+ import { BaseControllerV2 } from '@metamask/base-controller';
3
+ import type { Patch } from 'immer';
4
+ import { fetchExchangeRate as defaultFetchExchangeRate } from './crypto-compare';
5
+ /**
6
+ * @type CurrencyRateState
7
+ * @property conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
8
+ * @property conversionRate - Conversion rate from current base asset to the current currency
9
+ * @property currentCurrency - Currently-active ISO 4217 currency code
10
+ * @property nativeCurrency - Symbol for the base asset used for conversion
11
+ * @property pendingCurrentCurrency - The currency being switched to
12
+ * @property pendingNativeCurrency - The base asset currency being switched to
13
+ * @property usdConversionRate - Conversion rate from usd to the current currency
14
+ */
15
+ export declare type CurrencyRateState = {
16
+ conversionDate: number | null;
17
+ conversionRate: number | null;
18
+ currentCurrency: string;
19
+ nativeCurrency: string;
20
+ pendingCurrentCurrency: string | null;
21
+ pendingNativeCurrency: string | null;
22
+ usdConversionRate: number | null;
23
+ };
24
+ declare const name = "CurrencyRateController";
25
+ export declare type CurrencyRateStateChange = {
26
+ type: `${typeof name}:stateChange`;
27
+ payload: [CurrencyRateState, Patch[]];
28
+ };
29
+ export declare type GetCurrencyRateState = {
30
+ type: `${typeof name}:getState`;
31
+ handler: () => CurrencyRateState;
32
+ };
33
+ declare type CurrencyRateMessenger = RestrictedControllerMessenger<typeof name, GetCurrencyRateState, CurrencyRateStateChange, never, never>;
34
+ /**
35
+ * Controller that passively polls on a set interval for an exchange rate from the current network
36
+ * asset to the user's preferred currency.
37
+ */
38
+ export declare class CurrencyRateController extends BaseControllerV2<typeof name, CurrencyRateState, CurrencyRateMessenger> {
39
+ #private;
40
+ private readonly mutex;
41
+ private intervalId?;
42
+ private readonly intervalDelay;
43
+ private readonly fetchExchangeRate;
44
+ private readonly includeUsdRate;
45
+ /**
46
+ * Creates a CurrencyRateController instance.
47
+ *
48
+ * @param options - Constructor options.
49
+ * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
50
+ * @param options.interval - The polling interval, in milliseconds.
51
+ * @param options.messenger - A reference to the messaging system.
52
+ * @param options.state - Initial state to set on this controller.
53
+ * @param options.fetchExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
54
+ */
55
+ constructor({ includeUsdRate, interval, messenger, state, fetchExchangeRate, }: {
56
+ includeUsdRate?: boolean;
57
+ interval?: number;
58
+ messenger: CurrencyRateMessenger;
59
+ state?: Partial<CurrencyRateState>;
60
+ fetchExchangeRate?: typeof defaultFetchExchangeRate;
61
+ });
62
+ /**
63
+ * Start polling for the currency rate.
64
+ */
65
+ start(): Promise<void>;
66
+ /**
67
+ * Stop polling for the currency rate.
68
+ */
69
+ stop(): void;
70
+ /**
71
+ * Prepare to discard this controller.
72
+ *
73
+ * This stops any active polling.
74
+ */
75
+ destroy(): void;
76
+ /**
77
+ * Sets a currency to track.
78
+ *
79
+ * @param currentCurrency - ISO 4217 currency code.
80
+ */
81
+ setCurrentCurrency(currentCurrency: string): Promise<void>;
82
+ /**
83
+ * Sets a new native currency.
84
+ *
85
+ * @param symbol - Symbol for the base asset.
86
+ */
87
+ setNativeCurrency(symbol: string): Promise<void>;
88
+ private stopPolling;
89
+ /**
90
+ * Starts a new polling interval.
91
+ */
92
+ private startPolling;
93
+ /**
94
+ * Updates exchange rate for the current currency.
95
+ *
96
+ * @returns The controller state.
97
+ */
98
+ updateExchangeRate(): Promise<CurrencyRateState | void>;
99
+ }
100
+ export default CurrencyRateController;
101
+ //# sourceMappingURL=CurrencyRateController.d.ts.map