@metamask/connect-evm 0.1.0 → 0.1.2

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.
package/CHANGELOG.md CHANGED
@@ -7,11 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.2]
11
+
12
+ ### Added
13
+
14
+ - **BREAKING** Replace `chainId` property on `connect` method with `chainIds` to support for connecting to multiple chains ([#77](https://github.com/MetaMask/connect-monorepo/pull/77))
15
+
16
+ ### Changed
17
+
18
+ - Bump `@metamask/connect-multichain` removing `enable` flag from `analytics` ([#92](https://github.com/MetaMask/connect-monorepo/pull/92))
19
+ - **BREAKING** Change `connectWithMessage()` to expect param object with `message` and optional `chainIds` property ([#82](https://github.com/MetaMask/connect-monorepo/pull/82))
20
+ - `message` should be the value that the user will prompted to sign with their selected account after connecting. `message` is required.
21
+ - `chainIds` should be an array of chainIds that the wallet will prompt the user to grant permisson for. `chainIds` is optional.
22
+
23
+ ### Fixed
24
+
25
+ - Fix duplicate `onNotification` listener ([#81](https://github.com/MetaMask/connect-monorepo/pull/81))
26
+ - Fixed `addEthereumChain` not being prompted on mobile native browsers after a switch chain failure ([#79](https://github.com/MetaMask/connect-monorepo/pull/79))
27
+
28
+ ## [0.1.1]
29
+
30
+ ### Fixed
31
+
32
+ - Eagerly call `onChainChanged` when `switchChain` is called (rather than waiting for the `chainChanged` event), this ensures that the provider's selected chain ID is updated even if the `chainChanged` event is not received ([#62](https://github.com/MetaMask/connect-monorepo/pull/62))
33
+
34
+ - Fixed incorrect caching of error responses for some requests/events ([#59](https://github.com/MetaMask/connect-monorepo/pull/59))
35
+
10
36
  ## [0.1.0]
11
37
 
12
38
  ### Added
13
39
 
14
40
  - Initial release ([#58](https://github.com/MetaMask/connect-monorepo/pull/58))
15
41
 
16
- [Unreleased]: https://github.com/MetaMask/metamask-connect-monorepo/compare/@metamask/connect-evm@0.1.0...HEAD
17
- [0.1.0]: https://github.com/MetaMask/metamask-connect-monorepo/releases/tag/@metamask/connect-evm@0.1.0
42
+ [Unreleased]: https://github.com/MetaMask/connect-monorepo/compare/@metamask/connect-evm@0.1.2...HEAD
43
+ [0.1.2]: https://github.com/MetaMask/connect-monorepo/compare/@metamask/connect-evm@0.1.1...@metamask/connect-evm@0.1.2
44
+ [0.1.1]: https://github.com/MetaMask/connect-monorepo/compare/@metamask/connect-evm@0.1.0...@metamask/connect-evm@0.1.1
45
+ [0.1.0]: https://github.com/MetaMask/connect-monorepo/releases/tag/@metamask/connect-evm@0.1.0
package/README.md CHANGED
@@ -127,7 +127,7 @@ yarn workspace @metamask/connect-evm run test
127
127
 
128
128
  ## Contributing
129
129
 
130
- This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/metamask-connect-monorepo#readme).
130
+ This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/connect-monorepo#readme).
131
131
 
132
132
  ## License
133
133
 
@@ -228,7 +228,7 @@ ${invalidUrls.join("\n")}`
228
228
 
229
229
  // src/connect.ts
230
230
  var DEFAULT_CHAIN_ID = 1;
231
- var _core2, _provider, _sessionScopes, _eventHandlers, _sessionChangedHandler, _MetamaskConnectEVM_instances, getCoreOptions_fn, createInvokeOptions_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, requestInterceptor_fn, clearConnectionState_fn, addEthereumChain_fn, request_fn, onChainChanged_fn, onAccountsChanged_fn, onConnect_fn, onDisconnect_fn, attemptSessionRecovery_fn;
231
+ var _core2, _provider, _sessionScopes, _eventHandlers, _sessionChangedHandler, _removeNotificationHandler, _MetamaskConnectEVM_instances, getCoreOptions_fn, createInvokeOptions_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, requestInterceptor_fn, clearConnectionState_fn, addEthereumChain_fn, request_fn, onChainChanged_fn, onAccountsChanged_fn, onConnect_fn, onDisconnect_fn, attemptSessionRecovery_fn;
232
232
  var MetamaskConnectEVM = class {
233
233
  /**
234
234
  * Creates a new MetamaskConnectEVM instance.
@@ -249,6 +249,8 @@ var MetamaskConnectEVM = class {
249
249
  __privateAdd(this, _eventHandlers);
250
250
  /** The handler for the wallet_sessionChanged event */
251
251
  __privateAdd(this, _sessionChangedHandler);
252
+ /** The clean-up function for the notification handler */
253
+ __privateAdd(this, _removeNotificationHandler);
252
254
  __privateSet(this, _core2, core);
253
255
  __privateSet(this, _provider, new EIP1193Provider(
254
256
  core,
@@ -273,21 +275,29 @@ var MetamaskConnectEVM = class {
273
275
  * Connects to the wallet with the specified chain ID and optional account.
274
276
  *
275
277
  * @param options - The connection options
276
- * @param options.chainId - The chain ID to connect to (defaults to 1 for mainnet)
277
278
  * @param options.account - Optional specific account to connect to
278
279
  * @param options.forceRequest - Wwhether to force a request regardless of an existing session
280
+ * @param options.chainIds - Array of chain IDs to connect to
279
281
  * @returns A promise that resolves with the connected accounts and chain ID
280
282
  */
281
283
  connect() {
282
- return __async(this, arguments, function* ({
283
- chainId,
284
- account,
285
- forceRequest
286
- } = { chainId: DEFAULT_CHAIN_ID }) {
287
- logger("request: connect", { chainId, account });
288
- const caipChainId = chainId ? [`eip155:${chainId}`] : [];
289
- const caipAccountId = chainId && account ? [`eip155:${chainId}:${account}`] : [];
290
- yield __privateGet(this, _core2).connect(caipChainId, caipAccountId, forceRequest);
284
+ return __async(this, arguments, function* ({ account, forceRequest, chainIds } = {
285
+ chainIds: [DEFAULT_CHAIN_ID]
286
+ }) {
287
+ var _a, _b;
288
+ logger("request: connect", { account });
289
+ if (!chainIds || chainIds.length === 0) {
290
+ throw new Error("chainIds must be an array of at least one chain ID");
291
+ }
292
+ const caipChainIds = Array.from(
293
+ new Set((_a = chainIds.concat(DEFAULT_CHAIN_ID)) != null ? _a : [DEFAULT_CHAIN_ID])
294
+ ).map((id) => `eip155:${id}`);
295
+ const caipAccountIds = account ? caipChainIds.map((caipChainId) => `${caipChainId}:${account}`) : [];
296
+ yield __privateGet(this, _core2).connect(
297
+ caipChainIds,
298
+ caipAccountIds,
299
+ forceRequest
300
+ );
291
301
  const hexPermittedChainIds = getPermittedEthChainIds(__privateGet(this, _sessionScopes));
292
302
  const initialChainId = hexPermittedChainIds[0];
293
303
  const initialAccounts = yield __privateGet(this, _core2).transport.sendEip1193Message({ method: "eth_accounts", params: [] });
@@ -295,21 +305,24 @@ var MetamaskConnectEVM = class {
295
305
  chainId: initialChainId,
296
306
  accounts: initialAccounts.result
297
307
  });
298
- __privateGet(this, _core2).transport.onNotification((notification) => {
299
- var _a;
300
- if ((notification == null ? void 0 : notification.method) === "metamask_accountsChanged") {
301
- const accounts = notification == null ? void 0 : notification.params;
302
- logger("transport-event: accountsChanged", accounts);
303
- __privateMethod(this, _MetamaskConnectEVM_instances, onAccountsChanged_fn).call(this, accounts);
304
- }
305
- if ((notification == null ? void 0 : notification.method) === "metamask_chainChanged") {
306
- const notificationChainId = Number((_a = notification == null ? void 0 : notification.params) == null ? void 0 : _a.chainId);
307
- logger("transport-event: chainChanged", notificationChainId);
308
- __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, notificationChainId);
308
+ (_b = __privateGet(this, _removeNotificationHandler)) == null ? void 0 : _b.call(this);
309
+ __privateSet(this, _removeNotificationHandler, __privateGet(this, _core2).transport.onNotification(
310
+ (notification) => {
311
+ var _a2;
312
+ if ((notification == null ? void 0 : notification.method) === "metamask_accountsChanged") {
313
+ const accounts = notification == null ? void 0 : notification.params;
314
+ logger("transport-event: accountsChanged", accounts);
315
+ __privateMethod(this, _MetamaskConnectEVM_instances, onAccountsChanged_fn).call(this, accounts);
316
+ }
317
+ if ((notification == null ? void 0 : notification.method) === "metamask_chainChanged") {
318
+ const notificationChainId = Number((_a2 = notification == null ? void 0 : notification.params) == null ? void 0 : _a2.chainId);
319
+ logger("transport-event: chainChanged", notificationChainId);
320
+ __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, notificationChainId);
321
+ }
309
322
  }
310
- });
323
+ ));
311
324
  logger("fulfilled-request: connect", {
312
- chainId,
325
+ chainId: chainIds[0],
313
326
  accounts: __privateGet(this, _provider).accounts
314
327
  });
315
328
  return {
@@ -321,14 +334,21 @@ var MetamaskConnectEVM = class {
321
334
  /**
322
335
  * Connects to the wallet and signs a message using personal_sign.
323
336
  *
324
- * @param message - The message to sign
337
+ * @param options - The connection options
338
+ * @param options.message - The message to sign after connecting
339
+ * @param options.chainIds - Optional chain IDs to connect to (defaults to ethereum mainnet if not provided)
325
340
  * @returns A promise that resolves with the signature
326
341
  * @throws Error if the selected account is not available after timeout
327
342
  */
328
- connectAndSign(message) {
329
- return __async(this, null, function* () {
343
+ connectAndSign(_0) {
344
+ return __async(this, arguments, function* ({
345
+ message,
346
+ chainIds
347
+ }) {
330
348
  var _a, _b;
331
- const { accounts, chainId } = yield this.connect();
349
+ const { accounts, chainId } = yield this.connect({
350
+ chainIds: chainIds != null ? chainIds : [DEFAULT_CHAIN_ID]
351
+ });
332
352
  const result = yield __privateGet(this, _provider).request({
333
353
  method: "personal_sign",
334
354
  params: [accounts[0], message]
@@ -347,7 +367,7 @@ var MetamaskConnectEVM = class {
347
367
  * @param options - The options for connecting and invoking the method
348
368
  * @param options.method - The method name to invoke
349
369
  * @param options.params - The parameters to pass to the method, or a function that receives the account and returns params
350
- * @param options.chainId - Optional chain ID to connect to (defaults to mainnet)
370
+ * @param options.chainIds - Optional chain IDs to connect to (defaults to ethereum mainnet if not provided)
351
371
  * @param options.account - Optional specific account to connect to
352
372
  * @param options.forceRequest - Whether to force a request regardless of an existing session
353
373
  * @returns A promise that resolves with the result of the method invocation
@@ -357,13 +377,13 @@ var MetamaskConnectEVM = class {
357
377
  return __async(this, arguments, function* ({
358
378
  method,
359
379
  params,
360
- chainId,
380
+ chainIds,
361
381
  account,
362
382
  forceRequest
363
383
  }) {
364
384
  var _a, _b;
365
385
  const { accounts: connectedAccounts, chainId: connectedChainId } = yield this.connect({
366
- chainId: chainId != null ? chainId : DEFAULT_CHAIN_ID,
386
+ chainIds: chainIds != null ? chainIds : [DEFAULT_CHAIN_ID],
367
387
  account,
368
388
  forceRequest
369
389
  });
@@ -392,6 +412,10 @@ var MetamaskConnectEVM = class {
392
412
  __privateMethod(this, _MetamaskConnectEVM_instances, onDisconnect_fn).call(this);
393
413
  __privateMethod(this, _MetamaskConnectEVM_instances, clearConnectionState_fn).call(this);
394
414
  __privateGet(this, _core2).off("wallet_sessionChanged", __privateGet(this, _sessionChangedHandler));
415
+ if (__privateGet(this, _removeNotificationHandler)) {
416
+ __privateGet(this, _removeNotificationHandler).call(this);
417
+ __privateSet(this, _removeNotificationHandler, void 0);
418
+ }
395
419
  logger("fulfilled-request: disconnect");
396
420
  });
397
421
  }
@@ -427,7 +451,14 @@ var MetamaskConnectEVM = class {
427
451
  method: "wallet_switchEthereumChain",
428
452
  params
429
453
  });
454
+ const resultWithError = result;
455
+ if (resultWithError == null ? void 0 : resultWithError.error) {
456
+ throw new Error(resultWithError.error.message);
457
+ }
430
458
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionSucceeded_fn).call(this, method, scope, params);
459
+ if (result.result === null) {
460
+ __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, hexChainId);
461
+ }
431
462
  return result;
432
463
  } catch (error) {
433
464
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionFailed_fn).call(this, method, scope, params, error);
@@ -493,6 +524,7 @@ _provider = new WeakMap();
493
524
  _sessionScopes = new WeakMap();
494
525
  _eventHandlers = new WeakMap();
495
526
  _sessionChangedHandler = new WeakMap();
527
+ _removeNotificationHandler = new WeakMap();
496
528
  _MetamaskConnectEVM_instances = new WeakSet();
497
529
  /**
498
530
  * Gets the core options for analytics checks.
@@ -518,11 +550,7 @@ createInvokeOptions_fn = function(method, scope, params) {
518
550
  };
519
551
  trackWalletActionRequested_fn = function(method, scope, params) {
520
552
  return __async(this, null, function* () {
521
- var _a;
522
553
  const coreOptions = __privateMethod(this, _MetamaskConnectEVM_instances, getCoreOptions_fn).call(this);
523
- if (!((_a = coreOptions.analytics) == null ? void 0 : _a.enabled)) {
524
- return;
525
- }
526
554
  try {
527
555
  const invokeOptions = __privateMethod(this, _MetamaskConnectEVM_instances, createInvokeOptions_fn).call(this, method, scope, params);
528
556
  const props = yield getWalletActionAnalyticsProperties(
@@ -538,11 +566,7 @@ trackWalletActionRequested_fn = function(method, scope, params) {
538
566
  };
539
567
  trackWalletActionSucceeded_fn = function(method, scope, params) {
540
568
  return __async(this, null, function* () {
541
- var _a;
542
569
  const coreOptions = __privateMethod(this, _MetamaskConnectEVM_instances, getCoreOptions_fn).call(this);
543
- if (!((_a = coreOptions.analytics) == null ? void 0 : _a.enabled)) {
544
- return;
545
- }
546
570
  try {
547
571
  const invokeOptions = __privateMethod(this, _MetamaskConnectEVM_instances, createInvokeOptions_fn).call(this, method, scope, params);
548
572
  const props = yield getWalletActionAnalyticsProperties(
@@ -558,11 +582,7 @@ trackWalletActionSucceeded_fn = function(method, scope, params) {
558
582
  };
559
583
  trackWalletActionFailed_fn = function(method, scope, params, error) {
560
584
  return __async(this, null, function* () {
561
- var _a;
562
585
  const coreOptions = __privateMethod(this, _MetamaskConnectEVM_instances, getCoreOptions_fn).call(this);
563
- if (!((_a = coreOptions.analytics) == null ? void 0 : _a.enabled)) {
564
- return;
565
- }
566
586
  try {
567
587
  const invokeOptions = __privateMethod(this, _MetamaskConnectEVM_instances, createInvokeOptions_fn).call(this, method, scope, params);
568
588
  const props = yield getWalletActionAnalyticsProperties(
@@ -597,12 +617,12 @@ requestInterceptor_fn = function(request) {
597
617
  if (isConnectRequest(request)) {
598
618
  const shouldForceConnectionRequest = request.method === "wallet_requestPermissions";
599
619
  const { method, params } = request;
600
- const chainId = DEFAULT_CHAIN_ID;
601
- const scope = `eip155:${chainId}`;
620
+ const initiallySelectedChainId = DEFAULT_CHAIN_ID;
621
+ const scope = `eip155:${initiallySelectedChainId}`;
602
622
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionRequested_fn).call(this, method, scope, params);
603
623
  try {
604
624
  const result = yield this.connect({
605
- chainId,
625
+ chainIds: [initiallySelectedChainId],
606
626
  forceRequest: shouldForceConnectionRequest
607
627
  });
608
628
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionSucceeded_fn).call(this, method, scope, params);
@@ -653,10 +673,13 @@ addEthereumChain_fn = function(chainConfiguration) {
653
673
  const params = [chainConfiguration];
654
674
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionRequested_fn).call(this, method, scope, params);
655
675
  try {
656
- yield __privateMethod(this, _MetamaskConnectEVM_instances, request_fn).call(this, {
676
+ const result = yield __privateMethod(this, _MetamaskConnectEVM_instances, request_fn).call(this, {
657
677
  method: "wallet_addEthereumChain",
658
678
  params
659
679
  });
680
+ if (result.result === null) {
681
+ __privateMethod(this, _MetamaskConnectEVM_instances, onChainChanged_fn).call(this, chainId);
682
+ }
660
683
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionSucceeded_fn).call(this, method, scope, params);
661
684
  } catch (error) {
662
685
  yield __privateMethod(this, _MetamaskConnectEVM_instances, trackWalletActionFailed_fn).call(this, method, scope, params, error);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/index.ts","../../../src/connect.ts","../../../src/constants.ts","../../../src/logger.ts","../../../src/provider.ts","../../../src/utils/caip.ts","../../../src/utils/type-guards.ts"],"sourcesContent":["export { getInfuraRpcUrls } from '@metamask/connect-multichain';\nexport { createMetamaskConnectEVM, type MetamaskConnectEVM } from './connect';\nexport type { EIP1193Provider } from './provider';\n\nexport type * from './types';\n","import { analytics } from '@metamask/analytics';\nimport type { Caip25CaveatValue } from '@metamask/chain-agnostic-permission';\nimport type {\n MultichainCore,\n MultichainOptions,\n Scope,\n SessionData,\n} from '@metamask/connect-multichain';\nimport {\n createMetamaskConnect,\n getWalletActionAnalyticsProperties,\n isRejectionError,\n TransportType,\n} from '@metamask/connect-multichain';\nimport {\n numberToHex,\n hexToNumber,\n isHexString as isHex,\n} from '@metamask/utils';\n\nimport { IGNORED_METHODS } from './constants';\nimport { enableDebug, logger } from './logger';\nimport { EIP1193Provider } from './provider';\nimport type {\n AddEthereumChainParameter,\n Address,\n CaipAccountId,\n EventHandlers,\n Hex,\n MetamaskConnectEVMOptions,\n ProviderRequest,\n ProviderRequestInterceptor,\n} from './types';\nimport { getPermittedEthChainIds } from './utils/caip';\nimport {\n isAccountsRequest,\n isAddChainRequest,\n isConnectRequest,\n isSwitchChainRequest,\n validSupportedChainsUrls,\n} from './utils/type-guards';\n\nconst DEFAULT_CHAIN_ID = 1;\n\n/**\n * The MetamaskConnectEVM class provides an EIP-1193 compatible interface for connecting\n * to MetaMask and interacting with Ethereum Virtual Machine (EVM) networks.\n *\n * This class serves as a modern replacement for MetaMask SDK V1, offering enhanced\n * functionality and cross-platform compatibility. It wraps the Multichain SDK to provide\n * a simplified, EIP-1193 compliant API for dapp developers.\n *\n * Key features:\n * - EIP-1193 provider interface for seamless integration with existing dapp code\n * - Automatic session recovery when reloading or opening in new tabs\n * - Chain switching with automatic chain addition if not configured\n * - Event-driven architecture with support for connect, disconnect, accountsChanged, and chainChanged events\n * - Cross-platform support for browser extensions and mobile applications\n * - Built-in handling of common Ethereum methods (eth_accounts, wallet_switchEthereumChain, etc.)\n *\n * @example\n * ```typescript\n * const sdk = await createMetamaskConnectEVM({\n * dapp: { name: 'My DApp', url: 'https://mydapp.com' }\n * });\n *\n * await sdk.connect({ chainId: 1 });\n * const provider = await sdk.getProvider();\n * const accounts = await provider.request({ method: 'eth_accounts' });\n * ```\n */\nexport class MetamaskConnectEVM {\n /** The core instance of the Multichain SDK */\n readonly #core: MultichainCore;\n\n /** An instance of the EIP-1193 provider interface */\n readonly #provider: EIP1193Provider;\n\n /** The session scopes currently permitted */\n #sessionScopes: SessionData['sessionScopes'] = {};\n\n /** Optional event handlers for the EIP-1193 provider events. */\n readonly #eventHandlers?: Partial<EventHandlers> | undefined;\n\n /** The handler for the wallet_sessionChanged event */\n readonly #sessionChangedHandler: (session?: SessionData) => void;\n\n /**\n * Creates a new MetamaskConnectEVM instance.\n *\n * @param options - The options for the MetamaskConnectEVM instance\n * @param options.core - The core instance of the Multichain SDK\n * @param options.eventHandlers - Optional event handlers for EIP-1193 provider events\n */\n constructor({ core, eventHandlers }: MetamaskConnectEVMOptions) {\n this.#core = core;\n\n this.#provider = new EIP1193Provider(\n core,\n this.#requestInterceptor.bind(this),\n );\n\n this.#eventHandlers = eventHandlers;\n\n /**\n * Handles the wallet_sessionChanged event.\n * Updates the internal connection state with the new session data.\n *\n * @param session - The session data\n */\n this.#sessionChangedHandler = (session): void => {\n logger('event: wallet_sessionChanged', session);\n this.#sessionScopes = session?.sessionScopes ?? {};\n };\n this.#core.on(\n 'wallet_sessionChanged',\n this.#sessionChangedHandler.bind(this),\n );\n\n // Attempt to set the permitted accounts if there's a valid previous session.\n // TODO (wenfix): does it make sense to catch here?\n this.#attemptSessionRecovery().catch((error) => {\n console.error('Error attempting session recovery', error);\n });\n\n logger('Connect/EVM constructor completed');\n }\n\n /**\n * Gets the core options for analytics checks.\n *\n * @returns The multichain options from the core instance\n */\n #getCoreOptions(): MultichainOptions {\n return (this.#core as any).options as MultichainOptions;\n }\n\n /**\n * Creates invoke options for analytics tracking.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n * @returns Invoke options object for analytics\n */\n #createInvokeOptions(\n method: string,\n scope: Scope,\n params: unknown[],\n ): {\n scope: Scope;\n request: { method: string; params: unknown[] };\n } {\n return {\n scope,\n request: { method, params },\n };\n }\n\n /**\n * Tracks a wallet action requested event.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n */\n async #trackWalletActionRequested(\n method: string,\n scope: Scope,\n params: unknown[],\n ): Promise<void> {\n const coreOptions = this.#getCoreOptions();\n if (!coreOptions.analytics?.enabled) {\n return;\n }\n\n try {\n const invokeOptions = this.#createInvokeOptions(method, scope, params);\n const props = await getWalletActionAnalyticsProperties(\n coreOptions,\n this.#core.storage,\n invokeOptions,\n );\n analytics.track('mmconnect_wallet_action_requested', props);\n } catch (error) {\n logger('Error tracking mmconnect_wallet_action_requested event', error);\n }\n }\n\n /**\n * Tracks a wallet action succeeded event.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n */\n async #trackWalletActionSucceeded(\n method: string,\n scope: Scope,\n params: unknown[],\n ): Promise<void> {\n const coreOptions = this.#getCoreOptions();\n if (!coreOptions.analytics?.enabled) {\n return;\n }\n\n try {\n const invokeOptions = this.#createInvokeOptions(method, scope, params);\n const props = await getWalletActionAnalyticsProperties(\n coreOptions,\n this.#core.storage,\n invokeOptions,\n );\n analytics.track('mmconnect_wallet_action_succeeded', props);\n } catch (error) {\n logger('Error tracking mmconnect_wallet_action_succeeded event', error);\n }\n }\n\n /**\n * Tracks a wallet action failed or rejected event based on the error.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n * @param error - The error that occurred\n */\n async #trackWalletActionFailed(\n method: string,\n scope: Scope,\n params: unknown[],\n error: unknown,\n ): Promise<void> {\n const coreOptions = this.#getCoreOptions();\n if (!coreOptions.analytics?.enabled) {\n return;\n }\n\n try {\n const invokeOptions = this.#createInvokeOptions(method, scope, params);\n const props = await getWalletActionAnalyticsProperties(\n coreOptions,\n this.#core.storage,\n invokeOptions,\n );\n const isRejection = isRejectionError(error);\n if (isRejection) {\n analytics.track('mmconnect_wallet_action_rejected', props);\n } else {\n analytics.track('mmconnect_wallet_action_failed', props);\n }\n } catch {\n logger('Error tracking wallet action rejected or failed event', error);\n }\n }\n\n /**\n * Connects to the wallet with the specified chain ID and optional account.\n *\n * @param options - The connection options\n * @param options.chainId - The chain ID to connect to (defaults to 1 for mainnet)\n * @param options.account - Optional specific account to connect to\n * @param options.forceRequest - Wwhether to force a request regardless of an existing session\n * @returns A promise that resolves with the connected accounts and chain ID\n */\n async connect(\n {\n chainId,\n account,\n forceRequest,\n }: {\n chainId: number;\n account?: string | undefined;\n forceRequest?: boolean;\n } = { chainId: DEFAULT_CHAIN_ID }, // Default to mainnet if no chain ID is provided\n ): Promise<{ accounts: Address[]; chainId: number }> {\n logger('request: connect', { chainId, account });\n const caipChainId: Scope[] = chainId ? [`eip155:${chainId}`] : [];\n\n const caipAccountId: CaipAccountId[] =\n chainId && account ? [`eip155:${chainId}:${account}`] : [];\n\n await this.#core.connect(caipChainId, caipAccountId, forceRequest);\n\n const hexPermittedChainIds = getPermittedEthChainIds(this.#sessionScopes);\n const initialChainId = hexPermittedChainIds[0];\n\n const initialAccounts = await this.#core.transport.sendEip1193Message<\n { method: 'eth_accounts'; params: [] },\n { result: string[]; id: number; jsonrpc: '2.0' }\n >({ method: 'eth_accounts', params: [] });\n\n this.#onConnect({\n chainId: initialChainId,\n accounts: initialAccounts.result as Address[],\n });\n\n this.#core.transport.onNotification((notification) => {\n // @ts-expect-error TODO: address this\n if (notification?.method === 'metamask_accountsChanged') {\n // @ts-expect-error TODO: address this\n const accounts = notification?.params;\n logger('transport-event: accountsChanged', accounts);\n this.#onAccountsChanged(accounts);\n }\n\n // @ts-expect-error TODO: address this\n if (notification?.method === 'metamask_chainChanged') {\n // @ts-expect-error TODO: address this\n const notificationChainId = Number(notification?.params?.chainId);\n logger('transport-event: chainChanged', notificationChainId);\n this.#onChainChanged(notificationChainId);\n }\n });\n\n logger('fulfilled-request: connect', {\n chainId,\n accounts: this.#provider.accounts,\n });\n\n // TODO: update required here since accounts and chainId are now promises\n return {\n accounts: this.#provider.accounts,\n chainId: hexToNumber(initialChainId),\n };\n }\n\n /**\n * Connects to the wallet and signs a message using personal_sign.\n *\n * @param message - The message to sign\n * @returns A promise that resolves with the signature\n * @throws Error if the selected account is not available after timeout\n */\n async connectAndSign(message: string): Promise<string> {\n const { accounts, chainId } = await this.connect();\n\n const result = (await this.#provider.request({\n method: 'personal_sign',\n params: [accounts[0], message],\n })) as string;\n\n this.#eventHandlers?.connectAndSign?.({\n accounts,\n chainId,\n signResponse: result,\n })\n\n return result;\n }\n\n\n /**\n * Connects to the wallet and invokes a method with specified parameters.\n *\n * @param options - The options for connecting and invoking the method\n * @param options.method - The method name to invoke\n * @param options.params - The parameters to pass to the method, or a function that receives the account and returns params\n * @param options.chainId - Optional chain ID to connect to (defaults to mainnet)\n * @param options.account - Optional specific account to connect to\n * @param options.forceRequest - Whether to force a request regardless of an existing session\n * @returns A promise that resolves with the result of the method invocation\n * @throws Error if the selected account is not available after timeout (for methods that require an account)\n */\n async connectWith({\n method,\n params,\n chainId,\n account,\n forceRequest,\n }: {\n method: string;\n params: unknown[] | ((account: Address) => unknown[]);\n chainId?: number;\n account?: string | undefined;\n forceRequest?: boolean;\n }): Promise<unknown> {\n const { accounts: connectedAccounts, chainId: connectedChainId} = await this.connect({\n chainId: chainId ?? DEFAULT_CHAIN_ID,\n account,\n forceRequest,\n });\n\n const resolvedParams =\n typeof params === 'function' ? params(connectedAccounts[0]) : params;\n\n const result = await this.#provider.request({\n method,\n params: resolvedParams,\n });\n\n this.#eventHandlers?.connectWith?.({\n accounts: connectedAccounts,\n chainId: connectedChainId,\n connectWithResponse: result,\n })\n\n return result;\n }\n\n /**\n * Disconnects from the wallet by revoking the session and cleaning up event listeners.\n *\n * @returns A promise that resolves when disconnection is complete\n */\n async disconnect(): Promise<void> {\n logger('request: disconnect');\n\n await this.#core.disconnect();\n this.#onDisconnect();\n this.#clearConnectionState();\n\n this.#core.off('wallet_sessionChanged', this.#sessionChangedHandler);\n\n logger('fulfilled-request: disconnect');\n }\n\n /**\n * Switches the Ethereum chain. Will track state internally whenever possible.\n *\n * @param options - The options for the switch chain request\n * @param options.chainId - The chain ID to switch to\n * @param options.chainConfiguration - The chain configuration to use in case the chain is not present by the wallet\n * @returns The result of the switch chain request\n */\n async switchChain({\n chainId,\n chainConfiguration,\n }: {\n chainId: number | Hex;\n chainConfiguration?: AddEthereumChainParameter;\n }): Promise<unknown> {\n const method = 'wallet_switchEthereumChain';\n const hexChainId = isHex(chainId) ? chainId : numberToHex(chainId);\n const scope: Scope = `eip155:${isHex(chainId) ? hexToNumber(chainId) : chainId}`;\n const params = [{ chainId: hexChainId }];\n\n await this.#trackWalletActionRequested(method, scope, params);\n\n // TODO (wenfix): better way to return here other than resolving.\n if (this.selectedChainId === hexChainId) {\n return Promise.resolve();\n }\n\n const permittedChainIds = getPermittedEthChainIds(this.#sessionScopes);\n\n if (\n permittedChainIds.includes(hexChainId) &&\n this.#core.transportType === TransportType.MWP\n ) {\n this.#onChainChanged(hexChainId);\n await this.#trackWalletActionSucceeded(method, scope, params);\n return Promise.resolve();\n }\n\n try {\n const result = await this.#request({\n method: 'wallet_switchEthereumChain',\n params,\n });\n await this.#trackWalletActionSucceeded(method, scope, params);\n return result;\n } catch (error) {\n await this.#trackWalletActionFailed(method, scope, params, error);\n // Fallback to add the chain if its not configured in the wallet.\n if ((error as Error).message.includes('Unrecognized chain ID')) {\n return this.#addEthereumChain(chainConfiguration);\n }\n throw error;\n }\n }\n\n /**\n * Handles several EIP-1193 requests that require special handling\n * due the nature of the Multichain SDK.\n *\n * @param request - The request object containing the method and params\n * @returns The result of the request or undefined if the request is ignored\n */\n async #requestInterceptor(\n request: ProviderRequest,\n ): ReturnType<ProviderRequestInterceptor> {\n logger(`Intercepting request for method: ${request.method}`);\n\n if (IGNORED_METHODS.includes(request.method)) {\n // TODO: replace with correct method unsupported provider error\n return Promise.reject(\n new Error(\n `Method: ${request.method} is not supported by Metamask Connect/EVM`,\n ),\n );\n }\n\n if (request.method === 'wallet_revokePermissions') {\n return this.disconnect();\n }\n\n if (isConnectRequest(request)) {\n // When calling wallet_requestPermissions, we need to force a new session request to prompt\n // the user for accounts, because internally the Multichain SDK will check if\n // the user is already connected and skip the request if so, unless we\n // explicitly request a specific account. This is needed to workaround\n // wallet_requestPermissions not requesting specific accounts.\n const shouldForceConnectionRequest =\n request.method === 'wallet_requestPermissions';\n\n const { method, params } = request;\n const chainId = DEFAULT_CHAIN_ID;\n const scope: Scope = `eip155:${chainId}`;\n\n await this.#trackWalletActionRequested(method, scope, params);\n\n try {\n const result = await this.connect({\n chainId,\n forceRequest: shouldForceConnectionRequest,\n });\n await this.#trackWalletActionSucceeded(method, scope, params);\n return result;\n } catch (error) {\n await this.#trackWalletActionFailed(method, scope, params, error);\n throw error;\n }\n }\n\n if (isSwitchChainRequest(request)) {\n return this.switchChain({\n chainId: parseInt(request.params[0].chainId, 16),\n });\n }\n\n if (isAddChainRequest(request)) {\n return this.#addEthereumChain(request.params[0]);\n }\n\n if (isAccountsRequest(request)) {\n const { method } = request;\n const chainId = this.#provider.selectedChainId\n ? hexToNumber(this.#provider.selectedChainId)\n : 1;\n const scope: Scope = `eip155:${chainId}`;\n const params: unknown[] = [];\n\n await this.#trackWalletActionRequested(method, scope, params);\n await this.#trackWalletActionSucceeded(method, scope, params);\n\n return this.#provider.accounts;\n }\n\n logger('Request not intercepted, forwarding to default handler', request);\n return Promise.resolve();\n }\n\n /**\n * Clears the internal connection state: accounts and chainId\n */\n #clearConnectionState(): void {\n this.#provider.accounts = [];\n this.#provider.selectedChainId = undefined as unknown as number;\n }\n\n /**\n * Adds an Ethereum chain using the latest chain configuration received from\n * a switchEthereumChain request\n *\n * @param chainConfiguration - The chain configuration to use in case the chain is not present by the wallet\n * @returns Nothing\n */\n async #addEthereumChain(\n chainConfiguration?: AddEthereumChainParameter,\n ): Promise<void> {\n logger('addEthereumChain called', { chainConfiguration });\n const method = 'wallet_addEthereumChain';\n\n if (!chainConfiguration) {\n throw new Error('No chain configuration found.');\n }\n\n // Get chain ID from config or use current chain\n const chainId = chainConfiguration.chainId\n ? parseInt(chainConfiguration.chainId, 16)\n : hexToNumber(this.#provider.selectedChainId ?? '0x1');\n const scope: Scope = `eip155:${chainId}`;\n const params = [chainConfiguration];\n\n await this.#trackWalletActionRequested(method, scope, params);\n\n try {\n await this.#request({\n method: 'wallet_addEthereumChain',\n params,\n });\n await this.#trackWalletActionSucceeded(method, scope, params);\n } catch (error) {\n await this.#trackWalletActionFailed(method, scope, params, error);\n throw error;\n }\n }\n\n /**\n * Submits a request to the EIP-1193 provider\n *\n * @param request - The request object containing the method and params\n * @param request.method - The method to request\n * @param request.params - The parameters to pass to the method\n * @returns The result of the request\n */\n async #request(request: {\n method: string;\n params: unknown[];\n }): Promise<unknown> {\n logger('direct request to metamask-provider called', request);\n const result = this.#core.transport.sendEip1193Message(request);\n if (\n request.method === 'wallet_addEthereumChain' ||\n request.method === 'wallet_switchEthereumChain'\n ) {\n this.#core.openDeeplinkIfNeeded();\n }\n return result;\n }\n\n /**\n * Handles chain change events and updates the provider's selected chain ID.\n *\n * @param chainId - The new chain ID (can be hex string or number)\n */\n #onChainChanged(chainId: Hex | number): void {\n const hexChainId = isHex(chainId) ? chainId : numberToHex(chainId);\n if (hexChainId === this.#provider.selectedChainId) {\n return;\n }\n logger('handler: chainChanged', { chainId });\n this.#provider.selectedChainId = chainId;\n this.#eventHandlers?.chainChanged?.(hexChainId);\n this.#provider.emit('chainChanged', hexChainId);\n }\n\n /**\n * Handles accounts change events and updates the provider's accounts list.\n *\n * @param accounts - The new list of permitted accounts\n */\n #onAccountsChanged(accounts: Address[]): void {\n logger('handler: accountsChanged', accounts);\n this.#provider.accounts = accounts;\n this.#provider.emit('accountsChanged', accounts);\n this.#eventHandlers?.accountsChanged?.(accounts);\n }\n\n /**\n * Handles connection events and emits the connect event to listeners.\n *\n * @param options - The connection options\n * @param options.chainId - The chain ID of the connection (can be hex string or number)\n * @param options.accounts - The accounts of the connection\n */\n #onConnect({\n chainId,\n accounts,\n }: {\n chainId: Hex | number;\n accounts: Address[];\n }): void {\n logger('handler: connect', { chainId, accounts });\n const data = {\n chainId: isHex(chainId) ? chainId : numberToHex(chainId),\n accounts,\n };\n\n this.#provider.emit('connect', data);\n this.#eventHandlers?.connect?.(data);\n\n this.#onChainChanged(chainId);\n this.#onAccountsChanged(accounts);\n }\n\n /**\n * Handles disconnection events and emits the disconnect event to listeners.\n * Also clears accounts by triggering an accountsChanged event with an empty array.\n */\n #onDisconnect(): void {\n logger('handler: disconnect');\n this.#provider.emit('disconnect');\n this.#eventHandlers?.disconnect?.();\n\n this.#onAccountsChanged([]);\n }\n\n /**\n * Will trigger an accountsChanged event if there's a valid previous session.\n * This is needed because the accountsChanged event is not triggered when\n * revising, reloading or opening the app in a new tab.\n *\n * This works by checking by checking events received during MultichainCore initialization,\n * and if there's a wallet_sessionChanged event, it will add a 1-time listener for eth_accounts results\n * and trigger an accountsChanged event if the results are valid accounts.\n */\n async #attemptSessionRecovery(): Promise<void> {\n try {\n const response = await this.#core.transport.request<\n { method: 'wallet_getSession' },\n {\n result: { sessionScopes: Caip25CaveatValue };\n id: number;\n jsonrpc: '2.0';\n }\n >({\n method: 'wallet_getSession',\n });\n\n const { sessionScopes } = response.result;\n\n this.#sessionScopes = sessionScopes;\n const permittedChainIds = getPermittedEthChainIds(sessionScopes);\n\n // Instead of using the accounts we get back from calling `wallet_getSession`\n // we get permitted accounts from `eth_accounts` to make sure we have them ordered by last selected account\n // and correctly set the currently selected account for the dapp\n const permittedAccounts = await this.#core.transport.sendEip1193Message({\n method: 'eth_accounts',\n params: [],\n });\n\n if (permittedChainIds.length && permittedAccounts.result) {\n this.#onConnect({\n chainId: permittedChainIds[0],\n accounts: permittedAccounts.result as Address[],\n });\n }\n } catch (error) {\n console.error('Error attempting session recovery', error);\n }\n }\n\n /**\n * Gets the EIP-1193 provider instance\n *\n * @returns The EIP-1193 provider instance\n */\n getProvider(): EIP1193Provider {\n return this.#provider;\n }\n\n /**\n * Gets the currently selected chain ID on the wallet\n *\n * @returns The currently selected chain ID or undefined if no chain is selected\n */\n getChainId(): Hex | undefined {\n return this.selectedChainId;\n }\n\n /**\n * Gets the currently selected account on the wallet\n *\n * @returns The currently selected account or undefined if no account is selected\n */\n getAccount(): Address | undefined {\n return this.#provider.selectedAccount;\n }\n\n // Convenience getters for the EIP-1193 provider\n /**\n * Gets the currently permitted accounts\n *\n * @returns The currently permitted accounts\n */\n get accounts(): Address[] {\n return this.#provider.accounts;\n }\n\n /**\n * Gets the currently selected account on the wallet\n *\n * @returns The currently selected account or undefined if no account is selected\n */\n get selectedAccount(): Address | undefined {\n return this.#provider.selectedAccount;\n }\n\n /**\n * Gets the currently selected chain ID on the wallet\n *\n * @returns The currently selected chain ID or undefined if no chain is selected\n */\n get selectedChainId(): Hex | undefined {\n return this.#provider.selectedChainId;\n }\n}\n\n/**\n * Creates a new Metamask Connect/EVM instance\n *\n * @param options - The options for the Metamask Connect/EVM layer\n * @param options.dapp - Dapp identification and branding settings\n * @param options.api - API configuration including read-only RPC map\n * @param options.api.supportedNetworks - A map of CAIP chain IDs to RPC URLs for read-only requests\n * @param options.eventEmitter - The event emitter to use for the Metamask Connect/EVM layer\n * @param options.eventHandlers - The event handlers to use for the Metamask Connect/EVM layer\n * @returns The Metamask Connect/EVM layer instance\n */\nexport async function createMetamaskConnectEVM(\n options: Pick<MultichainOptions, 'dapp' | 'api'> & {\n eventHandlers?: Partial<EventHandlers>;\n debug?: boolean;\n },\n): Promise<MetamaskConnectEVM> {\n enableDebug(options.debug);\n\n logger('Creating Metamask Connect/EVM with options:', options);\n\n // Validate that supportedNetworks is provided and not empty\n if (\n !options.api?.supportedNetworks ||\n Object.keys(options.api.supportedNetworks).length === 0\n ) {\n throw new Error(\n 'supportedNetworks is required and must contain at least one chain configuration',\n );\n }\n\n validSupportedChainsUrls(options.api.supportedNetworks, 'supportedNetworks');\n\n try {\n const core = await createMetamaskConnect({\n ...options,\n api: {\n supportedNetworks: options.api.supportedNetworks,\n },\n });\n\n return new MetamaskConnectEVM({\n core,\n eventHandlers: options.eventHandlers,\n supportedNetworks: options.api.supportedNetworks,\n });\n } catch (error) {\n console.error('Error creating Metamask Connect/EVM', error);\n throw error;\n }\n}\n","export const IGNORED_METHODS = [\n 'metamask_getProviderState',\n 'metamask_sendDomainMetadata',\n 'metamask_logWeb3ShimUsage',\n 'wallet_registerOnboarding',\n 'net_version',\n 'wallet_getPermissions',\n];\n\nexport const CONNECT_METHODS = [\n 'wallet_requestPermissions',\n 'eth_requestAccounts',\n];\n\nexport const ACCOUNTS_METHODS = ['eth_accounts', 'eth_coinbase'];\n\nexport const INTERCEPTABLE_METHODS = [\n ...ACCOUNTS_METHODS,\n ...IGNORED_METHODS,\n ...CONNECT_METHODS,\n // These have bespoke handlers\n 'wallet_revokePermissions',\n 'wallet_switchEthereumChain',\n 'wallet_addEthereumChain',\n];\n","import {\n createLogger,\n enableDebug as debug,\n} from '@metamask/connect-multichain';\n\nconst namespace = 'metamask-connect:evm';\n\n// @ts-expect-error logger needs to be typed properly\nexport const logger = createLogger(namespace, '63');\n\nexport const enableDebug = (debugEnabled: boolean = false): void => {\n if (debugEnabled) {\n // @ts-expect-error logger needs to be typed properly\n debug(namespace);\n }\n};\n","import type { MultichainCore, Scope } from '@metamask/connect-multichain';\nimport { EventEmitter } from '@metamask/connect-multichain';\nimport { hexToNumber, numberToHex } from '@metamask/utils';\n\nimport { INTERCEPTABLE_METHODS } from './constants';\nimport { logger } from './logger';\nimport type {\n Address,\n EIP1193ProviderEvents,\n Hex,\n ProviderRequest,\n ProviderRequestInterceptor,\n} from './types';\n\n/**\n * EIP-1193 Provider wrapper around the Multichain SDK.\n */\nexport class EIP1193Provider extends EventEmitter<EIP1193ProviderEvents> {\n /** The core instance of the Multichain SDK */\n readonly #core: MultichainCore;\n\n /** Interceptor function to handle specific methods */\n readonly #requestInterceptor: ProviderRequestInterceptor;\n\n /** The currently permitted accounts */\n #accounts: Address[] = [];\n\n /** The currently selected chain ID on the wallet */\n #selectedChainId?: Hex | undefined;\n\n constructor(core: MultichainCore, interceptor: ProviderRequestInterceptor) {\n super();\n this.#core = core;\n this.#requestInterceptor = interceptor;\n }\n\n /**\n * Performs a EIP-1193 request.\n *\n * @param request - The request object containing the method and params\n * @returns The result of the request\n */\n async request(request: ProviderRequest): Promise<unknown> {\n logger(\n `request: ${request.method} - chainId: ${this.selectedChainId}`,\n request.params,\n );\n /* Some methods require special handling, so we intercept them here\n * and handle them in MetamaskConnectEVM.requestInterceptor method. */\n if (INTERCEPTABLE_METHODS.includes(request.method)) {\n return this.#requestInterceptor?.(request);\n }\n\n if (!this.#selectedChainId) {\n // TODO: replace with a better error\n throw new Error('No chain ID selected');\n }\n\n const chainId = hexToNumber(this.#selectedChainId);\n const scope: Scope = `eip155:${chainId}`;\n\n // Validate that the chain is configured in supportedNetworks\n // This check is performed here to provide better error messages\n // The RpcClient will also validate, but this gives us a chance to provide\n // a clearer error message before the request is routed\n const coreOptions = (this.#core as any).options; // TODO: options is `protected readonly` property, this needs to be refactored so `any` type assertion is not necessary\n const supportedNetworks = coreOptions?.api?.supportedNetworks ?? {};\n if (!supportedNetworks[scope]) {\n throw new Error(\n `Chain ${scope} is not configured in supportedNetworks. Requests cannot be made to chains not explicitly configured in supportedNetworks.`,\n );\n }\n\n return this.#core.invokeMethod({\n scope,\n request: {\n method: request.method,\n params: request.params,\n },\n });\n }\n\n // Getters and setters\n public get selectedAccount(): Address | undefined {\n return this.accounts[0];\n }\n\n public set accounts(accounts: Address[]) {\n this.#accounts = accounts;\n }\n\n public get accounts(): Address[] {\n return this.#accounts;\n }\n\n public get selectedChainId(): Hex | undefined {\n return this.#selectedChainId;\n }\n\n public set selectedChainId(chainId: Hex | number | undefined) {\n const hexChainId =\n chainId && typeof chainId === 'number' ? numberToHex(chainId) : chainId;\n\n // Don't overwrite the selected chain ID with an undefined value\n if (!hexChainId) {\n return;\n }\n\n this.#selectedChainId = hexChainId as Hex;\n }\n}\n","import type { InternalScopesObject } from '@metamask/chain-agnostic-permission';\nimport {\n getPermittedEthChainIds as _getPermittedEthChainIds,\n getEthAccounts as _getEthAccounts,\n} from '@metamask/chain-agnostic-permission';\nimport type { SessionData } from '@metamask/connect-multichain';\n\nimport type { Address, Hex } from '../types';\n\n/**\n * Get the Ethereum accounts from the session data\n *\n * @param sessionScopes - The session scopes\n * @returns The Ethereum accounts\n */\nexport const getEthAccounts = (\n sessionScopes: SessionData['sessionScopes'] | undefined,\n): Address[] => {\n if (!sessionScopes) {\n return [];\n }\n\n return _getEthAccounts({\n requiredScopes: sessionScopes as InternalScopesObject,\n optionalScopes: sessionScopes as InternalScopesObject,\n });\n};\n\n/**\n * Get the permitted Ethereum chain IDs from the session scopes.\n * Wrapper around getPermittedEthChainIds from @metamask/chain-agnostic-permission\n *\n * @param sessionScopes - The session scopes\n * @returns The permitted Ethereum chain IDs\n */\nexport const getPermittedEthChainIds = (\n sessionScopes: SessionData['sessionScopes'] | undefined,\n): Hex[] => {\n if (!sessionScopes) {\n return [];\n }\n\n return _getPermittedEthChainIds({\n requiredScopes: sessionScopes as InternalScopesObject,\n optionalScopes: sessionScopes as InternalScopesObject,\n });\n};\n","import type { ProviderRequest } from '../types';\n\n/**\n * Type guard for connect-like requests:\n * - wallet_requestPermissions\n * - eth_requestAccounts\n *\n * @param req - The request object to check\n * @returns True if the request is a connect-like request, false otherwise\n */\nexport function isConnectRequest(req: ProviderRequest): req is Extract<\n ProviderRequest,\n {\n method: 'wallet_requestPermissions' | 'eth_requestAccounts';\n }\n> {\n return (\n req.method === 'wallet_requestPermissions' ||\n req.method === 'eth_requestAccounts'\n );\n}\n\n/**\n * Type guard for wallet_switchEthereumChain request.\n *\n * @param req - The request object to check\n * @returns True if the request is a wallet_switchEthereumChain request, false otherwise\n */\nexport function isSwitchChainRequest(\n req: ProviderRequest,\n): req is Extract<ProviderRequest, { method: 'wallet_switchEthereumChain' }> {\n return req.method === 'wallet_switchEthereumChain';\n}\n\n/**\n * Type guard for wallet_addEthereumChain request.\n *\n * @param req - The request object to check\n * @returns True if the request is a wallet_addEthereumChain request, false otherwise\n */\nexport function isAddChainRequest(\n req: ProviderRequest,\n): req is Extract<ProviderRequest, { method: 'wallet_addEthereumChain' }> {\n return req.method === 'wallet_addEthereumChain';\n}\n\n/**\n * Type guard for generic accounts request:\n * - eth_accounts\n * - eth_coinbase\n *\n * @param req - The request object to check\n * @returns True if the request is a generic accounts request, false otherwise\n */\nexport function isAccountsRequest(\n req: ProviderRequest,\n): req is Extract<\n ProviderRequest,\n { method: 'eth_accounts' | 'eth_coinbase' }\n> {\n return req.method === 'eth_accounts' || req.method === 'eth_coinbase';\n}\n\n/**\n * Validates that all values in a Record are valid URLs.\n *\n * @param record - The record to validate (e.g., supportedNetworks)\n * @param recordName - The name of the record for error messages\n * @throws Error if any values are invalid URLs\n */\nexport function validSupportedChainsUrls(\n record: Record<string, string>,\n recordName: string,\n): void {\n const invalidUrls: string[] = [];\n for (const [key, url] of Object.entries(record)) {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n } catch {\n invalidUrls.push(`${key}: ${url}`);\n }\n }\n\n if (invalidUrls.length > 0) {\n throw new Error(\n `${recordName} contains invalid URLs:\\n${invalidUrls.join('\\n')}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,wBAAwB;;;ACAjC,SAAS,iBAAiB;AAQ1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE,eAAAA;AAAA,EACA,eAAAC;AAAA,EACA,eAAe;AAAA,OACV;;;AClBA,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AACF;AAEO,IAAM,mBAAmB,CAAC,gBAAgB,cAAc;AAExD,IAAM,wBAAwB;AAAA,EACnC,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA;AAAA,EAEH;AAAA,EACA;AAAA,EACA;AACF;;;ACxBA;AAAA,EACE;AAAA,EACA,eAAe;AAAA,OACV;AAEP,IAAM,YAAY;AAGX,IAAM,SAAS,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d,cAAQ,MAAM,uCAAuC,KAAK;AAC1D,YAAM;AAAA,IACR;AAAA,EACF;AAAA;","names":["numberToHex","hexToNumber","_core","hexToNumber","numberToHex"]}
1
+ {"version":3,"sources":["../../../src/index.ts","../../../src/connect.ts","../../../src/constants.ts","../../../src/logger.ts","../../../src/provider.ts","../../../src/utils/caip.ts","../../../src/utils/type-guards.ts"],"sourcesContent":["export { getInfuraRpcUrls } from '@metamask/connect-multichain';\nexport { createMetamaskConnectEVM, type MetamaskConnectEVM } from './connect';\nexport type { EIP1193Provider } from './provider';\n\nexport type * from './types';\n","import { analytics } from '@metamask/analytics';\nimport type { Caip25CaveatValue } from '@metamask/chain-agnostic-permission';\nimport type {\n MultichainCore,\n MultichainOptions,\n Scope,\n SessionData,\n} from '@metamask/connect-multichain';\nimport {\n createMetamaskConnect,\n getWalletActionAnalyticsProperties,\n isRejectionError,\n TransportType,\n} from '@metamask/connect-multichain';\nimport {\n numberToHex,\n hexToNumber,\n isHexString as isHex,\n} from '@metamask/utils';\n\nimport { IGNORED_METHODS } from './constants';\nimport { enableDebug, logger } from './logger';\nimport { EIP1193Provider } from './provider';\nimport type {\n AddEthereumChainParameter,\n Address,\n CaipAccountId,\n EventHandlers,\n Hex,\n MetamaskConnectEVMOptions,\n ProviderRequest,\n ProviderRequestInterceptor,\n} from './types';\nimport { getPermittedEthChainIds } from './utils/caip';\nimport {\n isAccountsRequest,\n isAddChainRequest,\n isConnectRequest,\n isSwitchChainRequest,\n validSupportedChainsUrls,\n} from './utils/type-guards';\n\nconst DEFAULT_CHAIN_ID = 1;\n\n/** The options for the connect method */\ntype ConnectOptions = {\n /** The account to connect to */\n account?: string | undefined;\n /** Whether to force a request regardless of an existing session */\n forceRequest?: boolean;\n /** All available chain IDs in the dapp */\n chainIds: number[];\n};\n\n/**\n * The MetamaskConnectEVM class provides an EIP-1193 compatible interface for connecting\n * to MetaMask and interacting with Ethereum Virtual Machine (EVM) networks.\n *\n * This class serves as a modern replacement for MetaMask SDK V1, offering enhanced\n * functionality and cross-platform compatibility. It wraps the Multichain SDK to provide\n * a simplified, EIP-1193 compliant API for dapp developers.\n *\n * Key features:\n * - EIP-1193 provider interface for seamless integration with existing dapp code\n * - Automatic session recovery when reloading or opening in new tabs\n * - Chain switching with automatic chain addition if not configured\n * - Event-driven architecture with support for connect, disconnect, accountsChanged, and chainChanged events\n * - Cross-platform support for browser extensions and mobile applications\n * - Built-in handling of common Ethereum methods (eth_accounts, wallet_switchEthereumChain, etc.)\n *\n * @example\n * ```typescript\n * const sdk = await createMetamaskConnectEVM({\n * dapp: { name: 'My DApp', url: 'https://mydapp.com' }\n * });\n *\n * await sdk.connect({ chainId: 1 });\n * const provider = await sdk.getProvider();\n * const accounts = await provider.request({ method: 'eth_accounts' });\n * ```\n */\nexport class MetamaskConnectEVM {\n /** The core instance of the Multichain SDK */\n readonly #core: MultichainCore;\n\n /** An instance of the EIP-1193 provider interface */\n readonly #provider: EIP1193Provider;\n\n /** The session scopes currently permitted */\n #sessionScopes: SessionData['sessionScopes'] = {};\n\n /** Optional event handlers for the EIP-1193 provider events. */\n readonly #eventHandlers?: Partial<EventHandlers> | undefined;\n\n /** The handler for the wallet_sessionChanged event */\n readonly #sessionChangedHandler: (session?: SessionData) => void;\n\n /** The clean-up function for the notification handler */\n #removeNotificationHandler?: () => void;\n\n /**\n * Creates a new MetamaskConnectEVM instance.\n *\n * @param options - The options for the MetamaskConnectEVM instance\n * @param options.core - The core instance of the Multichain SDK\n * @param options.eventHandlers - Optional event handlers for EIP-1193 provider events\n */\n constructor({ core, eventHandlers }: MetamaskConnectEVMOptions) {\n this.#core = core;\n\n this.#provider = new EIP1193Provider(\n core,\n this.#requestInterceptor.bind(this),\n );\n\n this.#eventHandlers = eventHandlers;\n\n /**\n * Handles the wallet_sessionChanged event.\n * Updates the internal connection state with the new session data.\n *\n * @param session - The session data\n */\n this.#sessionChangedHandler = (session): void => {\n logger('event: wallet_sessionChanged', session);\n this.#sessionScopes = session?.sessionScopes ?? {};\n };\n this.#core.on(\n 'wallet_sessionChanged',\n this.#sessionChangedHandler.bind(this),\n );\n\n // Attempt to set the permitted accounts if there's a valid previous session.\n // TODO (wenfix): does it make sense to catch here?\n this.#attemptSessionRecovery().catch((error) => {\n console.error('Error attempting session recovery', error);\n });\n\n logger('Connect/EVM constructor completed');\n }\n\n /**\n * Gets the core options for analytics checks.\n *\n * @returns The multichain options from the core instance\n */\n #getCoreOptions(): MultichainOptions {\n return (this.#core as any).options as MultichainOptions;\n }\n\n /**\n * Creates invoke options for analytics tracking.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n * @returns Invoke options object for analytics\n */\n #createInvokeOptions(\n method: string,\n scope: Scope,\n params: unknown[],\n ): {\n scope: Scope;\n request: { method: string; params: unknown[] };\n } {\n return {\n scope,\n request: { method, params },\n };\n }\n\n /**\n * Tracks a wallet action requested event.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n */\n async #trackWalletActionRequested(\n method: string,\n scope: Scope,\n params: unknown[],\n ): Promise<void> {\n const coreOptions = this.#getCoreOptions();\n try {\n const invokeOptions = this.#createInvokeOptions(method, scope, params);\n const props = await getWalletActionAnalyticsProperties(\n coreOptions,\n this.#core.storage,\n invokeOptions,\n );\n analytics.track('mmconnect_wallet_action_requested', props);\n } catch (error) {\n logger('Error tracking mmconnect_wallet_action_requested event', error);\n }\n }\n\n /**\n * Tracks a wallet action succeeded event.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n */\n async #trackWalletActionSucceeded(\n method: string,\n scope: Scope,\n params: unknown[],\n ): Promise<void> {\n const coreOptions = this.#getCoreOptions();\n try {\n const invokeOptions = this.#createInvokeOptions(method, scope, params);\n const props = await getWalletActionAnalyticsProperties(\n coreOptions,\n this.#core.storage,\n invokeOptions,\n );\n analytics.track('mmconnect_wallet_action_succeeded', props);\n } catch (error) {\n logger('Error tracking mmconnect_wallet_action_succeeded event', error);\n }\n }\n\n /**\n * Tracks a wallet action failed or rejected event based on the error.\n *\n * @param method - The RPC method name\n * @param scope - The CAIP chain ID scope\n * @param params - The method parameters\n * @param error - The error that occurred\n */\n async #trackWalletActionFailed(\n method: string,\n scope: Scope,\n params: unknown[],\n error: unknown,\n ): Promise<void> {\n const coreOptions = this.#getCoreOptions();\n try {\n const invokeOptions = this.#createInvokeOptions(method, scope, params);\n const props = await getWalletActionAnalyticsProperties(\n coreOptions,\n this.#core.storage,\n invokeOptions,\n );\n const isRejection = isRejectionError(error);\n if (isRejection) {\n analytics.track('mmconnect_wallet_action_rejected', props);\n } else {\n analytics.track('mmconnect_wallet_action_failed', props);\n }\n } catch {\n logger('Error tracking wallet action rejected or failed event', error);\n }\n }\n\n /**\n * Connects to the wallet with the specified chain ID and optional account.\n *\n * @param options - The connection options\n * @param options.account - Optional specific account to connect to\n * @param options.forceRequest - Wwhether to force a request regardless of an existing session\n * @param options.chainIds - Array of chain IDs to connect to\n * @returns A promise that resolves with the connected accounts and chain ID\n */\n async connect(\n { account, forceRequest, chainIds }: ConnectOptions = {\n chainIds: [DEFAULT_CHAIN_ID],\n },\n ): Promise<{ accounts: Address[]; chainId: number }> {\n logger('request: connect', { account });\n\n if (!chainIds || chainIds.length === 0) {\n throw new Error('chainIds must be an array of at least one chain ID');\n }\n\n const caipChainIds = Array.from(\n new Set(chainIds.concat(DEFAULT_CHAIN_ID) ?? [DEFAULT_CHAIN_ID]),\n ).map((id) => `eip155:${id}`);\n\n const caipAccountIds = account\n ? caipChainIds.map((caipChainId) => `${caipChainId}:${account}`)\n : [];\n\n await this.#core.connect(\n caipChainIds as Scope[],\n caipAccountIds as CaipAccountId[],\n forceRequest,\n );\n\n const hexPermittedChainIds = getPermittedEthChainIds(this.#sessionScopes);\n const initialChainId = hexPermittedChainIds[0];\n\n const initialAccounts = await this.#core.transport.sendEip1193Message<\n { method: 'eth_accounts'; params: [] },\n { result: string[]; id: number; jsonrpc: '2.0' }\n >({ method: 'eth_accounts', params: [] });\n\n this.#onConnect({\n chainId: initialChainId,\n accounts: initialAccounts.result as Address[],\n });\n\n // Remove previous notification handler if it exists\n this.#removeNotificationHandler?.();\n\n this.#removeNotificationHandler = this.#core.transport.onNotification(\n (notification) => {\n // @ts-expect-error TODO: address this\n if (notification?.method === 'metamask_accountsChanged') {\n // @ts-expect-error TODO: address this\n const accounts = notification?.params;\n logger('transport-event: accountsChanged', accounts);\n this.#onAccountsChanged(accounts);\n }\n\n // @ts-expect-error TODO: address this\n if (notification?.method === 'metamask_chainChanged') {\n // @ts-expect-error TODO: address this\n const notificationChainId = Number(notification?.params?.chainId);\n logger('transport-event: chainChanged', notificationChainId);\n this.#onChainChanged(notificationChainId);\n }\n },\n );\n\n logger('fulfilled-request: connect', {\n chainId: chainIds[0],\n accounts: this.#provider.accounts,\n });\n\n // TODO: update required here since accounts and chainId are now promises\n return {\n accounts: this.#provider.accounts,\n chainId: hexToNumber(initialChainId),\n };\n }\n\n /**\n * Connects to the wallet and signs a message using personal_sign.\n *\n * @param options - The connection options\n * @param options.message - The message to sign after connecting\n * @param options.chainIds - Optional chain IDs to connect to (defaults to ethereum mainnet if not provided)\n * @returns A promise that resolves with the signature\n * @throws Error if the selected account is not available after timeout\n */\n async connectAndSign({\n message,\n chainIds,\n }: {\n message: string;\n chainIds?: number[];\n }): Promise<string> {\n const { accounts, chainId } = await this.connect({\n chainIds: chainIds ?? [DEFAULT_CHAIN_ID],\n });\n\n const result = (await this.#provider.request({\n method: 'personal_sign',\n params: [accounts[0], message],\n })) as string;\n\n this.#eventHandlers?.connectAndSign?.({\n accounts,\n chainId,\n signResponse: result,\n });\n\n return result;\n }\n\n /**\n * Connects to the wallet and invokes a method with specified parameters.\n *\n * @param options - The options for connecting and invoking the method\n * @param options.method - The method name to invoke\n * @param options.params - The parameters to pass to the method, or a function that receives the account and returns params\n * @param options.chainIds - Optional chain IDs to connect to (defaults to ethereum mainnet if not provided)\n * @param options.account - Optional specific account to connect to\n * @param options.forceRequest - Whether to force a request regardless of an existing session\n * @returns A promise that resolves with the result of the method invocation\n * @throws Error if the selected account is not available after timeout (for methods that require an account)\n */\n async connectWith({\n method,\n params,\n chainIds,\n account,\n forceRequest,\n }: {\n method: string;\n params: unknown[] | ((account: Address) => unknown[]);\n chainIds?: number[];\n account?: string | undefined;\n forceRequest?: boolean;\n }): Promise<unknown> {\n const { accounts: connectedAccounts, chainId: connectedChainId } =\n await this.connect({\n chainIds: chainIds ?? [DEFAULT_CHAIN_ID],\n account,\n forceRequest,\n });\n\n const resolvedParams =\n typeof params === 'function' ? params(connectedAccounts[0]) : params;\n\n const result = await this.#provider.request({\n method,\n params: resolvedParams,\n });\n\n this.#eventHandlers?.connectWith?.({\n accounts: connectedAccounts,\n chainId: connectedChainId,\n connectWithResponse: result,\n });\n\n return result;\n }\n\n /**\n * Disconnects from the wallet by revoking the session and cleaning up event listeners.\n *\n * @returns A promise that resolves when disconnection is complete\n */\n async disconnect(): Promise<void> {\n logger('request: disconnect');\n\n await this.#core.disconnect();\n this.#onDisconnect();\n this.#clearConnectionState();\n\n this.#core.off('wallet_sessionChanged', this.#sessionChangedHandler);\n\n if (this.#removeNotificationHandler) {\n this.#removeNotificationHandler();\n this.#removeNotificationHandler = undefined;\n }\n\n logger('fulfilled-request: disconnect');\n }\n\n /**\n * Switches the Ethereum chain. Will track state internally whenever possible.\n *\n * @param options - The options for the switch chain request\n * @param options.chainId - The chain ID to switch to\n * @param options.chainConfiguration - The chain configuration to use in case the chain is not present by the wallet\n * @returns The result of the switch chain request\n */\n async switchChain({\n chainId,\n chainConfiguration,\n }: {\n chainId: number | Hex;\n chainConfiguration?: AddEthereumChainParameter;\n }): Promise<unknown> {\n const method = 'wallet_switchEthereumChain';\n const hexChainId = isHex(chainId) ? chainId : numberToHex(chainId);\n const scope: Scope = `eip155:${isHex(chainId) ? hexToNumber(chainId) : chainId}`;\n const params = [{ chainId: hexChainId }];\n\n await this.#trackWalletActionRequested(method, scope, params);\n\n // TODO (wenfix): better way to return here other than resolving.\n if (this.selectedChainId === hexChainId) {\n return Promise.resolve();\n }\n\n const permittedChainIds = getPermittedEthChainIds(this.#sessionScopes);\n\n if (\n permittedChainIds.includes(hexChainId) &&\n this.#core.transportType === TransportType.MWP\n ) {\n this.#onChainChanged(hexChainId);\n await this.#trackWalletActionSucceeded(method, scope, params);\n return Promise.resolve();\n }\n\n try {\n const result = await this.#request({\n method: 'wallet_switchEthereumChain',\n params,\n });\n\n // When using the MWP transport, the error is returned instead of thrown,\n // so we force it into the catch block here.\n const resultWithError = result as { error?: { message: string } };\n if (resultWithError?.error) {\n throw new Error(resultWithError.error.message);\n }\n\n await this.#trackWalletActionSucceeded(method, scope, params);\n if ((result as { result: unknown }).result === null) {\n // result is successful we eagerly call onChainChanged to update the provider's selected chain ID.\n this.#onChainChanged(hexChainId);\n }\n return result;\n } catch (error) {\n await this.#trackWalletActionFailed(method, scope, params, error);\n // Fallback to add the chain if its not configured in the wallet.\n if ((error as Error).message.includes('Unrecognized chain ID')) {\n return this.#addEthereumChain(chainConfiguration);\n }\n throw error;\n }\n }\n\n /**\n * Handles several EIP-1193 requests that require special handling\n * due the nature of the Multichain SDK.\n *\n * @param request - The request object containing the method and params\n * @returns The result of the request or undefined if the request is ignored\n */\n async #requestInterceptor(\n request: ProviderRequest,\n ): ReturnType<ProviderRequestInterceptor> {\n logger(`Intercepting request for method: ${request.method}`);\n\n if (IGNORED_METHODS.includes(request.method)) {\n // TODO: replace with correct method unsupported provider error\n return Promise.reject(\n new Error(\n `Method: ${request.method} is not supported by Metamask Connect/EVM`,\n ),\n );\n }\n\n if (request.method === 'wallet_revokePermissions') {\n return this.disconnect();\n }\n\n if (isConnectRequest(request)) {\n // When calling wallet_requestPermissions, we need to force a new session request to prompt\n // the user for accounts, because internally the Multichain SDK will check if\n // the user is already connected and skip the request if so, unless we\n // explicitly request a specific account. This is needed to workaround\n // wallet_requestPermissions not requesting specific accounts.\n const shouldForceConnectionRequest =\n request.method === 'wallet_requestPermissions';\n\n const { method, params } = request;\n const initiallySelectedChainId = DEFAULT_CHAIN_ID;\n const scope: Scope = `eip155:${initiallySelectedChainId}`;\n\n await this.#trackWalletActionRequested(method, scope, params);\n\n try {\n const result = await this.connect({\n chainIds: [initiallySelectedChainId],\n forceRequest: shouldForceConnectionRequest,\n });\n await this.#trackWalletActionSucceeded(method, scope, params);\n return result;\n } catch (error) {\n await this.#trackWalletActionFailed(method, scope, params, error);\n throw error;\n }\n }\n\n if (isSwitchChainRequest(request)) {\n return this.switchChain({\n chainId: parseInt(request.params[0].chainId, 16),\n });\n }\n\n if (isAddChainRequest(request)) {\n return this.#addEthereumChain(request.params[0]);\n }\n\n if (isAccountsRequest(request)) {\n const { method } = request;\n const chainId = this.#provider.selectedChainId\n ? hexToNumber(this.#provider.selectedChainId)\n : 1;\n const scope: Scope = `eip155:${chainId}`;\n const params: unknown[] = [];\n\n await this.#trackWalletActionRequested(method, scope, params);\n await this.#trackWalletActionSucceeded(method, scope, params);\n\n return this.#provider.accounts;\n }\n\n logger('Request not intercepted, forwarding to default handler', request);\n return Promise.resolve();\n }\n\n /**\n * Clears the internal connection state: accounts and chainId\n */\n #clearConnectionState(): void {\n this.#provider.accounts = [];\n this.#provider.selectedChainId = undefined as unknown as number;\n }\n\n /**\n * Adds an Ethereum chain using the latest chain configuration received from\n * a switchEthereumChain request\n *\n * @param chainConfiguration - The chain configuration to use in case the chain is not present by the wallet\n * @returns Nothing\n */\n async #addEthereumChain(\n chainConfiguration?: AddEthereumChainParameter,\n ): Promise<void> {\n logger('addEthereumChain called', { chainConfiguration });\n const method = 'wallet_addEthereumChain';\n\n if (!chainConfiguration) {\n throw new Error('No chain configuration found.');\n }\n\n // Get chain ID from config or use current chain\n const chainId = chainConfiguration.chainId\n ? parseInt(chainConfiguration.chainId, 16)\n : hexToNumber(this.#provider.selectedChainId ?? '0x1');\n const scope: Scope = `eip155:${chainId}`;\n const params = [chainConfiguration];\n\n await this.#trackWalletActionRequested(method, scope, params);\n\n try {\n const result = await this.#request({\n method: 'wallet_addEthereumChain',\n params,\n });\n\n if ((result as { result: unknown }).result === null) {\n // if result is successful we eagerly call onChainChanged to update the provider's selected chain ID.\n this.#onChainChanged(chainId);\n }\n await this.#trackWalletActionSucceeded(method, scope, params);\n } catch (error) {\n await this.#trackWalletActionFailed(method, scope, params, error);\n throw error;\n }\n }\n\n /**\n * Submits a request to the EIP-1193 provider\n *\n * @param request - The request object containing the method and params\n * @param request.method - The method to request\n * @param request.params - The parameters to pass to the method\n * @returns The result of the request\n */\n async #request(request: {\n method: string;\n params: unknown[];\n }): Promise<unknown> {\n logger('direct request to metamask-provider called', request);\n const result = this.#core.transport.sendEip1193Message(request);\n if (\n request.method === 'wallet_addEthereumChain' ||\n request.method === 'wallet_switchEthereumChain'\n ) {\n this.#core.openDeeplinkIfNeeded();\n }\n return result;\n }\n\n /**\n * Handles chain change events and updates the provider's selected chain ID.\n *\n * @param chainId - The new chain ID (can be hex string or number)\n */\n #onChainChanged(chainId: Hex | number): void {\n const hexChainId = isHex(chainId) ? chainId : numberToHex(chainId);\n if (hexChainId === this.#provider.selectedChainId) {\n return;\n }\n logger('handler: chainChanged', { chainId });\n this.#provider.selectedChainId = chainId;\n this.#eventHandlers?.chainChanged?.(hexChainId);\n this.#provider.emit('chainChanged', hexChainId);\n }\n\n /**\n * Handles accounts change events and updates the provider's accounts list.\n *\n * @param accounts - The new list of permitted accounts\n */\n #onAccountsChanged(accounts: Address[]): void {\n logger('handler: accountsChanged', accounts);\n this.#provider.accounts = accounts;\n this.#provider.emit('accountsChanged', accounts);\n this.#eventHandlers?.accountsChanged?.(accounts);\n }\n\n /**\n * Handles connection events and emits the connect event to listeners.\n *\n * @param options - The connection options\n * @param options.chainId - The chain ID of the connection (can be hex string or number)\n * @param options.accounts - The accounts of the connection\n */\n #onConnect({\n chainId,\n accounts,\n }: {\n chainId: Hex | number;\n accounts: Address[];\n }): void {\n logger('handler: connect', { chainId, accounts });\n const data = {\n chainId: isHex(chainId) ? chainId : numberToHex(chainId),\n accounts,\n };\n\n this.#provider.emit('connect', data);\n this.#eventHandlers?.connect?.(data);\n\n this.#onChainChanged(chainId);\n this.#onAccountsChanged(accounts);\n }\n\n /**\n * Handles disconnection events and emits the disconnect event to listeners.\n * Also clears accounts by triggering an accountsChanged event with an empty array.\n */\n #onDisconnect(): void {\n logger('handler: disconnect');\n this.#provider.emit('disconnect');\n this.#eventHandlers?.disconnect?.();\n\n this.#onAccountsChanged([]);\n }\n\n /**\n * Will trigger an accountsChanged event if there's a valid previous session.\n * This is needed because the accountsChanged event is not triggered when\n * revising, reloading or opening the app in a new tab.\n *\n * This works by checking by checking events received during MultichainCore initialization,\n * and if there's a wallet_sessionChanged event, it will add a 1-time listener for eth_accounts results\n * and trigger an accountsChanged event if the results are valid accounts.\n */\n async #attemptSessionRecovery(): Promise<void> {\n try {\n const response = await this.#core.transport.request<\n { method: 'wallet_getSession' },\n {\n result: { sessionScopes: Caip25CaveatValue };\n id: number;\n jsonrpc: '2.0';\n }\n >({\n method: 'wallet_getSession',\n });\n\n const { sessionScopes } = response.result;\n\n this.#sessionScopes = sessionScopes;\n const permittedChainIds = getPermittedEthChainIds(sessionScopes);\n\n // Instead of using the accounts we get back from calling `wallet_getSession`\n // we get permitted accounts from `eth_accounts` to make sure we have them ordered by last selected account\n // and correctly set the currently selected account for the dapp\n const permittedAccounts = await this.#core.transport.sendEip1193Message({\n method: 'eth_accounts',\n params: [],\n });\n\n if (permittedChainIds.length && permittedAccounts.result) {\n this.#onConnect({\n chainId: permittedChainIds[0],\n accounts: permittedAccounts.result as Address[],\n });\n }\n } catch (error) {\n console.error('Error attempting session recovery', error);\n }\n }\n\n /**\n * Gets the EIP-1193 provider instance\n *\n * @returns The EIP-1193 provider instance\n */\n getProvider(): EIP1193Provider {\n return this.#provider;\n }\n\n /**\n * Gets the currently selected chain ID on the wallet\n *\n * @returns The currently selected chain ID or undefined if no chain is selected\n */\n getChainId(): Hex | undefined {\n return this.selectedChainId;\n }\n\n /**\n * Gets the currently selected account on the wallet\n *\n * @returns The currently selected account or undefined if no account is selected\n */\n getAccount(): Address | undefined {\n return this.#provider.selectedAccount;\n }\n\n // Convenience getters for the EIP-1193 provider\n /**\n * Gets the currently permitted accounts\n *\n * @returns The currently permitted accounts\n */\n get accounts(): Address[] {\n return this.#provider.accounts;\n }\n\n /**\n * Gets the currently selected account on the wallet\n *\n * @returns The currently selected account or undefined if no account is selected\n */\n get selectedAccount(): Address | undefined {\n return this.#provider.selectedAccount;\n }\n\n /**\n * Gets the currently selected chain ID on the wallet\n *\n * @returns The currently selected chain ID or undefined if no chain is selected\n */\n get selectedChainId(): Hex | undefined {\n return this.#provider.selectedChainId;\n }\n}\n\n/**\n * Creates a new Metamask Connect/EVM instance\n *\n * @param options - The options for the Metamask Connect/EVM layer\n * @param options.dapp - Dapp identification and branding settings\n * @param options.api - API configuration including read-only RPC map\n * @param options.api.supportedNetworks - A map of CAIP chain IDs to RPC URLs for read-only requests\n * @param options.eventEmitter - The event emitter to use for the Metamask Connect/EVM layer\n * @param options.eventHandlers - The event handlers to use for the Metamask Connect/EVM layer\n * @returns The Metamask Connect/EVM layer instance\n */\nexport async function createMetamaskConnectEVM(\n options: Pick<MultichainOptions, 'dapp' | 'api'> & {\n eventHandlers?: Partial<EventHandlers>;\n debug?: boolean;\n },\n): Promise<MetamaskConnectEVM> {\n enableDebug(options.debug);\n\n logger('Creating Metamask Connect/EVM with options:', options);\n\n // Validate that supportedNetworks is provided and not empty\n if (\n !options.api?.supportedNetworks ||\n Object.keys(options.api.supportedNetworks).length === 0\n ) {\n throw new Error(\n 'supportedNetworks is required and must contain at least one chain configuration',\n );\n }\n\n validSupportedChainsUrls(options.api.supportedNetworks, 'supportedNetworks');\n\n try {\n const core = await createMetamaskConnect({\n ...options,\n api: {\n supportedNetworks: options.api.supportedNetworks,\n },\n });\n\n return new MetamaskConnectEVM({\n core,\n eventHandlers: options.eventHandlers,\n supportedNetworks: options.api.supportedNetworks,\n });\n } catch (error) {\n console.error('Error creating Metamask Connect/EVM', error);\n throw error;\n }\n}\n","export const IGNORED_METHODS = [\n 'metamask_getProviderState',\n 'metamask_sendDomainMetadata',\n 'metamask_logWeb3ShimUsage',\n 'wallet_registerOnboarding',\n 'net_version',\n 'wallet_getPermissions',\n];\n\nexport const CONNECT_METHODS = [\n 'wallet_requestPermissions',\n 'eth_requestAccounts',\n];\n\nexport const ACCOUNTS_METHODS = ['eth_accounts', 'eth_coinbase'];\n\nexport const INTERCEPTABLE_METHODS = [\n ...ACCOUNTS_METHODS,\n ...IGNORED_METHODS,\n ...CONNECT_METHODS,\n // These have bespoke handlers\n 'wallet_revokePermissions',\n 'wallet_switchEthereumChain',\n 'wallet_addEthereumChain',\n];\n","import {\n createLogger,\n enableDebug as debug,\n} from '@metamask/connect-multichain';\n\nconst namespace = 'metamask-connect:evm';\n\n// @ts-expect-error logger needs to be typed properly\nexport const logger = createLogger(namespace, '63');\n\nexport const enableDebug = (debugEnabled: boolean = false): void => {\n if (debugEnabled) {\n // @ts-expect-error logger needs to be typed properly\n debug(namespace);\n }\n};\n","import type { MultichainCore, Scope } from '@metamask/connect-multichain';\nimport { EventEmitter } from '@metamask/connect-multichain';\nimport { hexToNumber, numberToHex } from '@metamask/utils';\n\nimport { INTERCEPTABLE_METHODS } from './constants';\nimport { logger } from './logger';\nimport type {\n Address,\n EIP1193ProviderEvents,\n Hex,\n ProviderRequest,\n ProviderRequestInterceptor,\n} from './types';\n\n/**\n * EIP-1193 Provider wrapper around the Multichain SDK.\n */\nexport class EIP1193Provider extends EventEmitter<EIP1193ProviderEvents> {\n /** The core instance of the Multichain SDK */\n readonly #core: MultichainCore;\n\n /** Interceptor function to handle specific methods */\n readonly #requestInterceptor: ProviderRequestInterceptor;\n\n /** The currently permitted accounts */\n #accounts: Address[] = [];\n\n /** The currently selected chain ID on the wallet */\n #selectedChainId?: Hex | undefined;\n\n constructor(core: MultichainCore, interceptor: ProviderRequestInterceptor) {\n super();\n this.#core = core;\n this.#requestInterceptor = interceptor;\n }\n\n /**\n * Performs a EIP-1193 request.\n *\n * @param request - The request object containing the method and params\n * @returns The result of the request\n */\n async request(request: ProviderRequest): Promise<unknown> {\n logger(\n `request: ${request.method} - chainId: ${this.selectedChainId}`,\n request.params,\n );\n /* Some methods require special handling, so we intercept them here\n * and handle them in MetamaskConnectEVM.requestInterceptor method. */\n if (INTERCEPTABLE_METHODS.includes(request.method)) {\n return this.#requestInterceptor?.(request);\n }\n\n if (!this.#selectedChainId) {\n // TODO: replace with a better error\n throw new Error('No chain ID selected');\n }\n\n const chainId = hexToNumber(this.#selectedChainId);\n const scope: Scope = `eip155:${chainId}`;\n\n // Validate that the chain is configured in supportedNetworks\n // This check is performed here to provide better error messages\n // The RpcClient will also validate, but this gives us a chance to provide\n // a clearer error message before the request is routed\n const coreOptions = (this.#core as any).options; // TODO: options is `protected readonly` property, this needs to be refactored so `any` type assertion is not necessary\n const supportedNetworks = coreOptions?.api?.supportedNetworks ?? {};\n if (!supportedNetworks[scope]) {\n throw new Error(\n `Chain ${scope} is not configured in supportedNetworks. Requests cannot be made to chains not explicitly configured in supportedNetworks.`,\n );\n }\n\n return this.#core.invokeMethod({\n scope,\n request: {\n method: request.method,\n params: request.params,\n },\n });\n }\n\n // Getters and setters\n public get selectedAccount(): Address | undefined {\n return this.accounts[0];\n }\n\n public set accounts(accounts: Address[]) {\n this.#accounts = accounts;\n }\n\n public get accounts(): Address[] {\n return this.#accounts;\n }\n\n public get selectedChainId(): Hex | undefined {\n return this.#selectedChainId;\n }\n\n public set selectedChainId(chainId: Hex | number | undefined) {\n const hexChainId =\n chainId && typeof chainId === 'number' ? numberToHex(chainId) : chainId;\n\n // Don't overwrite the selected chain ID with an undefined value\n if (!hexChainId) {\n return;\n }\n\n this.#selectedChainId = hexChainId as Hex;\n }\n}\n","import type { InternalScopesObject } from '@metamask/chain-agnostic-permission';\nimport {\n getPermittedEthChainIds as _getPermittedEthChainIds,\n getEthAccounts as _getEthAccounts,\n} from '@metamask/chain-agnostic-permission';\nimport type { SessionData } from '@metamask/connect-multichain';\n\nimport type { Address, Hex } from '../types';\n\n/**\n * Get the Ethereum accounts from the session data\n *\n * @param sessionScopes - The session scopes\n * @returns The Ethereum accounts\n */\nexport const getEthAccounts = (\n sessionScopes: SessionData['sessionScopes'] | undefined,\n): Address[] => {\n if (!sessionScopes) {\n return [];\n }\n\n return _getEthAccounts({\n requiredScopes: sessionScopes as InternalScopesObject,\n optionalScopes: sessionScopes as InternalScopesObject,\n });\n};\n\n/**\n * Get the permitted Ethereum chain IDs from the session scopes.\n * Wrapper around getPermittedEthChainIds from @metamask/chain-agnostic-permission\n *\n * @param sessionScopes - The session scopes\n * @returns The permitted Ethereum chain IDs\n */\nexport const getPermittedEthChainIds = (\n sessionScopes: SessionData['sessionScopes'] | undefined,\n): Hex[] => {\n if (!sessionScopes) {\n return [];\n }\n\n return _getPermittedEthChainIds({\n requiredScopes: sessionScopes as InternalScopesObject,\n optionalScopes: sessionScopes as InternalScopesObject,\n });\n};\n","import type { ProviderRequest } from '../types';\n\n/**\n * Type guard for connect-like requests:\n * - wallet_requestPermissions\n * - eth_requestAccounts\n *\n * @param req - The request object to check\n * @returns True if the request is a connect-like request, false otherwise\n */\nexport function isConnectRequest(req: ProviderRequest): req is Extract<\n ProviderRequest,\n {\n method: 'wallet_requestPermissions' | 'eth_requestAccounts';\n }\n> {\n return (\n req.method === 'wallet_requestPermissions' ||\n req.method === 'eth_requestAccounts'\n );\n}\n\n/**\n * Type guard for wallet_switchEthereumChain request.\n *\n * @param req - The request object to check\n * @returns True if the request is a wallet_switchEthereumChain request, false otherwise\n */\nexport function isSwitchChainRequest(\n req: ProviderRequest,\n): req is Extract<ProviderRequest, { method: 'wallet_switchEthereumChain' }> {\n return req.method === 'wallet_switchEthereumChain';\n}\n\n/**\n * Type guard for wallet_addEthereumChain request.\n *\n * @param req - The request object to check\n * @returns True if the request is a wallet_addEthereumChain request, false otherwise\n */\nexport function isAddChainRequest(\n req: ProviderRequest,\n): req is Extract<ProviderRequest, { method: 'wallet_addEthereumChain' }> {\n return req.method === 'wallet_addEthereumChain';\n}\n\n/**\n * Type guard for generic accounts request:\n * - eth_accounts\n * - eth_coinbase\n *\n * @param req - The request object to check\n * @returns True if the request is a generic accounts request, false otherwise\n */\nexport function isAccountsRequest(\n req: ProviderRequest,\n): req is Extract<\n ProviderRequest,\n { method: 'eth_accounts' | 'eth_coinbase' }\n> {\n return req.method === 'eth_accounts' || req.method === 'eth_coinbase';\n}\n\n/**\n * Validates that all values in a Record are valid URLs.\n *\n * @param record - The record to validate (e.g., supportedNetworks)\n * @param recordName - The name of the record for error messages\n * @throws Error if any values are invalid URLs\n */\nexport function validSupportedChainsUrls(\n record: Record<string, string>,\n recordName: string,\n): void {\n const invalidUrls: string[] = [];\n for (const [key, url] of Object.entries(record)) {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n } catch {\n invalidUrls.push(`${key}: ${url}`);\n }\n }\n\n if (invalidUrls.length > 0) {\n throw new Error(\n `${recordName} contains invalid URLs:\\n${invalidUrls.join('\\n')}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,wBAAwB;;;ACAjC,SAAS,iBAAiB;AAQ1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE,eAAAA;AAAA,EACA,eAAAC;AAAA,EACA,eAAe;AAAA,OACV;;;AClBA,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AACF;AAEO,IAAM,mBAAmB,CAAC,gBAAgB,cAAc;AAExD,IAAM,wBAAwB;AAAA,EACnC,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA;AAAA,EAEH;AAAA,EACA;AAAA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