-
Notifications
You must be signed in to change notification settings - Fork 629
/
EthereumProvider.ts
664 lines (592 loc) · 21.1 KB
/
EthereumProvider.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
import { EventEmitter } from "events";
import { getAccountsFromNamespaces, getSdkError, isValidArray } from "@walletconnect/utils";
import { KeyValueStorageOptions } from "@walletconnect/keyvaluestorage";
import {
IEthereumProvider as IProvider,
IEthereumProviderEvents,
ProviderAccounts,
RequestArguments,
QrModalOptions,
} from "./types";
import { Metadata, Namespace, UniversalProvider } from "@walletconnect/universal-provider";
import { AuthTypes, SessionTypes, SignClientTypes } from "@walletconnect/types";
import { JsonRpcResult } from "@walletconnect/jsonrpc-types";
import {
STORAGE_KEY,
REQUIRED_METHODS,
REQUIRED_EVENTS,
RPC_URL,
OPTIONAL_METHODS,
OPTIONAL_EVENTS,
} from "./constants";
export type RpcMethod =
| "personal_sign"
| "eth_sendTransaction"
| "eth_accounts"
| "eth_requestAccounts"
| "eth_call"
| "eth_getBalance"
| "eth_sendRawTransaction"
| "eth_sign"
| "eth_signTransaction"
| "eth_signTypedData"
| "eth_signTypedData_v3"
| "eth_signTypedData_v4"
| "wallet_switchEthereumChain"
| "wallet_addEthereumChain"
| "wallet_getPermissions"
| "wallet_requestPermissions"
| "wallet_registerOnboarding"
| "wallet_watchAsset"
| "wallet_scanQRCode"
| "wallet_sendCalls"
| "wallet_getCapabilities"
| "wallet_getCallsStatus"
| "wallet_showCallsStatus";
export type RpcEvent = "accountsChanged" | "chainChanged" | "message" | "disconnect" | "connect";
export interface EthereumRpcMap {
[chainId: string]: string;
}
export interface SessionEvent {
event: { name: string; data: any };
chainId: string;
}
export interface EthereumRpcConfig {
chains: string[];
optionalChains: string[];
methods: string[];
optionalMethods?: string[];
/**
* @description Events that the wallet MUST support or the connection will be rejected
*/
events: string[];
optionalEvents?: string[];
rpcMap: EthereumRpcMap;
projectId: string;
metadata?: Metadata;
showQrModal: boolean;
qrModalOptions?: QrModalOptions;
}
export interface ConnectOps {
chains?: number[];
optionalChains?: number[];
rpcMap?: EthereumRpcMap;
pairingTopic?: string;
}
export type AuthenticateParams = {
chains?: number[];
} & Omit<AuthTypes.SessionAuthenticateParams, "chains">;
export interface IEthereumProvider extends IProvider {
connect(opts?: ConnectOps | undefined): Promise<void>;
}
export function getRpcUrl(chainId: string, rpc: EthereumRpcConfig): string | undefined {
let rpcUrl: string | undefined;
if (rpc.rpcMap) {
rpcUrl = rpc.rpcMap[getEthereumChainId([chainId])];
}
return rpcUrl;
}
export function getEthereumChainId(chains: string[]): number {
return Number(chains[0].split(":")[1]);
}
export function toHexChainId(chainId: number): string {
return `0x${chainId.toString(16)}`;
}
export type NamespacesParams = {
chains: EthereumRpcConfig["chains"];
optionalChains: EthereumRpcConfig["optionalChains"];
methods?: EthereumRpcConfig["methods"];
optionalMethods?: EthereumRpcConfig["methods"];
events?: EthereumRpcConfig["events"];
rpcMap: EthereumRpcConfig["rpcMap"];
optionalEvents?: EthereumRpcConfig["events"];
};
export function buildNamespaces(params: NamespacesParams): {
required?: Namespace;
optional?: Namespace;
} {
const { chains, optionalChains, methods, optionalMethods, events, optionalEvents, rpcMap } =
params;
if (!isValidArray(chains)) {
throw new Error("Invalid chains");
}
const required: Namespace = {
chains,
methods: methods || REQUIRED_METHODS,
events: events || REQUIRED_EVENTS,
rpcMap: {
...(chains.length
? { [getEthereumChainId(chains)]: rpcMap[getEthereumChainId(chains)] }
: {}),
},
};
// make a list of events and methods that require additional permissions
// so we know if we should to include the required chains in the optional namespace
const eventsRequiringPermissions = events?.filter((event) => !REQUIRED_EVENTS.includes(event));
const methodsRequiringPermissions = methods?.filter((event) => !REQUIRED_METHODS.includes(event));
if (
!optionalChains &&
!optionalEvents &&
!optionalMethods &&
!eventsRequiringPermissions?.length &&
!methodsRequiringPermissions?.length
) {
return { required: chains.length ? required : undefined };
}
/*
* decides whether or not to include the required chains in the optional namespace
* use case: if there is a single chain as required but additional methods/events as optional
*/
const shouldIncludeRequiredChains =
(eventsRequiringPermissions?.length && methodsRequiringPermissions?.length) || !optionalChains;
const optional: Namespace = {
chains: [
...new Set(
shouldIncludeRequiredChains ? required.chains.concat(optionalChains || []) : optionalChains,
),
],
methods: [
...new Set(
required.methods.concat(optionalMethods?.length ? optionalMethods : OPTIONAL_METHODS),
),
],
events: [
...new Set(required.events.concat(optionalEvents?.length ? optionalEvents : OPTIONAL_EVENTS)),
],
rpcMap,
};
return {
required: chains.length ? required : undefined,
optional: optionalChains.length ? optional : undefined,
};
}
// helper type to force setting at least one value in an array
type ArrayOneOrMore<T> = {
0: T;
} & Array<T>;
/**
* @param {number[]} chains - The Chains your app intents to use and the peer MUST support. If the peer does not support these chains, the connection will be rejected.
* @param {number[]} optionalChains - The Chains your app MAY attempt to use and the peer MAY support. If the peer does not support these chains, the connection will still be established.
* @description either chains or optionalChains must be provided
*/
export type ChainsProps =
| {
chains: ArrayOneOrMore<number>;
optionalChains?: number[];
}
| {
chains?: number[];
optionalChains: ArrayOneOrMore<number>;
};
export type EthereumProviderOptions = {
projectId: string;
/**
* @note Methods that your app intents to use and the peer MUST support. If the peer does not support these methods, the connection will be rejected.
* @default ["eth_sendTransaction", "personal_sign"]
*/
methods?: string[];
/**
* @note Methods that your app MAY attempt to use and the peer MAY support. If the peer does not support these methods, the connection will still be established.
*/
optionalMethods?: string[];
events?: string[];
optionalEvents?: string[];
rpcMap?: EthereumRpcMap;
metadata?: Metadata;
showQrModal: boolean;
qrModalOptions?: QrModalOptions;
disableProviderPing?: boolean;
relayUrl?: string;
storageOptions?: KeyValueStorageOptions;
} & ChainsProps;
export class EthereumProvider implements IEthereumProvider {
public events = new EventEmitter();
public namespace = "eip155";
public accounts: string[] = [];
public signer: InstanceType<typeof UniversalProvider>;
public chainId = 1;
public modal?: any;
protected rpc: EthereumRpcConfig;
protected readonly STORAGE_KEY = STORAGE_KEY;
constructor() {
// assigned during initialize
this.signer = {} as InstanceType<typeof UniversalProvider>;
this.rpc = {} as EthereumRpcConfig;
}
static async init(opts: EthereumProviderOptions): Promise<EthereumProvider> {
const provider = new EthereumProvider();
await provider.initialize(opts);
return provider;
}
public async request<T = unknown>(args: RequestArguments, expiry?: number): Promise<T> {
return await this.signer.request(args, this.formatChainId(this.chainId), expiry);
}
public sendAsync(
args: RequestArguments,
callback: (error: Error | null, response: JsonRpcResult) => void,
expiry?: number,
): void {
this.signer.sendAsync(args, callback, this.formatChainId(this.chainId), expiry);
}
get connected(): boolean {
if (!this.signer.client) return false;
return this.signer.client.core.relayer.connected;
}
get connecting(): boolean {
if (!this.signer.client) return false;
return this.signer.client.core.relayer.connecting;
}
public async enable(): Promise<ProviderAccounts> {
if (!this.session) await this.connect();
const accounts = await this.request({ method: "eth_requestAccounts" });
return accounts as ProviderAccounts;
}
public async connect(opts?: ConnectOps): Promise<void> {
if (!this.signer.client) {
throw new Error("Provider not initialized. Call init() first");
}
this.loadConnectOpts(opts);
const { required, optional } = buildNamespaces(this.rpc);
try {
const session = await new Promise<SessionTypes.Struct | undefined>(
async (resolve, reject) => {
if (this.rpc.showQrModal) {
this.modal?.subscribeModal((state: { open: boolean }) => {
// the modal was closed so reject the promise
if (!state.open && !this.signer.session) {
this.signer.abortPairingAttempt();
reject(new Error("Connection request reset. Please try again."));
}
});
}
await this.signer
.connect({
namespaces: {
...(required && {
[this.namespace]: required,
}),
},
...(optional && {
optionalNamespaces: {
[this.namespace]: optional,
},
}),
pairingTopic: opts?.pairingTopic,
})
.then((session?: SessionTypes.Struct) => {
resolve(session);
})
.catch((error: Error) => {
reject(new Error(error.message));
});
},
);
if (!session) return;
const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);
// if no required chains are set, use the approved accounts to fetch chainIds
this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);
this.setAccounts(accounts);
this.events.emit("connect", { chainId: toHexChainId(this.chainId) });
} catch (error) {
this.signer.logger.error(error);
throw error;
} finally {
if (this.modal) this.modal.closeModal();
}
}
public async authenticate(
params: AuthenticateParams,
): Promise<AuthTypes.AuthenticateResponseResult | undefined> {
if (!this.signer.client) {
throw new Error("Provider not initialized. Call init() first");
}
this.loadConnectOpts({
chains: params?.chains,
});
try {
const result = await new Promise<AuthTypes.AuthenticateResponseResult>(
async (resolve, reject) => {
if (this.rpc.showQrModal) {
this.modal?.subscribeModal((state: { open: boolean }) => {
// the modal was closed so reject the promise
if (!state.open && !this.signer.session) {
this.signer.abortPairingAttempt();
reject(new Error("Connection request reset. Please try again."));
}
});
}
await this.signer
.authenticate({
...params,
chains: this.rpc.chains,
})
.then((result: AuthTypes.AuthenticateResponseResult) => {
resolve(result);
})
.catch((error: Error) => {
reject(new Error(error.message));
});
},
);
const session = result.session;
if (session) {
const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);
// if no required chains are set, use the approved accounts to fetch chainIds as both contain <namespace>:<chainId>
this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);
this.setAccounts(accounts);
this.events.emit("connect", { chainId: toHexChainId(this.chainId) });
}
return result;
} catch (error) {
this.signer.logger.error(error);
throw error;
} finally {
if (this.modal) this.modal.closeModal();
}
}
public async disconnect(): Promise<void> {
if (this.session) {
await this.signer.disconnect();
}
this.reset();
}
public on: IEthereumProviderEvents["on"] = (event, listener) => {
this.events.on(event, listener);
return this;
};
public once: IEthereumProviderEvents["once"] = (event, listener) => {
this.events.once(event, listener);
return this;
};
public removeListener: IEthereumProviderEvents["removeListener"] = (event, listener) => {
this.events.removeListener(event, listener);
return this;
};
public off: IEthereumProviderEvents["off"] = (event, listener) => {
this.events.off(event, listener);
return this;
};
get isWalletConnect() {
return true;
}
get session() {
return this.signer.session;
}
// ---------- Protected --------------------------------------------- //
protected registerEventListeners() {
this.signer.on("session_event", (payload: SignClientTypes.EventArguments["session_event"]) => {
const { params } = payload;
const { event } = params;
if (event.name === "accountsChanged") {
this.accounts = this.parseAccounts(event.data);
this.events.emit("accountsChanged", this.accounts);
} else if (event.name === "chainChanged") {
this.setChainId(this.formatChainId(event.data));
} else {
this.events.emit(event.name as any, event.data);
}
this.events.emit("session_event", payload);
});
this.signer.on("chainChanged", (chainId: string) => {
const chain = parseInt(chainId);
this.chainId = chain;
this.events.emit("chainChanged", toHexChainId(this.chainId));
this.persist();
});
this.signer.on(
"session_update",
(payload: SignClientTypes.EventArguments["session_update"]) => {
this.events.emit("session_update", payload);
},
);
this.signer.on(
"session_delete",
(payload: SignClientTypes.EventArguments["session_delete"]) => {
this.reset();
this.events.emit("session_delete", payload);
this.events.emit("disconnect", {
...getSdkError("USER_DISCONNECTED"),
data: payload.topic,
name: "USER_DISCONNECTED",
});
},
);
this.signer.on("display_uri", (uri: string) => {
if (this.rpc.showQrModal) {
// to refresh the QR we have to close the modal and open it again
// until proper API is provided by walletconnect modal
this.modal?.closeModal();
this.modal?.openModal({ uri });
}
this.events.emit("display_uri", uri);
});
}
protected switchEthereumChain(chainId: number): void {
this.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: chainId.toString(16) }],
});
}
protected isCompatibleChainId(chainId: string): boolean {
return typeof chainId === "string" ? chainId.startsWith(`${this.namespace}:`) : false;
}
protected formatChainId(chainId: number): string {
return `${this.namespace}:${chainId}`;
}
protected parseChainId(chainId: string): number {
return Number(chainId.split(":")[1]);
}
protected setChainIds(chains: string[]) {
const compatible = chains.filter((x) => this.isCompatibleChainId(x));
const chainIds = compatible.map((c) => this.parseChainId(c));
if (chainIds.length) {
this.chainId = chainIds[0];
this.events.emit("chainChanged", toHexChainId(this.chainId));
this.persist();
}
}
protected setChainId(chain: string) {
if (this.isCompatibleChainId(chain)) {
const chainId = this.parseChainId(chain);
this.chainId = chainId;
this.switchEthereumChain(chainId);
}
}
protected parseAccountId(account: string): { chainId: string; address: string } {
const [namespace, reference, address] = account.split(":");
const chainId = `${namespace}:${reference}`;
return { chainId, address };
}
protected setAccounts(accounts: string[]) {
this.accounts = accounts
.filter((x) => this.parseChainId(this.parseAccountId(x).chainId) === this.chainId)
.map((x) => this.parseAccountId(x).address);
this.events.emit("accountsChanged", this.accounts);
}
protected getRpcConfig(opts: EthereumProviderOptions): EthereumRpcConfig {
const requiredChains = opts?.chains ?? [];
const optionalChains = opts?.optionalChains ?? [];
const allChains = requiredChains.concat(optionalChains);
if (!allChains.length)
throw new Error("No chains specified in either `chains` or `optionalChains`");
const requiredMethods = requiredChains.length ? opts?.methods || REQUIRED_METHODS : [];
const requiredEvents = requiredChains.length ? opts?.events || REQUIRED_EVENTS : [];
const optionalMethods = opts?.optionalMethods || [];
const optionalEvents = opts?.optionalEvents || [];
const rpcMap = opts?.rpcMap || this.buildRpcMap(allChains, opts.projectId);
const qrModalOptions = opts?.qrModalOptions || undefined;
return {
chains: requiredChains?.map((chain) => this.formatChainId(chain)),
optionalChains: optionalChains.map((chain) => this.formatChainId(chain)),
methods: requiredMethods,
events: requiredEvents,
optionalMethods,
optionalEvents,
rpcMap,
showQrModal: Boolean(opts?.showQrModal),
qrModalOptions,
projectId: opts.projectId,
metadata: opts.metadata,
};
}
protected buildRpcMap(chains: number[], projectId: string): EthereumRpcMap {
const map: EthereumRpcMap = {};
chains.forEach((chain) => {
map[chain] = this.getRpcUrl(chain, projectId);
});
return map;
}
protected async initialize(opts: EthereumProviderOptions) {
this.rpc = this.getRpcConfig(opts);
this.chainId = this.rpc.chains.length
? getEthereumChainId(this.rpc.chains)
: getEthereumChainId(this.rpc.optionalChains);
this.signer = await UniversalProvider.init({
projectId: this.rpc.projectId,
metadata: this.rpc.metadata,
disableProviderPing: opts.disableProviderPing,
relayUrl: opts.relayUrl,
storageOptions: opts.storageOptions,
});
this.registerEventListeners();
await this.loadPersistedSession();
if (this.rpc.showQrModal) {
let WalletConnectModalClass;
try {
const { WalletConnectModal } = await import("@walletconnect/modal");
WalletConnectModalClass = WalletConnectModal;
} catch {
throw new Error("To use QR modal, please install @walletconnect/modal package");
}
if (WalletConnectModalClass) {
try {
this.modal = new WalletConnectModalClass({
projectId: this.rpc.projectId,
...this.rpc.qrModalOptions,
});
} catch (e) {
this.signer.logger.error(e);
throw new Error("Could not generate WalletConnectModal Instance");
}
}
}
}
protected loadConnectOpts(opts?: ConnectOps) {
if (!opts) return;
const { chains, optionalChains, rpcMap } = opts;
if (chains && isValidArray(chains)) {
this.rpc.chains = chains.map((chain) => this.formatChainId(chain));
chains.forEach((chain) => {
this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);
});
}
if (optionalChains && isValidArray(optionalChains)) {
this.rpc.optionalChains = [];
this.rpc.optionalChains = optionalChains?.map((chain) => this.formatChainId(chain));
optionalChains.forEach((chain) => {
this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);
});
}
}
protected getRpcUrl(chainId: number, projectId?: string): string {
const providedRpc = this.rpc.rpcMap?.[chainId];
return (
providedRpc ||
`${RPC_URL}?chainId=eip155:${chainId}&projectId=${projectId || this.rpc.projectId}`
);
}
protected async loadPersistedSession() {
if (!this.session) return;
try {
const chainId = await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);
// cater to both inline & nested namespace formats
const namespace = this.session.namespaces[`${this.namespace}:${chainId}`]
? this.session.namespaces[`${this.namespace}:${chainId}`]
: this.session.namespaces[this.namespace];
this.setChainIds(chainId ? [this.formatChainId(chainId)] : namespace?.accounts);
this.setAccounts(namespace?.accounts);
} catch (error) {
this.signer.logger.error("Failed to load persisted session, clearing state...");
this.signer.logger.error(error);
await this.disconnect().catch((error) => this.signer.logger.warn(error));
}
}
protected reset() {
this.chainId = 1;
this.accounts = [];
}
protected persist() {
if (!this.session) return;
this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`, this.chainId);
}
protected parseAccounts(payload: string | string[]): string[] {
if (typeof payload === "string" || payload instanceof String) {
return [this.parseAccount(payload)];
}
return payload.map((account: string) => this.parseAccount(account));
}
protected parseAccount = (payload: any): string => {
return this.isCompatibleChainId(payload) ? this.parseAccountId(payload).address : payload;
};
}
export default EthereumProvider;