@metamask/connect-evm 0.4.0 → 0.5.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.
@@ -46,22 +46,40 @@ var __async = (__this, __arguments, generator) => {
46
46
  });
47
47
  };
48
48
 
49
- // src/index.ts
50
- import { getInfuraRpcUrls } from "@metamask/connect-multichain";
49
+ // src/utils/infura.ts
50
+ import { getInfuraRpcUrls as getInfuraRpcUrlsMultichain } from "@metamask/connect-multichain";
51
+ import {
52
+ KnownCaipNamespace,
53
+ numberToHex,
54
+ parseCaipChainId
55
+ } from "@metamask/utils";
56
+ var getInfuraRpcUrls = (infuraAPIKey) => {
57
+ const caipMap = getInfuraRpcUrlsMultichain(infuraAPIKey);
58
+ const hexMap = Object.entries(caipMap).reduce(
59
+ (acc, [key, url]) => {
60
+ const { namespace: namespace2, reference } = parseCaipChainId(key);
61
+ if (namespace2 !== KnownCaipNamespace.Eip155) {
62
+ return acc;
63
+ }
64
+ const chainId = numberToHex(parseInt(reference, 10));
65
+ acc[chainId] = url;
66
+ return acc;
67
+ },
68
+ {}
69
+ );
70
+ return hexMap;
71
+ };
51
72
 
52
73
  // src/connect.ts
53
74
  import { analytics } from "@metamask/analytics";
75
+ import { parseScopeString } from "@metamask/chain-agnostic-permission";
54
76
  import {
55
77
  createMultichainClient,
56
78
  getWalletActionAnalyticsProperties,
57
79
  isRejectionError,
58
80
  TransportType
59
81
  } from "@metamask/connect-multichain";
60
- import {
61
- numberToHex as numberToHex2,
62
- hexToNumber as hexToNumber2,
63
- isHexString as isHex
64
- } from "@metamask/utils";
82
+ import { hexToNumber as hexToNumber2 } from "@metamask/utils";
65
83
 
66
84
  // src/constants.ts
67
85
  var IGNORED_METHODS = [
@@ -96,15 +114,13 @@ import {
96
114
  } from "@metamask/connect-multichain";
97
115
  var namespace = "metamask-connect:evm";
98
116
  var logger = createLogger(namespace, "63");
99
- var enableDebug = (debugEnabled = false) => {
100
- if (debugEnabled) {
101
- debug(namespace);
102
- }
117
+ var enableDebug = () => {
118
+ debug(namespace);
103
119
  };
104
120
 
105
121
  // src/provider.ts
106
122
  import { EventEmitter } from "@metamask/connect-multichain";
107
- import { hexToNumber, numberToHex } from "@metamask/utils";
123
+ import { hexToNumber } from "@metamask/utils";
108
124
  var _core, _requestInterceptor, _accounts, _selectedChainId;
109
125
  var EIP1193Provider = class extends EventEmitter {
110
126
  constructor(core, interceptor) {
@@ -148,8 +164,8 @@ var EIP1193Provider = class extends EventEmitter {
148
164
  if (!__privateGet(this, _selectedChainId)) {
149
165
  throw new Error("No chain ID selected");
150
166
  }
151
- const chainId = hexToNumber(__privateGet(this, _selectedChainId));
152
- const scope = `eip155:${chainId}`;
167
+ const decimalChainId = hexToNumber(__privateGet(this, _selectedChainId));
168
+ const scope = `eip155:${decimalChainId}`;
153
169
  const coreOptions = __privateGet(this, _core).options;
154
170
  const supportedNetworks = (_c = (_b = coreOptions == null ? void 0 : coreOptions.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
155
171
  if (!supportedNetworks[scope]) {
@@ -180,11 +196,7 @@ var EIP1193Provider = class extends EventEmitter {
180
196
  return __privateGet(this, _selectedChainId);
181
197
  }
182
198
  set selectedChainId(chainId) {
183
- const hexChainId = chainId && typeof chainId === "number" ? numberToHex(chainId) : chainId;
184
- if (!hexChainId) {
185
- return;
186
- }
187
- __privateSet(this, _selectedChainId, hexChainId);
199
+ __privateSet(this, _selectedChainId, chainId);
188
200
  }
189
201
  // ==========================================
190
202
  // Legacy compatibility methods
@@ -198,6 +210,7 @@ var EIP1193Provider = class extends EventEmitter {
198
210
  }
199
211
  /**
200
212
  * Legacy method for sending JSON-RPC requests.
213
+ *
201
214
  * @deprecated Use `request` instead. This method is provided for backwards compatibility.
202
215
  * @param request - The JSON-RPC request object
203
216
  * @param callback - Optional callback function. If provided, the method returns void.
@@ -247,6 +260,7 @@ var EIP1193Provider = class extends EventEmitter {
247
260
  }
248
261
  /**
249
262
  * Legacy method for sending JSON-RPC requests synchronously (callback-based).
263
+ *
250
264
  * @deprecated Use `request` instead. This method is provided for backwards compatibility.
251
265
  * @param request - The JSON-RPC request object
252
266
  * @param callback - The callback function to receive the response
@@ -265,6 +279,15 @@ import {
265
279
  getPermittedEthChainIds as _getPermittedEthChainIds,
266
280
  getEthAccounts as _getEthAccounts
267
281
  } from "@metamask/chain-agnostic-permission";
282
+ var getEthAccounts = (sessionScopes) => {
283
+ if (!sessionScopes) {
284
+ return [];
285
+ }
286
+ return _getEthAccounts({
287
+ requiredScopes: sessionScopes,
288
+ optionalScopes: sessionScopes
289
+ });
290
+ };
268
291
  var getPermittedEthChainIds = (sessionScopes) => {
269
292
  if (!sessionScopes) {
270
293
  return [];
@@ -309,12 +332,13 @@ ${invalidUrls.join("\n")}`
309
332
  }
310
333
 
311
334
  // src/connect.ts
312
- var DEFAULT_CHAIN_ID = 1;
335
+ var DEFAULT_CHAIN_ID = "0x1";
313
336
  var CHAIN_STORE_KEY = "cache_eth_chainId";
314
- var _core2, _provider, _sessionScopes, _eventHandlers, _sessionChangedHandler, _displayUriHandler, _removeNotificationHandler, _MetamaskConnectEVM_instances, getCoreOptions_fn, createInvokeOptions_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, getSelectedChainId_fn, requestInterceptor_fn, clearConnectionState_fn, addEthereumChain_fn, request_fn, cacheChainId_fn, onChainChanged_fn, onAccountsChanged_fn, onConnect_fn, onDisconnect_fn, onDisplayUri_fn, attemptSessionRecovery_fn;
315
- var MetamaskConnectEVM = class {
337
+ var _core2, _provider, _sessionScopes, _eventHandlers, _sessionChangedHandler, _displayUriHandler, _removeNotificationHandler, _status, _MetamaskConnectEVM_instances, getCoreOptions_fn, createInvokeOptions_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, getSelectedChainId_fn, requestInterceptor_fn, clearConnectionState_fn, addEthereumChain_fn, request_fn, cacheChainId_fn, onSessionChanged_fn, onChainChanged_fn, onAccountsChanged_fn, onConnect_fn, onDisconnect_fn, onDisplayUri_fn;
338
+ var _MetamaskConnectEVM = class _MetamaskConnectEVM {
316
339
  /**
317
340
  * Creates a new MetamaskConnectEVM instance.
341
+ * Use the static `create()` method instead to ensure proper async initialization.
318
342
  *
319
343
  * @param options - The options for the MetamaskConnectEVM instance
320
344
  * @param options.core - The core instance of the Multichain SDK
@@ -336,90 +360,88 @@ var MetamaskConnectEVM = class {
336
360
  __privateAdd(this, _displayUriHandler);
337
361
  /** The clean-up function for the notification handler */
338
362
  __privateAdd(this, _removeNotificationHandler);
363
+ /** The current connection status */
364
+ __privateAdd(this, _status, "disconnected");
339
365
  __privateSet(this, _core2, core);
340
366
  __privateSet(this, _provider, new EIP1193Provider(
341
367
  core,
342
368
  __privateMethod(this, _MetamaskConnectEVM_instances, requestInterceptor_fn).bind(this)
343
369
  ));
344
370
  __privateSet(this, _eventHandlers, eventHandlers);
345
- __privateSet(this, _sessionChangedHandler, (session) => {
346
- var _a;
347
- logger("event: wallet_sessionChanged", session);
348
- __privateSet(this, _sessionScopes, (_a = session == null ? void 0 : session.sessionScopes) != null ? _a : {});
349
- });
350
- __privateGet(this, _core2).on(
351
- "wallet_sessionChanged",
352
- __privateGet(this, _sessionChangedHandler).bind(this)
353
- );
371
+ __privateSet(this, _sessionChangedHandler, __privateMethod(this, _MetamaskConnectEVM_instances, onSessionChanged_fn).bind(this));
372
+ __privateGet(this, _core2).on("wallet_sessionChanged", __privateGet(this, _sessionChangedHandler));
354
373
  __privateSet(this, _displayUriHandler, __privateMethod(this, _MetamaskConnectEVM_instances, onDisplayUri_fn).bind(this));
355
374
  __privateGet(this, _core2).on("display_uri", __privateGet(this, _displayUriHandler));
356
- __privateMethod(this, _MetamaskConnectEVM_instances, attemptSessionRecovery_fn).call(this).catch((error) => {
357
- console.error("Error attempting session recovery", error);
358
- });
359
375
  logger("Connect/EVM constructor completed");
360
376
  }
377
+ /**
378
+ * Creates a fully initialized MetamaskConnectEVM instance.
379
+ * This is the recommended way to instantiate the class, as it ensures
380
+ * all async initialization (like session recovery) completes before
381
+ * the instance is returned.
382
+ *
383
+ * @param options - The options for the MetamaskConnectEVM instance
384
+ * @param options.core - The core instance of the Multichain SDK
385
+ * @param options.eventHandlers - Optional event handlers for EIP-1193 provider events
386
+ * @returns A promise that resolves with a fully initialized MetamaskConnectEVM instance
387
+ */
388
+ static create(options) {
389
+ return __async(this, null, function* () {
390
+ const instance = new _MetamaskConnectEVM(options);
391
+ yield __privateGet(instance, _core2).emitSessionChanged();
392
+ return instance;
393
+ });
394
+ }
361
395
  /**
362
396
  * Connects to the wallet with the specified chain ID and optional account.
363
397
  *
364
398
  * @param options - The connection options
365
- * @param options.account - Optional specific account to connect to
366
- * @param options.forceRequest - Wwhether to force a request regardless of an existing session
367
- * @param options.chainIds - Array of chain IDs to connect to
399
+ * @param [options.account] - Optional param to specify an account to connect to
400
+ * @param [options.forceRequest] - Optional param to force a connection request regardless of whether there is a pre-existing session
401
+ * @param [options.chainIds] - Array of chain IDs to connect to (defaults to ethereum mainnet if not provided)
368
402
  * @returns A promise that resolves with the connected accounts and chain ID
369
403
  */
370
404
  connect() {
371
- return __async(this, arguments, function* ({ account, forceRequest, chainIds } = {
372
- chainIds: [DEFAULT_CHAIN_ID]
373
- }) {
374
- var _a, _b;
405
+ return __async(this, arguments, function* ({
406
+ account,
407
+ forceRequest,
408
+ chainIds = [DEFAULT_CHAIN_ID]
409
+ } = {}) {
410
+ var _a;
375
411
  logger("request: connect", { account });
376
412
  if (!chainIds || chainIds.length === 0) {
377
413
  throw new Error("chainIds must be an array of at least one chain ID");
378
414
  }
379
415
  const caipChainIds = Array.from(
380
416
  new Set((_a = chainIds.concat(DEFAULT_CHAIN_ID)) != null ? _a : [DEFAULT_CHAIN_ID])
381
- ).map((id) => `eip155:${id}`);
417
+ ).map((id) => `eip155:${hexToNumber2(id)}`);
382
418
  const caipAccountIds = account ? caipChainIds.map((caipChainId) => `${caipChainId}:${account}`) : [];
383
- yield __privateGet(this, _core2).connect(
384
- caipChainIds,
385
- caipAccountIds,
386
- void 0,
387
- forceRequest
388
- );
389
- const hexPermittedChainIds = getPermittedEthChainIds(__privateGet(this, _sessionScopes));
390
- const initialAccounts = yield __privateGet(this, _core2).transport.sendEip1193Message({ method: "eth_accounts", params: [] });
391
- const chainId = yield __privateMethod(this, _MetamaskConnectEVM_instances, getSelectedChainId_fn).call(this, hexPermittedChainIds);
392
- __privateMethod(this, _MetamaskConnectEVM_instances, onConnect_fn).call(this, {
393
- chainId,
394
- accounts: initialAccounts.result
395
- });
396
- (_b = __privateGet(this, _removeNotificationHandler)) == null ? void 0 : _b.call(this);
397
- __privateSet(this, _removeNotificationHandler, __privateGet(this, _core2).transport.onNotification(
398
- (notification) => {
399
- var _a2;
400
- if ((notification == null ? void 0 : notification.method) === "metamask_accountsChanged") {
401
- const accounts = notification == null ? void 0 : notification.params;
402
- logger("transport-event: accountsChanged", accounts);
403
- __privateMethod(this, _MetamaskConnectEVM_instances, onAccountsChanged_fn).call(this, accounts);
404
- }
405
- if ((notification == null ? void 0 : notification.method) === "metamask_chainChanged") {
406
- const notificationChainId = Number((_a2 = notification == null ? void 0 : notification.params) == null ? void 0 : _a2.chainId);
407
- logger("transport-event: chainChanged", notificationChainId);
408
- __privateMethod(this, _MetamaskConnectEVM_instances, cacheChainId_fn).call(this, notificationChainId).catch((error) => {
409
- logger("Error caching chainId in notification handler", error);
419
+ __privateSet(this, _status, "connecting");
420
+ try {
421
+ const result = new Promise((resolve) => {
422
+ __privateGet(this, _provider).once("connect", ({ chainId, accounts }) => {
423
+ logger("fulfilled-request: connect", {
424
+ chainId,
425
+ accounts
410
426
  });
411
- __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, notificationChainId);
412
- }
413
- }
414
- ));
415
- logger("fulfilled-request: connect", {
416
- chainId: chainIds[0],
417
- accounts: __privateGet(this, _provider).accounts
418
- });
419
- return {
420
- accounts: __privateGet(this, _provider).accounts,
421
- chainId: hexToNumber2(chainId)
422
- };
427
+ resolve({
428
+ accounts,
429
+ chainId
430
+ });
431
+ });
432
+ });
433
+ yield __privateGet(this, _core2).connect(
434
+ caipChainIds,
435
+ caipAccountIds,
436
+ void 0,
437
+ forceRequest
438
+ );
439
+ return result;
440
+ } catch (error) {
441
+ __privateSet(this, _status, "disconnected");
442
+ logger("Error connecting to wallet", error);
443
+ throw error;
444
+ }
423
445
  });
424
446
  }
425
447
  /**
@@ -427,7 +449,7 @@ var MetamaskConnectEVM = class {
427
449
  *
428
450
  * @param options - The connection options
429
451
  * @param options.message - The message to sign after connecting
430
- * @param options.chainIds - Optional chain IDs to connect to (defaults to ethereum mainnet if not provided)
452
+ * @param [options.chainIds] - Optional hex chain IDs to connect to (defaults to ethereum mainnet if not provided)
431
453
  * @returns A promise that resolves with the signature
432
454
  * @throws Error if the selected account is not available after timeout
433
455
  */
@@ -458,9 +480,9 @@ var MetamaskConnectEVM = class {
458
480
  * @param options - The options for connecting and invoking the method
459
481
  * @param options.method - The method name to invoke
460
482
  * @param options.params - The parameters to pass to the method, or a function that receives the account and returns params
461
- * @param options.chainIds - Optional chain IDs to connect to (defaults to ethereum mainnet if not provided)
462
- * @param options.account - Optional specific account to connect to
463
- * @param options.forceRequest - Whether to force a request regardless of an existing session
483
+ * @param [options.chainIds] - Optional hex chain IDs to connect to (defaults to ethereum mainnet if not provided)
484
+ * @param [options.account] - Optional specific account to connect to
485
+ * @param [options.forceRequest] - Whether to force a request regardless of an existing session
464
486
  * @returns A promise that resolves with the result of the method invocation
465
487
  * @throws Error if the selected account is not available after timeout (for methods that require an account)
466
488
  */
@@ -498,16 +520,18 @@ var MetamaskConnectEVM = class {
498
520
  */
499
521
  disconnect() {
500
522
  return __async(this, null, function* () {
523
+ var _a;
501
524
  logger("request: disconnect");
502
- yield __privateGet(this, _core2).disconnect();
525
+ const sessionScopes = __privateGet(this, _sessionScopes);
526
+ const eip155Scopes = Object.keys(sessionScopes).filter((scope) => {
527
+ const { namespace: namespace2 } = parseScopeString(scope);
528
+ return namespace2 === "eip155";
529
+ });
530
+ yield __privateGet(this, _core2).disconnect(eip155Scopes);
503
531
  __privateMethod(this, _MetamaskConnectEVM_instances, onDisconnect_fn).call(this);
504
532
  __privateMethod(this, _MetamaskConnectEVM_instances, clearConnectionState_fn).call(this);
505
- __privateGet(this, _core2).off("wallet_sessionChanged", __privateGet(this, _sessionChangedHandler));
506
- __privateGet(this, _core2).off("display_uri", __privateGet(this, _displayUriHandler));
507
- if (__privateGet(this, _removeNotificationHandler)) {
508
- __privateGet(this, _removeNotificationHandler).call(this);
509
- __privateSet(this, _removeNotificationHandler, void 0);
510
- }
533
+ (_a = __privateGet(this, _removeNotificationHandler)) == null ? void 0 : _a.call(this);
534
+ __privateSet(this, _removeNotificationHandler, void 0);
511
535
  logger("fulfilled-request: disconnect");
512
536
  });
513
537
  }
@@ -516,8 +540,8 @@ var MetamaskConnectEVM = class {
516
540
  *
517
541
  * @param options - The options for the switch chain request
518
542
  * @param options.chainId - The chain ID to switch to
519
- * @param options.chainConfiguration - The chain configuration to use in case the chain is not present by the wallet
520
- * @returns The result of the switch chain request
543
+ * @param [options.chainConfiguration] - The chain configuration to use in case the chain is not present by the wallet
544
+ * @returns A promise that resolves when the chain has been switched
521
545
  */
522
546
  switchChain(_0) {
523
547
  return __async(this, arguments, function* ({
@@ -525,17 +549,16 @@ var MetamaskConnectEVM = class {
525
549
  chainConfiguration
526
550
  }) {
527
551
  const method = "wallet_switchEthereumChain";
528
- const hexChainId = isHex(chainId) ? chainId : numberToHex2(chainId);
529
- const scope = `eip155:${isHex(chainId) ? hexToNumber2(chainId) : chainId}`;
530
- const params = [{ chainId: hexChainId }];
552
+ const scope = `eip155:${hexToNumber2(chainId)}`;
553
+ const params = [{ chainId }];
531
554
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionRequested_fn).call(this, method, scope, params);
532
- if (this.selectedChainId === hexChainId) {
555
+ if (this.selectedChainId === chainId) {
533
556
  return Promise.resolve();
534
557
  }
535
558
  const permittedChainIds = getPermittedEthChainIds(__privateGet(this, _sessionScopes));
536
- if (permittedChainIds.includes(hexChainId) && __privateGet(this, _core2).transportType === TransportType.MWP) {
537
- yield __privateMethod(this, _MetamaskConnectEVM_instances, cacheChainId_fn).call(this, hexChainId);
538
- __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, hexChainId);
559
+ if (permittedChainIds.includes(chainId) && __privateGet(this, _core2).transportType === TransportType.MWP) {
560
+ yield __privateMethod(this, _MetamaskConnectEVM_instances, cacheChainId_fn).call(this, chainId);
561
+ __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, chainId);
539
562
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionSucceeded_fn).call(this, method, scope, params);
540
563
  return Promise.resolve();
541
564
  }
@@ -550,10 +573,10 @@ var MetamaskConnectEVM = class {
550
573
  }
551
574
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionSucceeded_fn).call(this, method, scope, params);
552
575
  if (result.result === null) {
553
- yield __privateMethod(this, _MetamaskConnectEVM_instances, cacheChainId_fn).call(this, hexChainId);
554
- __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, hexChainId);
576
+ yield __privateMethod(this, _MetamaskConnectEVM_instances, cacheChainId_fn).call(this, chainId);
577
+ __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, chainId);
555
578
  }
556
- return result;
579
+ return Promise.resolve();
557
580
  } catch (error) {
558
581
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionFailed_fn).call(this, method, scope, params, error);
559
582
  if (error.message.includes("Unrecognized chain ID")) {
@@ -628,6 +651,7 @@ _eventHandlers = new WeakMap();
628
651
  _sessionChangedHandler = new WeakMap();
629
652
  _displayUriHandler = new WeakMap();
630
653
  _removeNotificationHandler = new WeakMap();
654
+ _status = new WeakMap();
631
655
  _MetamaskConnectEVM_instances = new WeakSet();
632
656
  /**
633
657
  * Gets the core options for analytics checks.
@@ -722,6 +746,7 @@ getSelectedChainId_fn = function(permittedChainIds) {
722
746
  };
723
747
  requestInterceptor_fn = function(request) {
724
748
  return __async(this, null, function* () {
749
+ var _a;
725
750
  logger(`Intercepting request for method: ${request.method}`);
726
751
  if (IGNORED_METHODS.includes(request.method)) {
727
752
  return Promise.reject(
@@ -753,7 +778,7 @@ requestInterceptor_fn = function(request) {
753
778
  }
754
779
  if (isSwitchChainRequest(request)) {
755
780
  return this.switchChain({
756
- chainId: parseInt(request.params[0].chainId, 16)
781
+ chainId: request.params[0].chainId
757
782
  });
758
783
  }
759
784
  if (isAddChainRequest(request)) {
@@ -761,8 +786,10 @@ requestInterceptor_fn = function(request) {
761
786
  }
762
787
  if (isAccountsRequest(request)) {
763
788
  const { method } = request;
764
- const chainId = __privateGet(this, _provider).selectedChainId ? hexToNumber2(__privateGet(this, _provider).selectedChainId) : 1;
765
- const scope = `eip155:${chainId}`;
789
+ const decimalChainId = hexToNumber2(
790
+ (_a = __privateGet(this, _provider).selectedChainId) != null ? _a : "0x1"
791
+ );
792
+ const scope = `eip155:${decimalChainId}`;
766
793
  const params = [];
767
794
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionRequested_fn).call(this, method, scope, params);
768
795
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionSucceeded_fn).call(this, method, scope, params);
@@ -784,14 +811,14 @@ clearConnectionState_fn = function() {
784
811
  };
785
812
  addEthereumChain_fn = function(chainConfiguration) {
786
813
  return __async(this, null, function* () {
787
- var _a;
788
814
  logger("addEthereumChain called", { chainConfiguration });
789
815
  const method = "wallet_addEthereumChain";
790
816
  if (!chainConfiguration) {
791
817
  throw new Error("No chain configuration found.");
792
818
  }
793
- const chainId = chainConfiguration.chainId ? parseInt(chainConfiguration.chainId, 16) : hexToNumber2((_a = __privateGet(this, _provider).selectedChainId) != null ? _a : "0x1");
794
- const scope = `eip155:${chainId}`;
819
+ const chainId = chainConfiguration.chainId || __privateGet(this, _provider).selectedChainId || "0x1";
820
+ const decimalChainId = hexToNumber2(chainId);
821
+ const scope = `eip155:${decimalChainId}`;
795
822
  const params = [chainConfiguration];
796
823
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionRequested_fn).call(this, method, scope, params);
797
824
  try {
@@ -815,7 +842,7 @@ request_fn = function(request) {
815
842
  logger("direct request to metamask-provider called", request);
816
843
  const result = __privateGet(this, _core2).transport.sendEip1193Message(request);
817
844
  if (request.method === "wallet_addEthereumChain" || request.method === "wallet_switchEthereumChain") {
818
- __privateGet(this, _core2).openDeeplinkIfNeeded();
845
+ __privateGet(this, _core2).openSimpleDeeplinkIfNeeded();
819
846
  }
820
847
  return result;
821
848
  });
@@ -823,31 +850,56 @@ request_fn = function(request) {
823
850
  cacheChainId_fn = function(chainId) {
824
851
  return __async(this, null, function* () {
825
852
  try {
826
- const hexChainId = isHex(chainId) ? chainId : numberToHex2(chainId);
827
853
  yield __privateGet(this, _core2).storage.adapter.set(
828
854
  CHAIN_STORE_KEY,
829
- JSON.stringify(hexChainId)
855
+ JSON.stringify(chainId)
830
856
  );
831
857
  } catch (error) {
832
858
  logger("Error caching chainId", error);
833
859
  }
834
860
  });
835
861
  };
862
+ onSessionChanged_fn = function(session) {
863
+ return __async(this, null, function* () {
864
+ var _a;
865
+ logger("event: wallet_sessionChanged", session);
866
+ __privateSet(this, _sessionScopes, (_a = session == null ? void 0 : session.sessionScopes) != null ? _a : {});
867
+ const hexPermittedChainIds = getPermittedEthChainIds(__privateGet(this, _sessionScopes));
868
+ if (hexPermittedChainIds.length === 0) {
869
+ __privateMethod(this, _MetamaskConnectEVM_instances, onDisconnect_fn).call(this);
870
+ } else {
871
+ let initialAccounts = [];
872
+ if (__privateGet(this, _core2).status === "connected") {
873
+ const ethAccountsResponse = yield __privateGet(this, _core2).transport.sendEip1193Message({
874
+ method: "eth_accounts",
875
+ params: []
876
+ });
877
+ initialAccounts = ethAccountsResponse.result;
878
+ } else {
879
+ initialAccounts = getEthAccounts(__privateGet(this, _sessionScopes));
880
+ }
881
+ const chainId = yield __privateMethod(this, _MetamaskConnectEVM_instances, getSelectedChainId_fn).call(this, hexPermittedChainIds);
882
+ __privateMethod(this, _MetamaskConnectEVM_instances, onConnect_fn).call(this, {
883
+ chainId,
884
+ accounts: initialAccounts
885
+ });
886
+ }
887
+ });
888
+ };
836
889
  /**
837
890
  * Handles chain change events and updates the provider's selected chain ID.
838
891
  *
839
- * @param chainId - The new chain ID (can be hex string or number)
892
+ * @param chainId - The new hex chain ID
840
893
  */
841
894
  onChainChanged_fn = function(chainId) {
842
895
  var _a, _b;
843
- const hexChainId = isHex(chainId) ? chainId : numberToHex2(chainId);
844
- if (hexChainId === __privateGet(this, _provider).selectedChainId) {
896
+ if (chainId === __privateGet(this, _provider).selectedChainId) {
845
897
  return;
846
898
  }
847
899
  logger("handler: chainChanged", { chainId });
848
900
  __privateGet(this, _provider).selectedChainId = chainId;
849
- (_b = (_a = __privateGet(this, _eventHandlers)) == null ? void 0 : _a.chainChanged) == null ? void 0 : _b.call(_a, hexChainId);
850
- __privateGet(this, _provider).emit("chainChanged", hexChainId);
901
+ (_b = (_a = __privateGet(this, _eventHandlers)) == null ? void 0 : _a.chainChanged) == null ? void 0 : _b.call(_a, chainId);
902
+ __privateGet(this, _provider).emit("chainChanged", chainId);
851
903
  };
852
904
  /**
853
905
  * Handles accounts change events and updates the provider's accounts list.
@@ -856,6 +908,10 @@ onChainChanged_fn = function(chainId) {
856
908
  */
857
909
  onAccountsChanged_fn = function(accounts) {
858
910
  var _a, _b;
911
+ const accountsUnchanged = accounts.length === __privateGet(this, _provider).accounts.length && accounts.every((acct, idx) => acct === __privateGet(this, _provider).accounts[idx]);
912
+ if (accountsUnchanged) {
913
+ return;
914
+ }
859
915
  logger("handler: accountsChanged", accounts);
860
916
  __privateGet(this, _provider).accounts = accounts;
861
917
  __privateGet(this, _provider).emit("accountsChanged", accounts);
@@ -865,21 +921,43 @@ onAccountsChanged_fn = function(accounts) {
865
921
  * Handles connection events and emits the connect event to listeners.
866
922
  *
867
923
  * @param options - The connection options
868
- * @param options.chainId - The chain ID of the connection (can be hex string or number)
924
+ * @param options.chainId - The hex chain ID of the connection
869
925
  * @param options.accounts - The accounts of the connection
870
926
  */
871
927
  onConnect_fn = function({
872
928
  chainId,
873
929
  accounts
874
930
  }) {
875
- var _a, _b;
931
+ var _a, _b, _c;
876
932
  logger("handler: connect", { chainId, accounts });
877
933
  const data = {
878
- chainId: isHex(chainId) ? chainId : numberToHex2(chainId),
934
+ chainId,
879
935
  accounts
880
936
  };
881
- __privateGet(this, _provider).emit("connect", data);
882
- (_b = (_a = __privateGet(this, _eventHandlers)) == null ? void 0 : _a.connect) == null ? void 0 : _b.call(_a, data);
937
+ if (__privateGet(this, _status) !== "connected") {
938
+ __privateSet(this, _status, "connected");
939
+ __privateGet(this, _provider).emit("connect", data);
940
+ (_b = (_a = __privateGet(this, _eventHandlers)) == null ? void 0 : _a.connect) == null ? void 0 : _b.call(_a, data);
941
+ (_c = __privateGet(this, _removeNotificationHandler)) == null ? void 0 : _c.call(this);
942
+ __privateSet(this, _removeNotificationHandler, __privateGet(this, _core2).transport.onNotification(
943
+ (notification) => {
944
+ var _a2;
945
+ if ((notification == null ? void 0 : notification.method) === "metamask_accountsChanged") {
946
+ const notificationAccounts = notification == null ? void 0 : notification.params;
947
+ logger("transport-event: accountsChanged", notificationAccounts);
948
+ __privateMethod(this, _MetamaskConnectEVM_instances, onAccountsChanged_fn).call(this, notificationAccounts);
949
+ }
950
+ if ((notification == null ? void 0 : notification.method) === "metamask_chainChanged") {
951
+ const notificationChainId = (_a2 = notification == null ? void 0 : notification.params) == null ? void 0 : _a2.chainId;
952
+ logger("transport-event: chainChanged", notificationChainId);
953
+ __privateMethod(this, _MetamaskConnectEVM_instances, cacheChainId_fn).call(this, notificationChainId).catch((error) => {
954
+ logger("Error caching chainId in notification handler", error);
955
+ });
956
+ __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, notificationChainId);
957
+ }
958
+ }
959
+ ));
960
+ }
883
961
  __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, chainId);
884
962
  __privateMethod(this, _MetamaskConnectEVM_instances, onAccountsChanged_fn).call(this, accounts);
885
963
  };
@@ -889,6 +967,10 @@ onConnect_fn = function({
889
967
  */
890
968
  onDisconnect_fn = function() {
891
969
  var _a, _b;
970
+ if (__privateGet(this, _status) === "disconnected") {
971
+ return;
972
+ }
973
+ __privateSet(this, _status, "disconnected");
892
974
  logger("handler: disconnect");
893
975
  __privateGet(this, _provider).emit("disconnect");
894
976
  (_b = (_a = __privateGet(this, _eventHandlers)) == null ? void 0 : _a.disconnect) == null ? void 0 : _b.call(_a);
@@ -902,39 +984,20 @@ onDisconnect_fn = function() {
902
984
  */
903
985
  onDisplayUri_fn = function(uri) {
904
986
  var _a, _b;
987
+ if (__privateGet(this, _status) !== "connecting") {
988
+ return;
989
+ }
905
990
  logger("handler: display_uri", uri);
906
991
  __privateGet(this, _provider).emit("display_uri", uri);
907
992
  (_b = (_a = __privateGet(this, _eventHandlers)) == null ? void 0 : _a.displayUri) == null ? void 0 : _b.call(_a, uri);
908
993
  };
909
- attemptSessionRecovery_fn = function() {
910
- return __async(this, null, function* () {
911
- if (__privateGet(this, _core2).status !== "connected" && __privateGet(this, _core2).status !== "connecting") {
912
- return;
913
- }
914
- try {
915
- const response = yield __privateGet(this, _core2).transport.request({
916
- method: "wallet_getSession"
917
- });
918
- const { sessionScopes } = response.result;
919
- __privateSet(this, _sessionScopes, sessionScopes);
920
- const permittedChainIds = getPermittedEthChainIds(sessionScopes);
921
- const permittedAccounts = yield __privateGet(this, _core2).transport.sendEip1193Message({ method: "eth_accounts", params: [] });
922
- const chainId = yield __privateMethod(this, _MetamaskConnectEVM_instances, getSelectedChainId_fn).call(this, permittedChainIds);
923
- if (permittedChainIds.length && permittedAccounts.result) {
924
- __privateMethod(this, _MetamaskConnectEVM_instances, onConnect_fn).call(this, {
925
- chainId,
926
- accounts: permittedAccounts.result
927
- });
928
- }
929
- } catch (error) {
930
- console.error("Error attempting session recovery", error);
931
- }
932
- });
933
- };
994
+ var MetamaskConnectEVM = _MetamaskConnectEVM;
934
995
  function createEVMClient(options) {
935
996
  return __async(this, null, function* () {
936
997
  var _a;
937
- enableDebug(options.debug);
998
+ if (options.debug) {
999
+ enableDebug();
1000
+ }
938
1001
  logger("Creating Metamask Connect/EVM with options:", options);
939
1002
  if (!((_a = options.api) == null ? void 0 : _a.supportedNetworks) || Object.keys(options.api.supportedNetworks).length === 0) {
940
1003
  throw new Error(
@@ -942,13 +1005,21 @@ function createEVMClient(options) {
942
1005
  );
943
1006
  }
944
1007
  validSupportedChainsUrls(options.api.supportedNetworks, "supportedNetworks");
1008
+ const supportedNetworksCaipChainId = Object.entries(
1009
+ options.api.supportedNetworks
1010
+ ).reduce((acc, [hexChainId, url]) => {
1011
+ const decimalChainId = parseInt(hexChainId, 16);
1012
+ const caip2ChainId = `eip155:${decimalChainId}`;
1013
+ acc[caip2ChainId] = url;
1014
+ return acc;
1015
+ }, {});
945
1016
  try {
946
1017
  const core = yield createMultichainClient(__spreadProps(__spreadValues({}, options), {
947
1018
  api: {
948
- supportedNetworks: options.api.supportedNetworks
1019
+ supportedNetworks: supportedNetworksCaipChainId
949
1020
  }
950
1021
  }));
951
- return new MetamaskConnectEVM({
1022
+ return MetamaskConnectEVM.create({
952
1023
  core,
953
1024
  eventHandlers: options.eventHandlers,
954
1025
  supportedNetworks: options.api.supportedNetworks