@metamask/assets-controllers 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +20 -0
  3. package/README.md +30 -0
  4. package/dist/AccountTrackerController.d.ts +88 -0
  5. package/dist/AccountTrackerController.js +138 -0
  6. package/dist/AccountTrackerController.js.map +1 -0
  7. package/dist/AssetsContractController.d.ts +176 -0
  8. package/dist/AssetsContractController.js +314 -0
  9. package/dist/AssetsContractController.js.map +1 -0
  10. package/dist/CurrencyRateController.d.ts +98 -0
  11. package/dist/CurrencyRateController.js +193 -0
  12. package/dist/CurrencyRateController.js.map +1 -0
  13. package/dist/NftController.d.ts +409 -0
  14. package/dist/NftController.js +835 -0
  15. package/dist/NftController.js.map +1 -0
  16. package/dist/NftDetectionController.d.ts +179 -0
  17. package/dist/NftDetectionController.js +204 -0
  18. package/dist/NftDetectionController.js.map +1 -0
  19. package/dist/Standards/ERC20Standard.d.ts +42 -0
  20. package/dist/Standards/ERC20Standard.js +121 -0
  21. package/dist/Standards/ERC20Standard.js.map +1 -0
  22. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts +78 -0
  23. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +148 -0
  24. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -0
  25. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts +88 -0
  26. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +182 -0
  27. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -0
  28. package/dist/Standards/standards-types.d.ts +14 -0
  29. package/dist/Standards/standards-types.js +3 -0
  30. package/dist/Standards/standards-types.js.map +1 -0
  31. package/dist/TokenBalancesController.d.ts +69 -0
  32. package/dist/TokenBalancesController.js +94 -0
  33. package/dist/TokenBalancesController.js.map +1 -0
  34. package/dist/TokenDetectionController.d.ts +84 -0
  35. package/dist/TokenDetectionController.js +185 -0
  36. package/dist/TokenDetectionController.js.map +1 -0
  37. package/dist/TokenListController.d.ts +114 -0
  38. package/dist/TokenListController.js +256 -0
  39. package/dist/TokenListController.js.map +1 -0
  40. package/dist/TokenRatesController.d.ts +167 -0
  41. package/dist/TokenRatesController.js +284 -0
  42. package/dist/TokenRatesController.js.map +1 -0
  43. package/dist/TokensController.d.ts +238 -0
  44. package/dist/TokensController.js +530 -0
  45. package/dist/TokensController.js.map +1 -0
  46. package/dist/assetsUtil.d.ts +106 -0
  47. package/dist/assetsUtil.js +228 -0
  48. package/dist/assetsUtil.js.map +1 -0
  49. package/dist/crypto-compare.d.ts +12 -0
  50. package/dist/crypto-compare.js +67 -0
  51. package/dist/crypto-compare.js.map +1 -0
  52. package/dist/index.d.ts +11 -0
  53. package/dist/index.js +31 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/token-service.d.ts +29 -0
  56. package/dist/token-service.js +134 -0
  57. package/dist/token-service.js.map +1 -0
  58. package/package.json +75 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [1.0.0]
10
+ ### Added
11
+ - Initial release
12
+ - As a result of converting our shared controllers repo into a monorepo ([#831](https://github.com/MetaMask/controllers/pull/831)), we've created this package from select parts of [`@metamask/controllers` v33.0.0](https://github.com/MetaMask/controllers/tree/v33.0.0), namely:
13
+ - Everything in `src/assets`
14
+ - Asset-related functions from `src/util.ts` and accompanying tests
15
+
16
+ All changes listed after this point were applied to this package following the monorepo conversion.
17
+
18
+ ### Changed
19
+ - Use Ethers for AssetsContractController ([#845](https://github.com/MetaMask/controllers/pull/845))
20
+
21
+ [Unreleased]: https://github.com/MetaMask/controllers/compare/@metamask/assets-controllers@1.0.0...HEAD
22
+ [1.0.0]: https://github.com/MetaMask/controllers/releases/tag/@metamask/assets-controllers@1.0.0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 MetaMask
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
package/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # `@metamask/assets-controllers`
2
+
3
+ Controllers which manage interactions involving ERC-20, ERC-721, and ERC-1155 tokens (including NFTs).
4
+
5
+ ## Installation
6
+
7
+ `yarn add @metamask/assets-controllers`
8
+
9
+ or
10
+
11
+ `npm install @metamask/assets-controllers`
12
+
13
+ ## Controllers
14
+
15
+ This package features the following controllers:
16
+
17
+ - [**AccountTrackerController**](src/AccountTrackerController.ts) keeps a updated list of the accounts in the currently selected keychain which is updated automatically on a schedule or on demand.
18
+ - [**AssetsContractController**](src/AssetsContractController.ts) provides a set of convenience methods that use contracts to retrieve information about tokens, read token balances, and transfer tokens.
19
+ - [**CollectibleDetectionController**](src/CollectibleDetectionController.ts) keeps a periodically updated list of ERC-721 tokens assigned to the currently selected address.
20
+ - [**CollectiblesController**](src/CollectiblesController.ts) tracks ERC-721 and ERC-1155 tokens assigned to the currently selected address, using OpenSea to retrieve token information.
21
+ - [**CurrencyRateController**](src/CurrencyRateController.ts) keeps a periodically updated value of the exchange rate from the currently selected "native" currency to another (handling testnet tokens specially).
22
+ - [**TokenBalancesController**](src/TokenBalancesController.ts) keeps a periodically updated set of balances for the current set of ERC-20 tokens.
23
+ - [**TokenDetectionController**](src/TokenDetectionController.ts) keeps a periodically updated list of ERC-20 tokens assigned to the currently selected address.
24
+ - [**TokenListController**](src/TokenListController.ts) uses the MetaSwap API to keep a periodically updated list of known ERC-20 tokens along with their metadata.
25
+ - [**TokenRatesController**](src/TokenRatesController.ts) keeps a periodically updated list of exchange rates for known ERC-20 tokens relative to the currently selected native currency.
26
+ - [**TokensController**](src/TokensController.ts) stores the ERC-20 and ERC-721 tokens, along with their metadata, that are listed in the wallet under the currently selected address on the currently selected chain.
27
+
28
+ ## Contributing
29
+
30
+ This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/controllers#readme).
@@ -0,0 +1,88 @@
1
+ import { BaseConfig, BaseController, BaseState } from '@metamask/base-controller';
2
+ import { PreferencesState } from '@metamask/preferences-controller';
3
+ /**
4
+ * @type AccountInformation
5
+ *
6
+ * Account information object
7
+ * @property balance - Hex string of an account balancec in wei
8
+ */
9
+ export interface AccountInformation {
10
+ balance: string;
11
+ }
12
+ /**
13
+ * @type AccountTrackerConfig
14
+ *
15
+ * Account tracker controller configuration
16
+ * @property provider - Provider used to create a new underlying EthQuery instance
17
+ */
18
+ export interface AccountTrackerConfig extends BaseConfig {
19
+ interval: number;
20
+ provider?: any;
21
+ }
22
+ /**
23
+ * @type AccountTrackerState
24
+ *
25
+ * Account tracker controller state
26
+ * @property accounts - Map of addresses to account information
27
+ */
28
+ export interface AccountTrackerState extends BaseState {
29
+ accounts: {
30
+ [address: string]: AccountInformation;
31
+ };
32
+ }
33
+ /**
34
+ * Controller that tracks the network balances for all user accounts.
35
+ */
36
+ export declare class AccountTrackerController extends BaseController<AccountTrackerConfig, AccountTrackerState> {
37
+ private ethQuery;
38
+ private mutex;
39
+ private handle?;
40
+ private syncAccounts;
41
+ /**
42
+ * Name of this controller used during composition
43
+ */
44
+ name: string;
45
+ private getIdentities;
46
+ /**
47
+ * Creates an AccountTracker instance.
48
+ *
49
+ * @param options - The controller options.
50
+ * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
51
+ * @param options.getIdentities - Gets the identities from the Preferences store.
52
+ * @param config - Initial options used to configure this controller.
53
+ * @param state - Initial state to set on this controller.
54
+ */
55
+ constructor({ onPreferencesStateChange, getIdentities, }: {
56
+ onPreferencesStateChange: (listener: (preferencesState: PreferencesState) => void) => void;
57
+ getIdentities: () => PreferencesState['identities'];
58
+ }, config?: Partial<AccountTrackerConfig>, state?: Partial<AccountTrackerState>);
59
+ /**
60
+ * Sets a new provider.
61
+ *
62
+ * TODO: Replace this wth a method.
63
+ *
64
+ * @param provider - Provider used to create a new underlying EthQuery instance.
65
+ */
66
+ set provider(provider: any);
67
+ get provider(): any;
68
+ /**
69
+ * Starts a new polling interval.
70
+ *
71
+ * @param interval - Polling interval trigger a 'refresh'.
72
+ */
73
+ poll(interval?: number): Promise<void>;
74
+ /**
75
+ * Refreshes all accounts in the current keychain.
76
+ */
77
+ refresh: () => Promise<void>;
78
+ /**
79
+ * Sync accounts balances with some additional addresses.
80
+ *
81
+ * @param addresses - the additional addresses, may be hardware wallet addresses.
82
+ * @returns accounts - addresses with synced balance
83
+ */
84
+ syncBalanceWithAddresses(addresses: string[]): Promise<Record<string, {
85
+ balance: string;
86
+ }>>;
87
+ }
88
+ export default AccountTrackerController;
@@ -0,0 +1,138 @@
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.AccountTrackerController = void 0;
16
+ const eth_query_1 = __importDefault(require("eth-query"));
17
+ const async_mutex_1 = require("async-mutex");
18
+ const base_controller_1 = require("@metamask/base-controller");
19
+ const controller_utils_1 = require("@metamask/controller-utils");
20
+ /**
21
+ * Controller that tracks the network balances for all user accounts.
22
+ */
23
+ class AccountTrackerController extends base_controller_1.BaseController {
24
+ /**
25
+ * Creates an AccountTracker instance.
26
+ *
27
+ * @param options - The controller options.
28
+ * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
29
+ * @param options.getIdentities - Gets the identities from the Preferences store.
30
+ * @param config - Initial options used to configure this controller.
31
+ * @param state - Initial state to set on this controller.
32
+ */
33
+ constructor({ onPreferencesStateChange, getIdentities, }, config, state) {
34
+ super(config, state);
35
+ this.mutex = new async_mutex_1.Mutex();
36
+ /**
37
+ * Name of this controller used during composition
38
+ */
39
+ this.name = 'AccountTrackerController';
40
+ /**
41
+ * Refreshes all accounts in the current keychain.
42
+ */
43
+ this.refresh = () => __awaiter(this, void 0, void 0, function* () {
44
+ this.syncAccounts();
45
+ const accounts = Object.assign({}, this.state.accounts);
46
+ for (const address in accounts) {
47
+ yield (0, controller_utils_1.safelyExecuteWithTimeout)(() => __awaiter(this, void 0, void 0, function* () {
48
+ const balance = yield (0, controller_utils_1.query)(this.ethQuery, 'getBalance', [address]);
49
+ accounts[address] = { balance: (0, controller_utils_1.BNToHex)(balance) };
50
+ }));
51
+ }
52
+ this.update({ accounts });
53
+ });
54
+ this.defaultConfig = {
55
+ interval: 10000,
56
+ };
57
+ this.defaultState = { accounts: {} };
58
+ this.initialize();
59
+ this.getIdentities = getIdentities;
60
+ onPreferencesStateChange(() => {
61
+ this.refresh();
62
+ });
63
+ this.poll();
64
+ }
65
+ syncAccounts() {
66
+ const { accounts } = this.state;
67
+ const addresses = Object.keys(this.getIdentities());
68
+ const existing = Object.keys(accounts);
69
+ const newAddresses = addresses.filter((address) => existing.indexOf(address) === -1);
70
+ const oldAddresses = existing.filter((address) => addresses.indexOf(address) === -1);
71
+ newAddresses.forEach((address) => {
72
+ accounts[address] = { balance: '0x0' };
73
+ });
74
+ oldAddresses.forEach((address) => {
75
+ delete accounts[address];
76
+ });
77
+ this.update({ accounts: Object.assign({}, accounts) });
78
+ }
79
+ /**
80
+ * Sets a new provider.
81
+ *
82
+ * TODO: Replace this wth a method.
83
+ *
84
+ * @param provider - Provider used to create a new underlying EthQuery instance.
85
+ */
86
+ set provider(provider) {
87
+ this.ethQuery = new eth_query_1.default(provider);
88
+ }
89
+ get provider() {
90
+ throw new Error('Property only used for setting');
91
+ }
92
+ /**
93
+ * Starts a new polling interval.
94
+ *
95
+ * @param interval - Polling interval trigger a 'refresh'.
96
+ */
97
+ poll(interval) {
98
+ return __awaiter(this, void 0, void 0, function* () {
99
+ const releaseLock = yield this.mutex.acquire();
100
+ interval && this.configure({ interval }, false, false);
101
+ this.handle && clearTimeout(this.handle);
102
+ yield this.refresh();
103
+ this.handle = setTimeout(() => {
104
+ releaseLock();
105
+ this.poll(this.config.interval);
106
+ }, this.config.interval);
107
+ });
108
+ }
109
+ /**
110
+ * Sync accounts balances with some additional addresses.
111
+ *
112
+ * @param addresses - the additional addresses, may be hardware wallet addresses.
113
+ * @returns accounts - addresses with synced balance
114
+ */
115
+ syncBalanceWithAddresses(addresses) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ return yield Promise.all(addresses.map((address) => {
118
+ return (0, controller_utils_1.safelyExecuteWithTimeout)(() => __awaiter(this, void 0, void 0, function* () {
119
+ const balance = yield (0, controller_utils_1.query)(this.ethQuery, 'getBalance', [address]);
120
+ return [address, balance];
121
+ }));
122
+ })).then((value) => {
123
+ return value.reduce((obj, item) => {
124
+ if (!item) {
125
+ return obj;
126
+ }
127
+ const [address, balance] = item;
128
+ return Object.assign(Object.assign({}, obj), { [address]: {
129
+ balance,
130
+ } });
131
+ }, {});
132
+ });
133
+ });
134
+ }
135
+ }
136
+ exports.AccountTrackerController = AccountTrackerController;
137
+ exports.default = AccountTrackerController;
138
+ //# sourceMappingURL=AccountTrackerController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AccountTrackerController.js","sourceRoot":"","sources":["../src/AccountTrackerController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,0DAAiC;AACjC,6CAAoC;AACpC,+DAImC;AAEnC,iEAIoC;AAiCpC;;GAEG;AACH,MAAa,wBAAyB,SAAQ,gCAG7C;IAkCC;;;;;;;;OAQG;IACH,YACE,EACE,wBAAwB,EACxB,aAAa,GAMd,EACD,MAAsC,EACtC,KAAoC;QAEpC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QArDf,UAAK,GAAG,IAAI,mBAAK,EAAE,CAAC;QAwB5B;;WAEG;QACM,SAAI,GAAG,0BAA0B,CAAC;QAsE3C;;WAEG;QACH,YAAO,GAAG,GAAS,EAAE;YACnB,IAAI,CAAC,YAAY,EAAE,CAAC;YACpB,MAAM,QAAQ,qBAAQ,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAE,CAAC;YAC5C,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;gBAC9B,MAAM,IAAA,2CAAwB,EAAC,GAAS,EAAE;oBACxC,MAAM,OAAO,GAAG,MAAM,IAAA,wBAAK,EAAC,IAAI,CAAC,QAAQ,EAAE,YAAY,EAAE,CAAC,OAAO,CAAC,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AM,IAAA,wBAAK,EAAC,IAAI,CAAC,QAAQ,EAAE,YAAY,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;oBACpE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;gBAC5B,CAAC,CAAA,CAAC,CAAC;YACL,CAAC,CAAC,CACH,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;gBACf,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;oBAChC,IAAI,CAAC,IAAI,EAAE;wBACT,OAAO,GAAG,CAAC;qBACZ;oBAED,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;oBAChC,uCACK,GAAG,KACN,CAAC,OAAO,CAAC,EAAE;4BACT,OAAO;yBACR,IACD;gBACJ,CAAC,EAAE,EAAE,CAAC,CAAC;YACT,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;CACF;AAtJD,4DAsJC;AAED,kBAAe,wBAAwB,CAAC","sourcesContent":["import EthQuery from 'eth-query';\nimport { Mutex } from 'async-mutex';\nimport {\n BaseConfig,\n BaseController,\n BaseState,\n} from '@metamask/base-controller';\nimport { PreferencesState } from '@metamask/preferences-controller';\nimport {\n BNToHex,\n query,\n safelyExecuteWithTimeout,\n} from '@metamask/controller-utils';\n\n/**\n * @type AccountInformation\n *\n * Account information object\n * @property balance - Hex string of an account balancec in wei\n */\nexport interface AccountInformation {\n balance: string;\n}\n\n/**\n * @type AccountTrackerConfig\n *\n * Account tracker controller configuration\n * @property provider - Provider used to create a new underlying EthQuery instance\n */\nexport interface AccountTrackerConfig extends BaseConfig {\n interval: number;\n provider?: any;\n}\n\n/**\n * @type AccountTrackerState\n *\n * Account tracker controller state\n * @property accounts - Map of addresses to account information\n */\nexport interface AccountTrackerState extends BaseState {\n accounts: { [address: string]: AccountInformation };\n}\n\n/**\n * Controller that tracks the network balances for all user accounts.\n */\nexport class AccountTrackerController extends BaseController<\n AccountTrackerConfig,\n AccountTrackerState\n> {\n private ethQuery: any;\n\n private mutex = new Mutex();\n\n private handle?: ReturnType<typeof setTimeout>;\n\n private syncAccounts() {\n const { accounts } = this.state;\n const addresses = Object.keys(this.getIdentities());\n const existing = Object.keys(accounts);\n const newAddresses = addresses.filter(\n (address) => existing.indexOf(address) === -1,\n );\n const oldAddresses = existing.filter(\n (address) => addresses.indexOf(address) === -1,\n );\n newAddresses.forEach((address) => {\n accounts[address] = { balance: '0x0' };\n });\n\n oldAddresses.forEach((address) => {\n delete accounts[address];\n });\n this.update({ accounts: { ...accounts } });\n }\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AccountTrackerController';\n\n private getIdentities: () => PreferencesState['identities'];\n\n /**\n * Creates an AccountTracker instance.\n *\n * @param options - The controller options.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.getIdentities - Gets the identities from the Preferences store.\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 onPreferencesStateChange,\n getIdentities,\n }: {\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n getIdentities: () => PreferencesState['identities'];\n },\n config?: Partial<AccountTrackerConfig>,\n state?: Partial<AccountTrackerState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval: 10000,\n };\n this.defaultState = { accounts: {} };\n this.initialize();\n this.getIdentities = getIdentities;\n onPreferencesStateChange(() => {\n this.refresh();\n });\n this.poll();\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @param provider - Provider used to create a new underlying EthQuery instance.\n */\n set provider(provider: any) {\n this.ethQuery = new EthQuery(provider);\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval trigger a 'refresh'.\n */\n async poll(interval?: number): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n interval && this.configure({ interval }, false, false);\n this.handle && clearTimeout(this.handle);\n await this.refresh();\n this.handle = setTimeout(() => {\n releaseLock();\n this.poll(this.config.interval);\n }, this.config.interval);\n }\n\n /**\n * Refreshes all accounts in the current keychain.\n */\n refresh = async () => {\n this.syncAccounts();\n const accounts = { ...this.state.accounts };\n for (const address in accounts) {\n await safelyExecuteWithTimeout(async () => {\n const balance = await query(this.ethQuery, 'getBalance', [address]);\n accounts[address] = { balance: BNToHex(balance) };\n });\n }\n this.update({ accounts });\n };\n\n /**\n * Sync accounts balances with some additional addresses.\n *\n * @param addresses - the additional addresses, may be hardware wallet addresses.\n * @returns accounts - addresses with synced balance\n */\n async syncBalanceWithAddresses(\n addresses: string[],\n ): Promise<Record<string, { balance: string }>> {\n return await Promise.all(\n addresses.map((address): Promise<[string, string] | undefined> => {\n return safelyExecuteWithTimeout(async () => {\n const balance = await query(this.ethQuery, 'getBalance', [address]);\n return [address, balance];\n });\n }),\n ).then((value) => {\n return value.reduce((obj, item) => {\n if (!item) {\n return obj;\n }\n\n const [address, balance] = item;\n return {\n ...obj,\n [address]: {\n balance,\n },\n };\n }, {});\n });\n }\n}\n\nexport default AccountTrackerController;\n"]}
@@ -0,0 +1,176 @@
1
+ /// <reference types="bn.js" />
2
+ import { BN } from 'ethereumjs-util';
3
+ import { BaseController, BaseConfig, BaseState } from '@metamask/base-controller';
4
+ import type { PreferencesState } from '@metamask/preferences-controller';
5
+ import { NetworkState } from '@metamask/network-controller';
6
+ /**
7
+ * Check if token detection is enabled for certain networks
8
+ *
9
+ * @param chainId - ChainID of network
10
+ * @returns Whether the current network supports token detection
11
+ */
12
+ export declare const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID: Record<string, string>;
13
+ export declare const MISSING_PROVIDER_ERROR = "AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available";
14
+ /**
15
+ * @type AssetsContractConfig
16
+ *
17
+ * Assets Contract controller configuration
18
+ * @property provider - Provider used to create a new web3 instance
19
+ */
20
+ export interface AssetsContractConfig extends BaseConfig {
21
+ provider: any;
22
+ ipfsGateway: string;
23
+ chainId: string;
24
+ }
25
+ /**
26
+ * @type BalanceMap
27
+ *
28
+ * Key value object containing the balance for each tokenAddress
29
+ * @property [tokenAddress] - Address of the token
30
+ */
31
+ export interface BalanceMap {
32
+ [tokenAddress: string]: BN;
33
+ }
34
+ /**
35
+ * Controller that interacts with contracts on mainnet through web3
36
+ */
37
+ export declare class AssetsContractController extends BaseController<AssetsContractConfig, BaseState> {
38
+ private _provider?;
39
+ private erc721Standard?;
40
+ private erc1155Standard?;
41
+ private erc20Standard?;
42
+ /**
43
+ * Name of this controller used during composition
44
+ */
45
+ name: string;
46
+ /**
47
+ * Creates a AssetsContractController instance.
48
+ *
49
+ * @param options - The controller options.
50
+ * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
51
+ * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
52
+ * @param config - Initial options used to configure this controller.
53
+ * @param state - Initial state to set on this controller.
54
+ */
55
+ constructor({ onPreferencesStateChange, onNetworkStateChange, }: {
56
+ onPreferencesStateChange: (listener: (preferencesState: PreferencesState) => void) => void;
57
+ onNetworkStateChange: (listener: (networkState: NetworkState) => void) => void;
58
+ }, config?: Partial<AssetsContractConfig>, state?: Partial<BaseState>);
59
+ /**
60
+ * Sets a new provider.
61
+ *
62
+ * TODO: Replace this wth a method.
63
+ *
64
+ * @property provider - Provider used to create a new underlying Web3 instance
65
+ */
66
+ set provider(provider: any);
67
+ get provider(): any;
68
+ /**
69
+ * Get balance or count for current account on specific asset contract.
70
+ *
71
+ * @param address - Asset ERC20 contract address.
72
+ * @param selectedAddress - Current account public address.
73
+ * @returns Promise resolving to BN object containing balance for current account on specific asset contract.
74
+ */
75
+ getERC20BalanceOf(address: string, selectedAddress: string): Promise<BN>;
76
+ /**
77
+ * Query for the decimals for a given ERC20 asset.
78
+ *
79
+ * @param address - ERC20 asset contract address.
80
+ * @returns Promise resolving to the 'decimals'.
81
+ */
82
+ getERC20TokenDecimals(address: string): Promise<string>;
83
+ /**
84
+ * Enumerate assets assigned to an owner.
85
+ *
86
+ * @param address - ERC721 asset contract address.
87
+ * @param selectedAddress - Current account public address.
88
+ * @param index - An NFT counter less than `balanceOf(selectedAddress)`.
89
+ * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.
90
+ */
91
+ getERC721NftTokenId(address: string, selectedAddress: string, index: number): Promise<string>;
92
+ /**
93
+ * Enumerate assets assigned to an owner.
94
+ *
95
+ * @param tokenAddress - ERC721 asset contract address.
96
+ * @param userAddress - Current account public address.
97
+ * @param tokenId - ERC721 asset identifier.
98
+ * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.
99
+ */
100
+ getTokenStandardAndDetails(tokenAddress: string, userAddress?: string, tokenId?: string): Promise<{
101
+ standard: string;
102
+ tokenURI?: string | undefined;
103
+ symbol?: string | undefined;
104
+ name?: string | undefined;
105
+ decimals?: string | undefined;
106
+ balance?: BN | undefined;
107
+ }>;
108
+ /**
109
+ * Query for tokenURI for a given ERC721 asset.
110
+ *
111
+ * @param address - ERC721 asset contract address.
112
+ * @param tokenId - ERC721 asset identifier.
113
+ * @returns Promise resolving to the 'tokenURI'.
114
+ */
115
+ getERC721TokenURI(address: string, tokenId: string): Promise<string>;
116
+ /**
117
+ * Query for name for a given asset.
118
+ *
119
+ * @param address - ERC721 or ERC20 asset contract address.
120
+ * @returns Promise resolving to the 'name'.
121
+ */
122
+ getERC721AssetName(address: string): Promise<string>;
123
+ /**
124
+ * Query for symbol for a given asset.
125
+ *
126
+ * @param address - ERC721 or ERC20 asset contract address.
127
+ * @returns Promise resolving to the 'symbol'.
128
+ */
129
+ getERC721AssetSymbol(address: string): Promise<string>;
130
+ /**
131
+ * Query for owner for a given ERC721 asset.
132
+ *
133
+ * @param address - ERC721 asset contract address.
134
+ * @param tokenId - ERC721 asset identifier.
135
+ * @returns Promise resolving to the owner address.
136
+ */
137
+ getERC721OwnerOf(address: string, tokenId: string): Promise<string>;
138
+ /**
139
+ * Query for tokenURI for a given asset.
140
+ *
141
+ * @param address - ERC1155 asset contract address.
142
+ * @param tokenId - ERC1155 asset identifier.
143
+ * @returns Promise resolving to the 'tokenURI'.
144
+ */
145
+ getERC1155TokenURI(address: string, tokenId: string): Promise<string>;
146
+ /**
147
+ * Query for balance of a given ERC 1155 token.
148
+ *
149
+ * @param userAddress - Wallet public address.
150
+ * @param nftAddress - ERC1155 asset contract address.
151
+ * @param nftId - ERC1155 asset identifier.
152
+ * @returns Promise resolving to the 'balanceOf'.
153
+ */
154
+ getERC1155BalanceOf(userAddress: string, nftAddress: string, nftId: string): Promise<BN>;
155
+ /**
156
+ * Transfer single ERC1155 token.
157
+ *
158
+ * @param nftAddress - ERC1155 token address.
159
+ * @param senderAddress - ERC1155 token sender.
160
+ * @param recipientAddress - ERC1155 token recipient.
161
+ * @param nftId - ERC1155 token id.
162
+ * @param qty - Quantity of tokens to be sent.
163
+ * @returns Promise resolving to the 'transferSingle' ERC1155 token.
164
+ */
165
+ transferSingleERC1155(nftAddress: string, senderAddress: string, recipientAddress: string, nftId: string, qty: string): Promise<void>;
166
+ /**
167
+ * Get the token balance for a list of token addresses in a single call. Only non-zero balances
168
+ * are returned.
169
+ *
170
+ * @param selectedAddress - The address to check token balances for.
171
+ * @param tokensToDetect - The token addresses to detect balances for.
172
+ * @returns The list of non-zero token balances.
173
+ */
174
+ getBalancesInSingleCall(selectedAddress: string, tokensToDetect: string[]): Promise<BalanceMap>;
175
+ }
176
+ export default AssetsContractController;