@metamask/connect-multichain 0.3.2 → 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.
Files changed (88) hide show
  1. package/CHANGELOG.md +55 -15
  2. package/README.md +1 -1
  3. package/dist/browser/es/connect-multichain.d.mts +26 -12
  4. package/dist/browser/es/connect-multichain.mjs +846 -598
  5. package/dist/browser/es/connect-multichain.mjs.map +1 -1
  6. package/dist/browser/es/metafile-esm.json +1 -1
  7. package/dist/browser/iife/connect-multichain.d.ts +26 -12
  8. package/dist/browser/iife/connect-multichain.js +4793 -2291
  9. package/dist/browser/iife/connect-multichain.js.map +1 -1
  10. package/dist/browser/iife/metafile-iife.json +1 -1
  11. package/dist/browser/umd/connect-multichain.d.ts +26 -12
  12. package/dist/browser/umd/connect-multichain.js +846 -598
  13. package/dist/browser/umd/connect-multichain.js.map +1 -1
  14. package/dist/browser/umd/metafile-cjs.json +1 -1
  15. package/dist/node/cjs/connect-multichain.d.ts +26 -12
  16. package/dist/node/cjs/connect-multichain.js +846 -609
  17. package/dist/node/cjs/connect-multichain.js.map +1 -1
  18. package/dist/node/cjs/metafile-cjs.json +1 -1
  19. package/dist/node/es/connect-multichain.d.mts +26 -12
  20. package/dist/node/es/connect-multichain.mjs +844 -607
  21. package/dist/node/es/connect-multichain.mjs.map +1 -1
  22. package/dist/node/es/metafile-esm.json +1 -1
  23. package/dist/react-native/es/connect-multichain.d.mts +26 -12
  24. package/dist/react-native/es/connect-multichain.mjs +827 -592
  25. package/dist/react-native/es/connect-multichain.mjs.map +1 -1
  26. package/dist/react-native/es/metafile-esm.json +1 -1
  27. package/dist/src/domain/multichain/index.d.ts +4 -4
  28. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  29. package/dist/src/domain/multichain/index.js.map +1 -1
  30. package/dist/src/domain/multichain/types.d.ts +4 -6
  31. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  32. package/dist/src/domain/ui/types.d.ts +7 -0
  33. package/dist/src/domain/ui/types.d.ts.map +1 -1
  34. package/dist/src/domain/ui/types.js.map +1 -1
  35. package/dist/src/index.browser.d.ts +1 -1
  36. package/dist/src/index.browser.d.ts.map +1 -1
  37. package/dist/src/index.browser.js +1 -1
  38. package/dist/src/index.browser.js.map +1 -1
  39. package/dist/src/index.native.d.ts +1 -1
  40. package/dist/src/index.native.d.ts.map +1 -1
  41. package/dist/src/index.native.js +2 -2
  42. package/dist/src/index.native.js.map +1 -1
  43. package/dist/src/index.node.d.ts +1 -1
  44. package/dist/src/index.node.d.ts.map +1 -1
  45. package/dist/src/index.node.js +1 -1
  46. package/dist/src/index.node.js.map +1 -1
  47. package/dist/src/multichain/index.d.ts +8 -27
  48. package/dist/src/multichain/index.d.ts.map +1 -1
  49. package/dist/src/multichain/index.js +480 -427
  50. package/dist/src/multichain/index.js.map +1 -1
  51. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -1
  52. package/dist/src/multichain/rpc/requestRouter.js +8 -15
  53. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  54. package/dist/src/multichain/transports/default/index.d.ts +2 -1
  55. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  56. package/dist/src/multichain/transports/default/index.js +1 -0
  57. package/dist/src/multichain/transports/default/index.js.map +1 -1
  58. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +21 -0
  59. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -0
  60. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +159 -0
  61. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -0
  62. package/dist/src/multichain/transports/mwp/index.d.ts +4 -1
  63. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  64. package/dist/src/multichain/transports/mwp/index.js +76 -6
  65. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  66. package/dist/src/ui/ModalFactory.d.ts +54 -0
  67. package/dist/src/ui/ModalFactory.d.ts.map +1 -0
  68. package/dist/src/ui/ModalFactory.js +171 -0
  69. package/dist/src/ui/ModalFactory.js.map +1 -0
  70. package/dist/src/ui/index.d.ts +11 -39
  71. package/dist/src/ui/index.d.ts.map +1 -1
  72. package/dist/src/ui/index.js +20 -179
  73. package/dist/src/ui/index.js.map +1 -1
  74. package/dist/src/ui/index.native.d.ts +13 -0
  75. package/dist/src/ui/index.native.d.ts.map +1 -0
  76. package/dist/src/ui/index.native.js +24 -0
  77. package/dist/src/ui/index.native.js.map +1 -0
  78. package/dist/src/ui/modals/base/AbstractInstallModal.d.ts.map +1 -1
  79. package/dist/src/ui/modals/base/AbstractInstallModal.js +0 -4
  80. package/dist/src/ui/modals/base/AbstractInstallModal.js.map +1 -1
  81. package/dist/src/ui/modals/node/install.js +2 -2
  82. package/dist/src/ui/modals/node/install.js.map +1 -1
  83. package/dist/types/connect-multichain.d.ts +26 -12
  84. package/package.json +10 -8
  85. package/dist/src/ui/qr.d.ts +0 -3
  86. package/dist/src/ui/qr.d.ts.map +0 -1
  87. package/dist/src/ui/qr.js +0 -32
  88. package/dist/src/ui/qr.js.map +0 -1
@@ -1,20 +1,3 @@
1
- /* eslint-disable consistent-return */
2
- /* eslint-disable no-else-return */
3
- /* eslint-disable promise/no-return-wrap */
4
- /* eslint-disable promise/always-return */
5
- /* eslint-disable promise/catch-or-return */
6
- /* eslint-disable no-async-promise-executor */
7
- /* eslint-disable no-negated-condition */
8
- /* eslint-disable @typescript-eslint/prefer-promise-reject-errors */
9
- /* eslint-disable promise/param-names */
10
- /* eslint-disable @typescript-eslint/no-floating-promises */
11
- /* eslint-disable @typescript-eslint/promise-function-async */
12
- /* eslint-disable @typescript-eslint/explicit-function-return-type */
13
- /* eslint-disable no-restricted-globals */
14
- /* eslint-disable @typescript-eslint/no-misused-promises */
15
- /* eslint-disable @typescript-eslint/naming-convention */
16
- /* eslint-disable no-restricted-syntax */
17
- /** biome-ignore-all lint/suspicious/noAsyncPromiseExecutor: <explanation> */
18
1
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
2
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
3
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -24,6 +7,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
24
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
25
8
  });
26
9
  };
10
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
11
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
12
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
13
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
14
+ };
15
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
16
+ if (kind === "m") throw new TypeError("Private method is not writable");
17
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
18
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
19
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
20
+ };
21
+ var _MultichainSDK_instances, _MultichainSDK_provider, _MultichainSDK_providerTransportWrapper, _MultichainSDK_transport, _MultichainSDK_dappClient, _MultichainSDK_beforeUnloadListener, _MultichainSDK_listener, _MultichainSDK_sdkInfo, _MultichainSDK_setupAnalytics, _MultichainSDK_onTransportNotification, _MultichainSDK_getStoredTransport, _MultichainSDK_setupTransport, _MultichainSDK_init, _MultichainSDK_createDappClient, _MultichainSDK_setupMWP, _MultichainSDK_onBeforeUnload, _MultichainSDK_createBeforeUnloadListener, _MultichainSDK_renderInstallModalAsync, _MultichainSDK_showInstallModal, _MultichainSDK_headlessConnect, _MultichainSDK_setupDefaultTransport, _MultichainSDK_deeplinkConnect, _MultichainSDK_handleConnection;
22
+ /* eslint-disable @typescript-eslint/no-misused-promises */
23
+ /* eslint-disable @typescript-eslint/naming-convention */
24
+ /* eslint-disable no-restricted-globals */
27
25
  import { analytics } from '@metamask/analytics';
28
26
  import { ErrorCode, ProtocolError, SessionStore, WebSocketTransport, } from '@metamask/mobile-wallet-protocol-core';
29
27
  import { DappClient } from '@metamask/mobile-wallet-protocol-dapp-client';
@@ -40,67 +38,62 @@ import { DefaultTransport } from './transports/default';
40
38
  import { MWPTransport } from './transports/mwp';
41
39
  import { keymanager } from './transports/mwp/KeyManager';
42
40
  import { getDappId, openDeeplink, setupDappMetadata } from './utils';
41
+ import { MultichainApiClientWrapperTransport } from './transports/multichainApiClientWrapper';
43
42
  export { getInfuraRpcUrls } from '../domain/multichain/api/infura';
44
43
  // ENFORCE NAMESPACE THAT CAN BE DISABLED
45
44
  const logger = createLogger('metamask-sdk:core');
46
45
  export class MultichainSDK extends MultichainCore {
47
- get state() {
48
- return this.__state;
46
+ get status() {
47
+ return this._status;
49
48
  }
50
- set state(value) {
49
+ set status(value) {
51
50
  var _a, _b;
52
- this.__state = value;
51
+ this._status = value;
53
52
  (_b = (_a = this.options.transport) === null || _a === void 0 ? void 0 : _a.onNotification) === null || _b === void 0 ? void 0 : _b.call(_a, {
54
53
  method: 'stateChanged',
55
54
  params: value,
56
55
  });
57
56
  }
58
57
  get provider() {
59
- if (!this.__provider && this.__transport) {
60
- this.__provider = getMultichainClient({ transport: this.__transport });
61
- return this.__provider;
62
- }
63
- if (!this.__provider) {
64
- throw new Error('Provider not initialized, establish connection first');
65
- }
66
- return this.__provider;
58
+ return __classPrivateFieldGet(this, _MultichainSDK_provider, "f");
67
59
  }
68
60
  get transport() {
69
- if (!this.__transport) {
61
+ if (!__classPrivateFieldGet(this, _MultichainSDK_transport, "f")) {
70
62
  throw new Error('Transport not initialized, establish connection first');
71
63
  }
72
- return this.__transport;
64
+ return __classPrivateFieldGet(this, _MultichainSDK_transport, "f");
73
65
  }
74
66
  get dappClient() {
75
- if (!this.__dappClient) {
67
+ if (!__classPrivateFieldGet(this, _MultichainSDK_dappClient, "f")) {
76
68
  throw new Error('DappClient not initialized, establish connection first');
77
69
  }
78
- return this.__dappClient;
70
+ return __classPrivateFieldGet(this, _MultichainSDK_dappClient, "f");
79
71
  }
80
72
  get storage() {
81
73
  return this.options.storage;
82
74
  }
83
75
  get transportType() {
84
- return this.__transport instanceof MWPTransport
76
+ return __classPrivateFieldGet(this, _MultichainSDK_transport, "f") instanceof MWPTransport
85
77
  ? TransportType.MWP
86
78
  : TransportType.Browser;
87
79
  }
88
- get sdkInfo() {
89
- var _a;
90
- return `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) !== null && _a !== void 0 ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`;
91
- }
92
80
  constructor(options) {
93
81
  var _a, _b, _c, _d, _e, _f, _g;
94
82
  const withDappMetadata = setupDappMetadata(options);
95
- const integrationType = ((_a = options.analytics) === null || _a === void 0 ? void 0 : _a.enabled)
96
- ? options.analytics.integrationType
97
- : 'direct';
98
- const allOptions = Object.assign(Object.assign({}, withDappMetadata), { ui: Object.assign(Object.assign({}, withDappMetadata.ui), { preferExtension: (_b = withDappMetadata.ui.preferExtension) !== null && _b !== void 0 ? _b : true, showInstallModal: (_c = withDappMetadata.ui.showInstallModal) !== null && _c !== void 0 ? _c : false, headless: (_d = withDappMetadata.ui.headless) !== null && _d !== void 0 ? _d : false }), analytics: Object.assign(Object.assign({}, ((_e = options.analytics) !== null && _e !== void 0 ? _e : {})), { enabled: (_g = (_f = options.analytics) === null || _f === void 0 ? void 0 : _f.enabled) !== null && _g !== void 0 ? _g : true, integrationType }) });
83
+ const integrationType = (_b = (_a = options.analytics) === null || _a === void 0 ? void 0 : _a.integrationType) !== null && _b !== void 0 ? _b : 'direct';
84
+ const allOptions = Object.assign(Object.assign({}, withDappMetadata), { ui: Object.assign(Object.assign({}, withDappMetadata.ui), { preferExtension: (_c = withDappMetadata.ui.preferExtension) !== null && _c !== void 0 ? _c : true, showInstallModal: (_d = withDappMetadata.ui.showInstallModal) !== null && _d !== void 0 ? _d : false, headless: (_e = withDappMetadata.ui.headless) !== null && _e !== void 0 ? _e : false }), analytics: Object.assign(Object.assign({}, ((_f = options.analytics) !== null && _f !== void 0 ? _f : {})), { integrationType }) });
99
85
  super(allOptions);
100
- this.__provider = undefined;
101
- this.__transport = undefined;
102
- this.__dappClient = undefined;
103
- this.__state = 'pending';
86
+ _MultichainSDK_instances.add(this);
87
+ _MultichainSDK_provider.set(this, void 0);
88
+ _MultichainSDK_providerTransportWrapper.set(this, void 0);
89
+ _MultichainSDK_transport.set(this, undefined);
90
+ _MultichainSDK_dappClient.set(this, undefined);
91
+ _MultichainSDK_beforeUnloadListener.set(this, void 0);
92
+ this._status = 'pending';
93
+ _MultichainSDK_listener.set(this, void 0);
94
+ _MultichainSDK_sdkInfo.set(this, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_g = this.options.dapp.url) !== null && _g !== void 0 ? _g : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
95
+ __classPrivateFieldSet(this, _MultichainSDK_providerTransportWrapper, new MultichainApiClientWrapperTransport(this), "f");
96
+ __classPrivateFieldSet(this, _MultichainSDK_provider, getMultichainClient({ transport: __classPrivateFieldGet(this, _MultichainSDK_providerTransportWrapper, "f") }), "f");
104
97
  }
105
98
  static create(options) {
106
99
  return __awaiter(this, void 0, void 0, function* () {
@@ -109,355 +102,17 @@ export class MultichainSDK extends MultichainCore {
109
102
  if (isEnabled) {
110
103
  enableDebug('metamask-sdk:core');
111
104
  }
112
- yield instance.init();
105
+ yield __classPrivateFieldGet(instance, _MultichainSDK_instances, "m", _MultichainSDK_init).call(instance);
113
106
  return instance;
114
107
  });
115
108
  }
116
- setupAnalytics() {
117
- return __awaiter(this, void 0, void 0, function* () {
118
- var _a, _b;
119
- if (!((_a = this.options.analytics) === null || _a === void 0 ? void 0 : _a.enabled)) {
120
- return;
121
- }
122
- const platform = getPlatformType();
123
- const isBrowser = platform === PlatformType.MetaMaskMobileWebview ||
124
- platform === PlatformType.DesktopWeb ||
125
- platform === PlatformType.MobileWeb;
126
- const isReactNative = platform === PlatformType.ReactNative;
127
- if (!isBrowser && !isReactNative) {
128
- return;
129
- }
130
- const version = getVersion();
131
- const dappId = getDappId(this.options.dapp);
132
- const anonId = yield this.storage.getAnonId();
133
- const { integrationType } = (_b = this.options.analytics) !== null && _b !== void 0 ? _b : {
134
- integrationType: '',
135
- };
136
- analytics.setGlobalProperty('mmconnect_version', version);
137
- analytics.setGlobalProperty('dapp_id', dappId);
138
- analytics.setGlobalProperty('anon_id', anonId);
139
- analytics.setGlobalProperty('platform', platform);
140
- analytics.setGlobalProperty('integration_type', integrationType);
141
- analytics.enable();
142
- });
143
- }
144
- onTransportNotification(payload) {
109
+ // TODO: make this into param object
110
+ connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
145
111
  return __awaiter(this, void 0, void 0, function* () {
146
112
  var _a;
147
- if (typeof payload === 'object' &&
148
- payload !== null &&
149
- 'method' in payload) {
150
- this.emit(payload.method, (_a = payload.params) !== null && _a !== void 0 ? _a : payload.result);
113
+ if (this.status !== 'connected') {
114
+ yield this.disconnect();
151
115
  }
152
- });
153
- }
154
- getStoredTransport() {
155
- return __awaiter(this, void 0, void 0, function* () {
156
- const transportType = yield this.storage.getTransport();
157
- const hasExtensionInstalled = yield hasExtension();
158
- if (transportType) {
159
- if (transportType === TransportType.Browser) {
160
- if (hasExtensionInstalled) {
161
- const apiTransport = new DefaultTransport();
162
- this.__transport = apiTransport;
163
- this.listener = apiTransport.onNotification(this.onTransportNotification.bind(this));
164
- return apiTransport;
165
- }
166
- }
167
- else if (transportType === TransportType.MWP) {
168
- const { adapter: kvstore } = this.options.storage;
169
- const dappClient = yield this.createDappClient();
170
- const apiTransport = new MWPTransport(dappClient, kvstore);
171
- this.__dappClient = dappClient;
172
- this.__transport = apiTransport;
173
- this.listener = apiTransport.onNotification(this.onTransportNotification.bind(this));
174
- return apiTransport;
175
- }
176
- yield this.storage.removeTransport();
177
- }
178
- return undefined;
179
- });
180
- }
181
- setupTransport() {
182
- return __awaiter(this, void 0, void 0, function* () {
183
- const transport = yield this.getStoredTransport();
184
- if (transport) {
185
- if (!this.transport.isConnected()) {
186
- this.state = 'connecting';
187
- yield this.transport.connect();
188
- }
189
- this.state = 'connected';
190
- if (this.transport instanceof MWPTransport) {
191
- yield this.storage.setTransport(TransportType.MWP);
192
- }
193
- else {
194
- yield this.storage.setTransport(TransportType.Browser);
195
- }
196
- }
197
- else {
198
- this.state = 'loaded';
199
- }
200
- });
201
- }
202
- init() {
203
- return __awaiter(this, void 0, void 0, function* () {
204
- var _a, _b;
205
- try {
206
- // @ts-expect-error mmsdk should be accessible
207
- if (typeof window !== 'undefined' && ((_a = window.mmsdk) === null || _a === void 0 ? void 0 : _a.isInitialized)) {
208
- logger('MetaMaskSDK: init already initialized');
209
- }
210
- else {
211
- yield this.setupAnalytics();
212
- yield this.setupTransport();
213
- if ((_b = this.options.analytics) === null || _b === void 0 ? void 0 : _b.enabled) {
214
- try {
215
- const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
216
- analytics.track('mmconnect_initialized', baseProps);
217
- }
218
- catch (error) {
219
- logger('Error tracking initialized event', error);
220
- }
221
- }
222
- if (typeof window !== 'undefined') {
223
- // @ts-expect-error mmsdk should be accessible
224
- window.mmsdk = this;
225
- }
226
- }
227
- }
228
- catch (error) {
229
- yield this.storage.removeTransport();
230
- this.state = 'pending';
231
- logger('MetaMaskSDK error during initialization', error);
232
- }
233
- });
234
- }
235
- createDappClient() {
236
- return __awaiter(this, void 0, void 0, function* () {
237
- const { adapter: kvstore } = this.options.storage;
238
- const sessionstore = new SessionStore(kvstore);
239
- const websocket =
240
- // eslint-disable-next-line no-negated-condition
241
- typeof window !== 'undefined'
242
- ? WebSocket
243
- : (yield import('ws')).WebSocket;
244
- const transport = yield WebSocketTransport.create({
245
- url: MWP_RELAY_URL,
246
- kvstore,
247
- websocket,
248
- });
249
- const dappClient = new DappClient({ transport, sessionstore, keymanager });
250
- return dappClient;
251
- });
252
- }
253
- setupMWP() {
254
- return __awaiter(this, void 0, void 0, function* () {
255
- if (this.__transport instanceof MWPTransport) {
256
- return;
257
- }
258
- // Only setup MWP if it is not already mwp
259
- const { adapter: kvstore } = this.options.storage;
260
- const dappClient = yield this.createDappClient();
261
- this.__dappClient = dappClient;
262
- const apiTransport = new MWPTransport(dappClient, kvstore);
263
- this.__transport = apiTransport;
264
- this.listener = this.transport.onNotification(this.onTransportNotification.bind(this));
265
- yield this.storage.setTransport(TransportType.MWP);
266
- });
267
- }
268
- onBeforeUnload() {
269
- return __awaiter(this, void 0, void 0, function* () {
270
- var _a;
271
- // Fixes glitch with "connecting" state when modal is still visible and we close screen or refresh
272
- if ((_a = this.options.ui.factory.modal) === null || _a === void 0 ? void 0 : _a.isMounted) {
273
- yield this.storage.removeTransport();
274
- }
275
- });
276
- }
277
- createBeforeUnloadListener() {
278
- if (typeof window !== 'undefined' &&
279
- typeof window.addEventListener !== 'undefined') {
280
- window.addEventListener('beforeunload', this.onBeforeUnload.bind(this));
281
- }
282
- return () => {
283
- if (typeof window !== 'undefined' &&
284
- typeof window.removeEventListener !== 'undefined') {
285
- window.removeEventListener('beforeunload', this.onBeforeUnload.bind(this));
286
- }
287
- };
288
- }
289
- showInstallModal(desktopPreferred, scopes, caipAccountIds) {
290
- return __awaiter(this, void 0, void 0, function* () {
291
- var _a;
292
- // create the listener only once to avoid memory leaks
293
- (_a = this.__beforeUnloadListener) !== null && _a !== void 0 ? _a : (this.__beforeUnloadListener = this.createBeforeUnloadListener());
294
- return new Promise((resolve, reject) => {
295
- // Use Connection Modal
296
- this.options.ui.factory.renderInstallModal(desktopPreferred, () => __awaiter(this, void 0, void 0, function* () {
297
- if (this.dappClient.state === 'CONNECTED' ||
298
- this.dappClient.state === 'CONNECTING') {
299
- yield this.dappClient.disconnect();
300
- }
301
- return new Promise((resolveConnectionRequest) => {
302
- this.dappClient.on('session_request', (sessionRequest) => {
303
- resolveConnectionRequest({
304
- sessionRequest,
305
- metadata: {
306
- dapp: this.options.dapp,
307
- sdk: {
308
- version: getVersion(),
309
- platform: getPlatformType(),
310
- },
311
- },
312
- });
313
- });
314
- this.transport
315
- .connect({ scopes, caipAccountIds })
316
- .then(() => {
317
- var _a;
318
- this.options.ui.factory.unload();
319
- (_a = this.options.ui.factory.modal) === null || _a === void 0 ? void 0 : _a.unmount();
320
- this.state = 'connected';
321
- return this.storage.setTransport(TransportType.MWP);
322
- })
323
- .catch((error) => {
324
- if (error instanceof ProtocolError) {
325
- // Ignore Request expired errors to allow modal to regenerate expired qr codes
326
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
327
- this.state = 'disconnected';
328
- reject(error);
329
- }
330
- // If request is expires, the QRCode will automatically be regenerated we can ignore this case
331
- }
332
- else {
333
- this.state = 'disconnected';
334
- reject(error);
335
- }
336
- });
337
- });
338
- }), (error) => __awaiter(this, void 0, void 0, function* () {
339
- if (!error) {
340
- yield this.storage.setTransport(TransportType.MWP);
341
- resolve();
342
- }
343
- else {
344
- yield this.storage.removeTransport();
345
- reject(error);
346
- }
347
- }));
348
- });
349
- });
350
- }
351
- setupDefaultTransport() {
352
- return __awaiter(this, void 0, void 0, function* () {
353
- this.state = 'connecting';
354
- yield this.storage.setTransport(TransportType.Browser);
355
- const transport = new DefaultTransport();
356
- this.listener = transport.onNotification(this.onTransportNotification.bind(this));
357
- this.__transport = transport;
358
- return transport;
359
- });
360
- }
361
- deeplinkConnect(scopes, caipAccountIds) {
362
- return __awaiter(this, void 0, void 0, function* () {
363
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
364
- this.dappClient.on('message', (payload) => {
365
- var _a, _b, _c;
366
- const data = payload.data;
367
- if (typeof data === 'object' && data !== null) {
368
- if ('method' in data && data.method === 'wallet_createSession') {
369
- if (data.error) {
370
- this.state = 'loaded';
371
- return reject(data.error);
372
- }
373
- // TODO: is it .params or .result?
374
- const session = ((_a = data.params) !== null && _a !== void 0 ? _a : data.result);
375
- if (session) {
376
- // Initial request will be what resolves the connection when options is specified
377
- (_c = (_b = this.options.transport) === null || _b === void 0 ? void 0 : _b.onNotification) === null || _c === void 0 ? void 0 : _c.call(_b, payload.data);
378
- this.emit('wallet_sessionChanged', session);
379
- }
380
- }
381
- }
382
- });
383
- let timeout;
384
- if (!this.transport.isConnected()) {
385
- this.dappClient.once('session_request', (sessionRequest) => {
386
- var _a;
387
- const connectionRequest = {
388
- sessionRequest,
389
- metadata: {
390
- dapp: this.options.dapp,
391
- sdk: { version: getVersion(), platform: getPlatformType() },
392
- },
393
- };
394
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
395
- const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
396
- if ((_a = this.options.mobile) === null || _a === void 0 ? void 0 : _a.preferredOpenLink) {
397
- this.options.mobile.preferredOpenLink(deeplink, '_self');
398
- }
399
- else {
400
- openDeeplink(this.options, deeplink, universalLink);
401
- }
402
- });
403
- }
404
- this.transport
405
- .connect({ scopes, caipAccountIds })
406
- .then(resolve)
407
- .catch((error) => {
408
- this.storage.removeTransport();
409
- reject(error);
410
- })
411
- .finally(() => {
412
- if (timeout) {
413
- clearTimeout(timeout);
414
- }
415
- });
416
- }));
417
- });
418
- }
419
- handleConnection(promise, scopes, transportType) {
420
- return __awaiter(this, void 0, void 0, function* () {
421
- this.state = 'connecting';
422
- return promise
423
- .then(() => __awaiter(this, void 0, void 0, function* () {
424
- var _a;
425
- this.state = 'connected';
426
- if ((_a = this.options.analytics) === null || _a === void 0 ? void 0 : _a.enabled) {
427
- try {
428
- const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
429
- analytics.track('mmconnect_connection_established', Object.assign(Object.assign({}, baseProps), { transport_type: transportType, user_permissioned_chains: scopes }));
430
- }
431
- catch (error) {
432
- logger('Error tracking connection_established event', error);
433
- }
434
- }
435
- }))
436
- .catch((error) => __awaiter(this, void 0, void 0, function* () {
437
- var _a;
438
- this.state = 'disconnected';
439
- if ((_a = this.options.analytics) === null || _a === void 0 ? void 0 : _a.enabled) {
440
- try {
441
- const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
442
- const isRejection = isRejectionError(error);
443
- if (isRejection) {
444
- analytics.track('mmconnect_connection_rejected', Object.assign(Object.assign({}, baseProps), { transport_type: transportType }));
445
- }
446
- else {
447
- analytics.track('mmconnect_connection_failed', Object.assign(Object.assign({}, baseProps), { transport_type: transportType }));
448
- }
449
- }
450
- catch (_b) {
451
- logger('Error tracking connection failed/rejected event', error);
452
- }
453
- }
454
- return Promise.reject(error);
455
- }));
456
- });
457
- }
458
- connect(scopes, caipAccountIds, forceRequest) {
459
- return __awaiter(this, void 0, void 0, function* () {
460
- var _a, _b;
461
116
  const { ui } = this.options;
462
117
  const platformType = getPlatformType();
463
118
  const isWeb = platformType === PlatformType.MetaMaskMobileWebview ||
@@ -473,51 +128,47 @@ export class MultichainSDK extends MultichainCore {
473
128
  else {
474
129
  transportType = TransportType.MWP;
475
130
  }
476
- if ((_a = this.options.analytics) === null || _a === void 0 ? void 0 : _a.enabled) {
477
- try {
478
- const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
479
- const dappConfiguredChains = Object.keys(this.options.api.supportedNetworks);
480
- analytics.track('mmconnect_connection_initiated', Object.assign(Object.assign({}, baseProps), { transport_type: transportType, dapp_configured_chains: dappConfiguredChains, dapp_requested_chains: scopes }));
481
- }
482
- catch (error) {
483
- logger('Error tracking connection_initiated event', error);
484
- }
131
+ try {
132
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
133
+ const dappConfiguredChains = Object.keys(this.options.api.supportedNetworks);
134
+ analytics.track('mmconnect_connection_initiated', Object.assign(Object.assign({}, baseProps), { transport_type: transportType, dapp_configured_chains: dappConfiguredChains, dapp_requested_chains: scopes }));
135
+ }
136
+ catch (error) {
137
+ logger('Error tracking connection_initiated event', error);
485
138
  }
486
- if (((_b = this.__transport) === null || _b === void 0 ? void 0 : _b.isConnected()) && !secure) {
487
- return this.handleConnection(this.__transport
488
- .connect({ scopes, caipAccountIds, forceRequest })
489
- .then(() => {
490
- if (this.__transport instanceof MWPTransport) {
139
+ if (((_a = __classPrivateFieldGet(this, _MultichainSDK_transport, "f")) === null || _a === void 0 ? void 0 : _a.isConnected()) && !secure) {
140
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, __classPrivateFieldGet(this, _MultichainSDK_transport, "f")
141
+ .connect({ scopes, caipAccountIds, sessionProperties, forceRequest })
142
+ .then(() => __awaiter(this, void 0, void 0, function* () {
143
+ if (__classPrivateFieldGet(this, _MultichainSDK_transport, "f") instanceof MWPTransport) {
491
144
  return this.storage.setTransport(TransportType.MWP);
492
145
  }
493
- else {
494
- return this.storage.setTransport(TransportType.Browser);
495
- }
496
- }), scopes, transportType);
146
+ return this.storage.setTransport(TransportType.Browser);
147
+ })), scopes, transportType);
497
148
  }
498
149
  // In MetaMask Mobile In App Browser, window.ethereum is available directly
499
150
  if (platformType === PlatformType.MetaMaskMobileWebview) {
500
- const defaultTransport = yield this.setupDefaultTransport();
501
- return this.handleConnection(defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
151
+ const defaultTransport = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupDefaultTransport).call(this);
152
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, defaultTransport.connect({ scopes, caipAccountIds, sessionProperties, forceRequest }), scopes, transportType);
502
153
  }
503
154
  if (isWeb && hasExtensionInstalled && preferExtension) {
504
155
  // If metamask extension is available, connect to it
505
- const defaultTransport = yield this.setupDefaultTransport();
156
+ const defaultTransport = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupDefaultTransport).call(this);
506
157
  // Web transport has no initial payload
507
- return this.handleConnection(defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
158
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, defaultTransport.connect({ scopes, caipAccountIds, sessionProperties, forceRequest }), scopes, transportType);
508
159
  }
509
160
  // Connection will now be InstallModal + QRCodes or Deeplinks, both require mwp
510
- yield this.setupMWP();
161
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupMWP).call(this);
511
162
  // Determine preferred option for install modal
512
163
  const shouldShowInstallModal = hasExtensionInstalled
513
164
  ? showInstallModal
514
165
  : !preferExtension || showInstallModal;
515
166
  if (secure && !shouldShowInstallModal) {
516
167
  // Desktop is not preferred option, so we use deeplinks (mobile web)
517
- return this.handleConnection(this.deeplinkConnect(scopes, caipAccountIds), scopes, transportType);
168
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_deeplinkConnect).call(this, scopes, caipAccountIds, sessionProperties), scopes, transportType);
518
169
  }
519
170
  // Show install modal for RN, Web + Node
520
- return this.handleConnection(this.showInstallModal(shouldShowInstallModal, scopes, caipAccountIds), scopes, transportType);
171
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_showInstallModal).call(this, shouldShowInstallModal, scopes, caipAccountIds, sessionProperties), scopes, transportType);
521
172
  });
522
173
  }
523
174
  emit(event, args) {
@@ -528,26 +179,24 @@ export class MultichainSDK extends MultichainCore {
528
179
  disconnect() {
529
180
  return __awaiter(this, void 0, void 0, function* () {
530
181
  var _a, _b, _c;
531
- (_a = this.listener) === null || _a === void 0 ? void 0 : _a.call(this);
532
- (_b = this.__beforeUnloadListener) === null || _b === void 0 ? void 0 : _b.call(this);
533
- yield ((_c = this.__transport) === null || _c === void 0 ? void 0 : _c.disconnect());
182
+ yield ((_a = __classPrivateFieldGet(this, _MultichainSDK_listener, "f")) === null || _a === void 0 ? void 0 : _a.call(this));
183
+ (_b = __classPrivateFieldGet(this, _MultichainSDK_beforeUnloadListener, "f")) === null || _b === void 0 ? void 0 : _b.call(this);
184
+ yield ((_c = __classPrivateFieldGet(this, _MultichainSDK_transport, "f")) === null || _c === void 0 ? void 0 : _c.disconnect());
534
185
  yield this.storage.removeTransport();
535
- this.emit('wallet_sessionChanged', undefined);
536
186
  this.emit('stateChanged', 'disconnected');
537
- this.listener = undefined;
538
- this.__beforeUnloadListener = undefined;
539
- this.__transport = undefined;
540
- this.__provider = undefined;
541
- this.__dappClient = undefined;
187
+ __classPrivateFieldSet(this, _MultichainSDK_listener, undefined, "f");
188
+ __classPrivateFieldSet(this, _MultichainSDK_beforeUnloadListener, undefined, "f");
189
+ __classPrivateFieldSet(this, _MultichainSDK_transport, undefined, "f");
190
+ __classPrivateFieldGet(this, _MultichainSDK_providerTransportWrapper, "f").clearNotificationCallbacks();
191
+ __classPrivateFieldSet(this, _MultichainSDK_dappClient, undefined, "f");
542
192
  });
543
193
  }
544
194
  invokeMethod(request) {
545
195
  return __awaiter(this, void 0, void 0, function* () {
546
- var _a;
547
- const { sdkInfo, transport, options } = this;
548
- (_a = this.__provider) !== null && _a !== void 0 ? _a : (this.__provider = getMultichainClient({ transport }));
549
- const rpcClient = new RpcClient(options, sdkInfo);
196
+ const { transport, options } = this;
197
+ const rpcClient = new RpcClient(options, __classPrivateFieldGet(this, _MultichainSDK_sdkInfo, "f"));
550
198
  const requestRouter = new RequestRouter(transport, rpcClient, options);
199
+ // TODO: need read only method support for solana
551
200
  return requestRouter.invokeMethod(request);
552
201
  });
553
202
  }
@@ -574,4 +223,408 @@ export class MultichainSDK extends MultichainCore {
574
223
  }
575
224
  }
576
225
  }
226
+ _MultichainSDK_provider = new WeakMap(), _MultichainSDK_providerTransportWrapper = new WeakMap(), _MultichainSDK_transport = new WeakMap(), _MultichainSDK_dappClient = new WeakMap(), _MultichainSDK_beforeUnloadListener = new WeakMap(), _MultichainSDK_listener = new WeakMap(), _MultichainSDK_sdkInfo = new WeakMap(), _MultichainSDK_instances = new WeakSet(), _MultichainSDK_setupAnalytics = function _MultichainSDK_setupAnalytics() {
227
+ return __awaiter(this, void 0, void 0, function* () {
228
+ var _a;
229
+ const platform = getPlatformType();
230
+ const isBrowser = platform === PlatformType.MetaMaskMobileWebview ||
231
+ platform === PlatformType.DesktopWeb ||
232
+ platform === PlatformType.MobileWeb;
233
+ const isReactNative = platform === PlatformType.ReactNative;
234
+ if (!isBrowser && !isReactNative) {
235
+ return;
236
+ }
237
+ const version = getVersion();
238
+ const dappId = getDappId(this.options.dapp);
239
+ const anonId = yield this.storage.getAnonId();
240
+ const { integrationType } = (_a = this.options.analytics) !== null && _a !== void 0 ? _a : {
241
+ integrationType: '',
242
+ };
243
+ analytics.setGlobalProperty('mmconnect_version', version);
244
+ analytics.setGlobalProperty('dapp_id', dappId);
245
+ analytics.setGlobalProperty('anon_id', anonId);
246
+ analytics.setGlobalProperty('platform', platform);
247
+ analytics.setGlobalProperty('integration_type', integrationType);
248
+ analytics.enable();
249
+ });
250
+ }, _MultichainSDK_onTransportNotification = function _MultichainSDK_onTransportNotification(payload) {
251
+ return __awaiter(this, void 0, void 0, function* () {
252
+ var _a;
253
+ if (typeof payload === 'object' &&
254
+ payload !== null &&
255
+ 'method' in payload) {
256
+ this.emit(payload.method, (_a = payload.params) !== null && _a !== void 0 ? _a : payload.result);
257
+ }
258
+ });
259
+ }, _MultichainSDK_getStoredTransport = function _MultichainSDK_getStoredTransport() {
260
+ return __awaiter(this, void 0, void 0, function* () {
261
+ const transportType = yield this.storage.getTransport();
262
+ const hasExtensionInstalled = yield hasExtension();
263
+ if (transportType) {
264
+ if (transportType === TransportType.Browser) {
265
+ if (hasExtensionInstalled) {
266
+ const apiTransport = new DefaultTransport();
267
+ __classPrivateFieldSet(this, _MultichainSDK_transport, apiTransport, "f");
268
+ __classPrivateFieldGet(this, _MultichainSDK_providerTransportWrapper, "f").setupNotifcationListener();
269
+ __classPrivateFieldSet(this, _MultichainSDK_listener, apiTransport.onNotification(__classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onTransportNotification).bind(this)), "f");
270
+ return apiTransport;
271
+ }
272
+ }
273
+ else if (transportType === TransportType.MWP) {
274
+ const { adapter: kvstore } = this.options.storage;
275
+ const dappClient = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_createDappClient).call(this);
276
+ const apiTransport = new MWPTransport(dappClient, kvstore);
277
+ __classPrivateFieldSet(this, _MultichainSDK_dappClient, dappClient, "f");
278
+ __classPrivateFieldSet(this, _MultichainSDK_transport, apiTransport, "f");
279
+ __classPrivateFieldGet(this, _MultichainSDK_providerTransportWrapper, "f").setupNotifcationListener();
280
+ __classPrivateFieldSet(this, _MultichainSDK_listener, apiTransport.onNotification(__classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onTransportNotification).bind(this)), "f");
281
+ return apiTransport;
282
+ }
283
+ yield this.storage.removeTransport();
284
+ }
285
+ return undefined;
286
+ });
287
+ }, _MultichainSDK_setupTransport = function _MultichainSDK_setupTransport() {
288
+ return __awaiter(this, void 0, void 0, function* () {
289
+ const transport = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_getStoredTransport).call(this);
290
+ if (transport) {
291
+ if (!this.transport.isConnected()) {
292
+ this.status = 'connecting';
293
+ yield this.transport.connect();
294
+ }
295
+ this.status = 'connected';
296
+ if (this.transport instanceof MWPTransport) {
297
+ yield this.storage.setTransport(TransportType.MWP);
298
+ }
299
+ else {
300
+ yield this.storage.setTransport(TransportType.Browser);
301
+ }
302
+ }
303
+ else {
304
+ this.status = 'loaded';
305
+ }
306
+ });
307
+ }, _MultichainSDK_init = function _MultichainSDK_init() {
308
+ return __awaiter(this, void 0, void 0, function* () {
309
+ var _a;
310
+ try {
311
+ // @ts-expect-error mmsdk should be accessible
312
+ if (typeof window !== 'undefined' && ((_a = window.mmsdk) === null || _a === void 0 ? void 0 : _a.isInitialized)) {
313
+ logger('MetaMaskSDK: init already initialized');
314
+ }
315
+ else {
316
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupAnalytics).call(this);
317
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupTransport).call(this);
318
+ try {
319
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
320
+ analytics.track('mmconnect_initialized', baseProps);
321
+ }
322
+ catch (error) {
323
+ logger('Error tracking initialized event', error);
324
+ }
325
+ if (typeof window !== 'undefined') {
326
+ // @ts-expect-error mmsdk should be accessible
327
+ window.mmsdk = this;
328
+ }
329
+ }
330
+ }
331
+ catch (error) {
332
+ yield this.storage.removeTransport();
333
+ this.status = 'pending';
334
+ logger('MetaMaskSDK error during initialization', error);
335
+ }
336
+ });
337
+ }, _MultichainSDK_createDappClient = function _MultichainSDK_createDappClient() {
338
+ return __awaiter(this, void 0, void 0, function* () {
339
+ const { adapter: kvstore } = this.options.storage;
340
+ const sessionstore = new SessionStore(kvstore);
341
+ const websocket =
342
+ // eslint-disable-next-line no-negated-condition
343
+ typeof window !== 'undefined'
344
+ ? WebSocket
345
+ : (yield import('ws')).WebSocket;
346
+ const transport = yield WebSocketTransport.create({
347
+ url: MWP_RELAY_URL,
348
+ kvstore,
349
+ websocket,
350
+ });
351
+ const dappClient = new DappClient({ transport, sessionstore, keymanager });
352
+ return dappClient;
353
+ });
354
+ }, _MultichainSDK_setupMWP = function _MultichainSDK_setupMWP() {
355
+ return __awaiter(this, void 0, void 0, function* () {
356
+ if (__classPrivateFieldGet(this, _MultichainSDK_transport, "f") instanceof MWPTransport) {
357
+ return;
358
+ }
359
+ // Only setup MWP if it is not already mwp
360
+ const { adapter: kvstore } = this.options.storage;
361
+ const dappClient = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_createDappClient).call(this);
362
+ __classPrivateFieldSet(this, _MultichainSDK_dappClient, dappClient, "f");
363
+ const apiTransport = new MWPTransport(dappClient, kvstore);
364
+ __classPrivateFieldSet(this, _MultichainSDK_transport, apiTransport, "f");
365
+ __classPrivateFieldGet(this, _MultichainSDK_providerTransportWrapper, "f").setupNotifcationListener();
366
+ __classPrivateFieldSet(this, _MultichainSDK_listener, this.transport.onNotification(__classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onTransportNotification).bind(this)), "f");
367
+ yield this.storage.setTransport(TransportType.MWP);
368
+ });
369
+ }, _MultichainSDK_onBeforeUnload = function _MultichainSDK_onBeforeUnload() {
370
+ return __awaiter(this, void 0, void 0, function* () {
371
+ var _a;
372
+ // Fixes glitch with "connecting" state when modal is still visible and we close screen or refresh
373
+ if ((_a = this.options.ui.factory.modal) === null || _a === void 0 ? void 0 : _a.isMounted) {
374
+ yield this.storage.removeTransport();
375
+ }
376
+ });
377
+ }, _MultichainSDK_createBeforeUnloadListener = function _MultichainSDK_createBeforeUnloadListener() {
378
+ if (typeof window !== 'undefined' &&
379
+ typeof window.addEventListener !== 'undefined') {
380
+ window.addEventListener('beforeunload', __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onBeforeUnload).bind(this));
381
+ }
382
+ return () => {
383
+ if (typeof window !== 'undefined' &&
384
+ typeof window.removeEventListener !== 'undefined') {
385
+ window.removeEventListener('beforeunload', __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onBeforeUnload).bind(this));
386
+ }
387
+ };
388
+ }, _MultichainSDK_renderInstallModalAsync = function _MultichainSDK_renderInstallModalAsync(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
389
+ return __awaiter(this, void 0, void 0, function* () {
390
+ return new Promise((resolve, reject) => {
391
+ // Use Connection Modal
392
+ this.options.ui.factory
393
+ .renderInstallModal(desktopPreferred, () => __awaiter(this, void 0, void 0, function* () {
394
+ if (this.dappClient.state === 'CONNECTED' ||
395
+ this.dappClient.state === 'CONNECTING') {
396
+ yield this.dappClient.disconnect();
397
+ }
398
+ return new Promise((_resolve) => {
399
+ this.dappClient.on('session_request', (sessionRequest) => {
400
+ _resolve({
401
+ sessionRequest,
402
+ metadata: {
403
+ dapp: this.options.dapp,
404
+ sdk: {
405
+ version: getVersion(),
406
+ platform: getPlatformType(),
407
+ },
408
+ },
409
+ });
410
+ });
411
+ (() => __awaiter(this, void 0, void 0, function* () {
412
+ var _a;
413
+ try {
414
+ yield this.transport.connect({ scopes, caipAccountIds, sessionProperties });
415
+ yield this.options.ui.factory.unload();
416
+ (_a = this.options.ui.factory.modal) === null || _a === void 0 ? void 0 : _a.unmount();
417
+ this.status = 'connected';
418
+ yield this.storage.setTransport(TransportType.MWP);
419
+ }
420
+ catch (error) {
421
+ if (error instanceof ProtocolError) {
422
+ // Ignore Request expired errors to allow modal to regenerate expired qr codes
423
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
424
+ this.status = 'disconnected';
425
+ reject(error);
426
+ }
427
+ // If request is expires, the QRCode will automatically be regenerated we can ignore this case
428
+ }
429
+ else {
430
+ this.status = 'disconnected';
431
+ reject(error instanceof Error ? error : new Error(String(error)));
432
+ }
433
+ }
434
+ }))().catch(() => {
435
+ // Error already handled in the async function
436
+ });
437
+ });
438
+ }), (error) => __awaiter(this, void 0, void 0, function* () {
439
+ if (error) {
440
+ yield this.storage.removeTransport();
441
+ reject(error);
442
+ }
443
+ else {
444
+ yield this.storage.setTransport(TransportType.MWP);
445
+ resolve();
446
+ }
447
+ }), (uri) => {
448
+ this.emit('display_uri', uri);
449
+ })
450
+ .catch((error) => {
451
+ reject(error instanceof Error ? error : new Error(String(error)));
452
+ });
453
+ });
454
+ });
455
+ }, _MultichainSDK_showInstallModal = function _MultichainSDK_showInstallModal(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
456
+ return __awaiter(this, void 0, void 0, function* () {
457
+ var _a;
458
+ // create the listener only once to avoid memory leaks
459
+ __classPrivateFieldSet(this, _MultichainSDK_beforeUnloadListener, (_a = __classPrivateFieldGet(this, _MultichainSDK_beforeUnloadListener, "f")) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_createBeforeUnloadListener).call(this), "f");
460
+ // In headless mode, don't render UI but still emit display_uri events
461
+ if (this.options.ui.headless) {
462
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_headlessConnect).call(this, scopes, caipAccountIds, sessionProperties);
463
+ }
464
+ else {
465
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_renderInstallModalAsync).call(this, desktopPreferred, scopes, caipAccountIds, sessionProperties);
466
+ }
467
+ });
468
+ }, _MultichainSDK_headlessConnect = function _MultichainSDK_headlessConnect(scopes, caipAccountIds, sessionProperties) {
469
+ return __awaiter(this, void 0, void 0, function* () {
470
+ return new Promise((resolve, reject) => {
471
+ if (this.dappClient.state === 'CONNECTED' ||
472
+ this.dappClient.state === 'CONNECTING') {
473
+ this.dappClient.disconnect().catch(() => {
474
+ // Ignore disconnect errors
475
+ });
476
+ }
477
+ // Listen for session_request to generate and emit the QR code link
478
+ this.dappClient.on('session_request', (sessionRequest) => {
479
+ const connectionRequest = {
480
+ sessionRequest,
481
+ metadata: {
482
+ dapp: this.options.dapp,
483
+ sdk: {
484
+ version: getVersion(),
485
+ platform: getPlatformType(),
486
+ },
487
+ },
488
+ };
489
+ // Generate and emit the QR code link
490
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
491
+ this.emit('display_uri', deeplink);
492
+ });
493
+ // Start the connection
494
+ this.transport
495
+ .connect({ scopes, caipAccountIds, sessionProperties })
496
+ .then(() => __awaiter(this, void 0, void 0, function* () {
497
+ this.status = 'connected';
498
+ yield this.storage.setTransport(TransportType.MWP);
499
+ resolve();
500
+ }))
501
+ .catch((error) => __awaiter(this, void 0, void 0, function* () {
502
+ if (error instanceof ProtocolError) {
503
+ // In headless mode, we don't auto-regenerate QR codes
504
+ // since there's no modal to display them
505
+ this.status = 'disconnected';
506
+ yield this.storage.removeTransport();
507
+ reject(error);
508
+ }
509
+ else {
510
+ this.status = 'disconnected';
511
+ yield this.storage.removeTransport();
512
+ reject(error instanceof Error ? error : new Error(String(error)));
513
+ }
514
+ }));
515
+ });
516
+ });
517
+ }, _MultichainSDK_setupDefaultTransport = function _MultichainSDK_setupDefaultTransport() {
518
+ return __awaiter(this, void 0, void 0, function* () {
519
+ this.status = 'connecting';
520
+ yield this.storage.setTransport(TransportType.Browser);
521
+ const transport = new DefaultTransport();
522
+ __classPrivateFieldSet(this, _MultichainSDK_listener, transport.onNotification(__classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onTransportNotification).bind(this)), "f");
523
+ __classPrivateFieldSet(this, _MultichainSDK_transport, transport, "f");
524
+ __classPrivateFieldGet(this, _MultichainSDK_providerTransportWrapper, "f").setupNotifcationListener();
525
+ return transport;
526
+ });
527
+ }, _MultichainSDK_deeplinkConnect = function _MultichainSDK_deeplinkConnect(scopes, caipAccountIds, sessionProperties) {
528
+ return __awaiter(this, void 0, void 0, function* () {
529
+ return new Promise((resolve, reject) => {
530
+ // Handle the response to the initial wallet_createSession request
531
+ const dappClientMessageHandler = (payload) => {
532
+ var _a;
533
+ if (typeof payload !== 'object' ||
534
+ payload === null ||
535
+ !('data' in payload)) {
536
+ return;
537
+ }
538
+ const data = payload.data;
539
+ if (typeof data === 'object' && data !== null) {
540
+ // optimistically assume any error is due to the initial wallet_createSession request failure
541
+ if (data.error) {
542
+ this.dappClient.off('message', dappClientMessageHandler);
543
+ reject(data.error);
544
+ }
545
+ // if sessionScopes is set in the result, then this is a response to wallet_createSession
546
+ if ((_a = data === null || data === void 0 ? void 0 : data.result) === null || _a === void 0 ? void 0 : _a.sessionScopes) {
547
+ this.dappClient.off('message', dappClientMessageHandler);
548
+ // unsure if we need to call resolve here like we do above for reject()
549
+ }
550
+ }
551
+ };
552
+ this.dappClient.on('message', dappClientMessageHandler);
553
+ let timeout;
554
+ if (this.transport.isConnected()) {
555
+ timeout = setTimeout(() => {
556
+ this.openDeeplinkIfNeeded();
557
+ }, 250);
558
+ }
559
+ else {
560
+ this.dappClient.once('session_request', (sessionRequest) => {
561
+ var _a;
562
+ const connectionRequest = {
563
+ sessionRequest,
564
+ metadata: {
565
+ dapp: this.options.dapp,
566
+ sdk: { version: getVersion(), platform: getPlatformType() },
567
+ },
568
+ };
569
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
570
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
571
+ // Emit display_uri event for deeplink connections
572
+ this.emit('display_uri', deeplink);
573
+ if ((_a = this.options.mobile) === null || _a === void 0 ? void 0 : _a.preferredOpenLink) {
574
+ this.options.mobile.preferredOpenLink(deeplink, '_self');
575
+ }
576
+ else {
577
+ openDeeplink(this.options, deeplink, universalLink);
578
+ }
579
+ });
580
+ }
581
+ return this.transport
582
+ .connect({ scopes, caipAccountIds, sessionProperties })
583
+ .then(resolve)
584
+ .catch((error) => __awaiter(this, void 0, void 0, function* () {
585
+ yield this.storage.removeTransport();
586
+ this.dappClient.off('message', dappClientMessageHandler);
587
+ reject(error instanceof Error ? error : new Error(String(error)));
588
+ }))
589
+ .finally(() => {
590
+ if (timeout) {
591
+ clearTimeout(timeout);
592
+ }
593
+ });
594
+ });
595
+ });
596
+ }, _MultichainSDK_handleConnection = function _MultichainSDK_handleConnection(promise, scopes, transportType) {
597
+ return __awaiter(this, void 0, void 0, function* () {
598
+ this.status = 'connecting';
599
+ return promise
600
+ .then(() => __awaiter(this, void 0, void 0, function* () {
601
+ this.status = 'connected';
602
+ try {
603
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
604
+ analytics.track('mmconnect_connection_established', Object.assign(Object.assign({}, baseProps), { transport_type: transportType, user_permissioned_chains: scopes }));
605
+ }
606
+ catch (error) {
607
+ logger('Error tracking connection_established event', error);
608
+ }
609
+ return undefined; // explicitly return `undefined` to avoid eslintpromise/always-return
610
+ }))
611
+ .catch((error) => __awaiter(this, void 0, void 0, function* () {
612
+ this.status = 'disconnected';
613
+ try {
614
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
615
+ const isRejection = isRejectionError(error);
616
+ if (isRejection) {
617
+ analytics.track('mmconnect_connection_rejected', Object.assign(Object.assign({}, baseProps), { transport_type: transportType }));
618
+ }
619
+ else {
620
+ analytics.track('mmconnect_connection_failed', Object.assign(Object.assign({}, baseProps), { transport_type: transportType }));
621
+ }
622
+ }
623
+ catch (_a) {
624
+ logger('Error tracking connection failed/rejected event', error);
625
+ }
626
+ throw error;
627
+ }));
628
+ });
629
+ };
577
630
  //# sourceMappingURL=index.js.map