@dynamic-labs/ethereum 2.0.0-alpha.2 → 2.0.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +223 -0
  2. package/package.json +10 -11
  3. package/src/EthWalletConnector.cjs +1 -20
  4. package/src/EthWalletConnector.d.ts +9 -10
  5. package/src/EthWalletConnector.js +3 -22
  6. package/src/coinbase/client/client.cjs +2 -2
  7. package/src/coinbase/client/client.d.ts +2 -2
  8. package/src/coinbase/client/client.js +2 -2
  9. package/src/coinbase/coinbase.cjs +30 -9
  10. package/src/coinbase/coinbase.d.ts +19 -17
  11. package/src/coinbase/coinbase.js +31 -10
  12. package/src/ethProviderHelper.cjs +10 -5
  13. package/src/ethProviderHelper.d.ts +4 -3
  14. package/src/ethProviderHelper.js +10 -5
  15. package/src/index.cjs +7 -13
  16. package/src/index.d.ts +1 -0
  17. package/src/index.js +7 -13
  18. package/src/injected/ExodusEvm.cjs +1 -0
  19. package/src/injected/ExodusEvm.d.ts +1 -0
  20. package/src/injected/ExodusEvm.js +1 -0
  21. package/src/injected/InjectedWalletBase.cjs +6 -14
  22. package/src/injected/InjectedWalletBase.d.ts +2 -2
  23. package/src/injected/InjectedWalletBase.js +6 -14
  24. package/src/injected/PhantomEvm.cjs +4 -3
  25. package/src/injected/PhantomEvm.d.ts +2 -1
  26. package/src/injected/PhantomEvm.js +4 -3
  27. package/src/injected/fetchInjectedWalletConnectors.d.ts +0 -1
  28. package/src/walletConnect/fetchWalletConnectWallets.cjs +14 -33
  29. package/src/walletConnect/fetchWalletConnectWallets.d.ts +2 -5
  30. package/src/walletConnect/fetchWalletConnectWallets.js +14 -33
  31. package/src/walletConnect/index.d.ts +1 -2
  32. package/src/walletConnect/walletConnect.cjs +418 -79
  33. package/src/walletConnect/walletConnect.d.ts +309 -28
  34. package/src/walletConnect/walletConnect.js +417 -79
  35. package/src/walletConnect/client/client.cjs +0 -201
  36. package/src/walletConnect/client/client.d.ts +0 -17
  37. package/src/walletConnect/client/client.js +0 -187
  38. package/src/walletConnect/client/index.d.ts +0 -1
  39. package/src/walletConnect/client/types.d.ts +0 -4
  40. package/src/walletConnect/walletConnectV2.cjs +0 -475
  41. package/src/walletConnect/walletConnectV2.d.ts +0 -333
  42. package/src/walletConnect/walletConnectV2.js +0 -466
@@ -3,106 +3,423 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _tslib = require('../../_virtual/_tslib.cjs');
6
- var WalletConnectProvider = require('@walletconnect/ethereum-provider');
6
+ var Provider = require('@walletconnect/universal-provider');
7
+ var EventEmitter = require('eventemitter3');
7
8
  var viem = require('viem');
8
- var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
9
- var walletBook = require('@dynamic-labs/wallet-book');
9
+ var accounts = require('viem/accounts');
10
10
  var utils = require('@dynamic-labs/utils');
11
+ var walletBook = require('@dynamic-labs/wallet-book');
12
+ var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
13
+ var viemUtils = require('@dynamic-labs/viem-utils');
11
14
  var EthWalletConnector = require('../EthWalletConnector.cjs');
12
- var constants = require('../constants.cjs');
13
- var client = require('./client/client.cjs');
15
+ var parseIntSafe = require('../utils/parseIntSafe.cjs');
14
16
 
15
17
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
18
 
17
- var WalletConnectProvider__default = /*#__PURE__*/_interopDefaultLegacy(WalletConnectProvider);
19
+ var Provider__default = /*#__PURE__*/_interopDefaultLegacy(Provider);
20
+ var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
18
21
 
22
+ const activeAccountKey = (walletName) => `dynamic-wc2-active-account-${walletName}`;
23
+ const sessionTopicKey = (walletName) => `dynamic-wc2-session-topic-${walletName}`;
24
+ const swicthedNetworkKey = (walletName) => `dynamic-wc2-switched-network-${walletName}`;
25
+ const currentChainKey = (walletName) => `dynamic-wc2-current-chain-${walletName}`;
26
+ const ee = new EventEmitter__default["default"]();
19
27
  class WalletConnect extends EthWalletConnector.EthWalletConnector {
20
- constructor(_a) {
21
- var { walletConnectV1Bridge, walletName } = _a, props = _tslib.__rest(_a, ["walletConnectV1Bridge", "walletName"]);
22
- super(props);
28
+ constructor(opts) {
29
+ var _a;
30
+ super(opts);
23
31
  this.supportedChains = ['EVM', 'ETH'];
24
32
  this.connectedChain = 'EVM';
25
- this.bridge = 'https://bridge.walletconnect.org';
33
+ this.isInitialized = false;
26
34
  this.canConnectViaQrCode = true;
27
35
  this.isWalletConnect = true;
28
- this.switchNetworkOnlyFromWallet = false;
29
- this.name = walletName;
30
- if (walletConnectV1Bridge) {
31
- this.bridge = walletConnectV1Bridge;
36
+ this.preferredChains = [];
37
+ // When trying to switch network for MetaMask, the switch promise gets stuck
38
+ // if the switch got trigged once already, so we need to keep track of that
39
+ this._hasSwitchedNetwork = false;
40
+ this.name = opts.walletName;
41
+ this.projectId = opts.projectId;
42
+ this.deepLinkPreference = opts.deepLinkPreference || 'native';
43
+ this.preferredChains = opts.walletConnectPreferredChains || [];
44
+ this.hasSwitchedNetwork =
45
+ (_a = Boolean(localStorage.getItem(this.swicthedNetworkKey))) !== null && _a !== void 0 ? _a : false;
46
+ const lsCurrentChain = localStorage.getItem(this.currentChainKey);
47
+ this.currentChainId = lsCurrentChain
48
+ ? parseIntSafe.parseIntSafe(lsCurrentChain)
49
+ : undefined;
50
+ }
51
+ getMappedChains() {
52
+ return (this.evmNetworks
53
+ // Filters out palm that crashes Trust Wallet
54
+ .filter((network) => network.chainId !== 11297108109)
55
+ .map((network) => `eip155:${network.chainId}`));
56
+ }
57
+ getMappedChainsByPreferredOrder() {
58
+ const allChains = this.getMappedChains();
59
+ const reorderedChains = this.preferredChains.filter((chain) => allChains.includes(chain));
60
+ const remainingChains = allChains.filter((chain) => !this.preferredChains.includes(chain));
61
+ return [...reorderedChains, ...remainingChains];
62
+ }
63
+ initConnection() {
64
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
65
+ const { provider } = WalletConnect;
66
+ if (!provider) {
67
+ throw new utils.DynamicError('No provider found (init connection)');
68
+ }
69
+ // this means there is already a connection in progress, so don't call connect again
70
+ if (provider === null || provider === void 0 ? void 0 : provider.uri) {
71
+ return;
72
+ }
73
+ const optionalNamespaces = {
74
+ eip155: {
75
+ chains: this.getMappedChainsByPreferredOrder(),
76
+ events: ['chainChanged', 'accountsChanged'],
77
+ methods: [
78
+ 'eth_chainId',
79
+ 'eth_signTypedData',
80
+ 'eth_signTransaction',
81
+ 'eth_sign',
82
+ 'personal_sign',
83
+ 'eth_sendTransaction',
84
+ 'eth_signTypedData_v4',
85
+ 'wallet_switchEthereumChain',
86
+ 'wallet_addEthereumChain',
87
+ ],
88
+ rpcMap: this.evmNetworkRpcMap(),
89
+ },
90
+ };
91
+ provider
92
+ .connect({
93
+ optionalNamespaces,
94
+ })
95
+ .catch((e) => {
96
+ walletConnectorCore.logger.error(e);
97
+ ee.emit('walletconnect_connection_failed', e);
98
+ });
99
+ });
100
+ }
101
+ createInitProviderPromise() {
102
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
103
+ WalletConnect.provider = yield Provider__default["default"].init({
104
+ logger: walletConnectorCore.logger.logLevel.toLowerCase() === 'debug' ? 'debug' : undefined,
105
+ projectId: this.projectId,
106
+ });
107
+ this.teardownEventListeners();
108
+ this.setupEventListeners();
109
+ });
110
+ }
111
+ // We need to add a gate to this method since we will be calling it asynchronously
112
+ // from different places (such as setShowAuthFlow), which means there's a chance for
113
+ // a race condition to happen where createInitProviderPromise is called multiple times
114
+ initProvider() {
115
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
116
+ const { provider } = WalletConnect;
117
+ if (!provider) {
118
+ if (this.initializePromise === undefined) {
119
+ this.initializePromise = this.createInitProviderPromise();
120
+ }
121
+ yield this.initializePromise;
122
+ }
123
+ });
124
+ }
125
+ refreshSession() {
126
+ var _a, _b, _c, _d, _e;
127
+ if ((_b = (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.session) === null || _b === void 0 ? void 0 : _b.topic) {
128
+ if (localStorage.getItem(this.sessionTopicKey) ===
129
+ ((_d = (_c = WalletConnect.provider) === null || _c === void 0 ? void 0 : _c.session) === null || _d === void 0 ? void 0 : _d.topic)) {
130
+ this.session = WalletConnect.provider.session;
131
+ this.activeAccount = ((_e = localStorage.getItem(this.activeAccountKey)) !== null && _e !== void 0 ? _e : undefined);
132
+ }
32
133
  }
33
- this.deepLinkPreference = props.deepLinkPreference || 'native';
34
134
  }
35
- getClient() {
36
- if (this.client) {
37
- return this.client;
135
+ init() {
136
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
137
+ yield this.initProvider();
138
+ yield this.initConnection();
139
+ this.isInitialized = true;
140
+ });
141
+ }
142
+ get sessionTopicKey() {
143
+ return sessionTopicKey(this.key);
144
+ }
145
+ get activeAccountKey() {
146
+ return activeAccountKey(this.key);
147
+ }
148
+ get swicthedNetworkKey() {
149
+ return swicthedNetworkKey(this.key);
150
+ }
151
+ get currentChainKey() {
152
+ return currentChainKey(this.key);
153
+ }
154
+ set currentChainId(value) {
155
+ this._currentChainId = value;
156
+ if (value) {
157
+ localStorage.setItem(this.currentChainKey, value.toString());
158
+ }
159
+ else {
160
+ localStorage.removeItem(this.currentChainKey);
38
161
  }
39
- this.client = client.initClient(this.key, this.bridge, this.clientOptions);
40
- return this.client;
41
162
  }
42
- supportsNetworkSwitching() {
43
- if (this.connectedChain === 'EVM') {
44
- return true;
163
+ get currentChainId() {
164
+ return this._currentChainId;
165
+ }
166
+ set hasSwitchedNetwork(value) {
167
+ this._hasSwitchedNetwork = value;
168
+ if (value) {
169
+ localStorage.setItem(this.swicthedNetworkKey, value.toString());
45
170
  }
46
171
  else {
47
- const client = this.getClient();
48
- return Boolean(client === null || client === void 0 ? void 0 : client.chainId);
172
+ localStorage.removeItem(this.swicthedNetworkKey);
49
173
  }
50
174
  }
175
+ get hasSwitchedNetwork() {
176
+ return this._hasSwitchedNetwork;
177
+ }
178
+ supportsNetworkSwitching() {
179
+ return true;
180
+ }
51
181
  setupEventListeners() {
52
- client.setupWalletConnectEventListeners(this, this.getClient());
182
+ if (!WalletConnect.provider) {
183
+ return;
184
+ }
185
+ WalletConnect.provider.client.on('session_event', ({ params }) => {
186
+ walletConnectorCore.logger.debug('session_event was called', { params });
187
+ if (!params || !params.event) {
188
+ walletConnectorCore.logger.debug('session_event was called without params or params.event');
189
+ return;
190
+ }
191
+ const { name, data } = params.event;
192
+ if (name === 'chainChanged') {
193
+ const chainId = parseIntSafe.parseIntSafe(data);
194
+ if (chainId === undefined) {
195
+ walletConnectorCore.logger.debug(`received unexpected data for chainChanged: ${data} with type ${typeof data}}`);
196
+ return;
197
+ }
198
+ this.currentChainId = chainId;
199
+ this.emit('chainChange', { chain: String(chainId) });
200
+ // When a user switches network from their wallet, we need the provider to change network
201
+ // such that any future calls to `getNetwork` will return the correct network
202
+ this.switchNetwork({ networkChainId: chainId });
203
+ }
204
+ else if (name === 'accountsChanged') {
205
+ if (!Array.isArray(data)) {
206
+ walletConnectorCore.logger.debug(`received unexpected data for accountsChanged: ${data} with type ${typeof data}}`);
207
+ return;
208
+ }
209
+ // eslint-disable-next-line prefer-destructuring
210
+ const account = data[0].split(':')[2];
211
+ this.setActiveAccount(account);
212
+ }
213
+ });
214
+ WalletConnect.provider.client.on('session_delete', () => _tslib.__awaiter(this, void 0, void 0, function* () {
215
+ this.endSession();
216
+ this.emit('disconnect');
217
+ }));
53
218
  }
54
219
  teardownEventListeners() {
55
- client.teardownWalletConnectEventListeners(this.getClient());
56
- }
57
- getWalletClient() {
58
- const client = this.getClient();
59
- return client
60
- ? viem.createWalletClient({
61
- transport: viem.custom(new WalletConnectProvider__default["default"]({
62
- connector: client,
63
- infuraId: constants.INFURA_ID,
64
- rpc: this.evmNetworkRpcMap(),
65
- })),
66
- })
67
- : undefined;
220
+ if (!WalletConnect.provider) {
221
+ return;
222
+ }
223
+ WalletConnect.provider.client.removeAllListeners('session_event');
224
+ WalletConnect.provider.client.removeAllListeners('session_delete');
225
+ }
226
+ getWalletClient(chainId) {
227
+ if (!WalletConnect.provider) {
228
+ return;
229
+ }
230
+ return viem.createWalletClient({
231
+ account: this.activeAccount ? accounts.toAccount(this.activeAccount) : undefined,
232
+ chain: chainId ? viemUtils.chainsMap[chainId] : undefined,
233
+ transport: viem.custom(WalletConnect.provider),
234
+ });
68
235
  }
69
- fetchPublicAddress(opts) {
236
+ getAddress(opts) {
237
+ var _a, _b;
70
238
  return _tslib.__awaiter(this, void 0, void 0, function* () {
71
- return client.fetchWalletConnectEVMPublicAddress(walletBook.getWalletBookWallet(this.walletBook, this.key), this.getClient(), this.deepLinkPreference, Object.assign(Object.assign({}, opts), { onConnect: (payload) => {
72
- var _a, _b;
73
- (_a = opts === null || opts === void 0 ? void 0 : opts.onConnect) === null || _a === void 0 ? void 0 : _a.call(opts, payload);
74
- this.connectedChain = payload.params[0].chainId ? 'EVM' : 'SOL';
75
- if ((_b = payload.params[0].accounts) === null || _b === void 0 ? void 0 : _b.length) {
76
- this.emit('accountChange', {
77
- accounts: payload.params[0].accounts,
78
- });
239
+ if (this.activeAccount) {
240
+ return this.activeAccount;
241
+ }
242
+ if (!WalletConnect.provider || !((_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.uri)) {
243
+ walletConnectorCore.logger.debug('No WC2 provider found, re-initializing...');
244
+ yield this.endSession();
245
+ yield this.init();
246
+ // sleep 1 s to wait for connect call to finish
247
+ // the connect call isn't await-ed because it only resolves once
248
+ // the connection is established, but we need to wait for it to
249
+ // finish setting up the connection URI and making it available
250
+ // on the provider
251
+ yield utils.sleep(1000);
252
+ if (!WalletConnect.provider || !((_b = WalletConnect.provider) === null || _b === void 0 ? void 0 : _b.uri)) {
253
+ walletConnectorCore.logger.debug('No WC2 provider found, escaping and throwing error');
254
+ throw new utils.DynamicError('No provider found');
255
+ }
256
+ }
257
+ const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key);
258
+ walletConnectorCore.performPlatformSpecificConnectionMethod(WalletConnect.provider.uri, metadata, {
259
+ onDesktopUri: opts === null || opts === void 0 ? void 0 : opts.onDesktopUri,
260
+ onDisplayUri: opts === null || opts === void 0 ? void 0 : opts.onDisplayUri,
261
+ }, this.deepLinkPreference);
262
+ return new Promise((resolve, reject) => {
263
+ if (!WalletConnect.provider) {
264
+ reject(new utils.DynamicError('No provider found'));
265
+ return;
266
+ }
267
+ const onFail = () => {
268
+ const error = new utils.DynamicError('Connection rejected. Please try again.');
269
+ error.code = 'connection_rejected';
270
+ if (WalletConnect.provider) {
271
+ WalletConnect.provider.uri = undefined;
272
+ // this is needed for mobile to work when using universal links.
273
+ // if the user cancels the connection, we need to re-initialize the provider
274
+ // so that the async work is done ahead of time, before the user tries to connect again,
275
+ // otherwise they will trigger the iOS bug where they are redirected to the app store
276
+ this.init();
277
+ }
278
+ reject(error);
279
+ // We must clean up the onConnect and onFail listeners
280
+ // whenever the connection attempt either succeeds or fails
281
+ cleanupListeners();
282
+ };
283
+ const onConnect = ({ session }) => {
284
+ if (!session) {
285
+ reject(new utils.DynamicError('No session found'));
79
286
  }
80
- } }));
287
+ this.setSession(session);
288
+ this.setActiveAccount(session.namespaces.eip155.accounts[0].split(':')[2]);
289
+ resolve(this.activeAccount);
290
+ // We must clean up the onConnect and onFail listeners
291
+ // whenever the connection attempt either succeeds or fails
292
+ cleanupListeners();
293
+ };
294
+ const cleanupListeners = () => {
295
+ var _a;
296
+ ee.off('walletconnect_connection_failed', onFail);
297
+ (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.off('connect', onConnect);
298
+ };
299
+ ee.on('walletconnect_connection_failed', onFail);
300
+ WalletConnect.provider.on('connect', onConnect);
301
+ });
302
+ });
303
+ }
304
+ /**
305
+ * WalletConnect V2 will fail to send the sign message request if the chainId
306
+ * is not the same as the one in the session. This method will wait for the
307
+ * chainId to change and then retry the sign message request.
308
+ *
309
+ * Otherwise it will just return the result of the sign message request.
310
+ *
311
+ * @param signMessageFn - Function to sign message with provider
312
+ * @param messageToSign - Message to sign
313
+ * @returns
314
+ */
315
+ waitForSignMessage(signMessageFn, messageToSign) {
316
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
317
+ const raceConditionPromise = new Promise((resolve) => {
318
+ // Create listener for chain change event
319
+ this.on('chainChange', () => resolve({ success: false }));
320
+ signMessageFn(messageToSign).then((result) => resolve({ signedMessage: result, success: true }));
321
+ });
322
+ const signedMessageResult = yield raceConditionPromise;
323
+ if (signedMessageResult.success === false) {
324
+ return signMessageFn(messageToSign);
325
+ }
326
+ return signedMessageResult.signedMessage;
81
327
  });
82
328
  }
83
329
  getDeepLink() {
84
330
  var _a;
85
- const wallet = walletBook.getWalletBookWallet(this.walletBook, this.key);
86
- if (!utils.isMobile() && !((_a = wallet.desktop) === null || _a === void 0 ? void 0 : _a.native)) {
87
- return undefined;
331
+ if (!this.session) {
332
+ return;
88
333
  }
89
- return walletConnectorCore.getDeepLink({
90
- metadata: wallet,
334
+ const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key);
335
+ const deepLink = walletConnectorCore.getDeepLink({
336
+ metadata,
91
337
  mode: 'regular',
92
338
  preference: this.deepLinkPreference,
93
- uri: this.getClient().uri,
339
+ uri: (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.uri,
94
340
  });
341
+ if (!deepLink) {
342
+ return;
343
+ }
344
+ // we need to include the session topic here because it helps the wallet
345
+ // auto redirect back to the dapp after signing
346
+ return `${deepLink}?sessionTopic=${this.session.topic}`;
95
347
  }
96
348
  signMessage(messageToSign) {
97
349
  return _tslib.__awaiter(this, void 0, void 0, function* () {
98
- return client.signWalletConnectPersonalMessage(messageToSign, walletBook.getWalletBookWallet(this.walletBook, this.key), this.getClient(), this.deepLinkPreference,
99
- // don't call getPublicClient until we really need to
100
- () => _tslib.__awaiter(this, void 0, void 0, function* () { return this.getPublicClient(); }));
350
+ if (!this.session) {
351
+ throw new utils.DynamicError('no session');
352
+ }
353
+ const web3Provider = this.getWalletClient();
354
+ if (!web3Provider) {
355
+ throw new utils.DynamicError('No WalletConnect provider found to handle signing');
356
+ }
357
+ const deepLink = this.getDeepLink();
358
+ if (utils.isMobile() && deepLink) {
359
+ window.location.href = deepLink;
360
+ }
361
+ const signMessageFn = (messageToSign) => _tslib.__awaiter(this, void 0, void 0, function* () {
362
+ const { activeAccount } = this;
363
+ if (!activeAccount) {
364
+ return;
365
+ }
366
+ return web3Provider.signMessage({
367
+ account: activeAccount,
368
+ message: messageToSign,
369
+ });
370
+ });
371
+ const response = yield this.waitForSignMessage(signMessageFn, messageToSign);
372
+ return response;
101
373
  });
102
374
  }
375
+ clearActiveAccount() {
376
+ localStorage.removeItem(this.activeAccountKey);
377
+ this.activeAccount = undefined;
378
+ }
379
+ clearSession() {
380
+ localStorage.removeItem(this.sessionTopicKey);
381
+ this.session = undefined;
382
+ }
383
+ setActiveAccount(account) {
384
+ localStorage.setItem(this.activeAccountKey, account);
385
+ this.activeAccount = account;
386
+ this.emit('accountChange', { accounts: [account] });
387
+ }
388
+ setSession(session) {
389
+ localStorage.setItem(this.sessionTopicKey, session.topic);
390
+ this.session = session;
391
+ }
103
392
  endSession() {
393
+ var _a;
104
394
  return _tslib.__awaiter(this, void 0, void 0, function* () {
105
- client.killWalletConnectSession(this.getClient());
395
+ this.clearActiveAccount();
396
+ this.clearSession();
397
+ this.hasSwitchedNetwork = false;
398
+ this.currentChainId = undefined;
399
+ if (!((_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.session)) {
400
+ return;
401
+ }
402
+ try {
403
+ yield WalletConnect.provider.disconnect();
404
+ // We must unset provider on logout so that a new session can be established
405
+ // If we don't then the provider will still have the old session and will hang
406
+ WalletConnect.provider = undefined;
407
+ }
408
+ catch (e) {
409
+ walletConnectorCore.logger.debug(e);
410
+ }
411
+ });
412
+ }
413
+ getNetwork() {
414
+ const _super = Object.create(null, {
415
+ getNetwork: { get: () => super.getNetwork }
416
+ });
417
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
418
+ if (this.currentChainId) {
419
+ return this.currentChainId;
420
+ }
421
+ yield this.initProvider();
422
+ return _super.getNetwork.call(this);
106
423
  });
107
424
  }
108
425
  providerSwitchNetwork({ network, provider, }) {
@@ -110,45 +427,67 @@ class WalletConnect extends EthWalletConnector.EthWalletConnector {
110
427
  providerSwitchNetwork: { get: () => super.providerSwitchNetwork }
111
428
  });
112
429
  return _tslib.__awaiter(this, void 0, void 0, function* () {
113
- const client = this.getClient();
114
430
  const currentNetworkId = yield this.getNetwork();
115
431
  if (currentNetworkId && currentNetworkId === network.chainId) {
116
432
  return;
117
433
  }
118
- if (this.switchNetworkOnlyFromWallet !== undefined &&
119
- this.switchNetworkOnlyFromWallet) {
434
+ if (this.switchNetworkOnlyFromWallet) {
120
435
  throw new utils.DynamicError('Network switching is only supported through the wallet');
121
436
  }
122
437
  if (!this.supportsNetworkSwitching()) {
123
438
  throw new utils.DynamicError('Network switching not supported');
124
439
  }
125
- if (!client) {
126
- throw new utils.DynamicError('Client not found');
440
+ if (!provider) {
441
+ throw new utils.DynamicError('Provider not found');
127
442
  }
128
- if (utils.isMobile()) {
129
- const deepLink = walletConnectorCore.getDeepLink({
130
- metadata: walletBook.getWalletBookWallet(this.walletBook, this.key),
131
- mode: 'regular',
132
- preference: this.deepLinkPreference,
133
- uri: client.uri,
134
- });
135
- window.location.href = deepLink;
136
- }
137
- return _super.providerSwitchNetwork.call(this, { network, provider });
443
+ yield _super.providerSwitchNetwork.call(this, { network, provider });
444
+ this.currentChainId = network.chainId;
445
+ this.hasSwitchedNetwork = true;
446
+ this.emit('chainChange', { chain: String(network.chainId) });
138
447
  });
139
448
  }
140
449
  getConnectedAccounts() {
141
450
  return _tslib.__awaiter(this, void 0, void 0, function* () {
142
- const client = this.getClient();
143
- if (!client.connected)
451
+ if (this.isInitialized === false) {
452
+ yield this.initProvider();
453
+ this.refreshSession();
454
+ this.isInitialized = true;
455
+ }
456
+ if (!this.activeAccount) {
144
457
  return [];
145
- return client.accounts;
458
+ }
459
+ return [this.activeAccount];
146
460
  });
147
461
  }
148
- getSession() {
462
+ isMetaMask() {
463
+ var _a, _b, _c, _d, _e;
464
+ return ((_e = (_d = (_c = (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.peer) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.name) === null || _d === void 0 ? void 0 : _d.toLowerCase().startsWith('metamask')) !== null && _e !== void 0 ? _e : false);
465
+ }
466
+ getSupportedNetworks() {
149
467
  var _a;
150
468
  return _tslib.__awaiter(this, void 0, void 0, function* () {
151
- return (_a = this.client) === null || _a === void 0 ? void 0 : _a.session;
469
+ // MM allows you to switch to any network the first time, even if it's not enabled in MM
470
+ // so we should consider all networks as supported if network switching hasn't been triggered yet
471
+ if (this.isMetaMask() && !this.hasSwitchedNetwork) {
472
+ return this.evmNetworks.map((network) => network.chainId.toString());
473
+ }
474
+ yield this.initProvider();
475
+ this.refreshSession();
476
+ if (!this.session) {
477
+ return [];
478
+ }
479
+ const chains = [];
480
+ // Some wallet (i.e ZenGo) use namespaces.account to list supported chains
481
+ // while others use keys within the namespaces object
482
+ Object.keys(this.session.namespaces).forEach((key) => {
483
+ if (key.startsWith('eip155:')) {
484
+ chains.push(key.split(':')[1]);
485
+ }
486
+ });
487
+ (_a = this.session.namespaces.eip155) === null || _a === void 0 ? void 0 : _a.accounts.forEach((account) => chains.push(account.split(':')[1]));
488
+ return chains.length
489
+ ? chains
490
+ : this.evmNetworks.map((network) => network.chainId.toString());
152
491
  });
153
492
  }
154
493
  }