This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
EthersModalConnector.ts
374 lines (325 loc) · 12.8 KB
/
EthersModalConnector.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { Web3Provider } from '@ethersproject/providers';
import { AbstractConnector } from '@web3-react/abstract-connector';
import { ConnectorUpdate } from '@web3-react/types';
import { BigNumber, Signer, utils } from 'ethers';
import { invariant } from 'ts-invariant';
import { ICoreOptions, ThemeColors } from 'web3modal';
import { UserClosedModalError, CouldNotActivateError } from './connectorErrors';
import {
connectorErrorText,
NoEthereumProviderFoundError,
NoStaticJsonRPCProviderFoundError,
} from '~~/context/ethers-app';
import { isEthersProvider } from '~~/functions/ethersHelpers';
import { Web3Modal } from '~~/helpers/esm-fixtures/web3modal';
import { TEthersProvider } from '~~/models';
import { const_web3DialogClosedByUser, const_web3DialogUserRejected } from '~~/models/constants/common';
type TEthersModalConfig = {
/**
* when network (chain) or provider changes reload the page
*/
reloadOnNetworkChange: boolean;
/**
* #### Summary
* ethers.io recomments an immutable provider, and by default doesn't allow
* network changes (i.e.) metamask changing chains.
* - if immutableProvider is true, it will follow the default behaviour
* - if immutableProvider is false, it will allow network changes
*
* ##### ✏️ Notes
* see https://github.com/ethers-io/ethers.js/discussions/1480
*/
immutableProvider: boolean;
};
type TWeb3ModalTheme = 'light' | 'dark';
/**
* #### Summary
* An interface implemented by {@link EthersModalConnector} in addition to AbstractConnector
*/
export interface ICommonModalConnector {
setModalTheme(theme: TWeb3ModalTheme | ThemeColors): void;
resetModal(): void;
hasCachedProvider(): boolean;
loadWeb3Modal: () => void;
getSigner: () => Signer | undefined;
changeSigner(signer: Signer): Promise<void>;
}
export type TEthersModalConnector = ICommonModalConnector & AbstractConnector;
/**
* #### Summary
* This is a connector for [web3-react](https://github.com/NoahZinsmeister/web3-react) that allows it to interface with [web3Modal](https://github.com/Web3Modal/web3modal).
* The provider selected by user via web3modal is interfaced to the web3-react context.
*
* ##### ✨ Features
* - This connector used with {@link useEthersContext} allows the app and all the hooks to effortlessly access the current network, provider, signer, address information {@link IEthersContext}
* - The connector centralizes and takes care of management of the web3 interaction and provides a consistent exprience for your app.
*
* ##### ✏️ Notes
* - inherits from web3-react class AbstractConnector
*
* @category EthersAppContext
*/
export class EthersModalConnector extends AbstractConnector implements ICommonModalConnector {
protected _options: Partial<ICoreOptions>;
protected _providerBase?: any;
protected _ethersProvider?: TEthersProvider;
protected _web3Modal?: typeof Web3Modal;
protected _id: string | undefined;
protected _debug: boolean = false;
protected _config: Readonly<TEthersModalConfig>;
protected _signer: Signer | undefined;
protected _theme: TWeb3ModalTheme | ThemeColors;
static isModalOpening: boolean = false;
get config(): Readonly<TEthersModalConfig> {
return this._config;
}
public hasCachedProvider(): boolean {
return !!this._web3Modal?.cachedProvider;
}
/**
* @param web3modalOptions see [web3modal docs](https://github.com/Web3Modal/web3modal#provider-options) for details. You can also check the [scaffold-eth-typescript web3config](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/src/config/web3ModalConfig.ts) for an example.
* @param config Configuration for EthersModalConnector
* @param id allows you to connect directly to a specific provider. [See docs](https://github.com/Web3Modal/web3modal#connect-to-specific-provider)
* @param debug turn on debug logging
*/
constructor(
web3modalOptions: Partial<ICoreOptions>,
config: TEthersModalConfig = { reloadOnNetworkChange: false, immutableProvider: false },
id?: string,
debug: boolean = false
) {
super();
this._options = web3modalOptions;
this._id = id;
this._debug = debug;
this._config = config;
this._theme = (web3modalOptions.theme as TWeb3ModalTheme | ThemeColors) ?? 'light';
this.handleChainChanged = this.handleChainChanged.bind(this);
this.handleAccountsChanged = this.handleAccountsChanged.bind(this);
this.handleDisconnect = this.handleDisconnect.bind(this);
this.handleClose = this.handleClose.bind(this);
}
protected log(...args: any[]): void {
if (this._debug) {
console.log('🔌 ', args);
}
}
private maybeReload(): void {
if (window && this._config.reloadOnNetworkChange) {
window.location.reload();
}
}
private setEthersProvider(): void {
if (this.isEthersProvider()) {
this._ethersProvider = this._providerBase as TEthersProvider;
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this._ethersProvider = new Web3Provider(this._providerBase, this._config.immutableProvider ? 'any' : undefined);
}
}
private handleChainChanged(chainId: number | string): void {
this.log(`Handling chain changed to ${chainId}! updating providers`);
this._signer = undefined;
this.emitUpdate?.({ chainId, provider: this._providerBase });
this.setEthersProvider();
void this.getSignerFromAccount();
this.maybeReload();
}
private handleAccountsChanged(accounts: string[]): void {
this.log(`Handling accounts changed`, accounts);
if (accounts.length === 0) {
this.emitDeactivate?.();
} else {
const newAccount = accounts[0];
void this.setSignerFromAccount(newAccount);
this.emitUpdate?.({ account: accounts[0] });
}
}
private handleDisconnect(code: any, reason: any): void {
this.log(`Handling disconnected event`, code, reason);
this.deactivate();
}
private handleClose(code: number, reason: string): void {
this.log("Handling 'close' event", code, reason);
this.deactivate();
}
public loadWeb3Modal(): void {
if (!this._web3Modal) {
// @ts-expect-error
this._web3Modal = new Web3Modal({ ...this._options, theme: this._theme });
}
}
/**
* #### Summary
* Inherits from AbstractConnector. This activates web3Modal and opens the modal.
*
* ##### ✏️ Notes
* Once the user selects a provider
* - this will activate the provider and attach the appropriate event listeners.
* - get the account and signer
* - gets the ethers compatable provider
*
* ##### ⚠️ Errors
* - {@link UserClosedModalError}
* - {@link CouldNotActivateError}
* @returns
*/
public async activate(): Promise<ConnectorUpdate> {
try {
this.loadWeb3Modal();
if (this._web3Modal) {
if (this._options.cacheProvider === false || !this.checkValidCachedProvider()) {
this.resetModal();
}
EthersModalConnector.isModalOpening = true;
console.log('Open provider modal');
await this._web3Modal.updateTheme(this._theme);
/* eslint-disable @typescript-eslint/no-unsafe-assignment*/
if (this._id) {
this._providerBase = await this._web3Modal.connectTo(this._id);
} else {
this._providerBase = await this._web3Modal.connect();
}
/* eslint-enable */
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call*/
this._providerBase.on('chainChanged', this.handleChainChanged);
this._providerBase.on('accountsChanged', this.handleAccountsChanged);
this._providerBase.on('disconnect', this.handleDisconnect as any);
this._providerBase.on('close', this.handleClose as any);
/* eslint-enable */
this.setEthersProvider();
}
/* eslint-disable */
const account: string = this._providerBase?.selectedAddress ?? (await this.getAccount());
let chainId: number =
this._providerBase?.networkVersion ?? BigNumber.from(this._providerBase?.chainId ?? 0).toNumber();
if (chainId === 0) {
chainId = (await this.getChainId()) as number;
}
this.setSignerFromAccount(account);
EthersModalConnector.isModalOpening = false;
return { provider: this._providerBase, account, chainId };
/* eslint-enable */
} catch (error) {
this.resetModal();
if (
typeof error === 'string' &&
(error?.includes(const_web3DialogClosedByUser) || error?.includes(const_web3DialogUserRejected))
) {
invariant.log(error);
this.deactivate();
throw new UserClosedModalError();
} else if (error instanceof NoStaticJsonRPCProviderFoundError) {
invariant.warn(`EthersModalConnector: ${connectorErrorText.NoStaticJsonRPCProviderFoundError}`);
throw error;
} else if (error instanceof NoEthereumProviderFoundError) {
invariant.warn(`EthersModalConnector: ${connectorErrorText.NoEthereumProviderFoundError}`);
throw error;
} else {
invariant.warn(`EthersModalConnector: ${connectorErrorText.CouldNotActivateError}`, error, this._providerBase);
throw new CouldNotActivateError(error);
}
}
}
private isEthersProvider(): boolean {
return isEthersProvider(this._providerBase);
}
/**
* #### Summary
* Safely deactivates the current provider and removes all event listeners
*/
public deactivate(): void {
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call */
this.emitDeactivate?.();
this._providerBase?.removeListener('disconnect', this.handleDisconnect);
this._providerBase?.removeListener('chainChanged', this.handleChainChanged);
this._providerBase?.removeListener('accountsChanged', this.handleAccountsChanged);
this._providerBase?.removeListener('close', this.handleClose);
const provider = this._providerBase;
// use disconnect function if exists
provider?.disconnect?.();
// use close function if exists
provider?.close?.();
this.maybeReload();
/* eslint-enable */
}
public getProvider(): Promise<TEthersProvider | undefined> {
return Promise.resolve(this._ethersProvider) as Promise<TEthersProvider | undefined>;
}
public async getChainId(): Promise<number | string> {
return Promise.resolve(this._ethersProvider?.network?.chainId ?? 0) as Promise<number | string>;
}
private async setSignerFromAccount(account: string | null): Promise<void> {
if (account && utils.isAddress(account) && (await this._signer?.getAddress()) !== account) {
this._signer = this._ethersProvider?.getSigner(account);
}
}
public async getAccount(): Promise<null | string> {
if (this._signer) {
const account = await this._signer.getAddress();
if (utils.isAddress(account)) return account;
}
const accounts = await this._ethersProvider?.listAccounts();
const account = accounts?.[0] ?? null;
await this.setSignerFromAccount(account);
return Promise.resolve(accounts?.[0] ?? null);
}
public getSigner(): Signer | undefined {
return this._signer;
}
public async getSignerFromAccount(): Promise<void> {
const account = await this.getAccount();
await this.setSignerFromAccount(account);
this.emitUpdate?.({ account });
}
/**
* #### Summary
* Change the current signer and account used by the connector
* @param signer
*/
public async changeSigner(signer: Signer): Promise<void> {
const account = await signer.getAddress();
if (utils.isAddress(account) && this.validState()) {
this._signer = signer;
this.handleAccountsChanged([account]);
console.log(`changeSigner: provider chainId ${await this.getChainId()}`);
console.log(`new signer chainId ${(await signer.provider?.getNetwork())?.chainId ?? ''}`);
}
}
protected validState(): boolean {
return this._providerBase != null && this._ethersProvider != null && this._web3Modal != null;
}
/**
* #### Summary
* Resets the web3Modal and clears the cache
*/
public resetModal(): void {
if (this._web3Modal) {
this._web3Modal.clearCachedProvider();
this._providerBase = undefined;
this._ethersProvider = undefined;
this._signer = undefined;
this.emitUpdate?.({ account: undefined, provider: undefined, chainId: undefined });
}
}
/**
* #### Summary
* Sets the web3modal theme: light | dark | ThemeColors
* @param theme
*/
public setModalTheme(theme: TWeb3ModalTheme | ThemeColors): void {
this._theme = theme;
}
public checkValidCachedProvider(): boolean {
if (EthersModalConnector.isModalOpening) {
return false;
}
const modal = this._web3Modal;
if (modal != null) {
if (!modal.getUserOptions().find((f) => f.id === modal.cachedProvider)) {
return false;
}
}
return true;
}
}