-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
AccountTrackerController.ts
201 lines (183 loc) · 5.26 KB
/
AccountTrackerController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import EthQuery from 'eth-query';
import { Mutex } from 'async-mutex';
import {
BaseConfig,
BaseController,
BaseState,
} from '@metamask/base-controller';
import { PreferencesState } from '@metamask/preferences-controller';
import {
BNToHex,
query,
safelyExecuteWithTimeout,
} from '@metamask/controller-utils';
/**
* @type AccountInformation
*
* Account information object
* @property balance - Hex string of an account balancec in wei
*/
export interface AccountInformation {
balance: string;
}
/**
* @type AccountTrackerConfig
*
* Account tracker controller configuration
* @property provider - Provider used to create a new underlying EthQuery instance
*/
export interface AccountTrackerConfig extends BaseConfig {
interval: number;
provider?: any;
}
/**
* @type AccountTrackerState
*
* Account tracker controller state
* @property accounts - Map of addresses to account information
*/
export interface AccountTrackerState extends BaseState {
accounts: { [address: string]: AccountInformation };
}
/**
* Controller that tracks the network balances for all user accounts.
*/
export class AccountTrackerController extends BaseController<
AccountTrackerConfig,
AccountTrackerState
> {
private ethQuery: any;
private mutex = new Mutex();
private handle?: ReturnType<typeof setTimeout>;
private syncAccounts() {
const { accounts } = this.state;
const addresses = Object.keys(this.getIdentities());
const existing = Object.keys(accounts);
const newAddresses = addresses.filter(
(address) => existing.indexOf(address) === -1,
);
const oldAddresses = existing.filter(
(address) => addresses.indexOf(address) === -1,
);
newAddresses.forEach((address) => {
accounts[address] = { balance: '0x0' };
});
oldAddresses.forEach((address) => {
delete accounts[address];
});
this.update({ accounts: { ...accounts } });
}
/**
* Name of this controller used during composition
*/
override name = 'AccountTrackerController';
private getIdentities: () => PreferencesState['identities'];
/**
* Creates an AccountTracker instance.
*
* @param options - The controller options.
* @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
* @param options.getIdentities - Gets the identities from the Preferences store.
* @param config - Initial options used to configure this controller.
* @param state - Initial state to set on this controller.
*/
constructor(
{
onPreferencesStateChange,
getIdentities,
}: {
onPreferencesStateChange: (
listener: (preferencesState: PreferencesState) => void,
) => void;
getIdentities: () => PreferencesState['identities'];
},
config?: Partial<AccountTrackerConfig>,
state?: Partial<AccountTrackerState>,
) {
super(config, state);
this.defaultConfig = {
interval: 10000,
};
this.defaultState = { accounts: {} };
this.initialize();
this.getIdentities = getIdentities;
onPreferencesStateChange(() => {
this.refresh();
});
this.poll();
}
/**
* Sets a new provider.
*
* TODO: Replace this wth a method.
*
* @param provider - Provider used to create a new underlying EthQuery instance.
*/
set provider(provider: any) {
this.ethQuery = new EthQuery(provider);
}
get provider() {
throw new Error('Property only used for setting');
}
/**
* Starts a new polling interval.
*
* @param interval - Polling interval trigger a 'refresh'.
*/
async poll(interval?: number): Promise<void> {
const releaseLock = await this.mutex.acquire();
interval && this.configure({ interval }, false, false);
this.handle && clearTimeout(this.handle);
await this.refresh();
this.handle = setTimeout(() => {
releaseLock();
this.poll(this.config.interval);
}, this.config.interval);
}
/**
* Refreshes all accounts in the current keychain.
*/
refresh = async () => {
this.syncAccounts();
const accounts = { ...this.state.accounts };
for (const address in accounts) {
await safelyExecuteWithTimeout(async () => {
const balance = await query(this.ethQuery, 'getBalance', [address]);
accounts[address] = { balance: BNToHex(balance) };
});
}
this.update({ accounts });
};
/**
* Sync accounts balances with some additional addresses.
*
* @param addresses - the additional addresses, may be hardware wallet addresses.
* @returns accounts - addresses with synced balance
*/
async syncBalanceWithAddresses(
addresses: string[],
): Promise<Record<string, { balance: string }>> {
return await Promise.all(
addresses.map((address): Promise<[string, string] | undefined> => {
return safelyExecuteWithTimeout(async () => {
const balance = await query(this.ethQuery, 'getBalance', [address]);
return [address, balance];
});
}),
).then((value) => {
return value.reduce((obj, item) => {
if (!item) {
return obj;
}
const [address, balance] = item;
return {
...obj,
[address]: {
balance,
},
};
}, {});
});
}
}
export default AccountTrackerController;