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

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 +236 -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 +427 -79
  33. package/src/walletConnect/walletConnect.d.ts +309 -28
  34. package/src/walletConnect/walletConnect.js +426 -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,432 @@
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 === this.currentChainId) {
195
+ walletConnectorCore.logger.debug(`ignoring chainChanged event with same chain id as current chain id: ${chainId}`);
196
+ return;
197
+ }
198
+ if (chainId === undefined) {
199
+ walletConnectorCore.logger.debug(`received unexpected data for chainChanged: ${data} with type ${typeof data}}`);
200
+ return;
201
+ }
202
+ this.currentChainId = chainId;
203
+ this.emit('chainChange', { chain: String(chainId) });
204
+ // When a user switches network from their wallet, we need the provider to change network
205
+ // such that any future calls to `getNetwork` will return the correct network
206
+ this.switchNetwork({ networkChainId: chainId });
207
+ }
208
+ else if (name === 'accountsChanged') {
209
+ if (!Array.isArray(data)) {
210
+ walletConnectorCore.logger.debug(`received unexpected data for accountsChanged: ${data} with type ${typeof data}}`);
211
+ return;
212
+ }
213
+ // eslint-disable-next-line prefer-destructuring
214
+ const account = data[0].split(':')[2];
215
+ this.setActiveAccount(account);
216
+ }
217
+ });
218
+ WalletConnect.provider.client.on('session_delete', () => _tslib.__awaiter(this, void 0, void 0, function* () {
219
+ this.endSession();
220
+ this.emit('disconnect');
221
+ }));
53
222
  }
54
223
  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;
224
+ if (!WalletConnect.provider) {
225
+ return;
226
+ }
227
+ WalletConnect.provider.client.removeAllListeners('session_event');
228
+ WalletConnect.provider.client.removeAllListeners('session_delete');
229
+ }
230
+ getWalletClient(chainId) {
231
+ if (!WalletConnect.provider) {
232
+ return;
233
+ }
234
+ return viem.createWalletClient({
235
+ account: this.activeAccount ? accounts.toAccount(this.activeAccount) : undefined,
236
+ chain: chainId ? viemUtils.chainsMap[chainId] : undefined,
237
+ transport: viem.custom(WalletConnect.provider),
238
+ });
68
239
  }
69
- fetchPublicAddress(opts) {
240
+ getAddress(opts) {
241
+ var _a, _b;
70
242
  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
- });
243
+ if (this.activeAccount) {
244
+ return this.activeAccount;
245
+ }
246
+ if (!WalletConnect.provider || !((_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.uri)) {
247
+ walletConnectorCore.logger.debug('No WC2 provider found, re-initializing...');
248
+ yield this.endSession();
249
+ yield this.init();
250
+ // sleep 1 s to wait for connect call to finish
251
+ // the connect call isn't await-ed because it only resolves once
252
+ // the connection is established, but we need to wait for it to
253
+ // finish setting up the connection URI and making it available
254
+ // on the provider
255
+ yield utils.sleep(1000);
256
+ if (!WalletConnect.provider || !((_b = WalletConnect.provider) === null || _b === void 0 ? void 0 : _b.uri)) {
257
+ walletConnectorCore.logger.debug('No WC2 provider found, escaping and throwing error');
258
+ throw new utils.DynamicError('No provider found');
259
+ }
260
+ }
261
+ const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key);
262
+ walletConnectorCore.performPlatformSpecificConnectionMethod(WalletConnect.provider.uri, metadata, {
263
+ onDesktopUri: opts === null || opts === void 0 ? void 0 : opts.onDesktopUri,
264
+ onDisplayUri: opts === null || opts === void 0 ? void 0 : opts.onDisplayUri,
265
+ }, this.deepLinkPreference);
266
+ return new Promise((resolve, reject) => {
267
+ if (!WalletConnect.provider) {
268
+ reject(new utils.DynamicError('No provider found'));
269
+ return;
270
+ }
271
+ const onFail = () => {
272
+ const error = new utils.DynamicError('Connection rejected. Please try again.');
273
+ error.code = 'connection_rejected';
274
+ if (WalletConnect.provider) {
275
+ WalletConnect.provider.uri = undefined;
276
+ // this is needed for mobile to work when using universal links.
277
+ // if the user cancels the connection, we need to re-initialize the provider
278
+ // so that the async work is done ahead of time, before the user tries to connect again,
279
+ // otherwise they will trigger the iOS bug where they are redirected to the app store
280
+ this.init();
281
+ }
282
+ reject(error);
283
+ // We must clean up the onConnect and onFail listeners
284
+ // whenever the connection attempt either succeeds or fails
285
+ cleanupListeners();
286
+ };
287
+ const onConnect = ({ session }) => {
288
+ if (!session) {
289
+ reject(new utils.DynamicError('No session found'));
79
290
  }
80
- } }));
291
+ this.setSession(session);
292
+ this.setActiveAccount(session.namespaces.eip155.accounts[0].split(':')[2]);
293
+ this.getNetwork().then((chainId) => {
294
+ this.currentChainId = chainId;
295
+ resolve(this.activeAccount);
296
+ });
297
+ // We must clean up the onConnect and onFail listeners
298
+ // whenever the connection attempt either succeeds or fails
299
+ cleanupListeners();
300
+ };
301
+ const cleanupListeners = () => {
302
+ var _a;
303
+ ee.off('walletconnect_connection_failed', onFail);
304
+ (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.off('connect', onConnect);
305
+ };
306
+ ee.on('walletconnect_connection_failed', onFail);
307
+ WalletConnect.provider.on('connect', onConnect);
308
+ });
309
+ });
310
+ }
311
+ /**
312
+ * WalletConnect V2 will fail to send the sign message request if the chainId
313
+ * is not the same as the one in the session. This method will wait for the
314
+ * chainId to change and then retry the sign message request.
315
+ *
316
+ * Otherwise it will just return the result of the sign message request.
317
+ *
318
+ * @param signMessageFn - Function to sign message with provider
319
+ * @param messageToSign - Message to sign
320
+ * @returns
321
+ */
322
+ waitForSignMessage(signMessageFn, messageToSign) {
323
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
324
+ const raceConditionPromise = new Promise((resolve, reject) => {
325
+ // Create listener for chain change event
326
+ this.on('chainChange', () => resolve({ success: false }));
327
+ signMessageFn(messageToSign)
328
+ .then((result) => resolve({ signedMessage: result, success: true }))
329
+ .catch(reject);
330
+ });
331
+ const signedMessageResult = yield raceConditionPromise;
332
+ if (signedMessageResult.success === false) {
333
+ return signMessageFn(messageToSign);
334
+ }
335
+ return signedMessageResult.signedMessage;
81
336
  });
82
337
  }
83
338
  getDeepLink() {
84
339
  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;
340
+ if (!this.session) {
341
+ return;
88
342
  }
89
- return walletConnectorCore.getDeepLink({
90
- metadata: wallet,
343
+ const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key);
344
+ const deepLink = walletConnectorCore.getDeepLink({
345
+ metadata,
91
346
  mode: 'regular',
92
347
  preference: this.deepLinkPreference,
93
- uri: this.getClient().uri,
348
+ uri: (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.uri,
94
349
  });
350
+ if (!deepLink) {
351
+ return;
352
+ }
353
+ // we need to include the session topic here because it helps the wallet
354
+ // auto redirect back to the dapp after signing
355
+ return `${deepLink}?sessionTopic=${this.session.topic}`;
95
356
  }
96
357
  signMessage(messageToSign) {
97
358
  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(); }));
359
+ if (!this.session) {
360
+ throw new utils.DynamicError('no session');
361
+ }
362
+ const web3Provider = this.getWalletClient();
363
+ if (!web3Provider) {
364
+ throw new utils.DynamicError('No WalletConnect provider found to handle signing');
365
+ }
366
+ const deepLink = this.getDeepLink();
367
+ if (utils.isMobile() && deepLink) {
368
+ window.location.href = deepLink;
369
+ }
370
+ const signMessageFn = (messageToSign) => _tslib.__awaiter(this, void 0, void 0, function* () {
371
+ const { activeAccount } = this;
372
+ if (!activeAccount) {
373
+ return;
374
+ }
375
+ return web3Provider.signMessage({
376
+ account: activeAccount,
377
+ message: messageToSign,
378
+ });
379
+ });
380
+ const response = yield this.waitForSignMessage(signMessageFn, messageToSign);
381
+ return response;
101
382
  });
102
383
  }
384
+ clearActiveAccount() {
385
+ localStorage.removeItem(this.activeAccountKey);
386
+ this.activeAccount = undefined;
387
+ }
388
+ clearSession() {
389
+ localStorage.removeItem(this.sessionTopicKey);
390
+ this.session = undefined;
391
+ }
392
+ setActiveAccount(account) {
393
+ localStorage.setItem(this.activeAccountKey, account);
394
+ this.activeAccount = account;
395
+ this.emit('accountChange', { accounts: [account] });
396
+ }
397
+ setSession(session) {
398
+ localStorage.setItem(this.sessionTopicKey, session.topic);
399
+ this.session = session;
400
+ }
103
401
  endSession() {
402
+ var _a;
104
403
  return _tslib.__awaiter(this, void 0, void 0, function* () {
105
- client.killWalletConnectSession(this.getClient());
404
+ this.clearActiveAccount();
405
+ this.clearSession();
406
+ this.hasSwitchedNetwork = false;
407
+ this.currentChainId = undefined;
408
+ if (!((_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.session)) {
409
+ return;
410
+ }
411
+ try {
412
+ yield WalletConnect.provider.disconnect();
413
+ // We must unset provider on logout so that a new session can be established
414
+ // If we don't then the provider will still have the old session and will hang
415
+ WalletConnect.provider = undefined;
416
+ }
417
+ catch (e) {
418
+ walletConnectorCore.logger.debug(e);
419
+ }
420
+ });
421
+ }
422
+ getNetwork() {
423
+ const _super = Object.create(null, {
424
+ getNetwork: { get: () => super.getNetwork }
425
+ });
426
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
427
+ if (this.currentChainId) {
428
+ return this.currentChainId;
429
+ }
430
+ yield this.initProvider();
431
+ return _super.getNetwork.call(this);
106
432
  });
107
433
  }
108
434
  providerSwitchNetwork({ network, provider, }) {
@@ -110,45 +436,67 @@ class WalletConnect extends EthWalletConnector.EthWalletConnector {
110
436
  providerSwitchNetwork: { get: () => super.providerSwitchNetwork }
111
437
  });
112
438
  return _tslib.__awaiter(this, void 0, void 0, function* () {
113
- const client = this.getClient();
114
439
  const currentNetworkId = yield this.getNetwork();
115
440
  if (currentNetworkId && currentNetworkId === network.chainId) {
116
441
  return;
117
442
  }
118
- if (this.switchNetworkOnlyFromWallet !== undefined &&
119
- this.switchNetworkOnlyFromWallet) {
443
+ if (this.switchNetworkOnlyFromWallet) {
120
444
  throw new utils.DynamicError('Network switching is only supported through the wallet');
121
445
  }
122
446
  if (!this.supportsNetworkSwitching()) {
123
447
  throw new utils.DynamicError('Network switching not supported');
124
448
  }
125
- if (!client) {
126
- throw new utils.DynamicError('Client not found');
449
+ if (!provider) {
450
+ throw new utils.DynamicError('Provider not found');
127
451
  }
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 });
452
+ yield _super.providerSwitchNetwork.call(this, { network, provider });
453
+ this.currentChainId = network.chainId;
454
+ this.hasSwitchedNetwork = true;
455
+ this.emit('chainChange', { chain: String(network.chainId) });
138
456
  });
139
457
  }
140
458
  getConnectedAccounts() {
141
459
  return _tslib.__awaiter(this, void 0, void 0, function* () {
142
- const client = this.getClient();
143
- if (!client.connected)
460
+ if (this.isInitialized === false) {
461
+ yield this.initProvider();
462
+ this.refreshSession();
463
+ this.isInitialized = true;
464
+ }
465
+ if (!this.activeAccount) {
144
466
  return [];
145
- return client.accounts;
467
+ }
468
+ return [this.activeAccount];
146
469
  });
147
470
  }
148
- getSession() {
471
+ isMetaMask() {
472
+ var _a, _b, _c, _d, _e;
473
+ 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);
474
+ }
475
+ getSupportedNetworks() {
149
476
  var _a;
150
477
  return _tslib.__awaiter(this, void 0, void 0, function* () {
151
- return (_a = this.client) === null || _a === void 0 ? void 0 : _a.session;
478
+ // MM allows you to switch to any network the first time, even if it's not enabled in MM
479
+ // so we should consider all networks as supported if network switching hasn't been triggered yet
480
+ if (this.isMetaMask() && !this.hasSwitchedNetwork) {
481
+ return this.evmNetworks.map((network) => network.chainId.toString());
482
+ }
483
+ yield this.initProvider();
484
+ this.refreshSession();
485
+ if (!this.session) {
486
+ return [];
487
+ }
488
+ const chains = [];
489
+ // Some wallet (i.e ZenGo) use namespaces.account to list supported chains
490
+ // while others use keys within the namespaces object
491
+ Object.keys(this.session.namespaces).forEach((key) => {
492
+ if (key.startsWith('eip155:')) {
493
+ chains.push(key.split(':')[1]);
494
+ }
495
+ });
496
+ (_a = this.session.namespaces.eip155) === null || _a === void 0 ? void 0 : _a.accounts.forEach((account) => chains.push(account.split(':')[1]));
497
+ return chains.length
498
+ ? chains
499
+ : this.evmNetworks.map((network) => network.chainId.toString());
152
500
  });
153
501
  }
154
502
  }