@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,2468 @@
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 { createLoggerMiddleware, getPopupFeatures, FEATURES_DEFAULT_POPUP_WINDOW, COMMUNICATION_JRPC_METHODS, COMMUNICATION_NOTIFICATIONS, PROVIDER_JRPC_METHODS, PROVIDER_NOTIFICATIONS, CHAIN_NAMESPACES, randomId, CONFIRMATION_STRATEGY, BUTTON_POSITION as BUTTON_POSITION$1, SETUP_COMPLETE, FEATURES_CONFIRM_WINDOW, FEATURES_PROVIDER_CHANGE_WINDOW } from '@toruslabs/base-controllers';
5
+ export { CONFIRMATION_STRATEGY } from '@toruslabs/base-controllers';
6
+ import { METHOD_TYPES } from '@toruslabs/ethereum-controllers';
7
+ import { rpcErrors, SafeEventEmitter, ObjectMultiplex, createStreamMiddleware, JRPCEngine, createIdRemapMiddleware, getRpcPromiseCallback, EthereumProviderError, WEB3AUTH_NETWORK, BasePostMessageStream } from '@web3auth/auth';
8
+ import _defineProperty from '@babel/runtime/helpers/defineProperty';
9
+ import pump from 'pump';
10
+ import loglevel from 'loglevel';
11
+ import dequal from 'fast-deep-equal';
12
+ import { firstValueFrom, filter, lastValueFrom, takeWhile, tap, forkJoin, last, first, Subject, distinctUntilChanged } from 'rxjs';
13
+
14
+ const AirAuthMessageTypes = {
15
+ SETUP_COMPLETED: "air_auth_setup_completed",
16
+ LOGIN_REQUEST: "air_auth_login_request",
17
+ LOGIN_RESPONSE: "air_auth_login_response",
18
+ LOGIN_WALLET_RESPONSE: "air_auth_login_wallet_response",
19
+ USER_INFO_REQUEST: "air_auth_user_info_request",
20
+ USER_INFO_RESPONSE: "air_auth_user_info_response",
21
+ PARTNER_USER_INFO_REQUEST: "air_auth_partner_user_info_request",
22
+ PARTNER_USER_INFO_RESPONSE: "air_auth_partner_user_info_response",
23
+ REFRESH_TOKEN_REQUEST: "air_auth_refresh_token_request",
24
+ REFRESH_TOKEN_RESPONSE: "air_auth_refresh_token_response",
25
+ WALLET_TOKEN_REQUEST: "air_auth_wallet_token_request",
26
+ WALLET_TOKEN_RESPONSE: "air_auth_wallet_token_response",
27
+ INITIALIZATION_REQUEST: "air_auth_initialization_request",
28
+ INITIALIZATION_RESPONSE: "air_auth_initialization_response",
29
+ INIT_WALLET_COMMUNICATION: "air_auth_init_wallet_communication",
30
+ IFRAME_VISIBILITY_REQUEST: "air_auth_iframe_visibility_request",
31
+ SETUP_WALLET_REQUEST: "air_auth_setup_wallet_request",
32
+ SETUP_WALLET_RESPONSE: "air_auth_setup_wallet_response",
33
+ SIGN_SIWE_MESSAGE_REQUEST: "air_auth_sign_siwe_message_request",
34
+ SIGN_SIWE_MESSAGE_RESPONSE: "air_auth_sign_siwe_message_response",
35
+ LOGOUT_REQUEST: "air_auth_logout_request",
36
+ LOGOUT_RESPONSE: "air_auth_logout_response"
37
+ };
38
+
39
+ const AirMessageTypes = {
40
+ SERVICE_INITIALIZED: "air_service_initialized",
41
+ SERVICE_INITIALIZED_ERROR: "air_service_initialized_error",
42
+ LOGIN_REQUEST: "air_login_request",
43
+ CLAIM_REQUEST: "air_claim_request",
44
+ LOGIN_CLAIM_STATE: "air_login_claim_state",
45
+ CLOSE_MODAL: "air_close_modal",
46
+ INIT_AUTH_COMMUNICATION: "air_init_auth_communication",
47
+ DEPLOY_SMART_ACCOUNT_REQUEST: "air_deploy_smart_account_request",
48
+ DEPLOY_SMART_ACCOUNT_RESPONSE: "air_deploy_smart_account_response"
49
+ };
50
+
51
+ /* eslint-disable @typescript-eslint/no-explicit-any */
52
+ function isStream(stream) {
53
+ return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
54
+ }
55
+ function isWritableStream(stream) {
56
+ return isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
57
+ }
58
+ function isReadableStream(stream) {
59
+ return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
60
+ }
61
+ function isDuplexStream(stream) {
62
+ return isWritableStream(stream) && isReadableStream(stream);
63
+ }
64
+
65
+ var messages = {
66
+ errors: {
67
+ disconnected: () => "Web3Auth: Lost connection to Web3Auth.",
68
+ permanentlyDisconnected: () => "Web3Auth: Disconnected from iframe. Page reload required.",
69
+ unsupportedSync: method => `Web3Auth: The Web3Auth Ethereum provider does not support synchronous methods like ${method} without a callback parameter.`,
70
+ invalidDuplexStream: () => "Must provide a Node.js-style duplex stream.",
71
+ invalidOptions: maxEventListeners => `Invalid options. Received: { maxEventListeners: ${maxEventListeners}}`,
72
+ invalidRequestArgs: () => `Expected a single, non-array, object argument.`,
73
+ invalidRequestMethod: () => `'args.method' must be a non-empty string.`,
74
+ invalidRequestParams: () => `'args.params' must be an object or array if provided.`,
75
+ invalidLoggerObject: () => `'args.logger' must be an object if provided.`,
76
+ invalidLoggerMethod: method => `'args.logger' must include required method '${method}'.`
77
+ },
78
+ info: {
79
+ connected: chainId => `Web3Auth: Connected to chain with ID "${chainId}".`
80
+ },
81
+ warnings: {}
82
+ };
83
+
84
+ const EMBED_BUILD_ENV = {
85
+ PRODUCTION: "production",
86
+ STAGING: "staging",
87
+ DEVELOPMENT: "development",
88
+ TESTING: "testing"
89
+ };
90
+ const BUTTON_POSITION = {
91
+ BOTTOM_LEFT: "bottom-left",
92
+ TOP_LEFT: "top-left",
93
+ BOTTOM_RIGHT: "bottom-right",
94
+ TOP_RIGHT: "top-right"
95
+ };
96
+ const EXTERNAL_LOGIN_PROVIDER = {
97
+ METAMASK: "metamask",
98
+ WALLET_CONNECT: "walletconnect",
99
+ WAGMI: "wagmi"
100
+ };
101
+
102
+ var log = loglevel.getLogger("ws-embed");
103
+
104
+ const AIR_URLS = {
105
+ [EMBED_BUILD_ENV.TESTING]: {
106
+ authUrl: "http://localhost:8100",
107
+ walletUrl: "https://lrc-mocaverse.web3auth.io",
108
+ logLevel: "debug"
109
+ },
110
+ [EMBED_BUILD_ENV.DEVELOPMENT]: {
111
+ authUrl: "http://localhost:8100",
112
+ walletUrl: "https://localhost:4050",
113
+ logLevel: "debug"
114
+ },
115
+ [EMBED_BUILD_ENV.STAGING]: {
116
+ authUrl: "https://login.staging.realmnetwork.io",
117
+ walletUrl: "https://account.staging.realmnetwork.io",
118
+ logLevel: "info"
119
+ },
120
+ [EMBED_BUILD_ENV.PRODUCTION]: {
121
+ authUrl: "https://login.realmnetwork.io",
122
+ walletUrl: "https://account.realmnetwork.io",
123
+ logLevel: "error"
124
+ }
125
+ };
126
+ const htmlToElement = html => {
127
+ const template = window.document.createElement("template");
128
+ const trimmedHtml = html.trim(); // Never return a text node of whitespace as the result
129
+ template.innerHTML = trimmedHtml;
130
+ return template.content.firstChild;
131
+ };
132
+ const isElement = element => element instanceof Element || element instanceof Document;
133
+
134
+ /**
135
+ * json-rpc-engine middleware that logs RPC errors and and validates req.method.
136
+ *
137
+ * @param log - The logging API to use.
138
+ * @returns json-rpc-engine middleware function
139
+ */
140
+ function createErrorMiddleware() {
141
+ return (req, res, next) => {
142
+ // json-rpc-engine will terminate the request when it notices this error
143
+ if (typeof req.method !== "string" || !req.method) {
144
+ res.error = rpcErrors.invalidRequest({
145
+ message: `The request 'method' must be a non-empty string.`,
146
+ data: _objectSpread(_objectSpread({}, req || {}), {}, {
147
+ cause: `The request 'method' must be a non-empty string.`
148
+ })
149
+ });
150
+ }
151
+ next(done => {
152
+ const {
153
+ error
154
+ } = res;
155
+ if (!error) {
156
+ return done();
157
+ }
158
+ log.error(`Ws-Embed - RPC Error: ${error.message}`, error);
159
+ return done();
160
+ });
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Logs a stream disconnection error. Emits an 'error' if given an
166
+ * EventEmitter that has listeners for the 'error' event.
167
+ *
168
+ * @param log - The logging API to use.
169
+ * @param remoteLabel - The label of the disconnected stream.
170
+ * @param error - The associated error to log.
171
+ * @param emitter - The logging API to use.
172
+ */
173
+ function logStreamDisconnectWarning(remoteLabel, error, emitter) {
174
+ let warningMsg = `Web3Auth: Lost connection to "${remoteLabel}".`;
175
+ if (error !== null && error !== void 0 && error.stack) {
176
+ warningMsg += `\n${error.stack}`;
177
+ }
178
+ log.warn(warningMsg);
179
+ if (emitter && emitter.listenerCount("error") > 0) {
180
+ emitter.emit("error", warningMsg);
181
+ }
182
+ }
183
+ const EMITTED_NOTIFICATIONS = ["eth_subscription" // per eth-json-rpc-filters/subscriptionManager
184
+ ];
185
+
186
+ /**
187
+ * @param connectionStream - A Node.js duplex stream
188
+ * @param opts - An options bag
189
+ */
190
+ class BaseProvider extends SafeEventEmitter {
191
+ constructor(connectionStream, {
192
+ maxEventListeners = 100,
193
+ jsonRpcStreamName = "provider"
194
+ }) {
195
+ super();
196
+ _defineProperty(this, "rpcEngine", void 0);
197
+ _defineProperty(this, "jsonRpcConnectionEvents", void 0);
198
+ /**
199
+ * Indicating that this provider is a Web3Auth provider.
200
+ */
201
+ _defineProperty(this, "isWeb3Auth", void 0);
202
+ _defineProperty(this, "state", void 0);
203
+ if (!isDuplexStream(connectionStream)) {
204
+ throw new Error(messages.errors.invalidDuplexStream());
205
+ }
206
+ this.isWeb3Auth = true;
207
+ this.setMaxListeners(maxEventListeners);
208
+ this.handleConnect = this.handleConnect.bind(this);
209
+ this.handleDisconnect = this.handleDisconnect.bind(this);
210
+ this.handleStreamDisconnect = this.handleStreamDisconnect.bind(this);
211
+ this.rpcRequest = this.rpcRequest.bind(this);
212
+ this.initializeState = this.initializeState.bind(this);
213
+ this.request = this.request.bind(this);
214
+ this.sendAsync = this.sendAsync.bind(this);
215
+ this.send = this.send.bind(this);
216
+ // this.enable = this.enable.bind(this);
217
+
218
+ // setup connectionStream multiplexing
219
+ const mux = new ObjectMultiplex();
220
+ pump(connectionStream, mux, connectionStream, this.handleStreamDisconnect.bind(this, "Web3Auth"));
221
+
222
+ // ignore phishing warning message (handled elsewhere)
223
+ mux.ignoreStream("phishing");
224
+
225
+ // setup own event listeners
226
+ // connect to async provider
227
+
228
+ const jsonRpcConnection = createStreamMiddleware();
229
+ pump(jsonRpcConnection.stream, mux.createStream(jsonRpcStreamName), jsonRpcConnection.stream, this.handleStreamDisconnect.bind(this, "Web3Auth RpcProvider"));
230
+
231
+ // handle RPC requests via dapp-side rpc engine
232
+ const rpcEngine = new JRPCEngine();
233
+ rpcEngine.push(createIdRemapMiddleware());
234
+ rpcEngine.push(createErrorMiddleware());
235
+ rpcEngine.push(createLoggerMiddleware({
236
+ origin: location.origin
237
+ }));
238
+ rpcEngine.push(jsonRpcConnection.middleware);
239
+ this.rpcEngine = rpcEngine;
240
+ this.jsonRpcConnectionEvents = jsonRpcConnection.events;
241
+ }
242
+
243
+ /**
244
+ * Submits an RPC request for the given method, with the given params.
245
+ * Resolves with the result of the method call, or rejects on error.
246
+ *
247
+ * @param args - The RPC request arguments.
248
+ * @returns A Promise that resolves with the result of the RPC method,
249
+ * or rejects if an error is encountered.
250
+ */
251
+ async request(args) {
252
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
253
+ throw rpcErrors.invalidRequest({
254
+ message: messages.errors.invalidRequestArgs(),
255
+ data: _objectSpread(_objectSpread({}, args || {}), {}, {
256
+ cause: messages.errors.invalidRequestArgs()
257
+ })
258
+ });
259
+ }
260
+ const {
261
+ method,
262
+ params
263
+ } = args;
264
+ if (typeof method !== "string" || method.length === 0) {
265
+ throw rpcErrors.invalidRequest({
266
+ message: messages.errors.invalidRequestMethod(),
267
+ data: _objectSpread(_objectSpread({}, args || {}), {}, {
268
+ cause: messages.errors.invalidRequestArgs()
269
+ })
270
+ });
271
+ }
272
+ if (params !== undefined && !Array.isArray(params) && (typeof params !== "object" || params === null)) {
273
+ throw rpcErrors.invalidRequest({
274
+ message: messages.errors.invalidRequestParams(),
275
+ data: _objectSpread(_objectSpread({}, args || {}), {}, {
276
+ cause: messages.errors.invalidRequestArgs()
277
+ })
278
+ });
279
+ }
280
+ return new Promise((resolve, reject) => {
281
+ this.rpcRequest({
282
+ method,
283
+ params
284
+ }, getRpcPromiseCallback(resolve, reject));
285
+ });
286
+ }
287
+ /**
288
+ * Submits an RPC request per the given JSON-RPC request object.
289
+ *
290
+ * @param payload - The RPC request object.
291
+ * @param cb - The callback function.
292
+ */
293
+ send(payload, callback) {
294
+ this.rpcRequest(payload, callback);
295
+ }
296
+ /**
297
+ * Submits an RPC request per the given JSON-RPC request object.
298
+ *
299
+ * @param payload - The RPC request object.
300
+ * @param cb - The callback function.
301
+ */
302
+ sendAsync(payload) {
303
+ return new Promise((resolve, reject) => {
304
+ this.rpcRequest(payload, getRpcPromiseCallback(resolve, reject));
305
+ });
306
+ }
307
+
308
+ /**
309
+ * Called when connection is lost to critical streams.
310
+ *
311
+ * emits InpageProvider#disconnect
312
+ */
313
+ handleStreamDisconnect(streamName, error) {
314
+ logStreamDisconnectWarning(streamName, error, this);
315
+ this.handleDisconnect(false, error ? error.message : undefined);
316
+ }
317
+
318
+ // Private Methods
319
+ //= ===================
320
+ /**
321
+ * Constructor helper.
322
+ * Populates initial state by calling 'wallet_getProviderState' and emits
323
+ * necessary events.
324
+ */
325
+
326
+ /**
327
+ * Internal RPC method. Forwards requests to background via the RPC engine.
328
+ * Also remap ids inbound and outbound
329
+ */
330
+
331
+ /**
332
+ * When the provider becomes connected, updates internal state and emits
333
+ * required events. Idempotent.
334
+ *
335
+ * @param chainId - The ID of the newly connected chain.
336
+ * emits InPageProvider#connect
337
+ */
338
+
339
+ /**
340
+ * When the provider becomes disconnected, updates internal state and emits
341
+ * required events. Idempotent with respect to the isRecoverable parameter.
342
+ *
343
+ * Error codes per the CloseEvent status codes as required by EIP-1193:
344
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
345
+ *
346
+ * @param isRecoverable - Whether the disconnection is recoverable.
347
+ * @param errorMessage - A custom error message.
348
+ * emits InpageProvider#disconnect
349
+ */
350
+ }
351
+
352
+ class PopupHandler extends SafeEventEmitter {
353
+ constructor({
354
+ url,
355
+ target,
356
+ features,
357
+ timeout = 30000
358
+ }) {
359
+ super();
360
+ _defineProperty(this, "url", void 0);
361
+ _defineProperty(this, "target", void 0);
362
+ _defineProperty(this, "features", void 0);
363
+ _defineProperty(this, "window", void 0);
364
+ _defineProperty(this, "windowTimer", void 0);
365
+ _defineProperty(this, "iClosedWindow", void 0);
366
+ _defineProperty(this, "timeout", void 0);
367
+ this.url = url;
368
+ this.target = target || "_blank";
369
+ this.features = features || getPopupFeatures(FEATURES_DEFAULT_POPUP_WINDOW);
370
+ this.window = undefined;
371
+ this.windowTimer = undefined;
372
+ this.iClosedWindow = false;
373
+ this.timeout = timeout;
374
+ this._setupTimer();
375
+ }
376
+ _setupTimer() {
377
+ this.windowTimer = Number(setInterval(() => {
378
+ if (this.window && this.window.closed) {
379
+ clearInterval(this.windowTimer);
380
+ setTimeout(() => {
381
+ if (!this.iClosedWindow) {
382
+ this.emit("close");
383
+ }
384
+ this.iClosedWindow = false;
385
+ this.window = undefined;
386
+ }, this.timeout);
387
+ }
388
+ if (this.window === undefined) clearInterval(this.windowTimer);
389
+ }, 500));
390
+ }
391
+ open() {
392
+ var _this$window;
393
+ this.window = window.open(this.url.href, this.target, this.features);
394
+ if ((_this$window = this.window) !== null && _this$window !== void 0 && _this$window.focus) this.window.focus();
395
+ }
396
+ close() {
397
+ this.iClosedWindow = true;
398
+ if (this.window) this.window.close();
399
+ }
400
+ redirect(locationReplaceOnRedirect) {
401
+ if (locationReplaceOnRedirect) {
402
+ window.location.replace(this.url.href);
403
+ } else {
404
+ window.location.href = this.url.href;
405
+ }
406
+ }
407
+ }
408
+
409
+ /**
410
+ * @param connectionStream - A Node.js duplex stream
411
+ * @param opts - An options bag
412
+ */
413
+ class CommunicationProvider extends BaseProvider {
414
+ constructor(connectionStream, {
415
+ maxEventListeners = 100,
416
+ jsonRpcStreamName = "provider"
417
+ }, state) {
418
+ super(connectionStream, {
419
+ maxEventListeners,
420
+ jsonRpcStreamName
421
+ });
422
+
423
+ // private state
424
+ _defineProperty(this, "tryWindowHandle", void 0);
425
+ _defineProperty(this, "onLoginStateHandle", void 0);
426
+ _defineProperty(this, "windowRefs", void 0);
427
+ _defineProperty(this, "iframeUrl", void 0);
428
+ _defineProperty(this, "iframeId", void 0);
429
+ this.state = _objectSpread(_objectSpread({}, CommunicationProvider.defaultState), state);
430
+
431
+ // public state
432
+ this.iframeUrl = "";
433
+ this.iframeId = "";
434
+ this.windowRefs = new Map();
435
+
436
+ // setup own event listeners
437
+
438
+ // EIP-1193 connect
439
+ this.on("connect", () => {
440
+ this.state.isConnected = true;
441
+ });
442
+ const notificationHandler = payload => {
443
+ const {
444
+ method,
445
+ params
446
+ } = payload;
447
+ // create_window should never come here..
448
+ // we either pre-open from embed.
449
+ // if it's blocked, we communicate down that it's blocked and we show full screen iframe and open from iframe
450
+ if (method === COMMUNICATION_NOTIFICATIONS.IFRAME_STATUS) {
451
+ const {
452
+ isFullScreen,
453
+ rid
454
+ } = params;
455
+ this.displayIframe({
456
+ isFull: isFullScreen,
457
+ rid: rid
458
+ }, true);
459
+ } else if (method === COMMUNICATION_NOTIFICATIONS.CLOSE_WINDOW) {
460
+ this.handleCloseWindow(params);
461
+ } else if (method === COMMUNICATION_NOTIFICATIONS.USER_LOGGED_IN) {
462
+ log.info("[TEST METAMASK] User received notification ", COMMUNICATION_NOTIFICATIONS.USER_LOGGED_IN);
463
+ const {
464
+ currentLoginProvider
465
+ } = params;
466
+ this.state.isLoggedIn = true;
467
+ this.state.currentLoginProvider = currentLoginProvider;
468
+ if (this.onLoginStateHandle) this.onLoginStateHandle(true);
469
+ } else if (method === COMMUNICATION_NOTIFICATIONS.USER_LOGGED_OUT) {
470
+ this.state.isLoggedIn = false;
471
+ this.state.currentLoginProvider = null;
472
+ this.displayIframe();
473
+ if (this.onLoginStateHandle) this.onLoginStateHandle(false);
474
+ }
475
+ };
476
+ this.jsonRpcConnectionEvents.on("notification", notificationHandler);
477
+ }
478
+ get isLoggedIn() {
479
+ return this.state.isLoggedIn;
480
+ }
481
+
482
+ // e.g. Metamask, WalletConnect, etc.
483
+ get isExternalWallet() {
484
+ return !this.state.currentLoginProvider || this.state.currentLoginProvider === EXTERNAL_LOGIN_PROVIDER.METAMASK || this.state.currentLoginProvider === EXTERNAL_LOGIN_PROVIDER.WALLET_CONNECT || this.state.currentLoginProvider === EXTERNAL_LOGIN_PROVIDER.WAGMI;
485
+ }
486
+ get isIFrameFullScreen() {
487
+ return this.state.isIFrameFullScreen;
488
+ }
489
+
490
+ /**
491
+ * Returns whether the inPage provider is connected to Torus.
492
+ */
493
+ isConnected() {
494
+ return this.state.isConnected;
495
+ }
496
+ async initializeState(params) {
497
+ try {
498
+ const {
499
+ torusUrl,
500
+ torusIframeId
501
+ } = params;
502
+ this.iframeUrl = torusUrl;
503
+ this.iframeId = torusIframeId;
504
+ const {
505
+ currentLoginProvider,
506
+ isLoggedIn
507
+ } = await this.request({
508
+ method: COMMUNICATION_JRPC_METHODS.GET_PROVIDER_STATE,
509
+ params: []
510
+ });
511
+
512
+ // indicate that we've connected, for EIP-1193 compliance
513
+ if (isLoggedIn) this.handleConnect(currentLoginProvider, isLoggedIn);
514
+ } catch (error) {
515
+ log.error("Web3Auth: Failed to get initial state. Please report this bug.", error);
516
+ } finally {
517
+ log.info("initialized communication state");
518
+ this.state.initialized = true;
519
+ }
520
+ }
521
+ hideTorusButton() {
522
+ this.state.widgetVisibility = false;
523
+ this.displayIframe();
524
+ }
525
+ showTorusButton() {
526
+ this.state.widgetVisibility = true;
527
+ this.displayIframe();
528
+ }
529
+ moveToBackground() {
530
+ this.state.isBackground = true;
531
+ this.displayIframe({
532
+ isFull: this.state.isIFrameFullScreen
533
+ });
534
+ }
535
+ moveToForeground() {
536
+ this.state.isBackground = false;
537
+ this.displayIframe({
538
+ isFull: this.state.isIFrameFullScreen
539
+ });
540
+ }
541
+ setIframeVisibility({
542
+ isVisible
543
+ }) {
544
+ this.state.isBackground = !isVisible;
545
+ }
546
+ displayIframe({
547
+ isFull = false,
548
+ rid = ""
549
+ } = {}, walletRequest = false) {
550
+ const style = {};
551
+ // set phase
552
+ if (!isFull) {
553
+ style.display = this.state.widgetVisibility && !this.state.isBackground ? "block" : "none";
554
+ style.height = "70px";
555
+ style.width = "70px";
556
+ switch (this.state.buttonPosition) {
557
+ case BUTTON_POSITION.TOP_LEFT:
558
+ style.top = "0px";
559
+ style.left = "0px";
560
+ style.right = "auto";
561
+ style.bottom = "auto";
562
+ break;
563
+ case BUTTON_POSITION.TOP_RIGHT:
564
+ style.top = "0px";
565
+ style.right = "0px";
566
+ style.left = "auto";
567
+ style.bottom = "auto";
568
+ break;
569
+ case BUTTON_POSITION.BOTTOM_RIGHT:
570
+ style.bottom = "0px";
571
+ style.right = "0px";
572
+ style.top = "auto";
573
+ style.left = "auto";
574
+ break;
575
+ case BUTTON_POSITION.BOTTOM_LEFT:
576
+ default:
577
+ style.bottom = "0px";
578
+ style.left = "0px";
579
+ style.top = "auto";
580
+ style.right = "auto";
581
+ break;
582
+ }
583
+ } else {
584
+ style.display = this.state.isBackground ? "none" : "block";
585
+ style.width = "100%";
586
+ style.height = "100%";
587
+ style.top = "0px";
588
+ style.right = "0px";
589
+ style.left = "0px";
590
+ style.bottom = "0px";
591
+ }
592
+ const iframe = document.getElementById(this.iframeId);
593
+ Object.assign(iframe.style, style);
594
+ this.state.isIFrameFullScreen = isFull;
595
+ if (!walletRequest) {
596
+ this.request({
597
+ method: COMMUNICATION_JRPC_METHODS.IFRAME_STATUS,
598
+ params: {
599
+ isIFrameFullScreen: isFull,
600
+ rid
601
+ }
602
+ });
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Scenarios:
608
+ * - Login request or pre-open confirmation windows
609
+ * We try to open here or send a rpc request to iframe that window is blocked.
610
+ */
611
+ async handleWindow(windowId, {
612
+ url,
613
+ target,
614
+ features,
615
+ timeout
616
+ } = {}) {
617
+ const finalUrl = new URL(url || `${this.iframeUrl}/redirect?windowId=${windowId}&sessionNamespace=${window.location.hostname}`);
618
+ const handledWindow = new PopupHandler({
619
+ url: finalUrl,
620
+ target,
621
+ features,
622
+ timeout
623
+ });
624
+ handledWindow.open();
625
+ if (!handledWindow.window) {
626
+ this.displayIframe({
627
+ isFull: true
628
+ });
629
+ this.request({
630
+ method: COMMUNICATION_JRPC_METHODS.WINDOW_BLOCKED,
631
+ params: {
632
+ windowId,
633
+ finalUrl: finalUrl.href
634
+ }
635
+ });
636
+ return;
637
+ }
638
+ // Add to collection only if window is opened
639
+ this.windowRefs.set(windowId, handledWindow);
640
+ handledWindow.once("close", () => {
641
+ // user closed the window
642
+ this.windowRefs.delete(windowId);
643
+ this.request({
644
+ method: COMMUNICATION_JRPC_METHODS.CLOSED_WINDOW,
645
+ params: {
646
+ windowId
647
+ }
648
+ });
649
+ });
650
+ }
651
+
652
+ /**
653
+ * Internal RPC method. Forwards requests to background via the RPC engine.
654
+ * Also remap ids inbound and outbound
655
+ */
656
+ rpcRequest(payload, callback) {
657
+ const cb = callback;
658
+ const _payload = payload;
659
+ if (!Array.isArray(_payload)) {
660
+ if (!_payload.jsonrpc) {
661
+ _payload.jsonrpc = "2.0";
662
+ }
663
+ }
664
+ this.rpcEngine.handle(_payload, cb);
665
+ }
666
+
667
+ /**
668
+ * When the provider becomes connected, updates internal state and emits
669
+ * required events. Idempotent.
670
+ *
671
+ * @param currentLoginProvider - The login Provider
672
+ * emits TorusInpageProvider#connect
673
+ */
674
+ handleConnect(currentLoginProvider, isLoggedIn) {
675
+ if (!this.state.isConnected) {
676
+ this.state.isConnected = true;
677
+ this.emit("connect", {
678
+ currentLoginProvider,
679
+ isLoggedIn
680
+ });
681
+ log.debug(messages.info.connected(currentLoginProvider));
682
+ }
683
+ }
684
+
685
+ /**
686
+ * When the provider becomes disconnected, updates internal state and emits
687
+ * required events. Idempotent with respect to the isRecoverable parameter.
688
+ *
689
+ * Error codes per the CloseEvent status codes as required by EIP-1193:
690
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
691
+ *
692
+ * @param isRecoverable - Whether the disconnection is recoverable.
693
+ * @param errorMessage - A custom error message.
694
+ * emits TorusInpageProvider#disconnect
695
+ */
696
+ handleDisconnect(isRecoverable, errorMessage) {
697
+ if (this.state.isConnected || !this.state.isPermanentlyDisconnected && !isRecoverable) {
698
+ this.state.isConnected = false;
699
+ let error;
700
+ if (isRecoverable) {
701
+ error = new EthereumProviderError(1013,
702
+ // Try again later
703
+ errorMessage || messages.errors.disconnected());
704
+ log.debug(error);
705
+ } else {
706
+ error = new EthereumProviderError(1011,
707
+ // Internal error
708
+ errorMessage || messages.errors.permanentlyDisconnected());
709
+ log.error(error);
710
+ this.state.currentLoginProvider = null;
711
+ this.state.isLoggedIn = false;
712
+ this.state.widgetVisibility = false;
713
+ this.state.isIFrameFullScreen = false;
714
+ this.state.isPermanentlyDisconnected = true;
715
+ }
716
+ this.emit("disconnect", error);
717
+ }
718
+ }
719
+ handleCloseWindow(params) {
720
+ const {
721
+ windowId
722
+ } = params;
723
+ if (this.windowRefs.has(windowId)) {
724
+ this.windowRefs.get(windowId).close();
725
+ this.windowRefs.delete(windowId);
726
+ }
727
+ }
728
+ }
729
+ _defineProperty(CommunicationProvider, "defaultState", {
730
+ buttonPosition: "bottom-left",
731
+ currentLoginProvider: null,
732
+ isIFrameFullScreen: false,
733
+ isBackground: false,
734
+ widgetVisibility: false,
735
+ initialized: false,
736
+ isLoggedIn: false,
737
+ isPermanentlyDisconnected: false,
738
+ isConnected: false,
739
+ hasEmittedConnection: false
740
+ });
741
+
742
+ class BaseError extends Error {
743
+ constructor(name, message, options = {}) {
744
+ const {
745
+ cause,
746
+ context
747
+ } = options;
748
+ super(message || name);
749
+ this.name = name;
750
+ this.stack = cause === null || cause === void 0 ? void 0 : cause.stack;
751
+ this.cause = cause;
752
+ this.context = context;
753
+ }
754
+ toJSON() {
755
+ return {
756
+ name: this.name,
757
+ message: this.message,
758
+ context: this.context,
759
+ cause: this.cause
760
+ };
761
+ }
762
+ }
763
+
764
+ class AirServiceError extends BaseError {
765
+ static from(error) {
766
+ if (error instanceof AirServiceError) {
767
+ return error;
768
+ } else if (error instanceof Object && "message" in error) {
769
+ if (error.message === "User cancelled login") {
770
+ return new AirServiceError("USER_CANCELLED", error.message);
771
+ }
772
+ return new AirServiceError("UNKNOWN_ERROR", error.message.toString());
773
+ }
774
+ return new AirServiceError("UNKNOWN_ERROR");
775
+ }
776
+ }
777
+ class RealmEmbedError extends AirServiceError {}
778
+
779
+ /**
780
+ * @param connectionStream - A Node.js duplex stream
781
+ * @param opts - An options bag
782
+ */
783
+ class AirInPageProvider extends BaseProvider {
784
+ constructor(connectionStream, {
785
+ maxEventListeners = 100,
786
+ jsonRpcStreamName = "provider"
787
+ }) {
788
+ super(connectionStream, {
789
+ maxEventListeners,
790
+ jsonRpcStreamName
791
+ });
792
+
793
+ // private state
794
+ /**
795
+ * The chain ID of the currently connected EVM chain.
796
+ * See [chainId.network]{@link https://chainid.network} for more information.
797
+ */
798
+ _defineProperty(this, "chainId", void 0);
799
+ /**
800
+ * The user's currently selected EVM address.
801
+ * If null, Torus is either locked or the user has not permitted any
802
+ * addresses to be viewed.
803
+ */
804
+ _defineProperty(this, "selectedAddress", void 0);
805
+ _defineProperty(this, "tryWindowHandle", void 0);
806
+ this.state = _objectSpread({}, AirInPageProvider.defaultState);
807
+
808
+ // public state
809
+ this.selectedAddress = null;
810
+ this.chainId = null;
811
+ this.handleAccountsChanged = this.handleAccountsChanged.bind(this);
812
+ this.handleChainChanged = this.handleChainChanged.bind(this);
813
+ this.handleUnlockStateChanged = this.handleUnlockStateChanged.bind(this);
814
+
815
+ // setup own event listeners
816
+
817
+ // EIP-1193 connect
818
+ this.on("connect", () => {
819
+ this.state.isConnected = true;
820
+ });
821
+ const jsonRpcNotificationHandler = payload => {
822
+ const {
823
+ method,
824
+ params
825
+ } = payload;
826
+ if (method === PROVIDER_NOTIFICATIONS.ACCOUNTS_CHANGED) {
827
+ this.handleAccountsChanged(params);
828
+ } else if (method === PROVIDER_NOTIFICATIONS.UNLOCK_STATE_CHANGED) {
829
+ this.handleUnlockStateChanged(params);
830
+ } else if (method === PROVIDER_NOTIFICATIONS.CHAIN_CHANGED) {
831
+ this.handleChainChanged(params);
832
+ } else if (EMITTED_NOTIFICATIONS.includes(method)) {
833
+ this.emit("data", payload);
834
+ this.emit("notification", params.result);
835
+ this.emit("message", {
836
+ type: method,
837
+ data: params
838
+ });
839
+ }
840
+ };
841
+
842
+ // json rpc notification listener
843
+ this.jsonRpcConnectionEvents.on("notification", jsonRpcNotificationHandler);
844
+ }
845
+
846
+ /**
847
+ * Returns whether the inpage provider is connected to Torus.
848
+ */
849
+ isConnected() {
850
+ return this.state.isConnected;
851
+ }
852
+
853
+ // Private Methods
854
+ //= ===================
855
+ /**
856
+ * Constructor helper.
857
+ * Populates initial state by calling 'wallet_getProviderState' and emits
858
+ * necessary events.
859
+ */
860
+ async initializeState() {
861
+ try {
862
+ const {
863
+ accounts,
864
+ chainId,
865
+ isUnlocked
866
+ } = await this.request({
867
+ method: PROVIDER_JRPC_METHODS.GET_PROVIDER_STATE,
868
+ params: []
869
+ });
870
+
871
+ // indicate that we've connected, for EIP-1193 compliance
872
+ this.emit("connect", {
873
+ chainId
874
+ });
875
+ this.handleChainChanged({
876
+ chainId
877
+ });
878
+ this.handleUnlockStateChanged({
879
+ accounts,
880
+ isUnlocked
881
+ });
882
+ this.handleAccountsChanged(accounts);
883
+ } catch (error) {
884
+ log.error("WsEmbed: Failed to get initial state. Please report this bug.", error);
885
+ } finally {
886
+ log.info("initialized provider state");
887
+ this.state.initialized = true;
888
+ }
889
+ }
890
+
891
+ /**
892
+ * Internal RPC method. Forwards requests to background via the RPC engine.
893
+ * Also remap ids inbound and outbound
894
+ */
895
+ rpcRequest(payload, callback, isInternal = false) {
896
+ let cb = callback;
897
+ const _payload = payload;
898
+ if (!Array.isArray(_payload)) {
899
+ if (!_payload.jsonrpc) {
900
+ _payload.jsonrpc = "2.0";
901
+ }
902
+ if (_payload.method === "eth_accounts" || _payload.method === "eth_requestAccounts") {
903
+ // handle accounts changing
904
+ cb = (err, res) => {
905
+ this.handleAccountsChanged(res.result || [], _payload.method === "eth_accounts", isInternal);
906
+ callback(err, res);
907
+ };
908
+ } else if (_payload.method === "wallet_getProviderState") {
909
+ this.rpcEngine.handle(payload, cb);
910
+ return;
911
+ }
912
+ }
913
+ this.tryWindowHandle(_payload, cb);
914
+ }
915
+
916
+ /**
917
+ * When the provider becomes connected, updates internal state and emits
918
+ * required events. Idempotent.
919
+ *
920
+ * @param chainId - The ID of the newly connected chain.
921
+ * emits TorusInpageProvider#connect
922
+ */
923
+ handleConnect(chainId) {
924
+ if (!this.state.isConnected) {
925
+ this.state.isConnected = true;
926
+ this.emit("connect", {
927
+ chainId
928
+ });
929
+ log.debug(messages.info.connected(chainId));
930
+ }
931
+ }
932
+
933
+ /**
934
+ * When the provider becomes disconnected, updates internal state and emits
935
+ * required events. Idempotent with respect to the isRecoverable parameter.
936
+ *
937
+ * Error codes per the CloseEvent status codes as required by EIP-1193:
938
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
939
+ *
940
+ * @param isRecoverable - Whether the disconnection is recoverable.
941
+ * @param errorMessage - A custom error message.
942
+ * emits TorusInpageProvider#disconnect
943
+ */
944
+ handleDisconnect(isRecoverable, errorMessage) {
945
+ if (this.state.isConnected || !this.state.isPermanentlyDisconnected && !isRecoverable) {
946
+ this.state.isConnected = false;
947
+ let error;
948
+ if (isRecoverable) {
949
+ error = new EthereumProviderError(1013,
950
+ // Try again later
951
+ errorMessage || messages.errors.disconnected());
952
+ log.debug(error);
953
+ } else {
954
+ error = new EthereumProviderError(1011,
955
+ // Internal error
956
+ errorMessage || messages.errors.permanentlyDisconnected());
957
+ log.error(error);
958
+ this.chainId = null;
959
+ this.state.accounts = null;
960
+ this.selectedAddress = null;
961
+ this.state.isUnlocked = false;
962
+ this.state.isPermanentlyDisconnected = true;
963
+ }
964
+ this.emit("disconnect", error);
965
+ }
966
+ }
967
+
968
+ /**
969
+ * Called when accounts may have changed.
970
+ */
971
+ handleAccountsChanged(accounts, isEthAccounts = false, isInternal = false) {
972
+ // defensive programming
973
+ let finalAccounts = accounts;
974
+ if (!Array.isArray(finalAccounts)) {
975
+ log.error("WsEmbed: Received non-array accounts parameter. Please report this bug.", finalAccounts);
976
+ finalAccounts = [];
977
+ }
978
+ for (const account of accounts) {
979
+ if (typeof account !== "string") {
980
+ log.error("WsEmbed: Received non-string account. Please report this bug.", accounts);
981
+ finalAccounts = [];
982
+ break;
983
+ }
984
+ }
985
+
986
+ // emit accountsChanged if anything about the accounts array has changed
987
+ if (!dequal(this.state.accounts, finalAccounts)) {
988
+ // we should always have the correct accounts even before eth_accounts
989
+ // returns, except in cases where isInternal is true
990
+ if (isEthAccounts && Array.isArray(this.state.accounts) && this.state.accounts.length > 0 && !isInternal) {
991
+ log.error('WsEmbed: "eth_accounts" unexpectedly updated accounts. Please report this bug.', finalAccounts);
992
+ }
993
+ this.state.accounts = finalAccounts;
994
+ this.emit("accountsChanged", finalAccounts);
995
+ }
996
+
997
+ // handle selectedAddress
998
+ if (this.selectedAddress !== finalAccounts[0]) {
999
+ this.selectedAddress = finalAccounts[0] || null;
1000
+ }
1001
+ }
1002
+
1003
+ /**
1004
+ * Upon receipt of a new chainId and networkVersion, emits corresponding
1005
+ * events and sets relevant public state.
1006
+ * Does nothing if neither the chainId nor the networkVersion are different
1007
+ * from existing values.
1008
+ *
1009
+ * emits TorusInpageProvider#chainChanged
1010
+ * @param networkInfo - An object with network info.
1011
+ */
1012
+ handleChainChanged({
1013
+ chainId
1014
+ } = {}) {
1015
+ if (!chainId) {
1016
+ log.error("WsEmbed: Received invalid network parameters. Please report this bug.", {
1017
+ chainId
1018
+ });
1019
+ return;
1020
+ }
1021
+ if (chainId === "loading") {
1022
+ this.handleDisconnect(true);
1023
+ } else {
1024
+ this.handleConnect(chainId);
1025
+ if (chainId !== this.chainId) {
1026
+ this.chainId = chainId;
1027
+ if (this.state.initialized) {
1028
+ this.emit("chainChanged", this.chainId);
1029
+ }
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ /**
1035
+ * Upon receipt of a new isUnlocked state, sets relevant public state.
1036
+ * Calls the accounts changed handler with the received accounts, or an empty
1037
+ * array.
1038
+ *
1039
+ * Does nothing if the received value is equal to the existing value.
1040
+ * There are no lock/unlock events.
1041
+ *
1042
+ * @param opts - Options bag.
1043
+ */
1044
+ handleUnlockStateChanged({
1045
+ accounts,
1046
+ isUnlocked
1047
+ } = {}) {
1048
+ if (typeof isUnlocked !== "boolean") {
1049
+ log.error("WsEmbed: Received invalid isUnlocked parameter. Please report this bug.", {
1050
+ isUnlocked
1051
+ });
1052
+ return;
1053
+ }
1054
+ if (isUnlocked !== this.state.isUnlocked) {
1055
+ this.state.isUnlocked = isUnlocked;
1056
+ this.handleAccountsChanged(accounts || []);
1057
+ }
1058
+ }
1059
+ }
1060
+ _defineProperty(AirInPageProvider, "defaultState", {
1061
+ accounts: null,
1062
+ isConnected: false,
1063
+ isUnlocked: false,
1064
+ initialized: false,
1065
+ isPermanentlyDisconnected: false,
1066
+ hasEmittedConnection: false
1067
+ });
1068
+ class TorusInPageProvider extends AirInPageProvider {}
1069
+
1070
+ const REALM_EMBED_MESSAGES = [AirMessageTypes.LOGIN_CLAIM_STATE, AirMessageTypes.CLOSE_MODAL, AirMessageTypes.SERVICE_INITIALIZED, AirMessageTypes.SERVICE_INITIALIZED_ERROR, AirMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE];
1071
+ const AUTH_EMBED_MESSAGES = [AirAuthMessageTypes.LOGIN_RESPONSE, AirAuthMessageTypes.USER_INFO_RESPONSE, AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE, AirAuthMessageTypes.REFRESH_TOKEN_RESPONSE, AirAuthMessageTypes.INITIALIZATION_RESPONSE, AirAuthMessageTypes.LOGOUT_RESPONSE, AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST, AirAuthMessageTypes.SETUP_WALLET_REQUEST];
1072
+ class AirMessageService {
1073
+ constructor() {
1074
+ _defineProperty(this, "airMessages$", void 0);
1075
+ _defineProperty(this, "_loginState$", void 0);
1076
+ _defineProperty(this, "_authMessage$", void 0);
1077
+ _defineProperty(this, "_authIframe", null);
1078
+ _defineProperty(this, "closeAuthMessageListeners", null);
1079
+ _defineProperty(this, "closeRealmMessageListeners", null);
1080
+ }
1081
+ static get instance() {
1082
+ if (!AirMessageService._instance) {
1083
+ AirMessageService._instance = new AirMessageService();
1084
+ }
1085
+ return AirMessageService._instance;
1086
+ }
1087
+ get messages$() {
1088
+ return this.airMessages$.asObservable();
1089
+ }
1090
+ get loginState$() {
1091
+ return this._loginState$;
1092
+ }
1093
+ get authMessage$() {
1094
+ return this._authMessage$.asObservable();
1095
+ }
1096
+ async openAuthObservables({
1097
+ authIframeOrigin
1098
+ }) {
1099
+ this.closeAuthObservables();
1100
+ this.setupAuthObservables();
1101
+ const handleAuthMessage = async ev => {
1102
+ if (ev.origin !== authIframeOrigin || !ev.data || !(ev.data instanceof Object)) return;
1103
+ log.debug("Embed auth message received from auth", ev.data);
1104
+ if (AUTH_EMBED_MESSAGES.includes(ev.data.type)) {
1105
+ this._authMessage$.next(ev.data);
1106
+ }
1107
+ };
1108
+ window.addEventListener("message", handleAuthMessage);
1109
+ this.closeAuthMessageListeners = () => {
1110
+ window.removeEventListener("message", handleAuthMessage);
1111
+ };
1112
+ }
1113
+ async openRealmObservables({
1114
+ walletIframeOrigin
1115
+ }) {
1116
+ this.closeRealmObservables();
1117
+ this.setupRealmObservables();
1118
+ const handleMessage = async ev => {
1119
+ if (ev.origin !== walletIframeOrigin || !ev.data || !(ev.data instanceof Object)) return;
1120
+ // filter out torus and communication provider messages
1121
+ if ("target" in ev.data && (ev.data.target === "embed_torus" || ev.data.target === "embed_communication")) return;
1122
+ log.debug("Embed realm message received from wallet", ev.data);
1123
+ if (REALM_EMBED_MESSAGES.includes(ev.data.type)) {
1124
+ this.airMessages$.next(ev.data);
1125
+ }
1126
+ };
1127
+ window.addEventListener("message", handleMessage);
1128
+ this.closeRealmMessageListeners = () => {
1129
+ window.removeEventListener("message", handleMessage);
1130
+ };
1131
+ }
1132
+
1133
+ // Note: Only use when embed is needed in airAuth
1134
+ setupAuthIframe(authIframe) {
1135
+ this._authIframe = authIframe;
1136
+ }
1137
+ setupIframeCommunication(walletIframe) {
1138
+ if (!this._authIframe) return;
1139
+ const channel = new MessageChannel();
1140
+ const authOrigin = new URL(this._authIframe.src).origin;
1141
+ this._authIframe.contentWindow.postMessage({
1142
+ type: AirAuthMessageTypes.INIT_WALLET_COMMUNICATION
1143
+ }, authOrigin, [channel.port1]);
1144
+ const walletOrigin = new URL(walletIframe.src).origin;
1145
+ walletIframe.contentWindow.postMessage({
1146
+ type: AirMessageTypes.INIT_AUTH_COMMUNICATION
1147
+ }, walletOrigin, [channel.port2]);
1148
+ this._authIframe = undefined;
1149
+ }
1150
+ onInitialized() {
1151
+ return firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirMessageTypes.SERVICE_INITIALIZED)));
1152
+ }
1153
+ sendLoginRequest(walletIframe, payload) {
1154
+ const response = lastValueFrom(this.loginState$.pipe(takeWhile(msg => (!payload.skipClaimFlow || msg.payload.state !== "connected") && msg.payload.state !== "logged_in" && msg.payload.state !== "claim_flow_cancelled", true), tap(msg => {
1155
+ switch (msg.payload.state) {
1156
+ case "claim_flow_cancelled":
1157
+ throw new RealmEmbedError(msg.payload.errorName, msg.payload.errorMessage);
1158
+ }
1159
+ })));
1160
+ const {
1161
+ origin
1162
+ } = new URL(walletIframe.src);
1163
+ walletIframe.contentWindow.postMessage({
1164
+ type: AirMessageTypes.LOGIN_REQUEST,
1165
+ payload
1166
+ }, origin);
1167
+ return response;
1168
+ }
1169
+ sendClaimRequest(walletIframe, options) {
1170
+ const response = lastValueFrom(forkJoin([this.loginState$.pipe(takeWhile(msg => !["logged_in", "claim_flow_cancelled"].includes(msg.payload.state), true), tap(msg => {
1171
+ if (msg.payload.state === "claim_flow_cancelled") {
1172
+ throw new RealmEmbedError(msg.payload.errorName, msg.payload.errorMessage);
1173
+ }
1174
+ }), last()), this.messages$.pipe(filter(msg => msg.type === AirMessageTypes.CLOSE_MODAL), first())]));
1175
+ const {
1176
+ origin
1177
+ } = new URL(walletIframe.src);
1178
+ walletIframe.contentWindow.postMessage({
1179
+ type: AirMessageTypes.CLAIM_REQUEST,
1180
+ payload: {
1181
+ token: options === null || options === void 0 ? void 0 : options.token,
1182
+ claimInBackground: options === null || options === void 0 ? void 0 : options.background
1183
+ }
1184
+ }, origin);
1185
+ return response;
1186
+ }
1187
+ sendDeploySmartAccountRequest(walletIframe) {
1188
+ const response = firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE)));
1189
+ const {
1190
+ origin
1191
+ } = new URL(walletIframe.src);
1192
+ walletIframe.contentWindow.postMessage({
1193
+ type: AirMessageTypes.DEPLOY_SMART_ACCOUNT_REQUEST
1194
+ }, origin);
1195
+ return response;
1196
+ }
1197
+ async sendUserInfoRequest(authIframe) {
1198
+ const response = firstValueFrom(this.authMessage$.pipe(filter(msg => msg.type === AirAuthMessageTypes.USER_INFO_RESPONSE)));
1199
+ const {
1200
+ origin
1201
+ } = new URL(authIframe.src);
1202
+ authIframe.contentWindow.postMessage({
1203
+ type: AirAuthMessageTypes.USER_INFO_REQUEST
1204
+ }, origin);
1205
+ return response;
1206
+ }
1207
+ async sendPartnerUserInfoRequest(authIframe) {
1208
+ const response = firstValueFrom(this.authMessage$.pipe(filter(msg => msg.type === AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE)));
1209
+ const {
1210
+ origin
1211
+ } = new URL(authIframe.src);
1212
+ authIframe.contentWindow.postMessage({
1213
+ type: AirAuthMessageTypes.PARTNER_USER_INFO_REQUEST
1214
+ }, origin);
1215
+ return response;
1216
+ }
1217
+ async sendAuthLoginRequest(authIframe, payload) {
1218
+ const response = firstValueFrom(this.authMessage$.pipe(filter(msg => msg.type === AirAuthMessageTypes.LOGIN_RESPONSE)));
1219
+ const {
1220
+ origin
1221
+ } = new URL(authIframe.src);
1222
+ authIframe.contentWindow.postMessage({
1223
+ type: AirAuthMessageTypes.LOGIN_REQUEST,
1224
+ payload
1225
+ }, origin);
1226
+ return response;
1227
+ }
1228
+ async logoutAuth(authIframe) {
1229
+ const response = firstValueFrom(this.authMessage$.pipe(filter(msg => msg.type === AirAuthMessageTypes.LOGOUT_RESPONSE)));
1230
+ const {
1231
+ origin
1232
+ } = new URL(authIframe.src);
1233
+ authIframe.contentWindow.postMessage({
1234
+ type: AirAuthMessageTypes.LOGOUT_REQUEST
1235
+ }, origin);
1236
+ return response;
1237
+ }
1238
+ async waitForAuthInitialization() {
1239
+ const response = await firstValueFrom(this._authMessage$.pipe(filter(msg => msg.type === AirAuthMessageTypes.INITIALIZATION_RESPONSE)));
1240
+ if (response.payload.success === false) {
1241
+ throw new RealmEmbedError(response.payload.errorName, response.payload.errorMessage);
1242
+ }
1243
+ return response.payload;
1244
+ }
1245
+ async waitForWalletInitialization() {
1246
+ const response = await firstValueFrom(this.messages$.pipe(filter(msg => msg.type === AirMessageTypes.SERVICE_INITIALIZED || msg.type === AirMessageTypes.SERVICE_INITIALIZED_ERROR)));
1247
+ if (response.type === AirMessageTypes.SERVICE_INITIALIZED_ERROR) {
1248
+ throw new RealmEmbedError(response.payload.errorName, response.payload.errorMessage);
1249
+ }
1250
+ }
1251
+ closeAuthObservables() {
1252
+ if (this._authMessage$ && !this._authMessage$.closed) this._authMessage$.complete();
1253
+ if (this.closeAuthMessageListeners) this.closeAuthMessageListeners();
1254
+ }
1255
+ closeRealmObservables() {
1256
+ if (this.airMessages$ && !this.airMessages$.closed) this.airMessages$.complete();
1257
+ if (this.closeRealmMessageListeners) this.closeRealmMessageListeners();
1258
+ }
1259
+ setupAuthObservables() {
1260
+ this._authMessage$ = new Subject();
1261
+ }
1262
+ setupRealmObservables() {
1263
+ this.airMessages$ = new Subject();
1264
+ this._loginState$ = this.airMessages$.pipe(filter(msg => msg.type === AirMessageTypes.LOGIN_CLAIM_STATE), distinctUntilChanged(dequal));
1265
+ }
1266
+ }
1267
+ // eslint-disable-next-line no-use-before-define
1268
+ _defineProperty(AirMessageService, "_instance", void 0);
1269
+ var AirMessageService$1 = AirMessageService.instance;
1270
+
1271
+ /**
1272
+ * Returns whether the given image URL exists
1273
+ * @param url - the url of the image
1274
+ * @returns whether the image exists
1275
+ */
1276
+ function imgExists(url) {
1277
+ return new Promise((resolve, reject) => {
1278
+ try {
1279
+ const img = document.createElement("img");
1280
+ img.onload = () => resolve(true);
1281
+ img.onerror = () => resolve(false);
1282
+ img.src = url;
1283
+ } catch (e) {
1284
+ reject(e);
1285
+ }
1286
+ });
1287
+ }
1288
+
1289
+ /**
1290
+ * Extracts a name for the site from the DOM
1291
+ */
1292
+ const getSiteName = window => {
1293
+ const {
1294
+ document
1295
+ } = window;
1296
+ const siteName = document.querySelector('head > meta[property="og:site_name"]');
1297
+ if (siteName) {
1298
+ return siteName.content;
1299
+ }
1300
+ const metaTitle = document.querySelector('head > meta[name="title"]');
1301
+ if (metaTitle) {
1302
+ return metaTitle.content;
1303
+ }
1304
+ if (document.title && document.title.length > 0) {
1305
+ return document.title;
1306
+ }
1307
+ return window.location.hostname;
1308
+ };
1309
+
1310
+ /**
1311
+ * Extracts an icon for the site from the DOM
1312
+ */
1313
+ async function getSiteIcon(window) {
1314
+ try {
1315
+ const {
1316
+ document
1317
+ } = window;
1318
+
1319
+ // Use the site's favicon if it exists
1320
+ let icon = document.querySelector('head > link[rel="shortcut icon"]');
1321
+ if (icon && (await imgExists(icon.href))) {
1322
+ return icon.href;
1323
+ }
1324
+
1325
+ // Search through available icons in no particular order
1326
+ icon = Array.from(document.querySelectorAll('head > link[rel="icon"]')).find(_icon => Boolean(_icon.href));
1327
+ if (icon && (await imgExists(icon.href))) {
1328
+ return icon.href;
1329
+ }
1330
+ return "";
1331
+ } catch (error) {
1332
+ return "";
1333
+ }
1334
+ }
1335
+
1336
+ /**
1337
+ * Gets site metadata and returns it
1338
+ *
1339
+ */
1340
+ const getSiteMetadata = async () => ({
1341
+ name: getSiteName(window),
1342
+ icon: await getSiteIcon(window)
1343
+ });
1344
+
1345
+ function _classPrivateFieldGet$1(s, a) { return s.get(_assertClassBrand$1(s, a)); }
1346
+ function _classPrivateFieldSet$1(s, a, r) { return s.set(_assertClassBrand$1(s, a), r), r; }
1347
+ function _assertClassBrand$1(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"); }
1348
+
1349
+ // preload for iframe doesn't work https://bugs.chromium.org/p/chromium/issues/detail?id=593267
1350
+ (async function preLoadIframe() {
1351
+ try {
1352
+ if (typeof document === "undefined") return;
1353
+ const airWalletIframeHtml = document.createElement("link");
1354
+ const {
1355
+ walletUrl: airWalletUrl
1356
+ } = AIR_URLS.production;
1357
+ airWalletIframeHtml.href = `${airWalletUrl}/frame`;
1358
+ airWalletIframeHtml.crossOrigin = "anonymous";
1359
+ airWalletIframeHtml.type = "text/html";
1360
+ airWalletIframeHtml.rel = "prefetch";
1361
+ if (airWalletIframeHtml.relList && airWalletIframeHtml.relList.supports) {
1362
+ if (airWalletIframeHtml.relList.supports("prefetch")) {
1363
+ document.head.appendChild(airWalletIframeHtml);
1364
+ }
1365
+ }
1366
+ } catch (error) {
1367
+ log.warn(error);
1368
+ }
1369
+ })();
1370
+ new Set([COMMUNICATION_JRPC_METHODS.SET_PROVIDER]);
1371
+ 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]);
1372
+ const embedChainConfig = {
1373
+ polygon: {
1374
+ chainNamespace: CHAIN_NAMESPACES.EIP155,
1375
+ chainId: "0x89",
1376
+ decimals: 18,
1377
+ displayName: "Polygon",
1378
+ blockExplorerUrl: "https://polygonscan.com",
1379
+ logo: "https://cryptologos.cc/logos/polygon-matic-logo.png",
1380
+ ticker: "MATIC",
1381
+ tickerName: "Matic Network Token"
1382
+ },
1383
+ polygonAmoy: {
1384
+ chainNamespace: CHAIN_NAMESPACES.EIP155,
1385
+ chainId: "0x13882",
1386
+ decimals: 18,
1387
+ displayName: "Polygon Amoy",
1388
+ blockExplorerUrl: "https://amoy.polygonscan.com",
1389
+ logo: "https://cryptologos.cc/logos/polygon-matic-logo.png",
1390
+ ticker: "MATIC",
1391
+ tickerName: "Matic Network Token",
1392
+ isTestnet: true
1393
+ }
1394
+ };
1395
+ const web3AuthClientId = "BANbxuTYFGeYi8HxUzaPQkvQlSAXiKRtUqb1vqsXbsZsZKrNr05PEPCM2J2PhUJZpIYl0XzQa6jxUjnYzSU9LXY";
1396
+ const web3AuthNetwork = WEB3AUTH_NETWORK.SAPPHIRE_MAINNET;
1397
+ var _embedNonce$1 = /*#__PURE__*/new WeakMap();
1398
+ var _provider = /*#__PURE__*/new WeakMap();
1399
+ var _isInitialized$1 = /*#__PURE__*/new WeakMap();
1400
+ var _rehydrationState = /*#__PURE__*/new WeakMap();
1401
+ var _modalZIndex = /*#__PURE__*/new WeakMap();
1402
+ var _communicationProvider = /*#__PURE__*/new WeakMap();
1403
+ var _buttonPosition = /*#__PURE__*/new WeakMap();
1404
+ var _realmPartnerId = /*#__PURE__*/new WeakMap();
1405
+ var _web3AuthClientId = /*#__PURE__*/new WeakMap();
1406
+ var _web3AuthNetwork = /*#__PURE__*/new WeakMap();
1407
+ var _isPluginMode = /*#__PURE__*/new WeakMap();
1408
+ var _confirmationStrategy = /*#__PURE__*/new WeakMap();
1409
+ var _walletIframe = /*#__PURE__*/new WeakMap();
1410
+ var _buildEnv$1 = /*#__PURE__*/new WeakMap();
1411
+ var _walletAddresses = /*#__PURE__*/new WeakMap();
1412
+ var _realmId = /*#__PURE__*/new WeakMap();
1413
+ var _loginToken = /*#__PURE__*/new WeakMap();
1414
+ var _sessionId = /*#__PURE__*/new WeakMap();
1415
+ var _embedListeners = /*#__PURE__*/new WeakMap();
1416
+ var _RealmEmbed_brand = /*#__PURE__*/new WeakSet();
1417
+ class RealmEmbed {
1418
+ constructor({
1419
+ modalZIndex = 99999,
1420
+ partnerId
1421
+ }) {
1422
+ _classPrivateMethodInitSpec(this, _RealmEmbed_brand);
1423
+ _classPrivateFieldInitSpec(this, _embedNonce$1, randomId());
1424
+ _classPrivateFieldInitSpec(this, _provider, void 0);
1425
+ _classPrivateFieldInitSpec(this, _isInitialized$1, void 0);
1426
+ _classPrivateFieldInitSpec(this, _rehydrationState, void 0);
1427
+ _classPrivateFieldInitSpec(this, _modalZIndex, void 0);
1428
+ _classPrivateFieldInitSpec(this, _communicationProvider, void 0);
1429
+ _classPrivateFieldInitSpec(this, _buttonPosition, void 0);
1430
+ _classPrivateFieldInitSpec(this, _realmPartnerId, void 0);
1431
+ _classPrivateFieldInitSpec(this, _web3AuthClientId, void 0);
1432
+ _classPrivateFieldInitSpec(this, _web3AuthNetwork, void 0);
1433
+ _classPrivateFieldInitSpec(this, _isPluginMode, void 0);
1434
+ _classPrivateFieldInitSpec(this, _confirmationStrategy, void 0);
1435
+ _classPrivateFieldInitSpec(this, _walletIframe, void 0);
1436
+ _classPrivateFieldInitSpec(this, _buildEnv$1, void 0);
1437
+ _classPrivateFieldInitSpec(this, _walletAddresses, void 0);
1438
+ _classPrivateFieldInitSpec(this, _realmId, void 0);
1439
+ _classPrivateFieldInitSpec(this, _loginToken, void 0);
1440
+ _classPrivateFieldInitSpec(this, _sessionId, void 0);
1441
+ _classPrivateFieldInitSpec(this, _embedListeners, []);
1442
+ _classPrivateFieldSet$1(_isInitialized$1, this, false); // init done
1443
+ _classPrivateFieldSet$1(_modalZIndex, this, modalZIndex);
1444
+ _classPrivateFieldSet$1(_realmPartnerId, this, partnerId);
1445
+ _classPrivateFieldSet$1(_web3AuthClientId, this, web3AuthClientId);
1446
+ _classPrivateFieldSet$1(_web3AuthNetwork, this, web3AuthNetwork);
1447
+ }
1448
+ get isConnected() {
1449
+ return !!_classPrivateFieldGet$1(_walletAddresses, this) && _classPrivateFieldGet$1(_communicationProvider, this).isLoggedIn;
1450
+ }
1451
+ get isInitialized() {
1452
+ return _classPrivateFieldGet$1(_isInitialized$1, this) && !!_classPrivateFieldGet$1(_rehydrationState, this);
1453
+ }
1454
+ get isLoggedIn() {
1455
+ return !!_classPrivateFieldGet$1(_realmId, this) && this.isConnected;
1456
+ }
1457
+ get getBuildEnv() {
1458
+ return _classPrivateFieldGet$1(_buildEnv$1, this);
1459
+ }
1460
+ get walletAddresses() {
1461
+ var _classPrivateFieldGet2;
1462
+ return (_classPrivateFieldGet2 = _classPrivateFieldGet$1(_walletAddresses, this)) !== null && _classPrivateFieldGet2 !== void 0 ? _classPrivateFieldGet2 : null;
1463
+ }
1464
+ get sessionId() {
1465
+ var _classPrivateFieldGet3;
1466
+ return (_classPrivateFieldGet3 = _classPrivateFieldGet$1(_sessionId, this)) !== null && _classPrivateFieldGet3 !== void 0 ? _classPrivateFieldGet3 : null;
1467
+ }
1468
+ get realmId() {
1469
+ var _classPrivateFieldGet4;
1470
+ return (_classPrivateFieldGet4 = _classPrivateFieldGet$1(_realmId, this)) !== null && _classPrivateFieldGet4 !== void 0 ? _classPrivateFieldGet4 : null;
1471
+ }
1472
+ get provider() {
1473
+ return _classPrivateFieldGet$1(_walletAddresses, this) ? _classPrivateFieldGet$1(_provider, this) : null;
1474
+ }
1475
+ async init({
1476
+ buildEnv = EMBED_BUILD_ENV.PRODUCTION,
1477
+ enableLogging = false,
1478
+ skipRehydration = false
1479
+ // confirmationStrategy = CONFIRMATION_STRATEGY.DEFAULT,
1480
+ } = {}) {
1481
+ if (_classPrivateFieldGet$1(_isInitialized$1, this)) throw new RealmEmbedError("ALREADY_INITIALISED", "Already initialized");
1482
+ _classPrivateFieldSet$1(_buildEnv$1, this, buildEnv);
1483
+ _classPrivateFieldSet$1(_confirmationStrategy, this, CONFIRMATION_STRATEGY.DEFAULT);
1484
+ _classPrivateFieldSet$1(_buttonPosition, this, BUTTON_POSITION$1.BOTTOM_LEFT);
1485
+ const {
1486
+ walletUrl,
1487
+ logLevel
1488
+ } = AIR_URLS[buildEnv];
1489
+ log.info(walletUrl, "url loaded");
1490
+ log.setDefaultLevel(logLevel);
1491
+ if (enableLogging) log.enableAll();else log.disableAll();
1492
+ const walletIframeUrl = _assertClassBrand$1(_RealmEmbed_brand, this, _getWsIframeUrl).call(this);
1493
+ const walletIframeOrigin = walletIframeUrl.origin;
1494
+ AirMessageService$1.openRealmObservables({
1495
+ walletIframeOrigin
1496
+ });
1497
+ _classPrivateFieldSet$1(_walletIframe, this, htmlToElement(`<iframe
1498
+ id="walletIframe-${_classPrivateFieldGet$1(_embedNonce$1, this)}"
1499
+ class="walletIframe-${_classPrivateFieldGet$1(_embedNonce$1, this)}"
1500
+ sandbox="allow-popups allow-scripts allow-same-origin allow-forms allow-modals allow-downloads"
1501
+ src="${walletIframeUrl.href}"
1502
+ 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$1(_modalZIndex, this).toString()}"
1503
+ allow="clipboard-write"
1504
+ ></iframe>`));
1505
+ AirMessageService$1.messages$.subscribe(msg => {
1506
+ switch (msg.type) {
1507
+ case AirMessageTypes.SERVICE_INITIALIZED:
1508
+ {
1509
+ _classPrivateFieldSet$1(_rehydrationState, this, msg.payload.rehydration);
1510
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerInitializedEvent).call(this);
1511
+ break;
1512
+ }
1513
+ }
1514
+ });
1515
+ AirMessageService$1.loginState$.subscribe(async msg => {
1516
+ switch (msg.payload.state) {
1517
+ case "connected":
1518
+ {
1519
+ await _assertClassBrand$1(_RealmEmbed_brand, this, _onInitialized).call(this);
1520
+ if (msg.payload.addresses && !this.isLoggedIn) {
1521
+ _classPrivateFieldSet$1(_walletAddresses, this, msg.payload.addresses);
1522
+ _classPrivateFieldSet$1(_loginToken, this, msg.payload.token);
1523
+ _classPrivateFieldSet$1(_sessionId, this, msg.payload.sessionId);
1524
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1525
+ event: "connected",
1526
+ result: {
1527
+ isLoggedIn: false,
1528
+ addresses: msg.payload.addresses,
1529
+ token: msg.payload.token,
1530
+ sessionId: msg.payload.sessionId
1531
+ }
1532
+ });
1533
+ }
1534
+ break;
1535
+ }
1536
+ case "logged_in":
1537
+ {
1538
+ await _assertClassBrand$1(_RealmEmbed_brand, this, _onInitialized).call(this);
1539
+ const isNotConnectedYet = !_classPrivateFieldGet$1(_walletAddresses, this);
1540
+ _classPrivateFieldSet$1(_realmId, this, msg.payload.airId);
1541
+ _classPrivateFieldSet$1(_walletAddresses, this, msg.payload.addresses);
1542
+ _classPrivateFieldSet$1(_loginToken, this, msg.payload.token);
1543
+ _classPrivateFieldSet$1(_sessionId, this, msg.payload.sessionId);
1544
+ if (isNotConnectedYet) {
1545
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1546
+ event: "connected",
1547
+ result: {
1548
+ isLoggedIn: false,
1549
+ addresses: msg.payload.addresses,
1550
+ token: msg.payload.token,
1551
+ sessionId: msg.payload.sessionId
1552
+ }
1553
+ });
1554
+ }
1555
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1556
+ event: "logged_in",
1557
+ result: {
1558
+ isLoggedIn: true,
1559
+ realmId: msg.payload.airId,
1560
+ addresses: msg.payload.addresses,
1561
+ token: msg.payload.token,
1562
+ sessionId: msg.payload.sessionId
1563
+ }
1564
+ });
1565
+ break;
1566
+ }
1567
+ case "minting_started":
1568
+ {
1569
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1570
+ event: "minting_started"
1571
+ });
1572
+ break;
1573
+ }
1574
+ case "minting_failed":
1575
+ {
1576
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1577
+ event: "minting_failed",
1578
+ errorMessage: msg.payload.errorMessage
1579
+ });
1580
+ break;
1581
+ }
1582
+ }
1583
+ });
1584
+ try {
1585
+ // Handle wallet iframe message
1586
+ window.document.body.appendChild(_classPrivateFieldGet$1(_walletIframe, this));
1587
+ const initializeWalletService = new Promise((resolve, reject) => {
1588
+ const handleMessage = async ev => {
1589
+ try {
1590
+ if (ev.origin !== walletIframeOrigin) return;
1591
+ if (ev.data === SETUP_COMPLETE) {
1592
+ window.removeEventListener("message", handleMessage);
1593
+ // send init params here
1594
+ const dappMetadata = await getSiteMetadata();
1595
+ _classPrivateFieldGet$1(_walletIframe, this).contentWindow.postMessage({
1596
+ chainConfig: _classPrivateFieldGet$1(_buildEnv$1, this) === EMBED_BUILD_ENV.PRODUCTION ? embedChainConfig.polygon : embedChainConfig.polygonAmoy,
1597
+ dappMetadata,
1598
+ enableLogging,
1599
+ skipRehydration,
1600
+ realmPartnerId: _classPrivateFieldGet$1(_realmPartnerId, this),
1601
+ web3AuthClientId: _classPrivateFieldGet$1(_web3AuthClientId, this),
1602
+ web3AuthNetwork: _classPrivateFieldGet$1(_web3AuthNetwork, this),
1603
+ confirmationStrategy: _classPrivateFieldGet$1(_confirmationStrategy, this)
1604
+ }, walletIframeOrigin);
1605
+ await _assertClassBrand$1(_RealmEmbed_brand, this, _setupWeb).call(this, {
1606
+ torusUrl: walletUrl
1607
+ });
1608
+ _classPrivateFieldGet$1(_communicationProvider, this).onLoginStateHandle = async isLoggedIn => {
1609
+ if (!isLoggedIn) {
1610
+ await _assertClassBrand$1(_RealmEmbed_brand, this, _logout).call(this);
1611
+ }
1612
+ };
1613
+ resolve();
1614
+ }
1615
+ } catch (err) {
1616
+ reject(err);
1617
+ }
1618
+ };
1619
+ window.addEventListener("message", handleMessage);
1620
+ });
1621
+ const walletServiceInitialization = AirMessageService$1.waitForWalletInitialization();
1622
+ await Promise.all([initializeWalletService, walletServiceInitialization]);
1623
+ AirMessageService$1.setupIframeCommunication(_classPrivateFieldGet$1(_walletIframe, this));
1624
+ _classPrivateFieldSet$1(_isInitialized$1, this, true);
1625
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerInitializedEvent).call(this);
1626
+ log.debug("Wallet service initialization resolved");
1627
+ } catch (error) {
1628
+ log.debug("Wallet service initialization error", error);
1629
+ _assertClassBrand$1(_RealmEmbed_brand, this, _clearInit).call(this, true);
1630
+ throw error;
1631
+ }
1632
+ }
1633
+ moveToBackground() {
1634
+ _classPrivateFieldGet$1(_communicationProvider, this).moveToBackground();
1635
+ }
1636
+ moveToForeground() {
1637
+ _classPrivateFieldGet$1(_communicationProvider, this).moveToForeground();
1638
+ }
1639
+ async getUserInfo() {
1640
+ if (!_classPrivateFieldGet$1(_realmId, this)) return null;
1641
+ const userInfoResponse = await _classPrivateFieldGet$1(_communicationProvider, this).request({
1642
+ method: COMMUNICATION_JRPC_METHODS.USER_INFO,
1643
+ params: []
1644
+ });
1645
+ return _objectSpread(_objectSpread({}, userInfoResponse), {}, {
1646
+ realmId: _classPrivateFieldGet$1(_realmId, this)
1647
+ });
1648
+ }
1649
+ async login(options) {
1650
+ var _options$legacy;
1651
+ return _assertClassBrand$1(_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);
1652
+ }
1653
+ async _deploySmartAccount() {
1654
+ if (!this.isConnected) throw new RealmEmbedError("NOT_LOGGED_IN", "User needs to be connected first");
1655
+ try {
1656
+ await AirMessageService$1.sendDeploySmartAccountRequest(_classPrivateFieldGet$1(_walletIframe, this));
1657
+ } catch (error) {
1658
+ throw RealmEmbedError.from(error);
1659
+ }
1660
+ }
1661
+ // async loginV2<T extends boolean>(options?: {
1662
+ // skipClaiming: T;
1663
+ // token?: string;
1664
+ // }): Promise<T extends true ? RealmLoginResult | RealmConnectResult : RealmLoginResult> {
1665
+ // if (!this.#isInitialized) throw new Error("Call init() first");
1666
+
1667
+ // const iframeController = this.#authIframeController;
1668
+ // iframeController.setIframeVisibility(true);
1669
+ // iframeController.updateIframeState();
1670
+
1671
+ // const { payload } = await RealmMessageService.sendAuthLoginRequest(iframeController.iframeElement);
1672
+
1673
+ // iframeController.setIframeVisibility(false);
1674
+ // iframeController.updateIframeState();
1675
+
1676
+ // if (payload.success === true) {
1677
+ // return this.#login({
1678
+ // skipClaiming: options?.skipClaiming,
1679
+ // token: options?.token,
1680
+ // });
1681
+ // }
1682
+ // throw new RealmEmbedError(payload.errorName, payload.errorMessage);
1683
+ // }
1684
+
1685
+ // This is for internal use only
1686
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1687
+ // @ts-ignore
1688
+ async _loginWithSessionId(params) {
1689
+ if (!_classPrivateFieldGet$1(_isInitialized$1, this)) throw new Error("Call init() first");
1690
+ if (!params.sessionId) throw new Error("sessionId is required");
1691
+ try {
1692
+ const res = await _classPrivateFieldGet$1(_communicationProvider, this).request({
1693
+ method: COMMUNICATION_JRPC_METHODS.LOGIN_WITH_SESSION_ID,
1694
+ params: [params.sessionId, ""]
1695
+ });
1696
+ log.info("Login with session id", res);
1697
+ return res.success;
1698
+ } catch (error) {
1699
+ log.error("login with session id failed", error);
1700
+ throw error;
1701
+ }
1702
+ }
1703
+
1704
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1705
+ // @ts-ignore
1706
+ async _showWalletWidget() {
1707
+ _classPrivateFieldGet$1(_communicationProvider, this).showTorusButton();
1708
+ }
1709
+ async claimRealmId(options) {
1710
+ if (!this.isConnected) throw new RealmEmbedError("NOT_CONNECTED", "User needs to be connected first");
1711
+ try {
1712
+ if (options !== null && options !== void 0 && options.background) {
1713
+ _classPrivateFieldGet$1(_communicationProvider, this).setIframeVisibility({
1714
+ isVisible: false
1715
+ });
1716
+ }
1717
+ _classPrivateFieldGet$1(_communicationProvider, this).displayIframe({
1718
+ isFull: true
1719
+ });
1720
+ const claimPromise = AirMessageService$1.sendClaimRequest(_classPrivateFieldGet$1(_walletIframe, this), options);
1721
+ log.debug("before claimPromise");
1722
+ await claimPromise;
1723
+ log.debug("after claimPromise");
1724
+ return {
1725
+ isLoggedIn: true,
1726
+ realmId: _classPrivateFieldGet$1(_realmId, this),
1727
+ addresses: _classPrivateFieldGet$1(_walletAddresses, this),
1728
+ token: _classPrivateFieldGet$1(_loginToken, this),
1729
+ sessionId: _classPrivateFieldGet$1(_sessionId, this)
1730
+ };
1731
+ } catch (e) {
1732
+ throw RealmEmbedError.from(e);
1733
+ } finally {
1734
+ if (options !== null && options !== void 0 && options.background) {
1735
+ _classPrivateFieldGet$1(_communicationProvider, this).setIframeVisibility({
1736
+ isVisible: true
1737
+ });
1738
+ }
1739
+ _classPrivateFieldGet$1(_communicationProvider, this).displayIframe({
1740
+ isFull: false
1741
+ });
1742
+ }
1743
+ }
1744
+ async logout() {
1745
+ if (!_classPrivateFieldGet$1(_communicationProvider, this).isLoggedIn) throw new RealmEmbedError("NOT_LOGGED_IN", "Not logged in");
1746
+ await _assertClassBrand$1(_RealmEmbed_brand, this, _logout).call(this);
1747
+ }
1748
+ async cleanUp() {
1749
+ var _classPrivateFieldGet5;
1750
+ if ((_classPrivateFieldGet5 = _classPrivateFieldGet$1(_communicationProvider, this)) !== null && _classPrivateFieldGet5 !== void 0 && _classPrivateFieldGet5.isLoggedIn) {
1751
+ await this.logout();
1752
+ }
1753
+ await this.clearInit();
1754
+ }
1755
+ async clearInit() {
1756
+ _assertClassBrand$1(_RealmEmbed_brand, this, _clearInit).call(this);
1757
+ }
1758
+ on(listener) {
1759
+ if (_classPrivateFieldGet$1(_embedListeners, this).indexOf(listener) < 0) _classPrivateFieldGet$1(_embedListeners, this).push(listener);
1760
+ }
1761
+ off(listener) {
1762
+ const index = _classPrivateFieldGet$1(_embedListeners, this).indexOf(listener);
1763
+ if (index >= 0) _classPrivateFieldGet$1(_embedListeners, this).splice(index, 1);
1764
+ }
1765
+ clearEventListeners() {
1766
+ _classPrivateFieldSet$1(_embedListeners, this, []);
1767
+ }
1768
+ }
1769
+ function _getWsIframeUrl() {
1770
+ const {
1771
+ walletUrl
1772
+ } = AIR_URLS[_classPrivateFieldGet$1(_buildEnv$1, this)];
1773
+ const torusIframeUrl = new URL(walletUrl);
1774
+ if (torusIframeUrl.pathname.endsWith("/")) torusIframeUrl.pathname += "frame";else torusIframeUrl.pathname += "/frame";
1775
+ const hashParams = new URLSearchParams();
1776
+ hashParams.append("origin", window.location.origin);
1777
+ torusIframeUrl.hash = hashParams.toString();
1778
+ return torusIframeUrl;
1779
+ }
1780
+ async function _login(options, isLegacyLogin) {
1781
+ let loginResult;
1782
+ if (this.isLoggedIn) {
1783
+ loginResult = _assertClassBrand$1(_RealmEmbed_brand, this, _createLoginResult$1).call(this);
1784
+ } else if (this.isConnected) {
1785
+ if ((options === null || options === void 0 ? void 0 : options.skipClaiming) === true) {
1786
+ loginResult = _assertClassBrand$1(_RealmEmbed_brand, this, _createLoginResult$1).call(this);
1787
+ } else {
1788
+ loginResult = await this.claimRealmId(options);
1789
+ }
1790
+ } else {
1791
+ loginResult = await _assertClassBrand$1(_RealmEmbed_brand, this, _realmLogin).call(this, options, isLegacyLogin);
1792
+ }
1793
+ return loginResult;
1794
+ }
1795
+ function _createLoginResult$1() {
1796
+ if (this.isLoggedIn) {
1797
+ return {
1798
+ isLoggedIn: true,
1799
+ realmId: _classPrivateFieldGet$1(_realmId, this),
1800
+ addresses: _classPrivateFieldGet$1(_walletAddresses, this),
1801
+ token: _classPrivateFieldGet$1(_loginToken, this),
1802
+ sessionId: _classPrivateFieldGet$1(_sessionId, this)
1803
+ };
1804
+ }
1805
+ return {
1806
+ isLoggedIn: false,
1807
+ addresses: _classPrivateFieldGet$1(_walletAddresses, this),
1808
+ token: _classPrivateFieldGet$1(_loginToken, this),
1809
+ sessionId: _classPrivateFieldGet$1(_sessionId, this)
1810
+ };
1811
+ }
1812
+ async function _authLogin(params = {}) {
1813
+ try {
1814
+ if (!params.loginProvider || params.loginProvider === EXTERNAL_LOGIN_PROVIDER.WALLET_CONNECT) {
1815
+ _classPrivateFieldGet$1(_communicationProvider, this).displayIframe({
1816
+ isFull: true
1817
+ });
1818
+ }
1819
+
1820
+ // If user is already logged in, we assume they have given access to the website
1821
+ const res = await new Promise((resolve, reject) => {
1822
+ // We use this method because we want to update inPage provider state with account info
1823
+ _classPrivateFieldGet$1(_provider, this).rpcRequest({
1824
+ method: "eth_requestAccounts",
1825
+ params: [params.loginProvider, params.login_hint]
1826
+ }, getRpcPromiseCallback(resolve, reject));
1827
+ });
1828
+ log.debug("check: res", res);
1829
+ if (Array.isArray(res) && res.length > 0) {
1830
+ if (_classPrivateFieldGet$1(_confirmationStrategy, this) === CONFIRMATION_STRATEGY.AUTO_APPROVE) log.warn("Confirmation strategy auto approve is not allowed on Embed Mode, using Default instead.");
1831
+ return res;
1832
+ }
1833
+ // This would never happen, but just in case
1834
+ throw new Error("Login failed");
1835
+ } catch (error) {
1836
+ log.error("login failed", error);
1837
+ throw error;
1838
+ }
1839
+ }
1840
+ async function _realmLogin(options, isLegacyLogin) {
1841
+ const skipClaimFlow = (options === null || options === void 0 ? void 0 : options.skipClaiming) === true;
1842
+ try {
1843
+ if (options !== null && options !== void 0 && options.authToken) {
1844
+ _classPrivateFieldGet$1(_communicationProvider, this).setIframeVisibility({
1845
+ isVisible: false
1846
+ });
1847
+ }
1848
+ const loginPromise = Promise.all([_assertClassBrand$1(_RealmEmbed_brand, this, _authLogin).call(this), AirMessageService$1.sendLoginRequest(_classPrivateFieldGet$1(_walletIframe, this), {
1849
+ skipClaimFlow,
1850
+ token: options === null || options === void 0 ? void 0 : options.token,
1851
+ customAuthToken: options === null || options === void 0 ? void 0 : options.authToken,
1852
+ isLegacyLogin: !!isLegacyLogin
1853
+ })]);
1854
+ log.debug("start logging in...");
1855
+ await loginPromise;
1856
+ log.debug("login ended");
1857
+ return _assertClassBrand$1(_RealmEmbed_brand, this, _createLoginResult$1).call(this);
1858
+ } catch (e) {
1859
+ await _assertClassBrand$1(_RealmEmbed_brand, this, _logout).call(this);
1860
+ throw RealmEmbedError.from(e);
1861
+ } finally {
1862
+ if (options !== null && options !== void 0 && options.authToken) {
1863
+ _classPrivateFieldGet$1(_communicationProvider, this).setIframeVisibility({
1864
+ isVisible: true
1865
+ });
1866
+ }
1867
+ _classPrivateFieldGet$1(_communicationProvider, this).displayIframe({
1868
+ isFull: false
1869
+ });
1870
+ }
1871
+ }
1872
+ async function _logout() {
1873
+ var _classPrivateFieldGet6;
1874
+ const silent = !_classPrivateFieldGet$1(_walletAddresses, this);
1875
+ if ((_classPrivateFieldGet6 = _classPrivateFieldGet$1(_communicationProvider, this)) !== null && _classPrivateFieldGet6 !== void 0 && _classPrivateFieldGet6.isLoggedIn) {
1876
+ await _classPrivateFieldGet$1(_communicationProvider, this).request({
1877
+ method: COMMUNICATION_JRPC_METHODS.LOGOUT,
1878
+ params: []
1879
+ });
1880
+ }
1881
+ if (_classPrivateFieldGet$1(_communicationProvider, this)) _classPrivateFieldGet$1(_communicationProvider, this).onLoginStateHandle = undefined;
1882
+ _classPrivateFieldSet$1(_walletAddresses, this, undefined);
1883
+ _classPrivateFieldSet$1(_realmId, this, undefined);
1884
+ if (!silent) {
1885
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1886
+ event: "logged_out"
1887
+ });
1888
+ }
1889
+ }
1890
+ async function _clearInit(isSilent) {
1891
+ function isElement(element) {
1892
+ return element instanceof Element || element instanceof Document;
1893
+ }
1894
+ if (isElement(_classPrivateFieldGet$1(_walletIframe, this)) && window.document.body.contains(_classPrivateFieldGet$1(_walletIframe, this))) {
1895
+ _classPrivateFieldGet$1(_walletIframe, this).remove();
1896
+ _classPrivateFieldSet$1(_walletIframe, this, undefined);
1897
+ }
1898
+ AirMessageService$1.closeRealmObservables();
1899
+ _classPrivateFieldSet$1(_isInitialized$1, this, false);
1900
+ _classPrivateFieldSet$1(_walletAddresses, this, undefined);
1901
+ _classPrivateFieldSet$1(_realmId, this, undefined);
1902
+ if (isSilent === true) _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1903
+ event: "reset"
1904
+ });
1905
+ }
1906
+ function _getConfirmationStrategyFinal(payload, communicationProvider) {
1907
+ // for external wallets, we'll show the modal and don't need to open a new window
1908
+ let confirmationStrategyFinal = _classPrivateFieldGet$1(_confirmationStrategy, this);
1909
+ if (!Array.isArray(payload) && PROVIDER_UNSAFE_METHODS.has(payload.method) && _classPrivateFieldGet$1(_confirmationStrategy, this) !== CONFIRMATION_STRATEGY.MODAL && !_classPrivateFieldGet$1(_isPluginMode, this) && !communicationProvider.isExternalWallet) {
1910
+ confirmationStrategyFinal = CONFIRMATION_STRATEGY.POPUP;
1911
+ }
1912
+ return confirmationStrategyFinal;
1913
+ }
1914
+ async function _setupWeb(providerParams) {
1915
+ log.debug("setup embed communication...");
1916
+ // setup background connection
1917
+ const providerStream = new BasePostMessageStream({
1918
+ name: "embed_torus",
1919
+ target: "iframe_torus",
1920
+ targetWindow: _classPrivateFieldGet$1(_walletIframe, this).contentWindow,
1921
+ targetOrigin: new URL(providerParams.torusUrl).origin
1922
+ });
1923
+
1924
+ // We create another LocalMessageDuplexStream for communication between dapp <> iframe
1925
+ const communicationStream = new BasePostMessageStream({
1926
+ name: "embed_communication",
1927
+ target: "iframe_communication",
1928
+ targetWindow: _classPrivateFieldGet$1(_walletIframe, this).contentWindow,
1929
+ targetOrigin: new URL(providerParams.torusUrl).origin
1930
+ });
1931
+
1932
+ // compose the inPage provider
1933
+ const inPageProvider = new TorusInPageProvider(providerStream, {});
1934
+ const communicationProvider = new CommunicationProvider(communicationStream, {}, {
1935
+ buttonPosition: _classPrivateFieldGet$1(_buttonPosition, this)
1936
+ });
1937
+ inPageProvider.tryWindowHandle = (payload, cb) => {
1938
+ const _payload = payload;
1939
+ const confirmationStrategyFinal = _assertClassBrand$1(_RealmEmbed_brand, this, _getConfirmationStrategyFinal).call(this, payload, communicationProvider);
1940
+ if (confirmationStrategyFinal === CONFIRMATION_STRATEGY.POPUP) {
1941
+ const windowId = randomId();
1942
+ communicationProvider.handleWindow(windowId, {
1943
+ target: "_blank",
1944
+ features: getPopupFeatures(FEATURES_CONFIRM_WINDOW),
1945
+ timeout: 500
1946
+ });
1947
+ // for inPageProvider methods sending windowId in request instead of params
1948
+ // as params might be positional.
1949
+ _payload.windowId = windowId;
1950
+ }
1951
+ inPageProvider.rpcEngine.handle(_payload, cb);
1952
+ };
1953
+ communicationProvider.tryWindowHandle = (payload, cb) => {
1954
+ const _payload = payload;
1955
+ const confirmationStrategyFinal = _assertClassBrand$1(_RealmEmbed_brand, this, _getConfirmationStrategyFinal).call(this, payload, communicationProvider);
1956
+ if (confirmationStrategyFinal === CONFIRMATION_STRATEGY.POPUP) {
1957
+ const windowId = randomId();
1958
+ communicationProvider.handleWindow(windowId, {
1959
+ target: "_blank",
1960
+ features: getPopupFeatures(FEATURES_PROVIDER_CHANGE_WINDOW),
1961
+ // todo: are these features generic for all
1962
+ timeout: 500
1963
+ });
1964
+ // for communication methods sending window id in jrpc req params
1965
+ _payload.params.windowId = windowId;
1966
+ }
1967
+ communicationProvider.rpcEngine.handle(_payload, cb);
1968
+ };
1969
+
1970
+ // detect eth_requestAccounts and pipe to enable for now
1971
+ const detectAccountRequestPrototypeModifier = m => {
1972
+ const originalMethod = inPageProvider[m];
1973
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1974
+ const self = this;
1975
+
1976
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1977
+ // @ts-ignore
1978
+ inPageProvider[m] = function providerFunc(request, cb) {
1979
+ const {
1980
+ method,
1981
+ params = []
1982
+ } = request;
1983
+ if (method === "eth_requestAccounts") {
1984
+ let login = _assertClassBrand$1(_RealmEmbed_brand, self, _authLogin).call(self, {
1985
+ loginProvider: params[0]
1986
+ });
1987
+ if (cb) {
1988
+ login = login.then(res => cb(null, res)).catch(err => cb(err));
1989
+ }
1990
+ return login.finally(() => {
1991
+ _classPrivateFieldGet$1(_communicationProvider, self).displayIframe({
1992
+ isFull: false
1993
+ });
1994
+ });
1995
+ }
1996
+ return originalMethod.apply(this, [request, cb]);
1997
+ };
1998
+ };
1999
+
2000
+ // Detects call to eth_requestAccounts in request & sendAsync and passes to login
2001
+ detectAccountRequestPrototypeModifier("request");
2002
+ detectAccountRequestPrototypeModifier("sendAsync");
2003
+ detectAccountRequestPrototypeModifier("send");
2004
+ const proxiedInPageProvider = new Proxy(inPageProvider, {
2005
+ // straight up lie that we deleted the property so that it doesn't
2006
+ // throw an error in strict mode
2007
+ deleteProperty: () => true
2008
+ });
2009
+ const proxiedCommunicationProvider = new Proxy(communicationProvider, {
2010
+ // straight up lie that we deleted the property so that it doesn't
2011
+ // throw an error in strict mode
2012
+ deleteProperty: () => true
2013
+ });
2014
+ _classPrivateFieldSet$1(_provider, this, proxiedInPageProvider);
2015
+ _classPrivateFieldSet$1(_communicationProvider, this, proxiedCommunicationProvider);
2016
+ await Promise.all([inPageProvider.initializeState(), communicationProvider.initializeState(_objectSpread(_objectSpread({}, providerParams), {}, {
2017
+ torusIframeId: _classPrivateFieldGet$1(_walletIframe, this).id
2018
+ }))]);
2019
+ log.debug("embed communication setup ended");
2020
+ }
2021
+ function _triggerEvent(data) {
2022
+ const listenersCopy = [..._classPrivateFieldGet$1(_embedListeners, this)];
2023
+ listenersCopy.forEach(listener => {
2024
+ try {
2025
+ listener(data);
2026
+ } catch (error) {
2027
+ log.error(error);
2028
+ }
2029
+ });
2030
+ }
2031
+ function _triggerInitializedEvent() {
2032
+ if (_classPrivateFieldGet$1(_isInitialized$1, this) && _classPrivateFieldGet$1(_rehydrationState, this)) {
2033
+ _assertClassBrand$1(_RealmEmbed_brand, this, _triggerEvent).call(this, {
2034
+ event: "initialized",
2035
+ result: {
2036
+ rehydration: _classPrivateFieldGet$1(_rehydrationState, this)
2037
+ }
2038
+ });
2039
+ }
2040
+ }
2041
+ function _onInitialized() {
2042
+ return new Promise(resolve => {
2043
+ if (!_classPrivateFieldGet$1(_isInitialized$1, this) || !_classPrivateFieldGet$1(_rehydrationState, this)) {
2044
+ const sub = event => {
2045
+ log.debug("onInitialized:", event);
2046
+ if (event.event === "initialized") {
2047
+ this.off(sub);
2048
+ resolve();
2049
+ }
2050
+ };
2051
+ this.on(sub);
2052
+ } else {
2053
+ resolve();
2054
+ }
2055
+ });
2056
+ }
2057
+
2058
+ class IframeController {
2059
+ constructor(iframeUrl, iframeId, state) {
2060
+ _defineProperty(this, "state", void 0);
2061
+ _defineProperty(this, "_iframeElement", null);
2062
+ _defineProperty(this, "iframeUrl", void 0);
2063
+ _defineProperty(this, "iframeId", void 0);
2064
+ this.state = _objectSpread(_objectSpread({}, IframeController.defaultState), state);
2065
+ this.iframeUrl = iframeUrl;
2066
+ this.iframeId = iframeId;
2067
+ }
2068
+ get iframeElement() {
2069
+ return this._iframeElement;
2070
+ }
2071
+ createIframe() {
2072
+ if (this._iframeElement) return this._iframeElement;
2073
+ const iframe = document.createElement("iframe");
2074
+ iframe.id = this.iframeId;
2075
+ iframe.allow = "publickey-credentials-get *; publickey-credentials-create *";
2076
+ iframe.src = this.iframeUrl;
2077
+ iframe.style.position = "fixed";
2078
+ iframe.style.zIndex = "999999";
2079
+ iframe.style.border = "none";
2080
+ iframe.style.margin = "0";
2081
+ iframe.style.padding = "0";
2082
+ iframe.style.display = "none";
2083
+ document.body.appendChild(iframe);
2084
+ this._iframeElement = iframe;
2085
+ return iframe;
2086
+ }
2087
+ setIframeVisibility(isVisible) {
2088
+ this.state.isVisible = isVisible;
2089
+ }
2090
+ updateIframeState() {
2091
+ if (!this.iframeElement) return;
2092
+ const style = {};
2093
+ style.display = this.state.isVisible ? "block" : "none";
2094
+ style.width = "100%";
2095
+ style.height = "100%";
2096
+ style.top = "0px";
2097
+ style.right = "0px";
2098
+ style.left = "0px";
2099
+ style.bottom = "0px";
2100
+ Object.assign(this.iframeElement.style, style);
2101
+ }
2102
+ destroy() {
2103
+ if (this.iframeElement) {
2104
+ this.iframeElement.remove();
2105
+ this._iframeElement = null;
2106
+ }
2107
+ }
2108
+ postMessage(message) {
2109
+ if (!this.iframeElement) return;
2110
+ const {
2111
+ origin
2112
+ } = new URL(this.iframeElement.src);
2113
+ this.iframeElement.contentWindow.postMessage(message, origin);
2114
+ }
2115
+ }
2116
+ _defineProperty(IframeController, "defaultState", {
2117
+ isVisible: false
2118
+ });
2119
+
2120
+ function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
2121
+ function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
2122
+ 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"); }
2123
+ var _authIframeController = /*#__PURE__*/new WeakMap();
2124
+ var _loginResult = /*#__PURE__*/new WeakMap();
2125
+ var _buildEnv = /*#__PURE__*/new WeakMap();
2126
+ var _embedNonce = /*#__PURE__*/new WeakMap();
2127
+ var _enableLogging = /*#__PURE__*/new WeakMap();
2128
+ var _isInitialized = /*#__PURE__*/new WeakMap();
2129
+ var _partnerId = /*#__PURE__*/new WeakMap();
2130
+ var _realmEmbed = /*#__PURE__*/new WeakMap();
2131
+ var _walletInitialization = /*#__PURE__*/new WeakMap();
2132
+ var _airAuthListener = /*#__PURE__*/new WeakMap();
2133
+ var _AirService_brand = /*#__PURE__*/new WeakSet();
2134
+ class AirService {
2135
+ constructor({
2136
+ partnerId
2137
+ }) {
2138
+ _classPrivateMethodInitSpec(this, _AirService_brand);
2139
+ _classPrivateFieldInitSpec(this, _authIframeController, void 0);
2140
+ _classPrivateFieldInitSpec(this, _loginResult, void 0);
2141
+ _classPrivateFieldInitSpec(this, _buildEnv, void 0);
2142
+ _classPrivateFieldInitSpec(this, _embedNonce, randomId());
2143
+ _classPrivateFieldInitSpec(this, _enableLogging, false);
2144
+ _classPrivateFieldInitSpec(this, _isInitialized, false);
2145
+ _classPrivateFieldInitSpec(this, _partnerId, void 0);
2146
+ // Realm Embed related
2147
+ _classPrivateFieldInitSpec(this, _realmEmbed, void 0);
2148
+ _classPrivateFieldInitSpec(this, _walletInitialization, void 0);
2149
+ _classPrivateFieldInitSpec(this, _airAuthListener, []);
2150
+ _classPrivateFieldSet(_partnerId, this, partnerId);
2151
+ _classPrivateFieldSet(_realmEmbed, this, new RealmEmbed({
2152
+ partnerId: _classPrivateFieldGet(_partnerId, this)
2153
+ }));
2154
+ }
2155
+ get buildEnv() {
2156
+ return _classPrivateFieldGet(_buildEnv, this);
2157
+ }
2158
+ get isAirAuth() {
2159
+ return true;
2160
+ }
2161
+ get isInitialized() {
2162
+ return _classPrivateFieldGet(_isInitialized, this);
2163
+ }
2164
+ get isLoggedIn() {
2165
+ return !!_classPrivateFieldGet(_loginResult, this);
2166
+ }
2167
+ get isWalletLoaded() {
2168
+ var _classPrivateFieldGet2;
2169
+ return (_classPrivateFieldGet2 = _classPrivateFieldGet(_realmEmbed, this)) === null || _classPrivateFieldGet2 === void 0 ? void 0 : _classPrivateFieldGet2.isInitialized;
2170
+ }
2171
+ async init({
2172
+ buildEnv = EMBED_BUILD_ENV.PRODUCTION,
2173
+ enableLogging = false,
2174
+ skipRehydration = false
2175
+ }) {
2176
+ if (!_classPrivateFieldGet(_partnerId, this)) throw new Error("Partner ID is required to initialize auth service");
2177
+ if (_classPrivateFieldGet(_isInitialized, this)) return;
2178
+ _classPrivateFieldSet(_buildEnv, this, buildEnv);
2179
+ _classPrivateFieldSet(_enableLogging, this, enableLogging);
2180
+ const {
2181
+ authUrl,
2182
+ logLevel
2183
+ } = AIR_URLS[buildEnv];
2184
+ log.setDefaultLevel(logLevel);
2185
+ if (_classPrivateFieldGet(_enableLogging, this)) log.enableAll();else log.disableAll();
2186
+ const authIframeOrigin = new URL(authUrl).origin;
2187
+ await AirMessageService$1.openAuthObservables({
2188
+ authIframeOrigin
2189
+ });
2190
+ _classPrivateFieldSet(_authIframeController, this, new IframeController(authUrl, `air-login-${_classPrivateFieldGet(_embedNonce, this)}`));
2191
+ AirMessageService$1.authMessage$.subscribe(async msg => {
2192
+ switch (msg.type) {
2193
+ case AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST:
2194
+ {
2195
+ const authIframeController = _classPrivateFieldGet(_authIframeController, this);
2196
+ authIframeController.setIframeVisibility(msg.payload.visible);
2197
+ authIframeController.updateIframeState();
2198
+ break;
2199
+ }
2200
+ case AirAuthMessageTypes.SETUP_WALLET_REQUEST:
2201
+ {
2202
+ await _assertClassBrand(_AirService_brand, this, _initializeWallet).call(this);
2203
+ break;
2204
+ }
2205
+ }
2206
+ });
2207
+ try {
2208
+ _classPrivateFieldGet(_authIframeController, this).createIframe();
2209
+ const initializationPromise = new Promise((resolve, reject) => {
2210
+ const handleAuthMessage = ev => {
2211
+ try {
2212
+ if (ev.origin !== authIframeOrigin) return;
2213
+ if (ev.data === AirAuthMessageTypes.SETUP_COMPLETED) {
2214
+ window.removeEventListener("message", handleAuthMessage);
2215
+ _classPrivateFieldGet(_authIframeController, this).postMessage({
2216
+ type: AirAuthMessageTypes.INITIALIZATION_REQUEST,
2217
+ payload: {
2218
+ partnerId: _classPrivateFieldGet(_partnerId, this),
2219
+ skipRehydration
2220
+ }
2221
+ });
2222
+ resolve();
2223
+ }
2224
+ } catch (err) {
2225
+ reject(err);
2226
+ }
2227
+ };
2228
+ window.addEventListener("message", handleAuthMessage);
2229
+ });
2230
+ const authServiceInitialization = AirMessageService$1.waitForAuthInitialization();
2231
+ const result = await Promise.all([initializationPromise, authServiceInitialization]);
2232
+ _classPrivateFieldSet(_isInitialized, this, true);
2233
+ _assertClassBrand(_AirService_brand, this, _triggerAirAuthInitialized).call(this);
2234
+ _assertClassBrand(_AirService_brand, this, _prepareRealmEmbedListeners).call(this);
2235
+
2236
+ // rehydrated auth session
2237
+ if (result[1].rehydrated) {
2238
+ _classPrivateFieldSet(_loginResult, this, _assertClassBrand(_AirService_brand, this, _createLoginResult).call(this, result[1]));
2239
+ _assertClassBrand(_AirService_brand, this, _triggerAirAuthLoggedIn).call(this);
2240
+ return _classPrivateFieldGet(_loginResult, this);
2241
+ }
2242
+ } catch (error) {
2243
+ log.debug("Error initializing auth service", error);
2244
+ await this.cleanUp();
2245
+ throw error;
2246
+ }
2247
+ return null;
2248
+ }
2249
+ async cleanUp() {
2250
+ var _classPrivateFieldGet3;
2251
+ // Clear up wallet service iframe if exists
2252
+ await _assertClassBrand(_AirService_brand, this, _cleanUpWallet).call(this);
2253
+
2254
+ // Logout auth session
2255
+ await AirMessageService$1.logoutAuth(_classPrivateFieldGet(_authIframeController, this).iframeElement);
2256
+
2257
+ // Destroy the auth iframe
2258
+ const authIframeElement = (_classPrivateFieldGet3 = _classPrivateFieldGet(_authIframeController, this)) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.iframeElement;
2259
+ if (isElement(authIframeElement) && window.document.body.contains(authIframeElement)) {
2260
+ _classPrivateFieldGet(_authIframeController, this).destroy();
2261
+ _classPrivateFieldSet(_authIframeController, this, undefined);
2262
+ }
2263
+
2264
+ // Close the message service
2265
+ AirMessageService$1.closeAuthObservables();
2266
+ this.clearEventListeners();
2267
+ _classPrivateFieldSet(_isInitialized, this, false);
2268
+ }
2269
+ async login(options) {
2270
+ if (!_classPrivateFieldGet(_isInitialized, this)) throw new Error("Service is not initialized");
2271
+ if (_classPrivateFieldGet(_loginResult, this)) return _classPrivateFieldGet(_loginResult, this);
2272
+ const iframeController = _classPrivateFieldGet(_authIframeController, this);
2273
+ const {
2274
+ payload
2275
+ } = await AirMessageService$1.sendAuthLoginRequest(iframeController.iframeElement, {
2276
+ partnerLoginToken: options === null || options === void 0 ? void 0 : options.authToken
2277
+ });
2278
+ if (payload.success === true) {
2279
+ _classPrivateFieldSet(_loginResult, this, _assertClassBrand(_AirService_brand, this, _createLoginResult).call(this, payload));
2280
+ _assertClassBrand(_AirService_brand, this, _triggerAirAuthLoggedIn).call(this);
2281
+ return _classPrivateFieldGet(_loginResult, this);
2282
+ }
2283
+ throw new AirServiceError("UNKNOWN_ERROR", "Unknown error occurred");
2284
+ }
2285
+ async deploySmartAccount() {
2286
+ if (!_classPrivateFieldGet(_isInitialized, this)) throw new Error("Service is not initialized");
2287
+ await _assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2288
+ return _classPrivateFieldGet(_realmEmbed, this)._deploySmartAccount();
2289
+ }
2290
+ async logout() {
2291
+ if (!_classPrivateFieldGet(_isInitialized, this)) throw new Error("Service is not initialized");
2292
+ if (!this.isLoggedIn) throw new Error("No active session to logout");
2293
+
2294
+ // Clear up wallet
2295
+ await _assertClassBrand(_AirService_brand, this, _cleanUpWallet).call(this);
2296
+ await AirMessageService$1.logoutAuth(_classPrivateFieldGet(_authIframeController, this).iframeElement);
2297
+ _classPrivateFieldSet(_loginResult, this, undefined);
2298
+ _assertClassBrand(_AirService_brand, this, _triggerAirAuthLoggedOut).call(this);
2299
+ }
2300
+ async getProvider() {
2301
+ if (!this.isLoggedIn) return null;
2302
+ await _assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2303
+ return _classPrivateFieldGet(_realmEmbed, this).provider;
2304
+ }
2305
+ async preloadWallet() {
2306
+ return _assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2307
+ }
2308
+ async claimAirId(options) {
2309
+ await _assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2310
+ return _classPrivateFieldGet(_realmEmbed, this).claimRealmId(options);
2311
+ }
2312
+ async getUserInfo() {
2313
+ if (!this.isLoggedIn) throw new Error("User not logged in");
2314
+ const info = await AirMessageService$1.sendUserInfoRequest(_classPrivateFieldGet(_authIframeController, this).iframeElement);
2315
+ if (info.payload.success === false) {
2316
+ throw new AirServiceError(info.payload.errorName, info.payload.errorMessage);
2317
+ }
2318
+ return {
2319
+ id: info.payload.id,
2320
+ abstractAccountAddress: info.payload.abstractAccountAddress,
2321
+ email: info.payload.email,
2322
+ airIds: info.payload.airIds
2323
+ };
2324
+ }
2325
+ async getPartnerUserInfo() {
2326
+ if (!this.isLoggedIn) throw new Error("User not logged in");
2327
+ const info = await AirMessageService$1.sendPartnerUserInfoRequest(_classPrivateFieldGet(_authIframeController, this).iframeElement);
2328
+ if (info.payload.success === false) {
2329
+ throw new AirServiceError(info.payload.errorName, info.payload.errorMessage);
2330
+ }
2331
+ return {
2332
+ partnerId: info.payload.partnerId,
2333
+ partnerUserId: info.payload.partnerUserId,
2334
+ airId: info.payload.airId
2335
+ };
2336
+ }
2337
+ on(listener) {
2338
+ if (_classPrivateFieldGet(_airAuthListener, this).indexOf(listener) < 0) _classPrivateFieldGet(_airAuthListener, this).push(listener);
2339
+ }
2340
+ off(listener) {
2341
+ if (_classPrivateFieldGet(_airAuthListener, this).indexOf(listener) >= 0) _classPrivateFieldGet(_airAuthListener, this).splice(_classPrivateFieldGet(_airAuthListener, this).indexOf(listener), 1);
2342
+ }
2343
+ clearEventListeners() {
2344
+ _classPrivateFieldSet(_airAuthListener, this, []);
2345
+ }
2346
+
2347
+ // This is for internal use only
2348
+ // @ts-expect-error for unused function
2349
+ async _showWalletWidget() {
2350
+ await _assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2351
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2352
+ return _classPrivateFieldGet(_realmEmbed, this)._showWalletWidget();
2353
+ }
2354
+ }
2355
+ async function _createWallet() {
2356
+ return _classPrivateFieldGet(_realmEmbed, this).login({
2357
+ skipClaiming: true,
2358
+ legacy: false
2359
+ });
2360
+ }
2361
+ async function _ensureWallet() {
2362
+ if (!this.isLoggedIn) throw new Error("No active session to create wallet");
2363
+ if (!_classPrivateFieldGet(_walletInitialization, this)) {
2364
+ AirMessageService$1.setupAuthIframe(_classPrivateFieldGet(_authIframeController, this).iframeElement);
2365
+ _classPrivateFieldSet(_walletInitialization, this, (async () => {
2366
+ try {
2367
+ await _assertClassBrand(_AirService_brand, this, _initializeWallet).call(this);
2368
+ return await _assertClassBrand(_AirService_brand, this, _createWallet).call(this);
2369
+ } catch (error) {
2370
+ log.error("Error initializing wallet", error);
2371
+ throw error;
2372
+ }
2373
+ })());
2374
+ }
2375
+ return _classPrivateFieldGet(_walletInitialization, this);
2376
+ }
2377
+ async function _cleanUpWallet() {
2378
+ if (_classPrivateFieldGet(_walletInitialization, this) || _classPrivateFieldGet(_realmEmbed, this)) {
2379
+ await _classPrivateFieldGet(_walletInitialization, this);
2380
+ await _classPrivateFieldGet(_realmEmbed, this).cleanUp();
2381
+ _classPrivateFieldSet(_walletInitialization, this, undefined);
2382
+ }
2383
+ }
2384
+ async function _initializeWallet() {
2385
+ if (!_classPrivateFieldGet(_realmEmbed, this).isInitialized) {
2386
+ try {
2387
+ await _classPrivateFieldGet(_realmEmbed, this).init({
2388
+ buildEnv: _classPrivateFieldGet(_buildEnv, this),
2389
+ skipRehydration: true,
2390
+ enableLogging: _classPrivateFieldGet(_enableLogging, this) || false
2391
+ });
2392
+ _classPrivateFieldGet(_authIframeController, this).postMessage({
2393
+ type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2394
+ payload: {
2395
+ success: true
2396
+ }
2397
+ });
2398
+ } catch (error) {
2399
+ log.error("Error initializing wallet", error);
2400
+ _classPrivateFieldGet(_authIframeController, this).postMessage({
2401
+ type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2402
+ payload: {
2403
+ success: false,
2404
+ errorName: "UNKNOWN_ERROR",
2405
+ errorMessage: "Unknown error occurred"
2406
+ }
2407
+ });
2408
+ throw error;
2409
+ }
2410
+ }
2411
+ }
2412
+ async function _triggerEventListeners(data) {
2413
+ _classPrivateFieldGet(_airAuthListener, this).forEach(listener => {
2414
+ listener(data);
2415
+ });
2416
+ }
2417
+ async function _triggerAirAuthInitialized() {
2418
+ await _assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2419
+ event: "initialized"
2420
+ });
2421
+ }
2422
+ async function _triggerAirAuthLoggedIn() {
2423
+ await _assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2424
+ event: "logged_in",
2425
+ result: _classPrivateFieldGet(_loginResult, this)
2426
+ });
2427
+ }
2428
+ async function _triggerAirAuthLoggedOut() {
2429
+ await _assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2430
+ event: "logged_out"
2431
+ });
2432
+ }
2433
+ function _createLoginResult(payload) {
2434
+ return {
2435
+ isLoggedIn: true,
2436
+ id: payload.id,
2437
+ abstractAccountAddress: payload.abstractAccountAddress,
2438
+ token: payload.partnerAccessToken
2439
+ };
2440
+ }
2441
+ async function _prepareRealmEmbedListeners() {
2442
+ _classPrivateFieldGet(_realmEmbed, this).on(data => {
2443
+ if (data.event === "connected" || data.event === "logged_in") {
2444
+ var _data$result$addresse;
2445
+ const result = _objectSpread(_objectSpread({}, data.result), {}, {
2446
+ addresses: {
2447
+ eoa: data.result.addresses.eoa,
2448
+ aa: (_data$result$addresse = data.result.addresses.aa) !== null && _data$result$addresse !== void 0 ? _data$result$addresse : ""
2449
+ }
2450
+ });
2451
+ _assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2452
+ event: "wallet_loaded",
2453
+ result
2454
+ });
2455
+ } else if (data.event === "minting_started") {
2456
+ _assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2457
+ event: "minting_started"
2458
+ });
2459
+ } else if (data.event === "minting_failed") {
2460
+ _assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2461
+ event: "minting_failed",
2462
+ errorMessage: data.errorMessage
2463
+ });
2464
+ }
2465
+ });
2466
+ }
2467
+
2468
+ export { AirInPageProvider, AirService, BUTTON_POSITION, EMBED_BUILD_ENV, EXTERNAL_LOGIN_PROVIDER, RealmEmbed };