forked from MetaMask/core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTokenBalancesController.ts
More file actions
222 lines (186 loc) · 5.96 KB
/
TokenBalancesController.ts
File metadata and controls
222 lines (186 loc) · 5.96 KB
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import {
type RestrictedControllerMessenger,
type ControllerGetStateAction,
type ControllerStateChangeEvent,
BaseController,
} from '@metamask/base-controller';
import { safelyExecute, toHex } from '@metamask/controller-utils';
import type { PreferencesControllerGetStateAction } from '@metamask/preferences-controller';
import type { AssetsContractController } from './AssetsContractController';
import type { Token } from './TokenRatesController';
import type { TokensControllerStateChangeEvent } from './TokensController';
const DEFAULT_INTERVAL = 180000;
const controllerName = 'TokenBalancesController';
const metadata = {
contractBalances: { persist: true, anonymous: false },
};
/**
* Token balances controller options
* @property interval - Polling interval used to fetch new token balances.
* @property tokens - List of tokens to track balances for.
* @property disabled - If set to true, all tracked tokens contract balances updates are blocked.
* @property getERC20BalanceOf - Gets the balance of the given account at the given contract address.
*/
type TokenBalancesControllerOptions = {
interval?: number;
tokens?: Token[];
disabled?: boolean;
getERC20BalanceOf: AssetsContractController['getERC20BalanceOf'];
messenger: TokenBalancesControllerMessenger;
state?: Partial<TokenBalancesControllerState>;
};
/**
* Represents a mapping of hash token contract addresses to their balances.
*/
type ContractBalances = Record<string, string>;
/**
* Token balances controller state
* @property contractBalances - Hash of token contract addresses to balances
*/
export type TokenBalancesControllerState = {
contractBalances: ContractBalances;
};
export type TokenBalancesControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
TokenBalancesControllerState
>;
export type TokenBalancesControllerActions =
TokenBalancesControllerGetStateAction;
export type AllowedActions = PreferencesControllerGetStateAction;
export type TokenBalancesControllerStateChangeEvent =
ControllerStateChangeEvent<
typeof controllerName,
TokenBalancesControllerState
>;
export type TokenBalancesControllerEvents =
TokenBalancesControllerStateChangeEvent;
export type AllowedEvents = TokensControllerStateChangeEvent;
export type TokenBalancesControllerMessenger = RestrictedControllerMessenger<
typeof controllerName,
TokenBalancesControllerActions | AllowedActions,
TokenBalancesControllerEvents | AllowedEvents,
AllowedActions['type'],
AllowedEvents['type']
>;
/**
* Get the default TokenBalancesController state.
*
* @returns The default TokenBalancesController state.
*/
export function getDefaultTokenBalancesState(): TokenBalancesControllerState {
return {
contractBalances: {},
};
}
/**
* Controller that passively polls on a set interval token balances
* for tokens stored in the TokensController
*/
export class TokenBalancesController extends BaseController<
typeof controllerName,
TokenBalancesControllerState,
TokenBalancesControllerMessenger
> {
#handle?: ReturnType<typeof setTimeout>;
#getERC20BalanceOf: AssetsContractController['getERC20BalanceOf'];
#interval: number;
#tokens: Token[];
#disabled: boolean;
/**
* Construct a Token Balances Controller.
*
* @param options - The controller options.
* @param options.interval - Polling interval used to fetch new token balances.
* @param options.tokens - List of tokens to track balances for.
* @param options.disabled - If set to true, all tracked tokens contract balances updates are blocked.
* @param options.getERC20BalanceOf - Gets the balance of the given account at the given contract address.
* @param options.state - Initial state to set on this controller.
* @param options.messenger - The controller restricted messenger.
*/
constructor({
interval = DEFAULT_INTERVAL,
tokens = [],
disabled = false,
getERC20BalanceOf,
messenger,
state = {},
}: TokenBalancesControllerOptions) {
super({
name: controllerName,
metadata,
messenger,
state: {
...getDefaultTokenBalancesState(),
...state,
},
});
this.#disabled = disabled;
this.#interval = interval;
this.#tokens = tokens;
this.messagingSystem.subscribe(
'TokensController:stateChange',
({ tokens: newTokens, detectedTokens }) => {
this.#tokens = [...newTokens, ...detectedTokens];
this.updateBalances();
},
);
this.#getERC20BalanceOf = getERC20BalanceOf;
this.poll();
}
/**
* Allows controller to update tracked tokens contract balances.
*/
enable() {
this.#disabled = false;
}
/**
* Blocks controller from updating tracked tokens contract balances.
*/
disable() {
this.#disabled = true;
}
/**
* Starts a new polling interval.
*
* @param interval - Polling interval used to fetch new token balances.
*/
async poll(interval?: number): Promise<void> {
if (interval) {
this.#interval = interval;
}
if (this.#handle) {
clearTimeout(this.#handle);
}
await safelyExecute(() => this.updateBalances());
this.#handle = setTimeout(() => {
this.poll(this.#interval);
}, this.#interval);
}
/**
* Updates balances for all tokens.
*/
async updateBalances() {
if (this.#disabled) {
return;
}
const { selectedAddress } = this.messagingSystem.call(
'PreferencesController:getState',
);
const newContractBalances: ContractBalances = {};
for (const token of this.#tokens) {
const { address } = token;
try {
const balance = await this.#getERC20BalanceOf(address, selectedAddress);
newContractBalances[address] = toHex(balance);
token.hasBalanceError = false;
} catch (error) {
newContractBalances[address] = toHex(0);
token.hasBalanceError = true;
}
}
this.update((state) => {
state.contractBalances = newContractBalances;
});
}
}
export default TokenBalancesController;