@metamask/connect-multichain 0.3.1 → 0.4.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 (61) hide show
  1. package/CHANGELOG.md +35 -13
  2. package/README.md +1 -1
  3. package/dist/browser/es/connect-multichain.d.mts +4 -6
  4. package/dist/browser/es/connect-multichain.mjs +593 -588
  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 +4 -6
  8. package/dist/browser/iife/connect-multichain.js +3821 -2109
  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 +4 -6
  12. package/dist/browser/umd/connect-multichain.js +593 -588
  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 +4 -6
  16. package/dist/node/cjs/connect-multichain.js +594 -600
  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 +4 -6
  20. package/dist/node/es/connect-multichain.mjs +593 -599
  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 +4 -6
  24. package/dist/react-native/es/connect-multichain.mjs +580 -584
  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/types.d.ts +2 -4
  28. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  29. package/dist/src/multichain/index.d.ts +3 -22
  30. package/dist/src/multichain/index.d.ts.map +1 -1
  31. package/dist/src/multichain/index.js +422 -424
  32. package/dist/src/multichain/index.js.map +1 -1
  33. package/dist/src/multichain/rpc/requestRouter.js +17 -19
  34. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  35. package/dist/src/multichain/transports/default/index.d.ts +2 -0
  36. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  37. package/dist/src/multichain/transports/default/index.js +6 -0
  38. package/dist/src/multichain/transports/default/index.js.map +1 -1
  39. package/dist/src/multichain/transports/mwp/index.d.ts +2 -1
  40. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  41. package/dist/src/multichain/transports/mwp/index.js +41 -16
  42. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  43. package/dist/src/ui/index.d.ts +2 -6
  44. package/dist/src/ui/index.d.ts.map +1 -1
  45. package/dist/src/ui/index.js +8 -49
  46. package/dist/src/ui/index.js.map +1 -1
  47. package/dist/src/ui/modals/node/install.js +2 -2
  48. package/dist/src/ui/modals/node/install.js.map +1 -1
  49. package/dist/src/ui/preload.native.d.ts +5 -0
  50. package/dist/src/ui/preload.native.d.ts.map +1 -0
  51. package/dist/src/ui/preload.native.js +18 -0
  52. package/dist/src/ui/preload.native.js.map +1 -0
  53. package/dist/src/ui/preload.web.d.ts +5 -0
  54. package/dist/src/ui/preload.web.d.ts.map +1 -0
  55. package/dist/src/ui/{qr.js → preload.web.js} +13 -18
  56. package/dist/src/ui/preload.web.js.map +1 -0
  57. package/dist/types/connect-multichain.d.ts +4 -6
  58. package/package.json +7 -7
  59. package/dist/src/ui/qr.d.ts +0 -3
  60. package/dist/src/ui/qr.d.ts.map +0 -1
  61. 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_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_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';
@@ -45,62 +43,60 @@ export { getInfuraRpcUrls } from '../domain/multichain/api/infura';
45
43
  const logger = createLogger('metamask-sdk:core');
46
44
  export class MultichainSDK extends MultichainCore {
47
45
  get state() {
48
- return this.__state;
46
+ return this._state;
49
47
  }
50
48
  set state(value) {
51
49
  var _a, _b;
52
- this.__state = value;
50
+ this._state = value;
53
51
  (_b = (_a = this.options.transport) === null || _a === void 0 ? void 0 : _a.onNotification) === null || _b === void 0 ? void 0 : _b.call(_a, {
54
52
  method: 'stateChanged',
55
53
  params: value,
56
54
  });
57
55
  }
58
56
  get provider() {
59
- if (!this.__provider && this.__transport) {
60
- this.__provider = getMultichainClient({ transport: this.__transport });
61
- return this.__provider;
57
+ if (!__classPrivateFieldGet(this, _MultichainSDK_provider, "f") && __classPrivateFieldGet(this, _MultichainSDK_transport, "f")) {
58
+ __classPrivateFieldSet(this, _MultichainSDK_provider, getMultichainClient({ transport: __classPrivateFieldGet(this, _MultichainSDK_transport, "f") }), "f");
59
+ return __classPrivateFieldGet(this, _MultichainSDK_provider, "f");
62
60
  }
63
- if (!this.__provider) {
61
+ if (!__classPrivateFieldGet(this, _MultichainSDK_provider, "f")) {
64
62
  throw new Error('Provider not initialized, establish connection first');
65
63
  }
66
- return this.__provider;
64
+ return __classPrivateFieldGet(this, _MultichainSDK_provider, "f");
67
65
  }
68
66
  get transport() {
69
- if (!this.__transport) {
67
+ if (!__classPrivateFieldGet(this, _MultichainSDK_transport, "f")) {
70
68
  throw new Error('Transport not initialized, establish connection first');
71
69
  }
72
- return this.__transport;
70
+ return __classPrivateFieldGet(this, _MultichainSDK_transport, "f");
73
71
  }
74
72
  get dappClient() {
75
- if (!this.__dappClient) {
73
+ if (!__classPrivateFieldGet(this, _MultichainSDK_dappClient, "f")) {
76
74
  throw new Error('DappClient not initialized, establish connection first');
77
75
  }
78
- return this.__dappClient;
76
+ return __classPrivateFieldGet(this, _MultichainSDK_dappClient, "f");
79
77
  }
80
78
  get storage() {
81
79
  return this.options.storage;
82
80
  }
83
81
  get transportType() {
84
- return this.__transport instanceof MWPTransport
82
+ return __classPrivateFieldGet(this, _MultichainSDK_transport, "f") instanceof MWPTransport
85
83
  ? TransportType.MWP
86
84
  : TransportType.Browser;
87
85
  }
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
86
  constructor(options) {
93
87
  var _a, _b, _c, _d, _e, _f, _g;
94
88
  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 }) });
89
+ const integrationType = (_b = (_a = options.analytics) === null || _a === void 0 ? void 0 : _a.integrationType) !== null && _b !== void 0 ? _b : 'direct';
90
+ 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
91
  super(allOptions);
100
- this.__provider = undefined;
101
- this.__transport = undefined;
102
- this.__dappClient = undefined;
103
- this.__state = 'pending';
92
+ _MultichainSDK_instances.add(this);
93
+ _MultichainSDK_provider.set(this, undefined);
94
+ _MultichainSDK_transport.set(this, undefined);
95
+ _MultichainSDK_dappClient.set(this, undefined);
96
+ _MultichainSDK_beforeUnloadListener.set(this, void 0);
97
+ this._state = 'pending';
98
+ _MultichainSDK_listener.set(this, void 0);
99
+ _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}`);
104
100
  }
105
101
  static create(options) {
106
102
  return __awaiter(this, void 0, void 0, function* () {
@@ -109,355 +105,16 @@ export class MultichainSDK extends MultichainCore {
109
105
  if (isEnabled) {
110
106
  enableDebug('metamask-sdk:core');
111
107
  }
112
- yield instance.init();
108
+ yield __classPrivateFieldGet(instance, _MultichainSDK_instances, "m", _MultichainSDK_init).call(instance);
113
109
  return instance;
114
110
  });
115
111
  }
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) {
145
- return __awaiter(this, void 0, void 0, function* () {
146
- 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);
151
- }
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() {
112
+ connect(scopes, caipAccountIds, forceRequest) {
269
113
  return __awaiter(this, void 0, void 0, function* () {
270
114
  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();
115
+ if (this.state !== 'connected') {
116
+ yield this.disconnect();
274
117
  }
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.createDeeplink(connectionRequest);
395
- const universalLink = this.options.ui.factory.createUniversalLink(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
118
  const { ui } = this.options;
462
119
  const platformType = getPlatformType();
463
120
  const isWeb = platformType === PlatformType.MetaMaskMobileWebview ||
@@ -473,51 +130,47 @@ export class MultichainSDK extends MultichainCore {
473
130
  else {
474
131
  transportType = TransportType.MWP;
475
132
  }
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
- }
133
+ try {
134
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
135
+ const dappConfiguredChains = Object.keys(this.options.api.supportedNetworks);
136
+ analytics.track('mmconnect_connection_initiated', Object.assign(Object.assign({}, baseProps), { transport_type: transportType, dapp_configured_chains: dappConfiguredChains, dapp_requested_chains: scopes }));
137
+ }
138
+ catch (error) {
139
+ logger('Error tracking connection_initiated event', error);
485
140
  }
486
- if (((_b = this.__transport) === null || _b === void 0 ? void 0 : _b.isConnected()) && !secure) {
487
- return this.handleConnection(this.__transport
141
+ if (((_a = __classPrivateFieldGet(this, _MultichainSDK_transport, "f")) === null || _a === void 0 ? void 0 : _a.isConnected()) && !secure) {
142
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, __classPrivateFieldGet(this, _MultichainSDK_transport, "f")
488
143
  .connect({ scopes, caipAccountIds, forceRequest })
489
- .then(() => {
490
- if (this.__transport instanceof MWPTransport) {
144
+ .then(() => __awaiter(this, void 0, void 0, function* () {
145
+ if (__classPrivateFieldGet(this, _MultichainSDK_transport, "f") instanceof MWPTransport) {
491
146
  return this.storage.setTransport(TransportType.MWP);
492
147
  }
493
- else {
494
- return this.storage.setTransport(TransportType.Browser);
495
- }
496
- }), scopes, transportType);
148
+ return this.storage.setTransport(TransportType.Browser);
149
+ })), scopes, transportType);
497
150
  }
498
151
  // In MetaMask Mobile In App Browser, window.ethereum is available directly
499
152
  if (platformType === PlatformType.MetaMaskMobileWebview) {
500
- const defaultTransport = yield this.setupDefaultTransport();
501
- return this.handleConnection(defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
153
+ const defaultTransport = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupDefaultTransport).call(this);
154
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
502
155
  }
503
156
  if (isWeb && hasExtensionInstalled && preferExtension) {
504
157
  // If metamask extension is available, connect to it
505
- const defaultTransport = yield this.setupDefaultTransport();
158
+ const defaultTransport = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupDefaultTransport).call(this);
506
159
  // Web transport has no initial payload
507
- return this.handleConnection(defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
160
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
508
161
  }
509
162
  // Connection will now be InstallModal + QRCodes or Deeplinks, both require mwp
510
- yield this.setupMWP();
163
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupMWP).call(this);
511
164
  // Determine preferred option for install modal
512
165
  const shouldShowInstallModal = hasExtensionInstalled
513
166
  ? showInstallModal
514
167
  : !preferExtension || showInstallModal;
515
168
  if (secure && !shouldShowInstallModal) {
516
169
  // Desktop is not preferred option, so we use deeplinks (mobile web)
517
- return this.handleConnection(this.deeplinkConnect(scopes, caipAccountIds), scopes, transportType);
170
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_deeplinkConnect).call(this, scopes, caipAccountIds), scopes, transportType);
518
171
  }
519
172
  // Show install modal for RN, Web + Node
520
- return this.handleConnection(this.showInstallModal(shouldShowInstallModal, scopes, caipAccountIds), scopes, transportType);
173
+ return __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_handleConnection).call(this, __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_showInstallModal).call(this, shouldShowInstallModal, scopes, caipAccountIds), scopes, transportType);
521
174
  });
522
175
  }
523
176
  emit(event, args) {
@@ -528,25 +181,24 @@ export class MultichainSDK extends MultichainCore {
528
181
  disconnect() {
529
182
  return __awaiter(this, void 0, void 0, function* () {
530
183
  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());
184
+ yield ((_a = __classPrivateFieldGet(this, _MultichainSDK_listener, "f")) === null || _a === void 0 ? void 0 : _a.call(this));
185
+ (_b = __classPrivateFieldGet(this, _MultichainSDK_beforeUnloadListener, "f")) === null || _b === void 0 ? void 0 : _b.call(this);
186
+ yield ((_c = __classPrivateFieldGet(this, _MultichainSDK_transport, "f")) === null || _c === void 0 ? void 0 : _c.disconnect());
534
187
  yield this.storage.removeTransport();
535
- this.emit('wallet_sessionChanged', undefined);
536
188
  this.emit('stateChanged', 'disconnected');
537
- this.listener = undefined;
538
- this.__beforeUnloadListener = undefined;
539
- this.__transport = undefined;
540
- this.__provider = undefined;
541
- this.__dappClient = undefined;
189
+ __classPrivateFieldSet(this, _MultichainSDK_listener, undefined, "f");
190
+ __classPrivateFieldSet(this, _MultichainSDK_beforeUnloadListener, undefined, "f");
191
+ __classPrivateFieldSet(this, _MultichainSDK_transport, undefined, "f");
192
+ __classPrivateFieldSet(this, _MultichainSDK_provider, undefined, "f");
193
+ __classPrivateFieldSet(this, _MultichainSDK_dappClient, undefined, "f");
542
194
  });
543
195
  }
544
196
  invokeMethod(request) {
545
197
  return __awaiter(this, void 0, void 0, function* () {
546
198
  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);
199
+ const { transport, options } = this;
200
+ __classPrivateFieldSet(this, _MultichainSDK_provider, (_a = __classPrivateFieldGet(this, _MultichainSDK_provider, "f")) !== null && _a !== void 0 ? _a : getMultichainClient({ transport }), "f");
201
+ const rpcClient = new RpcClient(options, __classPrivateFieldGet(this, _MultichainSDK_sdkInfo, "f"));
550
202
  const requestRouter = new RequestRouter(transport, rpcClient, options);
551
203
  return requestRouter.invokeMethod(request);
552
204
  });
@@ -558,15 +210,361 @@ export class MultichainSDK extends MultichainCore {
558
210
  const secure = isSecure();
559
211
  const shouldOpenDeeplink = secure && !showInstallModal;
560
212
  if (shouldOpenDeeplink) {
561
- setTimeout(() => {
213
+ setTimeout(() => __awaiter(this, void 0, void 0, function* () {
214
+ const session = yield this.transport.getActiveSession();
215
+ if (!session) {
216
+ throw new Error('No active session found');
217
+ }
218
+ const url = `${METAMASK_DEEPLINK_BASE}/mwp?id=${encodeURIComponent(session.id)}`;
562
219
  if (mobile === null || mobile === void 0 ? void 0 : mobile.preferredOpenLink) {
563
- mobile.preferredOpenLink(METAMASK_DEEPLINK_BASE, '_self');
220
+ mobile.preferredOpenLink(url, '_self');
564
221
  }
565
222
  else {
566
- openDeeplink(this.options, METAMASK_DEEPLINK_BASE, METAMASK_CONNECT_BASE_URL);
223
+ openDeeplink(this.options, url, METAMASK_CONNECT_BASE_URL);
567
224
  }
568
- }, 10); // small delay to ensure the message encryption and dispatch completes
225
+ }), 10); // small delay to ensure the message encryption and dispatch completes
569
226
  }
570
227
  }
571
228
  }
229
+ _MultichainSDK_provider = 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() {
230
+ return __awaiter(this, void 0, void 0, function* () {
231
+ var _a;
232
+ const platform = getPlatformType();
233
+ const isBrowser = platform === PlatformType.MetaMaskMobileWebview ||
234
+ platform === PlatformType.DesktopWeb ||
235
+ platform === PlatformType.MobileWeb;
236
+ const isReactNative = platform === PlatformType.ReactNative;
237
+ if (!isBrowser && !isReactNative) {
238
+ return;
239
+ }
240
+ const version = getVersion();
241
+ const dappId = getDappId(this.options.dapp);
242
+ const anonId = yield this.storage.getAnonId();
243
+ const { integrationType } = (_a = this.options.analytics) !== null && _a !== void 0 ? _a : {
244
+ integrationType: '',
245
+ };
246
+ analytics.setGlobalProperty('mmconnect_version', version);
247
+ analytics.setGlobalProperty('dapp_id', dappId);
248
+ analytics.setGlobalProperty('anon_id', anonId);
249
+ analytics.setGlobalProperty('platform', platform);
250
+ analytics.setGlobalProperty('integration_type', integrationType);
251
+ analytics.enable();
252
+ });
253
+ }, _MultichainSDK_onTransportNotification = function _MultichainSDK_onTransportNotification(payload) {
254
+ return __awaiter(this, void 0, void 0, function* () {
255
+ var _a;
256
+ if (typeof payload === 'object' &&
257
+ payload !== null &&
258
+ 'method' in payload) {
259
+ this.emit(payload.method, (_a = payload.params) !== null && _a !== void 0 ? _a : payload.result);
260
+ }
261
+ });
262
+ }, _MultichainSDK_getStoredTransport = function _MultichainSDK_getStoredTransport() {
263
+ return __awaiter(this, void 0, void 0, function* () {
264
+ const transportType = yield this.storage.getTransport();
265
+ const hasExtensionInstalled = yield hasExtension();
266
+ if (transportType) {
267
+ if (transportType === TransportType.Browser) {
268
+ if (hasExtensionInstalled) {
269
+ const apiTransport = new DefaultTransport();
270
+ __classPrivateFieldSet(this, _MultichainSDK_transport, apiTransport, "f");
271
+ __classPrivateFieldSet(this, _MultichainSDK_listener, apiTransport.onNotification(__classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onTransportNotification).bind(this)), "f");
272
+ return apiTransport;
273
+ }
274
+ }
275
+ else if (transportType === TransportType.MWP) {
276
+ const { adapter: kvstore } = this.options.storage;
277
+ const dappClient = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_createDappClient).call(this);
278
+ const apiTransport = new MWPTransport(dappClient, kvstore);
279
+ __classPrivateFieldSet(this, _MultichainSDK_dappClient, dappClient, "f");
280
+ __classPrivateFieldSet(this, _MultichainSDK_transport, apiTransport, "f");
281
+ __classPrivateFieldSet(this, _MultichainSDK_listener, apiTransport.onNotification(__classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onTransportNotification).bind(this)), "f");
282
+ return apiTransport;
283
+ }
284
+ yield this.storage.removeTransport();
285
+ }
286
+ return undefined;
287
+ });
288
+ }, _MultichainSDK_setupTransport = function _MultichainSDK_setupTransport() {
289
+ return __awaiter(this, void 0, void 0, function* () {
290
+ const transport = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_getStoredTransport).call(this);
291
+ if (transport) {
292
+ if (!this.transport.isConnected()) {
293
+ this.state = 'connecting';
294
+ yield this.transport.connect();
295
+ }
296
+ this.state = 'connected';
297
+ if (this.transport instanceof MWPTransport) {
298
+ yield this.storage.setTransport(TransportType.MWP);
299
+ }
300
+ else {
301
+ yield this.storage.setTransport(TransportType.Browser);
302
+ }
303
+ }
304
+ else {
305
+ this.state = 'loaded';
306
+ }
307
+ });
308
+ }, _MultichainSDK_init = function _MultichainSDK_init() {
309
+ return __awaiter(this, void 0, void 0, function* () {
310
+ var _a;
311
+ try {
312
+ // @ts-expect-error mmsdk should be accessible
313
+ if (typeof window !== 'undefined' && ((_a = window.mmsdk) === null || _a === void 0 ? void 0 : _a.isInitialized)) {
314
+ logger('MetaMaskSDK: init already initialized');
315
+ }
316
+ else {
317
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupAnalytics).call(this);
318
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_setupTransport).call(this);
319
+ try {
320
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
321
+ analytics.track('mmconnect_initialized', baseProps);
322
+ }
323
+ catch (error) {
324
+ logger('Error tracking initialized event', error);
325
+ }
326
+ if (typeof window !== 'undefined') {
327
+ // @ts-expect-error mmsdk should be accessible
328
+ window.mmsdk = this;
329
+ }
330
+ }
331
+ }
332
+ catch (error) {
333
+ yield this.storage.removeTransport();
334
+ this.state = 'pending';
335
+ logger('MetaMaskSDK error during initialization', error);
336
+ }
337
+ });
338
+ }, _MultichainSDK_createDappClient = function _MultichainSDK_createDappClient() {
339
+ return __awaiter(this, void 0, void 0, function* () {
340
+ const { adapter: kvstore } = this.options.storage;
341
+ const sessionstore = new SessionStore(kvstore);
342
+ const websocket =
343
+ // eslint-disable-next-line no-negated-condition
344
+ typeof window !== 'undefined'
345
+ ? WebSocket
346
+ : (yield import('ws')).WebSocket;
347
+ const transport = yield WebSocketTransport.create({
348
+ url: MWP_RELAY_URL,
349
+ kvstore,
350
+ websocket,
351
+ });
352
+ const dappClient = new DappClient({ transport, sessionstore, keymanager });
353
+ return dappClient;
354
+ });
355
+ }, _MultichainSDK_setupMWP = function _MultichainSDK_setupMWP() {
356
+ return __awaiter(this, void 0, void 0, function* () {
357
+ if (__classPrivateFieldGet(this, _MultichainSDK_transport, "f") instanceof MWPTransport) {
358
+ return;
359
+ }
360
+ // Only setup MWP if it is not already mwp
361
+ const { adapter: kvstore } = this.options.storage;
362
+ const dappClient = yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_createDappClient).call(this);
363
+ __classPrivateFieldSet(this, _MultichainSDK_dappClient, dappClient, "f");
364
+ const apiTransport = new MWPTransport(dappClient, kvstore);
365
+ __classPrivateFieldSet(this, _MultichainSDK_transport, apiTransport, "f");
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) {
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 });
415
+ yield this.options.ui.factory.unload();
416
+ (_a = this.options.ui.factory.modal) === null || _a === void 0 ? void 0 : _a.unmount();
417
+ this.state = '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.state = '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.state = '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
+ }))
448
+ .catch((error) => {
449
+ reject(error instanceof Error ? error : new Error(String(error)));
450
+ });
451
+ });
452
+ });
453
+ }, _MultichainSDK_showInstallModal = function _MultichainSDK_showInstallModal(desktopPreferred, scopes, caipAccountIds) {
454
+ return __awaiter(this, void 0, void 0, function* () {
455
+ var _a;
456
+ // create the listener only once to avoid memory leaks
457
+ __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");
458
+ yield __classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_renderInstallModalAsync).call(this, desktopPreferred, scopes, caipAccountIds);
459
+ });
460
+ }, _MultichainSDK_setupDefaultTransport = function _MultichainSDK_setupDefaultTransport() {
461
+ return __awaiter(this, void 0, void 0, function* () {
462
+ this.state = 'connecting';
463
+ yield this.storage.setTransport(TransportType.Browser);
464
+ const transport = new DefaultTransport();
465
+ __classPrivateFieldSet(this, _MultichainSDK_listener, transport.onNotification(__classPrivateFieldGet(this, _MultichainSDK_instances, "m", _MultichainSDK_onTransportNotification).bind(this)), "f");
466
+ __classPrivateFieldSet(this, _MultichainSDK_transport, transport, "f");
467
+ return transport;
468
+ });
469
+ }, _MultichainSDK_deeplinkConnect = function _MultichainSDK_deeplinkConnect(scopes, caipAccountIds) {
470
+ return __awaiter(this, void 0, void 0, function* () {
471
+ return new Promise((resolve, reject) => {
472
+ // Handle the response to the initial wallet_createSession request
473
+ const dappClientMessageHandler = (payload) => {
474
+ var _a;
475
+ if (typeof payload !== 'object' ||
476
+ payload === null ||
477
+ !('data' in payload)) {
478
+ return;
479
+ }
480
+ const data = payload.data;
481
+ if (typeof data === 'object' && data !== null) {
482
+ // optimistically assume any error is due to the initial wallet_createSession request failure
483
+ if (data.error) {
484
+ this.dappClient.off('message', dappClientMessageHandler);
485
+ reject(data.error);
486
+ }
487
+ // if sessionScopes is set in the result, then this is a response to wallet_createSession
488
+ if ((_a = data === null || data === void 0 ? void 0 : data.result) === null || _a === void 0 ? void 0 : _a.sessionScopes) {
489
+ this.dappClient.off('message', dappClientMessageHandler);
490
+ // unsure if we need to call resolve here like we do above for reject()
491
+ }
492
+ }
493
+ };
494
+ this.dappClient.on('message', dappClientMessageHandler);
495
+ let timeout;
496
+ if (this.transport.isConnected()) {
497
+ timeout = setTimeout(() => {
498
+ this.openDeeplinkIfNeeded();
499
+ }, 250);
500
+ }
501
+ else {
502
+ this.dappClient.once('session_request', (sessionRequest) => {
503
+ var _a;
504
+ const connectionRequest = {
505
+ sessionRequest,
506
+ metadata: {
507
+ dapp: this.options.dapp,
508
+ sdk: { version: getVersion(), platform: getPlatformType() },
509
+ },
510
+ };
511
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
512
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
513
+ if ((_a = this.options.mobile) === null || _a === void 0 ? void 0 : _a.preferredOpenLink) {
514
+ this.options.mobile.preferredOpenLink(deeplink, '_self');
515
+ }
516
+ else {
517
+ openDeeplink(this.options, deeplink, universalLink);
518
+ }
519
+ });
520
+ }
521
+ return this.transport
522
+ .connect({ scopes, caipAccountIds })
523
+ .then(resolve)
524
+ .catch((error) => __awaiter(this, void 0, void 0, function* () {
525
+ yield this.storage.removeTransport();
526
+ this.dappClient.off('message', dappClientMessageHandler);
527
+ reject(error instanceof Error ? error : new Error(String(error)));
528
+ }))
529
+ .finally(() => {
530
+ if (timeout) {
531
+ clearTimeout(timeout);
532
+ }
533
+ });
534
+ });
535
+ });
536
+ }, _MultichainSDK_handleConnection = function _MultichainSDK_handleConnection(promise, scopes, transportType) {
537
+ return __awaiter(this, void 0, void 0, function* () {
538
+ this.state = 'connecting';
539
+ return promise
540
+ .then(() => __awaiter(this, void 0, void 0, function* () {
541
+ this.state = 'connected';
542
+ try {
543
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
544
+ analytics.track('mmconnect_connection_established', Object.assign(Object.assign({}, baseProps), { transport_type: transportType, user_permissioned_chains: scopes }));
545
+ }
546
+ catch (error) {
547
+ logger('Error tracking connection_established event', error);
548
+ }
549
+ return undefined; // explicitly return `undefined` to avoid eslintpromise/always-return
550
+ }))
551
+ .catch((error) => __awaiter(this, void 0, void 0, function* () {
552
+ this.state = 'disconnected';
553
+ try {
554
+ const baseProps = yield getBaseAnalyticsProperties(this.options, this.storage);
555
+ const isRejection = isRejectionError(error);
556
+ if (isRejection) {
557
+ analytics.track('mmconnect_connection_rejected', Object.assign(Object.assign({}, baseProps), { transport_type: transportType }));
558
+ }
559
+ else {
560
+ analytics.track('mmconnect_connection_failed', Object.assign(Object.assign({}, baseProps), { transport_type: transportType }));
561
+ }
562
+ }
563
+ catch (_a) {
564
+ logger('Error tracking connection failed/rejected event', error);
565
+ }
566
+ throw error;
567
+ }));
568
+ });
569
+ };
572
570
  //# sourceMappingURL=index.js.map