@mocanetwork/airkit 0.5.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +177 -0
  2. package/dist/airkit.cjs.js +2662 -0
  3. package/dist/airkit.esm.js +2468 -0
  4. package/dist/airkit.umd.min.js +2 -0
  5. package/dist/airkit.umd.min.js.LICENSE.txt +12 -0
  6. package/dist/lib.cjs/common/src/error.js +25 -0
  7. package/dist/lib.cjs/common/src/realm/messaging/auth.js +28 -0
  8. package/dist/lib.cjs/common/src/realm/messaging/types.js +15 -0
  9. package/dist/lib.cjs/ws-embed/src/PopupHandler.js +64 -0
  10. package/dist/lib.cjs/ws-embed/src/airService.js +364 -0
  11. package/dist/lib.cjs/ws-embed/src/baseProvider.js +178 -0
  12. package/dist/lib.cjs/ws-embed/src/communicationProvider.js +346 -0
  13. package/dist/lib.cjs/ws-embed/src/embed.js +735 -0
  14. package/dist/lib.cjs/ws-embed/src/error.js +21 -0
  15. package/dist/lib.cjs/ws-embed/src/iframeController.js +68 -0
  16. package/dist/lib.cjs/ws-embed/src/inPageProvider.js +307 -0
  17. package/dist/lib.cjs/ws-embed/src/index.js +20 -0
  18. package/dist/lib.cjs/ws-embed/src/interfaces.js +29 -0
  19. package/dist/lib.cjs/ws-embed/src/isStream.js +20 -0
  20. package/dist/lib.cjs/ws-embed/src/loglevel.js +7 -0
  21. package/dist/lib.cjs/ws-embed/src/messageService.js +212 -0
  22. package/dist/lib.cjs/ws-embed/src/messages.js +22 -0
  23. package/dist/lib.cjs/ws-embed/src/siteMetadata.js +77 -0
  24. package/dist/lib.cjs/ws-embed/src/utils.js +95 -0
  25. package/dist/lib.esm/common/src/error.js +23 -0
  26. package/dist/lib.esm/common/src/realm/messaging/auth.js +26 -0
  27. package/dist/lib.esm/common/src/realm/messaging/types.js +13 -0
  28. package/dist/lib.esm/ws-embed/src/PopupHandler.js +62 -0
  29. package/dist/lib.esm/ws-embed/src/airService.js +362 -0
  30. package/dist/lib.esm/ws-embed/src/baseProvider.js +176 -0
  31. package/dist/lib.esm/ws-embed/src/communicationProvider.js +344 -0
  32. package/dist/lib.esm/ws-embed/src/embed.js +730 -0
  33. package/dist/lib.esm/ws-embed/src/error.js +18 -0
  34. package/dist/lib.esm/ws-embed/src/iframeController.js +66 -0
  35. package/dist/lib.esm/ws-embed/src/inPageProvider.js +302 -0
  36. package/dist/lib.esm/ws-embed/src/index.js +5 -0
  37. package/dist/lib.esm/ws-embed/src/interfaces.js +21 -0
  38. package/dist/lib.esm/ws-embed/src/isStream.js +15 -0
  39. package/dist/lib.esm/ws-embed/src/loglevel.js +5 -0
  40. package/dist/lib.esm/ws-embed/src/messageService.js +210 -0
  41. package/dist/lib.esm/ws-embed/src/messages.js +20 -0
  42. package/dist/lib.esm/ws-embed/src/siteMetadata.js +75 -0
  43. package/dist/lib.esm/ws-embed/src/utils.js +88 -0
  44. package/dist/types/PopupHandler.d.ts +24 -0
  45. package/dist/types/airService.d.ts +34 -0
  46. package/dist/types/baseProvider.d.ts +66 -0
  47. package/dist/types/common/custom.d.ts +4 -0
  48. package/dist/types/common/error.d.ts +17 -0
  49. package/dist/types/common/realm/error/auth.d.ts +1 -0
  50. package/dist/types/common/realm/error/types.d.ts +1 -0
  51. package/dist/types/common/realm/messaging/auth.d.ts +138 -0
  52. package/dist/types/common/realm/messaging/types.d.ts +95 -0
  53. package/dist/types/common/realm/partner/config.d.ts +68 -0
  54. package/dist/types/common/realm/user/types.d.ts +78 -0
  55. package/dist/types/common/realm/wallet/bybit/bybit.d.ts +2 -0
  56. package/dist/types/common/realm/wallet/coinbase/coinbase.d.ts +2 -0
  57. package/dist/types/common/realm/wallet/cryptoCom/cryptoCom.d.ts +2 -0
  58. package/dist/types/common/realm/wallet/index.d.ts +22 -0
  59. package/dist/types/common/realm/wallet/metamask/metamask.d.ts +2 -0
  60. package/dist/types/common/realm/wallet/okx/okx.d.ts +2 -0
  61. package/dist/types/common/realm/wallet/phantom/phantom.d.ts +2 -0
  62. package/dist/types/common/realm/wallet/rabby/rabby.d.ts +2 -0
  63. package/dist/types/common/realm/wallet/rainbow/rainbow.d.ts +2 -0
  64. package/dist/types/common/realm/wallet/trust/trust.d.ts +2 -0
  65. package/dist/types/common/types.d.ts +8 -0
  66. package/dist/types/common/utils.d.ts +2 -0
  67. package/dist/types/communicationProvider.d.ts +82 -0
  68. package/dist/types/embed.d.ts +42 -0
  69. package/dist/types/error.d.ts +9 -0
  70. package/dist/types/iframeController.d.ts +18 -0
  71. package/dist/types/inPageProvider.d.ts +106 -0
  72. package/dist/types/index.d.ts +4 -0
  73. package/dist/types/interfaces.d.ts +261 -0
  74. package/dist/types/isStream.d.ts +4 -0
  75. package/dist/types/loglevel.d.ts +3 -0
  76. package/dist/types/messageService.d.ts +51 -0
  77. package/dist/types/messages.d.ts +19 -0
  78. package/dist/types/siteMetadata.d.ts +9 -0
  79. package/dist/types/utils.d.ts +24 -0
  80. package/package.json +76 -0
@@ -0,0 +1,730 @@
1
+ import _objectSpread from '@babel/runtime/helpers/objectSpread2';
2
+ import _classPrivateMethodInitSpec from '@babel/runtime/helpers/classPrivateMethodInitSpec';
3
+ import _classPrivateFieldInitSpec from '@babel/runtime/helpers/classPrivateFieldInitSpec';
4
+ import { COMMUNICATION_JRPC_METHODS, CHAIN_NAMESPACES, randomId, CONFIRMATION_STRATEGY, BUTTON_POSITION, SETUP_COMPLETE, getPopupFeatures, FEATURES_CONFIRM_WINDOW, FEATURES_PROVIDER_CHANGE_WINDOW } from '@toruslabs/base-controllers';
5
+ import { METHOD_TYPES } from '@toruslabs/ethereum-controllers';
6
+ import { WEB3AUTH_NETWORK, BasePostMessageStream, getRpcPromiseCallback } from '@web3auth/auth';
7
+ import { AirMessageTypes } from '../../common/src/realm/messaging/types.js';
8
+ import CommunicationProvider from './communicationProvider.js';
9
+ import { RealmEmbedError } from './error.js';
10
+ import { TorusInPageProvider } from './inPageProvider.js';
11
+ import { EMBED_BUILD_ENV, EXTERNAL_LOGIN_PROVIDER } from './interfaces.js';
12
+ import log from './loglevel.js';
13
+ import AirMessageService from './messageService.js';
14
+ import getSiteMetadata from './siteMetadata.js';
15
+ import { AIR_URLS, htmlToElement } from './utils.js';
16
+
17
+ function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
18
+ function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
19
+ function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
20
+
21
+ // preload for iframe doesn't work https://bugs.chromium.org/p/chromium/issues/detail?id=593267
22
+ (async function preLoadIframe() {
23
+ try {
24
+ if (typeof document === "undefined") return;
25
+ const airWalletIframeHtml = document.createElement("link");
26
+ const {
27
+ walletUrl: airWalletUrl
28
+ } = AIR_URLS.production;
29
+ airWalletIframeHtml.href = `${airWalletUrl}/frame`;
30
+ airWalletIframeHtml.crossOrigin = "anonymous";
31
+ airWalletIframeHtml.type = "text/html";
32
+ airWalletIframeHtml.rel = "prefetch";
33
+ if (airWalletIframeHtml.relList && airWalletIframeHtml.relList.supports) {
34
+ if (airWalletIframeHtml.relList.supports("prefetch")) {
35
+ document.head.appendChild(airWalletIframeHtml);
36
+ }
37
+ }
38
+ } catch (error) {
39
+ log.warn(error);
40
+ }
41
+ })();
42
+ new Set([COMMUNICATION_JRPC_METHODS.SET_PROVIDER]);
43
+ const PROVIDER_UNSAFE_METHODS = new Set([METHOD_TYPES.ETH_SIGN, METHOD_TYPES.ETH_SIGN_TYPED_DATA_V4, METHOD_TYPES.PERSONAL_SIGN, METHOD_TYPES.ETH_TRANSACTION, METHOD_TYPES.ADD_CHAIN, METHOD_TYPES.SWITCH_CHAIN]);
44
+ const embedChainConfig = {
45
+ polygon: {
46
+ chainNamespace: CHAIN_NAMESPACES.EIP155,
47
+ chainId: "0x89",
48
+ decimals: 18,
49
+ displayName: "Polygon",
50
+ blockExplorerUrl: "https://polygonscan.com",
51
+ logo: "https://cryptologos.cc/logos/polygon-matic-logo.png",
52
+ ticker: "MATIC",
53
+ tickerName: "Matic Network Token"
54
+ },
55
+ polygonAmoy: {
56
+ chainNamespace: CHAIN_NAMESPACES.EIP155,
57
+ chainId: "0x13882",
58
+ decimals: 18,
59
+ displayName: "Polygon Amoy",
60
+ blockExplorerUrl: "https://amoy.polygonscan.com",
61
+ logo: "https://cryptologos.cc/logos/polygon-matic-logo.png",
62
+ ticker: "MATIC",
63
+ tickerName: "Matic Network Token",
64
+ isTestnet: true
65
+ }
66
+ };
67
+ const web3AuthClientId = "BANbxuTYFGeYi8HxUzaPQkvQlSAXiKRtUqb1vqsXbsZsZKrNr05PEPCM2J2PhUJZpIYl0XzQa6jxUjnYzSU9LXY";
68
+ const web3AuthNetwork = WEB3AUTH_NETWORK.SAPPHIRE_MAINNET;
69
+ var _embedNonce = /*#__PURE__*/new WeakMap();
70
+ var _provider = /*#__PURE__*/new WeakMap();
71
+ var _isInitialized = /*#__PURE__*/new WeakMap();
72
+ var _rehydrationState = /*#__PURE__*/new WeakMap();
73
+ var _modalZIndex = /*#__PURE__*/new WeakMap();
74
+ var _communicationProvider = /*#__PURE__*/new WeakMap();
75
+ var _buttonPosition = /*#__PURE__*/new WeakMap();
76
+ var _realmPartnerId = /*#__PURE__*/new WeakMap();
77
+ var _web3AuthClientId = /*#__PURE__*/new WeakMap();
78
+ var _web3AuthNetwork = /*#__PURE__*/new WeakMap();
79
+ var _isPluginMode = /*#__PURE__*/new WeakMap();
80
+ var _confirmationStrategy = /*#__PURE__*/new WeakMap();
81
+ var _walletIframe = /*#__PURE__*/new WeakMap();
82
+ var _buildEnv = /*#__PURE__*/new WeakMap();
83
+ var _walletAddresses = /*#__PURE__*/new WeakMap();
84
+ var _realmId = /*#__PURE__*/new WeakMap();
85
+ var _loginToken = /*#__PURE__*/new WeakMap();
86
+ var _sessionId = /*#__PURE__*/new WeakMap();
87
+ var _embedListeners = /*#__PURE__*/new WeakMap();
88
+ var _RealmEmbed_brand = /*#__PURE__*/new WeakSet();
89
+ class RealmEmbed {
90
+ constructor({
91
+ modalZIndex = 99999,
92
+ partnerId
93
+ }) {
94
+ _classPrivateMethodInitSpec(this, _RealmEmbed_brand);
95
+ _classPrivateFieldInitSpec(this, _embedNonce, randomId());
96
+ _classPrivateFieldInitSpec(this, _provider, void 0);
97
+ _classPrivateFieldInitSpec(this, _isInitialized, void 0);
98
+ _classPrivateFieldInitSpec(this, _rehydrationState, void 0);
99
+ _classPrivateFieldInitSpec(this, _modalZIndex, void 0);
100
+ _classPrivateFieldInitSpec(this, _communicationProvider, void 0);
101
+ _classPrivateFieldInitSpec(this, _buttonPosition, void 0);
102
+ _classPrivateFieldInitSpec(this, _realmPartnerId, void 0);
103
+ _classPrivateFieldInitSpec(this, _web3AuthClientId, void 0);
104
+ _classPrivateFieldInitSpec(this, _web3AuthNetwork, void 0);
105
+ _classPrivateFieldInitSpec(this, _isPluginMode, void 0);
106
+ _classPrivateFieldInitSpec(this, _confirmationStrategy, void 0);
107
+ _classPrivateFieldInitSpec(this, _walletIframe, void 0);
108
+ _classPrivateFieldInitSpec(this, _buildEnv, void 0);
109
+ _classPrivateFieldInitSpec(this, _walletAddresses, void 0);
110
+ _classPrivateFieldInitSpec(this, _realmId, void 0);
111
+ _classPrivateFieldInitSpec(this, _loginToken, void 0);
112
+ _classPrivateFieldInitSpec(this, _sessionId, void 0);
113
+ _classPrivateFieldInitSpec(this, _embedListeners, []);
114
+ _classPrivateFieldSet(_isInitialized, this, false); // init done
115
+ _classPrivateFieldSet(_modalZIndex, this, modalZIndex);
116
+ _classPrivateFieldSet(_realmPartnerId, this, partnerId);
117
+ _classPrivateFieldSet(_web3AuthClientId, this, web3AuthClientId);
118
+ _classPrivateFieldSet(_web3AuthNetwork, this, web3AuthNetwork);
119
+ }
120
+ get isConnected() {
121
+ return !!_classPrivateFieldGet(_walletAddresses, this) && _classPrivateFieldGet(_communicationProvider, this).isLoggedIn;
122
+ }
123
+ get isInitialized() {
124
+ return _classPrivateFieldGet(_isInitialized, this) && !!_classPrivateFieldGet(_rehydrationState, this);
125
+ }
126
+ get isLoggedIn() {
127
+ return !!_classPrivateFieldGet(_realmId, this) && this.isConnected;
128
+ }
129
+ get getBuildEnv() {
130
+ return _classPrivateFieldGet(_buildEnv, this);
131
+ }
132
+ get walletAddresses() {
133
+ var _classPrivateFieldGet2;
134
+ return (_classPrivateFieldGet2 = _classPrivateFieldGet(_walletAddresses, this)) !== null && _classPrivateFieldGet2 !== void 0 ? _classPrivateFieldGet2 : null;
135
+ }
136
+ get sessionId() {
137
+ var _classPrivateFieldGet3;
138
+ return (_classPrivateFieldGet3 = _classPrivateFieldGet(_sessionId, this)) !== null && _classPrivateFieldGet3 !== void 0 ? _classPrivateFieldGet3 : null;
139
+ }
140
+ get realmId() {
141
+ var _classPrivateFieldGet4;
142
+ return (_classPrivateFieldGet4 = _classPrivateFieldGet(_realmId, this)) !== null && _classPrivateFieldGet4 !== void 0 ? _classPrivateFieldGet4 : null;
143
+ }
144
+ get provider() {
145
+ return _classPrivateFieldGet(_walletAddresses, this) ? _classPrivateFieldGet(_provider, this) : null;
146
+ }
147
+ async init({
148
+ buildEnv = EMBED_BUILD_ENV.PRODUCTION,
149
+ enableLogging = false,
150
+ skipRehydration = false
151
+ // confirmationStrategy = CONFIRMATION_STRATEGY.DEFAULT,
152
+ } = {}) {
153
+ if (_classPrivateFieldGet(_isInitialized, this)) throw new RealmEmbedError("ALREADY_INITIALISED", "Already initialized");
154
+ _classPrivateFieldSet(_buildEnv, this, buildEnv);
155
+ _classPrivateFieldSet(_confirmationStrategy, this, CONFIRMATION_STRATEGY.DEFAULT);
156
+ _classPrivateFieldSet(_buttonPosition, this, BUTTON_POSITION.BOTTOM_LEFT);
157
+ const {
158
+ walletUrl,
159
+ logLevel
160
+ } = AIR_URLS[buildEnv];
161
+ log.info(walletUrl, "url loaded");
162
+ log.setDefaultLevel(logLevel);
163
+ if (enableLogging) log.enableAll();else log.disableAll();
164
+ const walletIframeUrl = _assertClassBrand(_RealmEmbed_brand, this, _getWsIframeUrl).call(this);
165
+ const walletIframeOrigin = walletIframeUrl.origin;
166
+ AirMessageService.openRealmObservables({
167
+ walletIframeOrigin
168
+ });
169
+ _classPrivateFieldSet(_walletIframe, this, htmlToElement(`<iframe
170
+ id="walletIframe-${_classPrivateFieldGet(_embedNonce, this)}"
171
+ class="walletIframe-${_classPrivateFieldGet(_embedNonce, this)}"
172
+ sandbox="allow-popups allow-scripts allow-same-origin allow-forms allow-modals allow-downloads"
173
+ src="${walletIframeUrl.href}"
174
+ style="display: none; position: fixed; top: 0; right: 0; width: 100%; color-scheme: none; border-width: 0px; height: 100%; border: none; border-radius: 0; z-index: ${_classPrivateFieldGet(_modalZIndex, this).toString()}"
175
+ allow="clipboard-write"
176
+ ></iframe>`));
177
+ AirMessageService.messages$.subscribe(msg => {
178
+ switch (msg.type) {
179
+ case AirMessageTypes.SERVICE_INITIALIZED:
180
+ {
181
+ _classPrivateFieldSet(_rehydrationState, this, msg.payload.rehydration);
182
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerInitializedEvent).call(this);
183
+ break;
184
+ }
185
+ }
186
+ });
187
+ AirMessageService.loginState$.subscribe(async msg => {
188
+ switch (msg.payload.state) {
189
+ case "connected":
190
+ {
191
+ await _assertClassBrand(_RealmEmbed_brand, this, _onInitialized).call(this);
192
+ if (msg.payload.addresses && !this.isLoggedIn) {
193
+ _classPrivateFieldSet(_walletAddresses, this, msg.payload.addresses);
194
+ _classPrivateFieldSet(_loginToken, this, msg.payload.token);
195
+ _classPrivateFieldSet(_sessionId, this, msg.payload.sessionId);
196
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
197
+ event: "connected",
198
+ result: {
199
+ isLoggedIn: false,
200
+ addresses: msg.payload.addresses,
201
+ token: msg.payload.token,
202
+ sessionId: msg.payload.sessionId
203
+ }
204
+ });
205
+ }
206
+ break;
207
+ }
208
+ case "logged_in":
209
+ {
210
+ await _assertClassBrand(_RealmEmbed_brand, this, _onInitialized).call(this);
211
+ const isNotConnectedYet = !_classPrivateFieldGet(_walletAddresses, this);
212
+ _classPrivateFieldSet(_realmId, this, msg.payload.airId);
213
+ _classPrivateFieldSet(_walletAddresses, this, msg.payload.addresses);
214
+ _classPrivateFieldSet(_loginToken, this, msg.payload.token);
215
+ _classPrivateFieldSet(_sessionId, this, msg.payload.sessionId);
216
+ if (isNotConnectedYet) {
217
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
218
+ event: "connected",
219
+ result: {
220
+ isLoggedIn: false,
221
+ addresses: msg.payload.addresses,
222
+ token: msg.payload.token,
223
+ sessionId: msg.payload.sessionId
224
+ }
225
+ });
226
+ }
227
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
228
+ event: "logged_in",
229
+ result: {
230
+ isLoggedIn: true,
231
+ realmId: msg.payload.airId,
232
+ addresses: msg.payload.addresses,
233
+ token: msg.payload.token,
234
+ sessionId: msg.payload.sessionId
235
+ }
236
+ });
237
+ break;
238
+ }
239
+ case "minting_started":
240
+ {
241
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
242
+ event: "minting_started"
243
+ });
244
+ break;
245
+ }
246
+ case "minting_failed":
247
+ {
248
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
249
+ event: "minting_failed",
250
+ errorMessage: msg.payload.errorMessage
251
+ });
252
+ break;
253
+ }
254
+ }
255
+ });
256
+ try {
257
+ // Handle wallet iframe message
258
+ window.document.body.appendChild(_classPrivateFieldGet(_walletIframe, this));
259
+ const initializeWalletService = new Promise((resolve, reject) => {
260
+ const handleMessage = async ev => {
261
+ try {
262
+ if (ev.origin !== walletIframeOrigin) return;
263
+ if (ev.data === SETUP_COMPLETE) {
264
+ window.removeEventListener("message", handleMessage);
265
+ // send init params here
266
+ const dappMetadata = await getSiteMetadata();
267
+ _classPrivateFieldGet(_walletIframe, this).contentWindow.postMessage({
268
+ chainConfig: _classPrivateFieldGet(_buildEnv, this) === EMBED_BUILD_ENV.PRODUCTION ? embedChainConfig.polygon : embedChainConfig.polygonAmoy,
269
+ dappMetadata,
270
+ enableLogging,
271
+ skipRehydration,
272
+ realmPartnerId: _classPrivateFieldGet(_realmPartnerId, this),
273
+ web3AuthClientId: _classPrivateFieldGet(_web3AuthClientId, this),
274
+ web3AuthNetwork: _classPrivateFieldGet(_web3AuthNetwork, this),
275
+ confirmationStrategy: _classPrivateFieldGet(_confirmationStrategy, this)
276
+ }, walletIframeOrigin);
277
+ await _assertClassBrand(_RealmEmbed_brand, this, _setupWeb).call(this, {
278
+ torusUrl: walletUrl
279
+ });
280
+ _classPrivateFieldGet(_communicationProvider, this).onLoginStateHandle = async isLoggedIn => {
281
+ if (!isLoggedIn) {
282
+ await _assertClassBrand(_RealmEmbed_brand, this, _logout).call(this);
283
+ }
284
+ };
285
+ resolve();
286
+ }
287
+ } catch (err) {
288
+ reject(err);
289
+ }
290
+ };
291
+ window.addEventListener("message", handleMessage);
292
+ });
293
+ const walletServiceInitialization = AirMessageService.waitForWalletInitialization();
294
+ await Promise.all([initializeWalletService, walletServiceInitialization]);
295
+ AirMessageService.setupIframeCommunication(_classPrivateFieldGet(_walletIframe, this));
296
+ _classPrivateFieldSet(_isInitialized, this, true);
297
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerInitializedEvent).call(this);
298
+ log.debug("Wallet service initialization resolved");
299
+ } catch (error) {
300
+ log.debug("Wallet service initialization error", error);
301
+ _assertClassBrand(_RealmEmbed_brand, this, _clearInit).call(this, true);
302
+ throw error;
303
+ }
304
+ }
305
+ moveToBackground() {
306
+ _classPrivateFieldGet(_communicationProvider, this).moveToBackground();
307
+ }
308
+ moveToForeground() {
309
+ _classPrivateFieldGet(_communicationProvider, this).moveToForeground();
310
+ }
311
+ async getUserInfo() {
312
+ if (!_classPrivateFieldGet(_realmId, this)) return null;
313
+ const userInfoResponse = await _classPrivateFieldGet(_communicationProvider, this).request({
314
+ method: COMMUNICATION_JRPC_METHODS.USER_INFO,
315
+ params: []
316
+ });
317
+ return _objectSpread(_objectSpread({}, userInfoResponse), {}, {
318
+ realmId: _classPrivateFieldGet(_realmId, this)
319
+ });
320
+ }
321
+ async login(options) {
322
+ var _options$legacy;
323
+ return _assertClassBrand(_RealmEmbed_brand, this, _login).call(this, options, (_options$legacy = options === null || options === void 0 ? void 0 : options.legacy) !== null && _options$legacy !== void 0 ? _options$legacy : true);
324
+ }
325
+ async _deploySmartAccount() {
326
+ if (!this.isConnected) throw new RealmEmbedError("NOT_LOGGED_IN", "User needs to be connected first");
327
+ try {
328
+ await AirMessageService.sendDeploySmartAccountRequest(_classPrivateFieldGet(_walletIframe, this));
329
+ } catch (error) {
330
+ throw RealmEmbedError.from(error);
331
+ }
332
+ }
333
+ // async loginV2<T extends boolean>(options?: {
334
+ // skipClaiming: T;
335
+ // token?: string;
336
+ // }): Promise<T extends true ? RealmLoginResult | RealmConnectResult : RealmLoginResult> {
337
+ // if (!this.#isInitialized) throw new Error("Call init() first");
338
+
339
+ // const iframeController = this.#authIframeController;
340
+ // iframeController.setIframeVisibility(true);
341
+ // iframeController.updateIframeState();
342
+
343
+ // const { payload } = await RealmMessageService.sendAuthLoginRequest(iframeController.iframeElement);
344
+
345
+ // iframeController.setIframeVisibility(false);
346
+ // iframeController.updateIframeState();
347
+
348
+ // if (payload.success === true) {
349
+ // return this.#login({
350
+ // skipClaiming: options?.skipClaiming,
351
+ // token: options?.token,
352
+ // });
353
+ // }
354
+ // throw new RealmEmbedError(payload.errorName, payload.errorMessage);
355
+ // }
356
+
357
+ // This is for internal use only
358
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
359
+ // @ts-ignore
360
+ async _loginWithSessionId(params) {
361
+ if (!_classPrivateFieldGet(_isInitialized, this)) throw new Error("Call init() first");
362
+ if (!params.sessionId) throw new Error("sessionId is required");
363
+ try {
364
+ const res = await _classPrivateFieldGet(_communicationProvider, this).request({
365
+ method: COMMUNICATION_JRPC_METHODS.LOGIN_WITH_SESSION_ID,
366
+ params: [params.sessionId, ""]
367
+ });
368
+ log.info("Login with session id", res);
369
+ return res.success;
370
+ } catch (error) {
371
+ log.error("login with session id failed", error);
372
+ throw error;
373
+ }
374
+ }
375
+
376
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
377
+ // @ts-ignore
378
+ async _showWalletWidget() {
379
+ _classPrivateFieldGet(_communicationProvider, this).showTorusButton();
380
+ }
381
+ async claimRealmId(options) {
382
+ if (!this.isConnected) throw new RealmEmbedError("NOT_CONNECTED", "User needs to be connected first");
383
+ try {
384
+ if (options !== null && options !== void 0 && options.background) {
385
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
386
+ isVisible: false
387
+ });
388
+ }
389
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
390
+ isFull: true
391
+ });
392
+ const claimPromise = AirMessageService.sendClaimRequest(_classPrivateFieldGet(_walletIframe, this), options);
393
+ log.debug("before claimPromise");
394
+ await claimPromise;
395
+ log.debug("after claimPromise");
396
+ return {
397
+ isLoggedIn: true,
398
+ realmId: _classPrivateFieldGet(_realmId, this),
399
+ addresses: _classPrivateFieldGet(_walletAddresses, this),
400
+ token: _classPrivateFieldGet(_loginToken, this),
401
+ sessionId: _classPrivateFieldGet(_sessionId, this)
402
+ };
403
+ } catch (e) {
404
+ throw RealmEmbedError.from(e);
405
+ } finally {
406
+ if (options !== null && options !== void 0 && options.background) {
407
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
408
+ isVisible: true
409
+ });
410
+ }
411
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
412
+ isFull: false
413
+ });
414
+ }
415
+ }
416
+ async logout() {
417
+ if (!_classPrivateFieldGet(_communicationProvider, this).isLoggedIn) throw new RealmEmbedError("NOT_LOGGED_IN", "Not logged in");
418
+ await _assertClassBrand(_RealmEmbed_brand, this, _logout).call(this);
419
+ }
420
+ async cleanUp() {
421
+ var _classPrivateFieldGet5;
422
+ if ((_classPrivateFieldGet5 = _classPrivateFieldGet(_communicationProvider, this)) !== null && _classPrivateFieldGet5 !== void 0 && _classPrivateFieldGet5.isLoggedIn) {
423
+ await this.logout();
424
+ }
425
+ await this.clearInit();
426
+ }
427
+ async clearInit() {
428
+ _assertClassBrand(_RealmEmbed_brand, this, _clearInit).call(this);
429
+ }
430
+ on(listener) {
431
+ if (_classPrivateFieldGet(_embedListeners, this).indexOf(listener) < 0) _classPrivateFieldGet(_embedListeners, this).push(listener);
432
+ }
433
+ off(listener) {
434
+ const index = _classPrivateFieldGet(_embedListeners, this).indexOf(listener);
435
+ if (index >= 0) _classPrivateFieldGet(_embedListeners, this).splice(index, 1);
436
+ }
437
+ clearEventListeners() {
438
+ _classPrivateFieldSet(_embedListeners, this, []);
439
+ }
440
+ }
441
+ function _getWsIframeUrl() {
442
+ const {
443
+ walletUrl
444
+ } = AIR_URLS[_classPrivateFieldGet(_buildEnv, this)];
445
+ const torusIframeUrl = new URL(walletUrl);
446
+ if (torusIframeUrl.pathname.endsWith("/")) torusIframeUrl.pathname += "frame";else torusIframeUrl.pathname += "/frame";
447
+ const hashParams = new URLSearchParams();
448
+ hashParams.append("origin", window.location.origin);
449
+ torusIframeUrl.hash = hashParams.toString();
450
+ return torusIframeUrl;
451
+ }
452
+ async function _login(options, isLegacyLogin) {
453
+ let loginResult;
454
+ if (this.isLoggedIn) {
455
+ loginResult = _assertClassBrand(_RealmEmbed_brand, this, _createLoginResult).call(this);
456
+ } else if (this.isConnected) {
457
+ if ((options === null || options === void 0 ? void 0 : options.skipClaiming) === true) {
458
+ loginResult = _assertClassBrand(_RealmEmbed_brand, this, _createLoginResult).call(this);
459
+ } else {
460
+ loginResult = await this.claimRealmId(options);
461
+ }
462
+ } else {
463
+ loginResult = await _assertClassBrand(_RealmEmbed_brand, this, _realmLogin).call(this, options, isLegacyLogin);
464
+ }
465
+ return loginResult;
466
+ }
467
+ function _createLoginResult() {
468
+ if (this.isLoggedIn) {
469
+ return {
470
+ isLoggedIn: true,
471
+ realmId: _classPrivateFieldGet(_realmId, this),
472
+ addresses: _classPrivateFieldGet(_walletAddresses, this),
473
+ token: _classPrivateFieldGet(_loginToken, this),
474
+ sessionId: _classPrivateFieldGet(_sessionId, this)
475
+ };
476
+ }
477
+ return {
478
+ isLoggedIn: false,
479
+ addresses: _classPrivateFieldGet(_walletAddresses, this),
480
+ token: _classPrivateFieldGet(_loginToken, this),
481
+ sessionId: _classPrivateFieldGet(_sessionId, this)
482
+ };
483
+ }
484
+ async function _authLogin(params = {}) {
485
+ try {
486
+ if (!params.loginProvider || params.loginProvider === EXTERNAL_LOGIN_PROVIDER.WALLET_CONNECT) {
487
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
488
+ isFull: true
489
+ });
490
+ }
491
+
492
+ // If user is already logged in, we assume they have given access to the website
493
+ const res = await new Promise((resolve, reject) => {
494
+ // We use this method because we want to update inPage provider state with account info
495
+ _classPrivateFieldGet(_provider, this).rpcRequest({
496
+ method: "eth_requestAccounts",
497
+ params: [params.loginProvider, params.login_hint]
498
+ }, getRpcPromiseCallback(resolve, reject));
499
+ });
500
+ log.debug("check: res", res);
501
+ if (Array.isArray(res) && res.length > 0) {
502
+ if (_classPrivateFieldGet(_confirmationStrategy, this) === CONFIRMATION_STRATEGY.AUTO_APPROVE) log.warn("Confirmation strategy auto approve is not allowed on Embed Mode, using Default instead.");
503
+ return res;
504
+ }
505
+ // This would never happen, but just in case
506
+ throw new Error("Login failed");
507
+ } catch (error) {
508
+ log.error("login failed", error);
509
+ throw error;
510
+ }
511
+ }
512
+ async function _realmLogin(options, isLegacyLogin) {
513
+ const skipClaimFlow = (options === null || options === void 0 ? void 0 : options.skipClaiming) === true;
514
+ try {
515
+ if (options !== null && options !== void 0 && options.authToken) {
516
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
517
+ isVisible: false
518
+ });
519
+ }
520
+ const loginPromise = Promise.all([_assertClassBrand(_RealmEmbed_brand, this, _authLogin).call(this), AirMessageService.sendLoginRequest(_classPrivateFieldGet(_walletIframe, this), {
521
+ skipClaimFlow,
522
+ token: options === null || options === void 0 ? void 0 : options.token,
523
+ customAuthToken: options === null || options === void 0 ? void 0 : options.authToken,
524
+ isLegacyLogin: !!isLegacyLogin
525
+ })]);
526
+ log.debug("start logging in...");
527
+ await loginPromise;
528
+ log.debug("login ended");
529
+ return _assertClassBrand(_RealmEmbed_brand, this, _createLoginResult).call(this);
530
+ } catch (e) {
531
+ await _assertClassBrand(_RealmEmbed_brand, this, _logout).call(this);
532
+ throw RealmEmbedError.from(e);
533
+ } finally {
534
+ if (options !== null && options !== void 0 && options.authToken) {
535
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
536
+ isVisible: true
537
+ });
538
+ }
539
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
540
+ isFull: false
541
+ });
542
+ }
543
+ }
544
+ async function _logout() {
545
+ var _classPrivateFieldGet6;
546
+ const silent = !_classPrivateFieldGet(_walletAddresses, this);
547
+ if ((_classPrivateFieldGet6 = _classPrivateFieldGet(_communicationProvider, this)) !== null && _classPrivateFieldGet6 !== void 0 && _classPrivateFieldGet6.isLoggedIn) {
548
+ await _classPrivateFieldGet(_communicationProvider, this).request({
549
+ method: COMMUNICATION_JRPC_METHODS.LOGOUT,
550
+ params: []
551
+ });
552
+ }
553
+ if (_classPrivateFieldGet(_communicationProvider, this)) _classPrivateFieldGet(_communicationProvider, this).onLoginStateHandle = undefined;
554
+ _classPrivateFieldSet(_walletAddresses, this, undefined);
555
+ _classPrivateFieldSet(_realmId, this, undefined);
556
+ if (!silent) {
557
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
558
+ event: "logged_out"
559
+ });
560
+ }
561
+ }
562
+ async function _clearInit(isSilent) {
563
+ function isElement(element) {
564
+ return element instanceof Element || element instanceof Document;
565
+ }
566
+ if (isElement(_classPrivateFieldGet(_walletIframe, this)) && window.document.body.contains(_classPrivateFieldGet(_walletIframe, this))) {
567
+ _classPrivateFieldGet(_walletIframe, this).remove();
568
+ _classPrivateFieldSet(_walletIframe, this, undefined);
569
+ }
570
+ AirMessageService.closeRealmObservables();
571
+ _classPrivateFieldSet(_isInitialized, this, false);
572
+ _classPrivateFieldSet(_walletAddresses, this, undefined);
573
+ _classPrivateFieldSet(_realmId, this, undefined);
574
+ if (isSilent === true) _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
575
+ event: "reset"
576
+ });
577
+ }
578
+ function _getConfirmationStrategyFinal(payload, communicationProvider) {
579
+ // for external wallets, we'll show the modal and don't need to open a new window
580
+ let confirmationStrategyFinal = _classPrivateFieldGet(_confirmationStrategy, this);
581
+ if (!Array.isArray(payload) && PROVIDER_UNSAFE_METHODS.has(payload.method) && _classPrivateFieldGet(_confirmationStrategy, this) !== CONFIRMATION_STRATEGY.MODAL && !_classPrivateFieldGet(_isPluginMode, this) && !communicationProvider.isExternalWallet) {
582
+ confirmationStrategyFinal = CONFIRMATION_STRATEGY.POPUP;
583
+ }
584
+ return confirmationStrategyFinal;
585
+ }
586
+ async function _setupWeb(providerParams) {
587
+ log.debug("setup embed communication...");
588
+ // setup background connection
589
+ const providerStream = new BasePostMessageStream({
590
+ name: "embed_torus",
591
+ target: "iframe_torus",
592
+ targetWindow: _classPrivateFieldGet(_walletIframe, this).contentWindow,
593
+ targetOrigin: new URL(providerParams.torusUrl).origin
594
+ });
595
+
596
+ // We create another LocalMessageDuplexStream for communication between dapp <> iframe
597
+ const communicationStream = new BasePostMessageStream({
598
+ name: "embed_communication",
599
+ target: "iframe_communication",
600
+ targetWindow: _classPrivateFieldGet(_walletIframe, this).contentWindow,
601
+ targetOrigin: new URL(providerParams.torusUrl).origin
602
+ });
603
+
604
+ // compose the inPage provider
605
+ const inPageProvider = new TorusInPageProvider(providerStream, {});
606
+ const communicationProvider = new CommunicationProvider(communicationStream, {}, {
607
+ buttonPosition: _classPrivateFieldGet(_buttonPosition, this)
608
+ });
609
+ inPageProvider.tryWindowHandle = (payload, cb) => {
610
+ const _payload = payload;
611
+ const confirmationStrategyFinal = _assertClassBrand(_RealmEmbed_brand, this, _getConfirmationStrategyFinal).call(this, payload, communicationProvider);
612
+ if (confirmationStrategyFinal === CONFIRMATION_STRATEGY.POPUP) {
613
+ const windowId = randomId();
614
+ communicationProvider.handleWindow(windowId, {
615
+ target: "_blank",
616
+ features: getPopupFeatures(FEATURES_CONFIRM_WINDOW),
617
+ timeout: 500
618
+ });
619
+ // for inPageProvider methods sending windowId in request instead of params
620
+ // as params might be positional.
621
+ _payload.windowId = windowId;
622
+ }
623
+ inPageProvider.rpcEngine.handle(_payload, cb);
624
+ };
625
+ communicationProvider.tryWindowHandle = (payload, cb) => {
626
+ const _payload = payload;
627
+ const confirmationStrategyFinal = _assertClassBrand(_RealmEmbed_brand, this, _getConfirmationStrategyFinal).call(this, payload, communicationProvider);
628
+ if (confirmationStrategyFinal === CONFIRMATION_STRATEGY.POPUP) {
629
+ const windowId = randomId();
630
+ communicationProvider.handleWindow(windowId, {
631
+ target: "_blank",
632
+ features: getPopupFeatures(FEATURES_PROVIDER_CHANGE_WINDOW),
633
+ // todo: are these features generic for all
634
+ timeout: 500
635
+ });
636
+ // for communication methods sending window id in jrpc req params
637
+ _payload.params.windowId = windowId;
638
+ }
639
+ communicationProvider.rpcEngine.handle(_payload, cb);
640
+ };
641
+
642
+ // detect eth_requestAccounts and pipe to enable for now
643
+ const detectAccountRequestPrototypeModifier = m => {
644
+ const originalMethod = inPageProvider[m];
645
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
646
+ const self = this;
647
+
648
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
649
+ // @ts-ignore
650
+ inPageProvider[m] = function providerFunc(request, cb) {
651
+ const {
652
+ method,
653
+ params = []
654
+ } = request;
655
+ if (method === "eth_requestAccounts") {
656
+ let login = _assertClassBrand(_RealmEmbed_brand, self, _authLogin).call(self, {
657
+ loginProvider: params[0]
658
+ });
659
+ if (cb) {
660
+ login = login.then(res => cb(null, res)).catch(err => cb(err));
661
+ }
662
+ return login.finally(() => {
663
+ _classPrivateFieldGet(_communicationProvider, self).displayIframe({
664
+ isFull: false
665
+ });
666
+ });
667
+ }
668
+ return originalMethod.apply(this, [request, cb]);
669
+ };
670
+ };
671
+
672
+ // Detects call to eth_requestAccounts in request & sendAsync and passes to login
673
+ detectAccountRequestPrototypeModifier("request");
674
+ detectAccountRequestPrototypeModifier("sendAsync");
675
+ detectAccountRequestPrototypeModifier("send");
676
+ const proxiedInPageProvider = new Proxy(inPageProvider, {
677
+ // straight up lie that we deleted the property so that it doesn't
678
+ // throw an error in strict mode
679
+ deleteProperty: () => true
680
+ });
681
+ const proxiedCommunicationProvider = new Proxy(communicationProvider, {
682
+ // straight up lie that we deleted the property so that it doesn't
683
+ // throw an error in strict mode
684
+ deleteProperty: () => true
685
+ });
686
+ _classPrivateFieldSet(_provider, this, proxiedInPageProvider);
687
+ _classPrivateFieldSet(_communicationProvider, this, proxiedCommunicationProvider);
688
+ await Promise.all([inPageProvider.initializeState(), communicationProvider.initializeState(_objectSpread(_objectSpread({}, providerParams), {}, {
689
+ torusIframeId: _classPrivateFieldGet(_walletIframe, this).id
690
+ }))]);
691
+ log.debug("embed communication setup ended");
692
+ }
693
+ function _triggerEvent(data) {
694
+ const listenersCopy = [..._classPrivateFieldGet(_embedListeners, this)];
695
+ listenersCopy.forEach(listener => {
696
+ try {
697
+ listener(data);
698
+ } catch (error) {
699
+ log.error(error);
700
+ }
701
+ });
702
+ }
703
+ function _triggerInitializedEvent() {
704
+ if (_classPrivateFieldGet(_isInitialized, this) && _classPrivateFieldGet(_rehydrationState, this)) {
705
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
706
+ event: "initialized",
707
+ result: {
708
+ rehydration: _classPrivateFieldGet(_rehydrationState, this)
709
+ }
710
+ });
711
+ }
712
+ }
713
+ function _onInitialized() {
714
+ return new Promise(resolve => {
715
+ if (!_classPrivateFieldGet(_isInitialized, this) || !_classPrivateFieldGet(_rehydrationState, this)) {
716
+ const sub = event => {
717
+ log.debug("onInitialized:", event);
718
+ if (event.event === "initialized") {
719
+ this.off(sub);
720
+ resolve();
721
+ }
722
+ };
723
+ this.on(sub);
724
+ } else {
725
+ resolve();
726
+ }
727
+ });
728
+ }
729
+
730
+ export { PROVIDER_UNSAFE_METHODS, RealmEmbed as default };