@dynamic-labs/ethereum 0.0.0-exp20240808.0

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