-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathTokenBalancesController.ts
234 lines (200 loc) · 6.42 KB
/
TokenBalancesController.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';
import type {
RestrictedControllerMessenger,
ControllerGetStateAction,
ControllerStateChangeEvent,
} from '@metamask/base-controller';
import { BaseController } from '@metamask/base-controller';
import { safelyExecute, toHex } from '@metamask/controller-utils';
import type { AssetsContractControllerGetERC20BalanceOfAction } 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.
*/
type TokenBalancesControllerOptions = {
interval?: number;
tokens?: Token[];
disabled?: boolean;
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 =
| AccountsControllerGetSelectedAccountAction
| AssetsContractControllerGetERC20BalanceOfAction;
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>;
#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.state - Initial state to set on this controller.
* @param options.messenger - The controller restricted messenger.
*/
constructor({
interval = DEFAULT_INTERVAL,
tokens = [],
disabled = false,
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];
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.updateBalances();
},
);
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
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(() => {
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.poll(this.#interval);
}, this.#interval);
}
/**
* Updates balances for all tokens.
*/
async updateBalances() {
if (this.#disabled) {
return;
}
const selectedInternalAccount = this.messagingSystem.call(
'AccountsController:getSelectedAccount',
);
const newContractBalances: ContractBalances = {};
for (const token of this.#tokens) {
const { address } = token;
try {
const balance = await this.messagingSystem.call(
'AssetsContractController:getERC20BalanceOf',
address,
selectedInternalAccount.address,
);
newContractBalances[address] = toHex(balance);
token.hasBalanceError = false;
} catch (error) {
newContractBalances[address] = toHex(0);
token.hasBalanceError = true;
}
}
this.update((state) => {
state.contractBalances = newContractBalances;
});
}
/**
* Reset the controller state to the default state.
*/
resetState() {
this.update(() => {
return getDefaultTokenBalancesState();
});
}
}
export default TokenBalancesController;