@mocanetwork/airkit 0.5.0 → 1.0.0

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