@dynamic-labs/ethereum 2.0.0-alpha.1 → 2.0.0-alpha.10

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