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