@getpara/core-sdk 2.0.0-dev.1 → 2.0.0-dev.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 (97) hide show
  1. package/dist/cjs/ParaCore.js +3378 -0
  2. package/dist/cjs/PlatformUtils.js +15 -0
  3. package/dist/cjs/StorageUtils.js +15 -0
  4. package/dist/cjs/constants.js +87 -0
  5. package/dist/cjs/cryptography/utils.js +350 -0
  6. package/dist/cjs/errors.js +51 -0
  7. package/dist/cjs/external/mpcComputationClient.js +62 -0
  8. package/dist/cjs/external/userManagementClient.js +106 -0
  9. package/dist/cjs/index.js +100 -5043
  10. package/dist/cjs/package.json +3 -0
  11. package/dist/cjs/shares/KeyContainer.js +89 -0
  12. package/dist/cjs/shares/recovery.js +127 -0
  13. package/dist/cjs/shares/shareDistribution.js +104 -0
  14. package/dist/cjs/transmission/transmissionUtils.js +93 -0
  15. package/dist/cjs/types/auth.js +33 -0
  16. package/dist/cjs/types/config.js +43 -0
  17. package/dist/cjs/types/coreApi.js +89 -0
  18. package/dist/cjs/types/events.js +41 -0
  19. package/dist/cjs/types/index.js +54 -0
  20. package/dist/cjs/types/methods.js +15 -0
  21. package/dist/cjs/types/onRamps.js +33 -0
  22. package/dist/cjs/types/popup.js +35 -0
  23. package/dist/cjs/types/recovery.js +34 -0
  24. package/dist/cjs/types/theme.js +15 -0
  25. package/dist/cjs/types/wallet.js +31 -0
  26. package/dist/cjs/utils/autobind.js +41 -0
  27. package/dist/cjs/utils/events.js +45 -0
  28. package/dist/cjs/utils/formatting.js +116 -0
  29. package/dist/cjs/utils/index.js +41 -0
  30. package/dist/cjs/utils/json.js +37 -0
  31. package/dist/cjs/utils/listeners.js +71 -0
  32. package/dist/cjs/utils/onRamps.js +92 -0
  33. package/dist/cjs/utils/phone.js +73 -0
  34. package/dist/cjs/utils/polling.js +58 -0
  35. package/dist/cjs/utils/types.js +29 -0
  36. package/dist/cjs/utils/url.js +135 -0
  37. package/dist/cjs/utils/wallet.js +159 -0
  38. package/dist/esm/ParaCore.js +3343 -0
  39. package/dist/esm/PlatformUtils.js +0 -0
  40. package/dist/esm/StorageUtils.js +0 -0
  41. package/dist/esm/chunk-7B52C2XE.js +70 -0
  42. package/dist/esm/constants.js +45 -0
  43. package/dist/esm/cryptography/utils.js +282 -0
  44. package/dist/esm/errors.js +27 -0
  45. package/dist/esm/external/mpcComputationClient.js +30 -0
  46. package/dist/esm/external/userManagementClient.js +71 -0
  47. package/dist/esm/index.js +76 -5011
  48. package/dist/esm/package.json +4 -0
  49. package/dist/esm/shares/KeyContainer.js +57 -0
  50. package/dist/esm/shares/recovery.js +74 -0
  51. package/dist/esm/shares/shareDistribution.js +64 -0
  52. package/dist/esm/transmission/transmissionUtils.js +42 -0
  53. package/dist/esm/types/auth.js +11 -0
  54. package/dist/esm/types/config.js +20 -0
  55. package/dist/esm/types/coreApi.js +66 -0
  56. package/dist/esm/types/events.js +19 -0
  57. package/dist/esm/types/index.js +23 -0
  58. package/dist/esm/types/methods.js +0 -0
  59. package/dist/esm/types/onRamps.js +11 -0
  60. package/dist/esm/types/popup.js +13 -0
  61. package/dist/esm/types/recovery.js +12 -0
  62. package/dist/esm/types/theme.js +0 -0
  63. package/dist/esm/types/wallet.js +9 -0
  64. package/dist/esm/utils/autobind.js +19 -0
  65. package/dist/esm/utils/events.js +11 -0
  66. package/dist/esm/utils/formatting.js +76 -0
  67. package/dist/esm/utils/index.js +11 -0
  68. package/dist/esm/utils/json.js +15 -0
  69. package/dist/esm/utils/listeners.js +38 -0
  70. package/dist/esm/utils/onRamps.js +66 -0
  71. package/dist/esm/utils/phone.js +39 -0
  72. package/dist/esm/utils/polling.js +18 -0
  73. package/dist/esm/utils/types.js +7 -0
  74. package/dist/esm/utils/url.js +90 -0
  75. package/dist/esm/utils/wallet.js +103 -0
  76. package/dist/types/ParaCore.d.ts +115 -449
  77. package/dist/types/PlatformUtils.d.ts +4 -5
  78. package/dist/types/constants.d.ts +16 -13
  79. package/dist/types/index.d.ts +3 -3
  80. package/dist/types/shares/KeyContainer.d.ts +0 -2
  81. package/dist/types/types/auth.d.ts +16 -0
  82. package/dist/types/types/config.d.ts +12 -5
  83. package/dist/types/types/coreApi.d.ts +152 -58
  84. package/dist/types/types/events.d.ts +4 -1
  85. package/dist/types/types/index.d.ts +1 -0
  86. package/dist/types/types/methods.d.ts +49 -57
  87. package/dist/types/types/onRamps.d.ts +3 -3
  88. package/dist/types/types/wallet.d.ts +8 -3
  89. package/dist/types/utils/formatting.d.ts +5 -2
  90. package/dist/types/utils/onRamps.d.ts +12 -5
  91. package/dist/types/utils/phone.d.ts +4 -0
  92. package/dist/types/utils/wallet.d.ts +8 -7
  93. package/package.json +27 -26
  94. package/dist/cjs/index.js.br +0 -0
  95. package/dist/cjs/index.js.gz +0 -0
  96. package/dist/esm/index.js.br +0 -0
  97. package/dist/esm/index.js.gz +0 -0
@@ -0,0 +1,3378 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __typeError = (msg) => {
12
+ throw TypeError(msg);
13
+ };
14
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
15
+ var __spreadValues = (a, b) => {
16
+ for (var prop in b || (b = {}))
17
+ if (__hasOwnProp.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ if (__getOwnPropSymbols)
20
+ for (var prop of __getOwnPropSymbols(b)) {
21
+ if (__propIsEnum.call(b, prop))
22
+ __defNormalProp(a, prop, b[prop]);
23
+ }
24
+ return a;
25
+ };
26
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
27
+ var __objRest = (source, exclude) => {
28
+ var target = {};
29
+ for (var prop in source)
30
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
31
+ target[prop] = source[prop];
32
+ if (source != null && __getOwnPropSymbols)
33
+ for (var prop of __getOwnPropSymbols(source)) {
34
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
35
+ target[prop] = source[prop];
36
+ }
37
+ return target;
38
+ };
39
+ var __export = (target, all) => {
40
+ for (var name in all)
41
+ __defProp(target, name, { get: all[name], enumerable: true });
42
+ };
43
+ var __copyProps = (to, from, except, desc) => {
44
+ if (from && typeof from === "object" || typeof from === "function") {
45
+ for (let key of __getOwnPropNames(from))
46
+ if (!__hasOwnProp.call(to, key) && key !== except)
47
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
48
+ }
49
+ return to;
50
+ };
51
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
52
+ // If the importer is in node compatibility mode or this is not an ESM
53
+ // file that has been converted to a CommonJS file using a Babel-
54
+ // compatible transform (i.e. "__esModule" has not been set), then set
55
+ // "default" to the CommonJS "module.exports" for node compatibility.
56
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
57
+ mod
58
+ ));
59
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
60
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
61
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
62
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
63
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
64
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
65
+ var __async = (__this, __arguments, generator) => {
66
+ return new Promise((resolve, reject) => {
67
+ var fulfilled = (value) => {
68
+ try {
69
+ step(generator.next(value));
70
+ } catch (e) {
71
+ reject(e);
72
+ }
73
+ };
74
+ var rejected = (value) => {
75
+ try {
76
+ step(generator.throw(value));
77
+ } catch (e) {
78
+ reject(e);
79
+ }
80
+ };
81
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
82
+ step((generator = generator.apply(__this, __arguments)).next());
83
+ });
84
+ };
85
+ var ParaCore_exports = {};
86
+ __export(ParaCore_exports, {
87
+ ParaCore: () => ParaCore
88
+ });
89
+ module.exports = __toCommonJS(ParaCore_exports);
90
+ var import_buffer = require("buffer");
91
+ var import_user_management_client = require("@getpara/user-management-client");
92
+ var import_node_forge = __toESM(require("node-forge"));
93
+ var import_utils = require("./cryptography/utils.js");
94
+ var import_userManagementClient = require("./external/userManagementClient.js");
95
+ var mpcComputationClient = __toESM(require("./external/mpcComputationClient.js"));
96
+ var import_shareDistribution = require("./shares/shareDistribution.js");
97
+ var import_types = require("./types/index.js");
98
+ var import_recovery = require("./shares/recovery.js");
99
+ var import_utils2 = require("./utils/index.js");
100
+ var import_errors = require("./errors.js");
101
+ var constants = __toESM(require("./constants.js"));
102
+ var _authInfo, _partner, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareLogin_fn, prepareLoginState_fn, prepareSignUpState_fn;
103
+ if (typeof global !== "undefined") {
104
+ global.Buffer = global.Buffer || import_buffer.Buffer;
105
+ } else if (typeof window !== "undefined") {
106
+ window.Buffer = window.Buffer || import_buffer.Buffer;
107
+ window.global = window.global || window;
108
+ } else {
109
+ self.Buffer = self.Buffer || import_buffer.Buffer;
110
+ self.global = self.global || self;
111
+ }
112
+ const { pki, jsbn } = import_node_forge.default;
113
+ const _ParaCore = class _ParaCore {
114
+ /**
115
+ * Constructs a new `ParaCore` instance.
116
+ * @param env - `Environment` to use.
117
+ * @param apiKey - API key to use.
118
+ * @param opts - Additional constructor options; see `ConstructorOpts`.
119
+ * @returns - A new ParaCore instance.
120
+ */
121
+ constructor(env, apiKey, opts) {
122
+ __privateAdd(this, _ParaCore_instances);
123
+ __privateAdd(this, _authInfo);
124
+ this.isNativePasskey = false;
125
+ this.isReady = false;
126
+ __privateAdd(this, _partner);
127
+ this.accountLinkInProgress = void 0;
128
+ this.isAwaitingAccountCreation = false;
129
+ this.isAwaitingLogin = false;
130
+ this.isAwaitingFarcaster = false;
131
+ this.isAwaitingOAuth = false;
132
+ /**
133
+ * The IDs of the currently active wallets, for each supported wallet type. Any signer integrations will default to the first viable wallet ID in this dictionary.
134
+ */
135
+ this.currentWalletIds = {};
136
+ /**
137
+ * Wallets associated with the `ParaCore` instance.
138
+ */
139
+ this.externalWallets = {};
140
+ this.localStorageGetItem = (key) => {
141
+ return this.platformUtils.localStorage.get(key);
142
+ };
143
+ this.localStorageSetItem = (key, value) => {
144
+ return this.platformUtils.localStorage.set(key, value);
145
+ };
146
+ this.localStorageRemoveItem = (key) => {
147
+ return this.platformUtils.localStorage.removeItem(key);
148
+ };
149
+ this.sessionStorageGetItem = (key) => {
150
+ return this.platformUtils.sessionStorage.get(key);
151
+ };
152
+ this.sessionStorageSetItem = (key, value) => {
153
+ return this.platformUtils.sessionStorage.set(key, value);
154
+ };
155
+ this.sessionStorageRemoveItem = (key) => {
156
+ return this.platformUtils.sessionStorage.removeItem(key);
157
+ };
158
+ this.retrieveSessionCookie = () => {
159
+ return this.sessionCookie;
160
+ };
161
+ /**
162
+ * Remove all local storage and prefixed session storage.
163
+ * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
164
+ */
165
+ this.clearStorage = (type = "all") => __async(this, null, function* () {
166
+ const isAll = type === "all";
167
+ (isAll || type === "local") && this.platformUtils.localStorage.clear(constants.PREFIX);
168
+ (isAll || type === "session") && this.platformUtils.sessionStorage.clear(constants.PREFIX);
169
+ if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
170
+ this.platformUtils.secureStorage.clear(constants.PREFIX);
171
+ }
172
+ });
173
+ this.trackError = (methodName, err) => __async(this, null, function* () {
174
+ try {
175
+ yield this.ctx.client.trackError({
176
+ methodName,
177
+ sdkType: this.platformUtils.sdkType,
178
+ userId: this.userId,
179
+ error: {
180
+ name: err.name,
181
+ message: err.message
182
+ }
183
+ });
184
+ } catch (e) {
185
+ console.error("error tracking error:", e);
186
+ }
187
+ throw err;
188
+ });
189
+ this.wrapMethodsWithErrorTracking = (methodNames) => {
190
+ for (const methodName of methodNames) {
191
+ const original = this[methodName];
192
+ if (typeof original === "function") {
193
+ this[methodName] = (...args) => {
194
+ try {
195
+ const result = original.apply(this, args);
196
+ return result instanceof Promise ? result.catch((err) => this.trackError(methodName, err)) : result;
197
+ } catch (err) {
198
+ return this.trackError(methodName, err);
199
+ }
200
+ };
201
+ }
202
+ }
203
+ };
204
+ this.initializeFromStorage = () => {
205
+ this.updateExternalWalletsFromStorage();
206
+ this.updateAuthInfoFromStorage();
207
+ this.updateUserIdFromStorage();
208
+ this.updateWalletsFromStorage();
209
+ this.updateWalletIdsFromStorage();
210
+ this.updateSessionCookieFromStorage();
211
+ this.updateLoginEncryptionKeyPairFromStorage();
212
+ };
213
+ this.updateAuthInfoFromStorage = () => {
214
+ var _a;
215
+ const storageAuthInfo = this.localStorageGetItem(constants.LOCAL_STORAGE_AUTH_INFO) || void 0;
216
+ let authInfo = (0, import_utils2.jsonParse)(storageAuthInfo);
217
+ if (!authInfo) {
218
+ const authParams = {
219
+ email: this.localStorageGetItem(constants.LOCAL_STORAGE_EMAIL) || void 0,
220
+ phone: this.localStorageGetItem(constants.LOCAL_STORAGE_PHONE) || void 0,
221
+ countryCode: this.localStorageGetItem(constants.LOCAL_STORAGE_COUNTRY_CODE) || void 0,
222
+ farcasterUsername: this.localStorageGetItem(constants.LOCAL_STORAGE_FARCASTER_USERNAME) || void 0,
223
+ telegramUserId: this.localStorageGetItem(constants.LOCAL_STORAGE_TELEGRAM_USER_ID) || void 0,
224
+ // Using id here since we store the bech32 address for cosmos in the address field of the wallet
225
+ externalWalletAddress: ((_a = this.externalWalletWithParaAuth) == null ? void 0 : _a.id) || void 0
226
+ };
227
+ authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
228
+ }
229
+ __privateSet(this, _authInfo, authInfo);
230
+ };
231
+ this.updateUserIdFromStorage = () => {
232
+ this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
233
+ };
234
+ this.updateWalletsFromStorage = () => __async(this, null, function* () {
235
+ var _a;
236
+ const _currentWalletIds = (_a = this.localStorageGetItem(constants.LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
237
+ const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
238
+ const fromJson = JSON.parse(_currentWalletIds);
239
+ return Array.isArray(fromJson) ? import_user_management_client.WALLET_TYPES.reduce((acc, type) => {
240
+ const wallet = Object.values(this.wallets).find(
241
+ (w) => fromJson.includes(w.id) && import_utils2.WalletSchemeTypeMap[w.scheme][type]
242
+ );
243
+ return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
244
+ }, {}) : fromJson;
245
+ })();
246
+ this.setCurrentWalletIds(currentWalletIds);
247
+ const stringWallets = this.platformUtils.secureStorage ? this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_WALLETS) : this.localStorageGetItem(constants.LOCAL_STORAGE_WALLETS);
248
+ const _wallets = JSON.parse(stringWallets || "{}");
249
+ const stringEd25519Wallets = this.platformUtils.secureStorage ? this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_ED25519_WALLETS) : this.localStorageGetItem(constants.LOCAL_STORAGE_ED25519_WALLETS);
250
+ const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
251
+ const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
252
+ return __spreadProps(__spreadValues({}, res), {
253
+ [key]: (0, import_utils2.migrateWallet)(_wallets[key])
254
+ });
255
+ }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
256
+ return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: (0, import_utils2.migrateWallet)(_ed25519Wallets[key]) } : {});
257
+ }, {}));
258
+ this.setWallets(wallets);
259
+ });
260
+ this.updateWalletIdsFromStorage = () => {
261
+ var _a;
262
+ const _currentWalletIds = (_a = this.localStorageGetItem(constants.LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
263
+ const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
264
+ const fromJson = JSON.parse(_currentWalletIds);
265
+ return Array.isArray(fromJson) ? import_user_management_client.WALLET_TYPES.reduce((acc, type) => {
266
+ const wallet = Object.values(this.wallets).find(
267
+ (w) => fromJson.includes(w.id) && import_utils2.WalletSchemeTypeMap[w.scheme][type]
268
+ );
269
+ return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
270
+ }, {}) : fromJson;
271
+ })();
272
+ this.setCurrentWalletIds(currentWalletIds);
273
+ if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
274
+ this.findWalletId(void 0, { forbidPregen: true });
275
+ }
276
+ };
277
+ this.updateSessionCookieFromStorage = () => {
278
+ this.sessionCookie = this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || void 0;
279
+ };
280
+ this.updateLoginEncryptionKeyPairFromStorage = () => {
281
+ const loginEncryptionKey = this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
282
+ if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
283
+ this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
284
+ }
285
+ };
286
+ this.updateExternalWalletsFromStorage = () => {
287
+ const stringExternalWallets = this.localStorageGetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS);
288
+ const _externalWallets = JSON.parse(stringExternalWallets || "{}");
289
+ this.setExternalWallets(_externalWallets);
290
+ };
291
+ /**
292
+ * Creates several new wallets with the desired types. If no types are provided, this method
293
+ * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
294
+ * object that are not already present. This is automatically called upon account creation to ensure that
295
+ * the user has a wallet of each required type.
296
+ *
297
+ * @deprecated alias for `createWalletPerType`
298
+ **/
299
+ this.createWalletPerMissingType = this.createWalletPerType;
300
+ __privateAdd(this, _isCreateGuestWalletsPending, false);
301
+ this.getWalletBalance = (_0) => __async(this, [_0], function* ({
302
+ walletId,
303
+ rpcUrl
304
+ }) {
305
+ return (yield this.ctx.client.getWalletBalance({ walletId, rpcUrl })).balance;
306
+ });
307
+ if (!apiKey) {
308
+ throw new Error("A Para API key is required.");
309
+ }
310
+ if (!opts) opts = {};
311
+ let isE2E = false;
312
+ if (env === "E2E") {
313
+ isE2E = true;
314
+ env = import_types.Environment.SANDBOX;
315
+ }
316
+ this.externalWalletConnectionOnly = opts.externalWalletConnectionOnly;
317
+ this.emailPrimaryColor = opts.emailPrimaryColor;
318
+ this.emailTheme = opts.emailTheme;
319
+ this.homepageUrl = opts.homepageUrl;
320
+ this.supportUrl = opts.supportUrl;
321
+ this.xUrl = opts.xUrl;
322
+ this.githubUrl = opts.githubUrl;
323
+ this.linkedinUrl = opts.linkedinUrl;
324
+ this.portalBackgroundColor = opts.portalBackgroundColor;
325
+ this.portalPrimaryButtonColor = opts.portalPrimaryButtonColor;
326
+ this.portalTextColor = opts.portalTextColor;
327
+ this.portalPrimaryButtonTextColor = opts.portalPrimaryButtonTextColor;
328
+ this.portalTheme = opts.portalTheme;
329
+ this.platformUtils = this.getPlatformUtils();
330
+ this.disableProviderModal = this.platformUtils.disableProviderModal;
331
+ this.fetchPregenWalletsOverride = opts.fetchPregenWalletsOverride;
332
+ if (opts.useStorageOverrides) {
333
+ this.localStorageGetItem = opts.localStorageGetItemOverride;
334
+ this.localStorageSetItem = opts.localStorageSetItemOverride;
335
+ this.sessionStorageGetItem = opts.sessionStorageGetItemOverride;
336
+ this.sessionStorageSetItem = opts.sessionStorageSetItemOverride;
337
+ this.sessionStorageRemoveItem = opts.sessionStorageRemoveItemOverride;
338
+ this.clearStorage = opts.clearStorageOverride;
339
+ }
340
+ if (opts.useSessionStorage) {
341
+ this.localStorageGetItem = this.sessionStorageGetItem;
342
+ this.localStorageSetItem = this.sessionStorageSetItem;
343
+ }
344
+ this.persistSessionCookie = (cookie) => {
345
+ this.sessionCookie = cookie;
346
+ (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
347
+ constants.LOCAL_STORAGE_SESSION_COOKIE,
348
+ cookie
349
+ );
350
+ };
351
+ this.ctx = {
352
+ env,
353
+ apiKey,
354
+ client: (0, import_userManagementClient.initClient)({
355
+ env,
356
+ version: _ParaCore.version,
357
+ apiKey,
358
+ partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
359
+ useFetchAdapter: !!opts.disableWorkers,
360
+ retrieveSessionCookie: this.retrieveSessionCookie,
361
+ persistSessionCookie: this.persistSessionCookie
362
+ }),
363
+ disableWorkers: opts.disableWorkers,
364
+ offloadMPCComputationURL: opts.offloadMPCComputationURL,
365
+ useLocalFiles: opts.useLocalFiles,
366
+ useDKLS: opts.useDKLSForCreation || !opts.offloadMPCComputationURL,
367
+ disableWebSockets: !!opts.disableWebSockets,
368
+ wasmOverride: opts.wasmOverride,
369
+ isE2E
370
+ };
371
+ if (opts.offloadMPCComputationURL) {
372
+ this.ctx.mpcComputationClient = mpcComputationClient.initClient(opts.offloadMPCComputationURL, opts.disableWorkers);
373
+ }
374
+ if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
375
+ return;
376
+ }
377
+ this.initializeFromStorage();
378
+ import_utils2.setupListeners.bind(this)();
379
+ (0, import_utils2.autoBind)(this);
380
+ if (env !== import_types.Environment.PROD) {
381
+ this.wrapMethodsWithErrorTracking([
382
+ "signUpOrLogIn",
383
+ "verifyNewAccount",
384
+ "waitForLogin",
385
+ "waitForSignup",
386
+ "waitForWalletCreation",
387
+ "verifyOAuth",
388
+ "verifyTelegram",
389
+ "verifyFarcaster",
390
+ "createPregenWallet",
391
+ "claimPregenWallets",
392
+ "signMessage",
393
+ "signTransaction"
394
+ ]);
395
+ }
396
+ }
397
+ get authInfo() {
398
+ return __privateGet(this, _authInfo);
399
+ }
400
+ get email() {
401
+ var _a;
402
+ return (0, import_user_management_client.isEmail)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.email : void 0;
403
+ }
404
+ get phone() {
405
+ var _a;
406
+ return (0, import_user_management_client.isPhone)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.phone : void 0;
407
+ }
408
+ get farcasterUsername() {
409
+ var _a;
410
+ return (0, import_user_management_client.isFarcaster)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.farcasterUsername : void 0;
411
+ }
412
+ get telegramUserId() {
413
+ var _a;
414
+ return (0, import_user_management_client.isTelegram)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.telegramUserId : void 0;
415
+ }
416
+ get externalWalletWithParaAuth() {
417
+ const externalWallets = Object.values(this.externalWallets);
418
+ return externalWallets.find((w) => w.isExternalWithParaAuth);
419
+ }
420
+ get externalWalletConnectionType() {
421
+ if (this.isExternalWalletAuth) {
422
+ return "AUTHENTICATED";
423
+ } else if (this.isExternalWalletWithVerification) {
424
+ return "VERIFICATION";
425
+ } else if (!!Object.keys(this.externalWallets).length) {
426
+ return "CONNECTION_ONLY";
427
+ }
428
+ return "NONE";
429
+ }
430
+ get isEmail() {
431
+ var _a;
432
+ return (0, import_user_management_client.isEmail)((_a = this.authInfo) == null ? void 0 : _a.auth);
433
+ }
434
+ get isPhone() {
435
+ var _a;
436
+ return (0, import_user_management_client.isPhone)((_a = this.authInfo) == null ? void 0 : _a.auth);
437
+ }
438
+ get isFarcaster() {
439
+ var _a;
440
+ return (0, import_user_management_client.isFarcaster)((_a = this.authInfo) == null ? void 0 : _a.auth);
441
+ }
442
+ get isTelegram() {
443
+ var _a;
444
+ return (0, import_user_management_client.isTelegram)((_a = this.authInfo) == null ? void 0 : _a.auth);
445
+ }
446
+ get isExternalWalletAuth() {
447
+ var _a, _b, _c;
448
+ return (0, import_user_management_client.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withFullParaAuth);
449
+ }
450
+ get isExternalWalletWithVerification() {
451
+ var _a, _b, _c;
452
+ return (0, import_user_management_client.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withVerification);
453
+ }
454
+ get partnerId() {
455
+ var _a;
456
+ return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id;
457
+ }
458
+ get currentWalletIdsArray() {
459
+ var _a, _b;
460
+ return ((_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
461
+ (acc, { type }) => {
462
+ var _a2;
463
+ return [
464
+ ...acc,
465
+ ...((_a2 = this.currentWalletIds[type]) != null ? _a2 : []).map((id) => {
466
+ return [id, type];
467
+ })
468
+ ];
469
+ },
470
+ []
471
+ );
472
+ }
473
+ get currentWalletIdsUnique() {
474
+ return [...new Set(Object.values(this.currentWalletIds).flat())];
475
+ }
476
+ /**
477
+ * A map of pre-generated wallet identifiers that can be claimed in the current instance.
478
+ */
479
+ get pregenIds() {
480
+ return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
481
+ var _a, _b;
482
+ if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
483
+ return acc;
484
+ }
485
+ return __spreadProps(__spreadValues({}, acc), {
486
+ [wallet.pregenIdentifierType]: [
487
+ .../* @__PURE__ */ new Set([...(_b = acc[wallet.pregenIdentifierType]) != null ? _b : [], wallet.pregenIdentifier])
488
+ ]
489
+ });
490
+ }, {}));
491
+ }
492
+ /**
493
+ * Whether the instance has multiple wallets connected.
494
+ */
495
+ get isMultiWallet() {
496
+ return this.currentWalletIdsArray.length > 1 || __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 1;
497
+ }
498
+ get isNoWalletConfig() {
499
+ var _a;
500
+ return !!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) && __privateGet(this, _partner).supportedWalletTypes.length === 0;
501
+ }
502
+ get supportedWalletTypes() {
503
+ var _a, _b;
504
+ return (_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
505
+ }
506
+ get cosmosPrefix() {
507
+ var _a;
508
+ return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix;
509
+ }
510
+ get supportedAccountLinks() {
511
+ var _a, _b;
512
+ return (_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedAccountLinks) != null ? _b : [...import_user_management_client.LINKED_ACCOUNT_TYPES];
513
+ }
514
+ get isWalletTypeEnabled() {
515
+ var _a;
516
+ return (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
517
+ return __spreadProps(__spreadValues({}, acc), { [type]: true });
518
+ }, {});
519
+ }
520
+ convertBigInt(bigInt) {
521
+ const convertedBigInt = new jsbn.BigInteger(null);
522
+ convertedBigInt.data = bigInt.data;
523
+ convertedBigInt.s = bigInt.s;
524
+ convertedBigInt.t = bigInt.t;
525
+ return convertedBigInt;
526
+ }
527
+ convertEncryptionKeyPair(jsonKeyPair) {
528
+ return {
529
+ privateKey: pki.setRsaPrivateKey(
530
+ this.convertBigInt(jsonKeyPair.privateKey.n),
531
+ this.convertBigInt(jsonKeyPair.privateKey.e),
532
+ this.convertBigInt(jsonKeyPair.privateKey.d),
533
+ this.convertBigInt(jsonKeyPair.privateKey.p),
534
+ this.convertBigInt(jsonKeyPair.privateKey.q),
535
+ this.convertBigInt(jsonKeyPair.privateKey.dP),
536
+ this.convertBigInt(jsonKeyPair.privateKey.dQ),
537
+ this.convertBigInt(jsonKeyPair.privateKey.qInv)
538
+ ),
539
+ publicKey: pki.setRsaPublicKey(
540
+ this.convertBigInt(jsonKeyPair.publicKey.n),
541
+ this.convertBigInt(jsonKeyPair.publicKey.e)
542
+ )
543
+ };
544
+ }
545
+ isPortal(envOverride) {
546
+ var _a;
547
+ if (typeof window === "undefined") return false;
548
+ return !!((_a = window.location) == null ? void 0 : _a.host) && (0, import_utils2.getPortalBaseURL)(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
549
+ }
550
+ isParaConnect() {
551
+ var _a;
552
+ if (typeof window === "undefined") return false;
553
+ return !!((_a = window.location) == null ? void 0 : _a.host) && (0, import_utils2.getParaConnectBaseUrl)(this.ctx).includes(window.location.host);
554
+ }
555
+ requireApiKey() {
556
+ if (!this.ctx.apiKey) {
557
+ throw new Error(
558
+ `in order to create a wallet or user with Para, you
559
+ must provide an API key to the Para instance`
560
+ );
561
+ }
562
+ }
563
+ isWalletSupported(wallet) {
564
+ var _a, _b;
565
+ return !((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || (0, import_utils2.isWalletSupported)((_b = __privateGet(this, _partner).supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
566
+ }
567
+ isWalletOwned(wallet) {
568
+ return this.isWalletSupported(wallet) && !(wallet == null ? void 0 : wallet.pregenIdentifier) && !(wallet == null ? void 0 : wallet.pregenIdentifierType) && !!this.userId && (wallet == null ? void 0 : wallet.userId) === this.userId;
569
+ }
570
+ isPregenWalletUnclaimed(wallet) {
571
+ return this.isWalletSupported(wallet) && (!(wallet == null ? void 0 : wallet.userId) || (wallet == null ? void 0 : wallet.isPregen) && !!(wallet == null ? void 0 : wallet.pregenIdentifier) && !!(wallet == null ? void 0 : wallet.pregenIdentifierType));
572
+ }
573
+ isPregenWalletClaimable(wallet) {
574
+ return this.isWalletSupported(wallet) && this.isPregenWalletUnclaimed(wallet) && (!["EMAIL", "PHONE", "TELEGRAM"].includes(wallet == null ? void 0 : wallet.pregenIdentifierType) || (0, import_utils2.isPregenIdentifierMatch)(
575
+ (wallet == null ? void 0 : wallet.pregenIdentifierType) === "EMAIL" ? this.email : (wallet == null ? void 0 : wallet.pregenIdentifierType) === "TELEGRAM" ? this.telegramUserId : this.getPhoneNumber(),
576
+ wallet == null ? void 0 : wallet.pregenIdentifier,
577
+ wallet == null ? void 0 : wallet.pregenIdentifierType
578
+ ));
579
+ }
580
+ isWalletUsable(walletId, { type: types, scheme: schemes, forbidPregen = false } = {}, throwError = false) {
581
+ var _a, _b;
582
+ let error;
583
+ if ((_a = this.externalWallets) == null ? void 0 : _a[walletId]) {
584
+ return true;
585
+ }
586
+ if (!this.wallets[walletId]) {
587
+ error = `wallet with id ${walletId} does not exist`;
588
+ } else {
589
+ const wallet = this.wallets[walletId];
590
+ const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
591
+ if (forbidPregen && isUnclaimed && wallet.pregenIdentifierType !== "GUEST_ID") {
592
+ error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
593
+ } else if (!isOwned && !isUnclaimed) {
594
+ error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
595
+ } else if (!this.isWalletSupported(wallet)) {
596
+ error = `wallet with id ${wallet.id} and type ${wallet.type} is not supported, supported types are: ${(((_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes) || []).map(({ type }) => type).join(", ")}`;
597
+ } else if (types && (!(0, import_utils2.getEquivalentTypes)(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
598
+ var _a2, _b2;
599
+ return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
600
+ }))) {
601
+ error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} cannot be selected`;
602
+ } else if (schemes && !schemes.includes(wallet == null ? void 0 : wallet.scheme)) {
603
+ error = `wallet with id ${wallet == null ? void 0 : wallet.id} and scheme ${wallet == null ? void 0 : wallet.scheme} cannot be selected`;
604
+ }
605
+ }
606
+ if (error) {
607
+ if (throwError) {
608
+ throw new Error(error);
609
+ }
610
+ return false;
611
+ }
612
+ return true;
613
+ }
614
+ /**
615
+ * Returns the formatted address for the desired wallet ID, depending on your app settings.
616
+ * @param {string} walletId the ID of the wallet address to display.
617
+ * @param {object} options additional options for formatting the address.
618
+ * @param {boolean} options.truncate whether to truncate the address.
619
+ * @param {TWalletType} options.addressType the type of address to display.
620
+ * @returns the formatted address
621
+ */
622
+ getDisplayAddress(walletId, options = {}) {
623
+ var _a, _b, _c, _d;
624
+ if (this.externalWallets[walletId]) {
625
+ const wallet2 = this.externalWallets[walletId];
626
+ return options.truncate ? (0, import_utils2.truncateAddress)(wallet2.address, wallet2.type, {
627
+ prefix: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix,
628
+ targetLength: options.targetLength
629
+ }) : wallet2.address;
630
+ }
631
+ const wallet = this.findWallet(walletId, options.addressType);
632
+ if (!wallet) {
633
+ return void 0;
634
+ }
635
+ let str;
636
+ let prefix;
637
+ switch (wallet.type) {
638
+ case "COSMOS":
639
+ prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
640
+ str = (0, import_utils2.getCosmosAddress)(wallet.publicKey, prefix);
641
+ break;
642
+ default:
643
+ prefix = this.cosmosPrefix;
644
+ str = wallet.address;
645
+ break;
646
+ }
647
+ return options.truncate ? (0, import_utils2.truncateAddress)(str, wallet.type, { prefix, targetLength: options.targetLength }) : str;
648
+ }
649
+ /**
650
+ * Returns a unique hash for a wallet suitable for use as an identicon seed.
651
+ * @param {string} walletId the ID of the wallet.
652
+ * @param {boolean} options.addressType used to format the hash for another wallet type.
653
+ * @returns the identicon hash string
654
+ */
655
+ getIdenticonHash(walletId, overrideType) {
656
+ if (this.externalWallets[walletId]) {
657
+ const wallet2 = this.externalWallets[walletId];
658
+ return `${wallet2.id}-${wallet2.address}-${wallet2.type}`;
659
+ }
660
+ const wallet = this.findWallet(walletId, overrideType);
661
+ return wallet ? `${wallet.id}-${wallet.address}-${wallet.type}` : void 0;
662
+ }
663
+ getWallets() {
664
+ return this.wallets;
665
+ }
666
+ getAddress(walletId) {
667
+ var _a, _b, _c;
668
+ return walletId ? (_a = this.wallets[walletId]) == null ? void 0 : _a.address : (_c = (_b = Object.values(this.wallets)) == null ? void 0 : _b[0]) == null ? void 0 : _c.address;
669
+ }
670
+ constructPortalUrl(_0) {
671
+ return __async(this, arguments, function* (type, opts = {}) {
672
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
673
+ const [isCreate, isLogin, isOnRamp] = [
674
+ ["createAuth", "createPassword"].includes(type),
675
+ ["loginAuth", "loginPassword"].includes(type),
676
+ type === "onRamp"
677
+ ];
678
+ if (isCreate || isLogin) {
679
+ this.assertIsAuthSet();
680
+ }
681
+ let sessionId = opts.sessionId;
682
+ if ((isLogin || isOnRamp) && !sessionId) {
683
+ const session = yield this.touchSession(true);
684
+ sessionId = session.sessionId;
685
+ }
686
+ if (!this.loginEncryptionKeyPair) {
687
+ yield this.setLoginEncryptionKeyPair();
688
+ }
689
+ const base = type === "onRamp" || type === "telegramLogin" ? (0, import_utils2.getPortalBaseURL)(this.ctx, type === "telegramLogin") : yield this.getPortalURL();
690
+ let path;
691
+ switch (type) {
692
+ case "createPassword": {
693
+ path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
694
+ break;
695
+ }
696
+ case "createAuth": {
697
+ path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
698
+ break;
699
+ }
700
+ case "loginPassword": {
701
+ path = "/web/passwords/login";
702
+ break;
703
+ }
704
+ case "loginAuth": {
705
+ path = "/web/biometrics/login";
706
+ break;
707
+ }
708
+ case "txReview": {
709
+ path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
710
+ break;
711
+ }
712
+ case "onRamp": {
713
+ path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
714
+ break;
715
+ }
716
+ case "telegramLogin": {
717
+ path = `/auth/telegram`;
718
+ break;
719
+ }
720
+ default: {
721
+ throw new Error(`invalid URL type ${type}`);
722
+ }
723
+ }
724
+ let partner = void 0;
725
+ try {
726
+ partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
727
+ } catch (e) {
728
+ if (this.isPartnerOptional) {
729
+ partner = void 0;
730
+ } else {
731
+ throw e;
732
+ }
733
+ }
734
+ const thisDevice = (_a = opts.thisDevice) != null ? _a : {
735
+ encryptionKey: (0, import_utils.getPublicKeyHex)(this.loginEncryptionKeyPair),
736
+ sessionId
737
+ };
738
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
739
+ apiKey: this.ctx.apiKey,
740
+ partnerId: partner == null ? void 0 : partner.id,
741
+ portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
742
+ portalBorderRadius: ((_d = opts.portalTheme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
743
+ portalThemeMode: ((_f = opts.portalTheme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
744
+ portalAccentColor: ((_h = opts.portalTheme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
745
+ portalForegroundColor: ((_j = opts.portalTheme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
746
+ portalBackgroundColor: ((_l = opts.portalTheme) == null ? void 0 : _l.backgroundColor) || (partner == null ? void 0 : partner.backgroundColor) || this.portalBackgroundColor || ((_m = this.portalTheme) == null ? void 0 : _m.backgroundColor),
747
+ portalPrimaryButtonColor: this.portalPrimaryButtonColor,
748
+ portalTextColor: this.portalTextColor,
749
+ portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
750
+ isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
751
+ }, isCreate || isLogin ? __spreadProps(__spreadValues({
752
+ authInfo: JSON.stringify(this.authInfo)
753
+ }, (0, import_user_management_client.isPhone)(this.authInfo.auth) ? (0, import_utils2.splitPhoneNumber)(this.authInfo.auth.phone) : this.authInfo.auth), {
754
+ pfpUrl: this.authInfo.pfpUrl,
755
+ displayName: this.authInfo.displayName
756
+ }) : {}), isOnRamp ? { sessionId } : {}), isLogin ? __spreadProps(__spreadValues({
757
+ sessionId: thisDevice.sessionId,
758
+ encryptionKey: thisDevice.encryptionKey
759
+ }, opts.newDevice ? {
760
+ newDeviceSessionLookupId: opts.newDevice.sessionId,
761
+ newDeviceEncryptionKey: opts.newDevice.encryptionKey
762
+ } : {}), {
763
+ pregenIds: JSON.stringify(this.pregenIds)
764
+ }) : {}), type === "telegramLogin" ? { isEmbed: "true" } : {}), opts.params || {});
765
+ const url = (0, import_utils2.constructUrl)({ base, path, params });
766
+ if (opts.shorten) {
767
+ return (0, import_utils2.shortenUrl)(this.ctx, url);
768
+ }
769
+ return url;
770
+ });
771
+ }
772
+ touchSession(regenerate = false) {
773
+ return __async(this, null, function* () {
774
+ var _a, _b, _c;
775
+ if (!this.isReady) {
776
+ yield this.ready();
777
+ }
778
+ const session = yield this.ctx.client.touchSession(regenerate);
779
+ if (!__privateGet(this, _partner) || ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) !== session.partnerId || !(0, import_utils2.supportedWalletTypesEq)(((_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
780
+ yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
781
+ }
782
+ return session;
783
+ });
784
+ }
785
+ getVerificationEmailProps() {
786
+ return {
787
+ brandColor: this.emailPrimaryColor,
788
+ theme: this.emailTheme,
789
+ supportUrl: this.supportUrl,
790
+ homepageUrl: this.homepageUrl,
791
+ xUrl: this.xUrl,
792
+ githubUrl: this.githubUrl,
793
+ linkedinUrl: this.linkedinUrl
794
+ };
795
+ }
796
+ getBackupKitEmailProps() {
797
+ return {
798
+ brandColor: this.emailPrimaryColor,
799
+ theme: this.emailTheme,
800
+ homepageUrl: this.homepageUrl,
801
+ xUrl: this.xUrl,
802
+ linkedinUrl: this.linkedinUrl,
803
+ githubUrl: this.githubUrl,
804
+ supportUrl: this.supportUrl
805
+ };
806
+ }
807
+ /**
808
+ * Initialize storage relating to a `ParaCore` instance.
809
+ *
810
+ * Init only needs to be called for storage that is async.
811
+ */
812
+ init() {
813
+ return __async(this, null, function* () {
814
+ var _a, _b;
815
+ this.userId = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID)) || void 0;
816
+ const storageAuthInfo = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_AUTH_INFO)) || void 0;
817
+ const stringExternalWallets = yield this.localStorageGetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS);
818
+ const _externalWallets = JSON.parse(stringExternalWallets || "{}");
819
+ yield this.setExternalWallets(_externalWallets);
820
+ let authInfo = (0, import_utils2.jsonParse)(storageAuthInfo);
821
+ if (!authInfo) {
822
+ const authParams = {
823
+ email: (yield this.localStorageGetItem(constants.LOCAL_STORAGE_EMAIL)) || void 0,
824
+ phone: (yield this.localStorageGetItem(constants.LOCAL_STORAGE_PHONE)) || void 0,
825
+ countryCode: (yield this.localStorageGetItem(constants.LOCAL_STORAGE_COUNTRY_CODE)) || void 0,
826
+ farcasterUsername: (yield this.localStorageGetItem(constants.LOCAL_STORAGE_FARCASTER_USERNAME)) || void 0,
827
+ telegramUserId: (yield this.localStorageGetItem(constants.LOCAL_STORAGE_TELEGRAM_USER_ID)) || void 0,
828
+ // Using id here since we store the bech32 address for cosmos in the address field of the wallet
829
+ externalWalletAddress: ((_a = this.externalWalletWithParaAuth) == null ? void 0 : _a.id) || void 0
830
+ };
831
+ authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
832
+ }
833
+ __privateSet(this, _authInfo, authInfo);
834
+ const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(constants.LOCAL_STORAGE_WALLETS);
835
+ const _wallets = JSON.parse(stringWallets || "{}");
836
+ const stringEd25519Wallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_ED25519_WALLETS) : yield this.localStorageGetItem(constants.LOCAL_STORAGE_ED25519_WALLETS);
837
+ const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
838
+ const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
839
+ return __spreadProps(__spreadValues({}, res), {
840
+ [key]: (0, import_utils2.migrateWallet)(_wallets[key])
841
+ });
842
+ }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
843
+ return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: (0, import_utils2.migrateWallet)(_ed25519Wallets[key]) } : {});
844
+ }, {}));
845
+ yield this.setWallets(wallets);
846
+ const _currentWalletIds = (_b = yield this.localStorageGetItem(constants.LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _b : void 0;
847
+ const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
848
+ const fromJson = JSON.parse(_currentWalletIds);
849
+ return Array.isArray(fromJson) ? import_user_management_client.WALLET_TYPES.reduce((acc, type) => {
850
+ const wallet = Object.values(this.wallets).find(
851
+ (w) => fromJson.includes(w.id) && import_utils2.WalletSchemeTypeMap[w.scheme][type]
852
+ );
853
+ return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
854
+ }, {}) : fromJson;
855
+ })();
856
+ yield this.setCurrentWalletIds(currentWalletIds);
857
+ this.sessionCookie = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
858
+ if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
859
+ this.findWalletId(void 0, { forbidPregen: true });
860
+ }
861
+ const loginEncryptionKey = yield this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
862
+ if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
863
+ this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
864
+ }
865
+ import_utils2.setupListeners.bind(this)();
866
+ yield this.touchSession();
867
+ });
868
+ }
869
+ setAuth(_0) {
870
+ return __async(this, arguments, function* (auth, { extras = {}, userId } = {}) {
871
+ const authInfo = __spreadValues(__spreadValues({}, (0, import_user_management_client.extractAuthInfo)(auth, { isRequired: true })), extras || {});
872
+ yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
873
+ if (!!userId) {
874
+ yield this.setUserId(userId);
875
+ }
876
+ return __privateGet(this, _authInfo);
877
+ });
878
+ }
879
+ assertUserId() {
880
+ if (!this.userId || this.isGuestMode) {
881
+ throw new Error("no userId is set");
882
+ }
883
+ return this.userId;
884
+ }
885
+ assertIsAuthSet(allowed) {
886
+ if (!__privateGet(this, _authInfo)) {
887
+ throw new Error("auth is not set");
888
+ }
889
+ if (allowed && !allowed.includes(__privateGet(this, _authInfo).authType)) {
890
+ throw new Error(`invalid auth type, expected ${allowed.join(", ")}`);
891
+ }
892
+ return __privateGet(this, _authInfo);
893
+ }
894
+ /**
895
+ * Sets the email associated with the `ParaCore` instance.
896
+ * @param email - Email to set.
897
+ */
898
+ setEmail(email) {
899
+ return __async(this, null, function* () {
900
+ yield this.setAuth({ email });
901
+ });
902
+ }
903
+ /**
904
+ * Sets the Telegram user ID associated with the `ParaCore` instance.
905
+ * @param telegramUserId - Telegram user ID to set.
906
+ */
907
+ setTelegramUserId(telegramUserId) {
908
+ return __async(this, null, function* () {
909
+ yield this.setAuth({ telegramUserId });
910
+ });
911
+ }
912
+ /**
913
+ * Sets the phone number associated with the `ParaCore` instance.
914
+ * @param phone - Phone number to set.
915
+ * @param countryCode - Country Code to set.
916
+ */
917
+ setPhoneNumber(phone, countryCode) {
918
+ return __async(this, null, function* () {
919
+ yield this.setAuth({ phone: (0, import_utils2.formatPhoneNumber)(phone, countryCode) });
920
+ });
921
+ }
922
+ /**
923
+ * Sets the farcaster username associated with the `ParaCore` instance.
924
+ * @param farcasterUsername - Farcaster Username to set.
925
+ */
926
+ setFarcasterUsername(farcasterUsername) {
927
+ return __async(this, null, function* () {
928
+ yield this.setAuth({ farcasterUsername });
929
+ });
930
+ }
931
+ /**
932
+ * Sets the external wallet address and type associated with the `ParaCore` instance.
933
+ * @param externalAddress - External wallet address to set.
934
+ * @param externalType - Type of external wallet to set.
935
+ */
936
+ setExternalWallet(externalWallet) {
937
+ return __async(this, null, function* () {
938
+ this.externalWallets = (Array.isArray(externalWallet) ? externalWallet : [externalWallet]).reduce(
939
+ (acc, { address, type, provider, providerId, addressBech32, withFullParaAuth, isConnectionOnly, withVerification }) => {
940
+ return __spreadProps(__spreadValues({}, acc), {
941
+ [address]: {
942
+ id: address,
943
+ address: addressBech32 != null ? addressBech32 : address,
944
+ type,
945
+ name: provider,
946
+ isExternal: true,
947
+ isExternalWithParaAuth: withFullParaAuth,
948
+ externalProviderId: providerId,
949
+ signer: "",
950
+ isExternalConnectionOnly: isConnectionOnly,
951
+ isExternalWithVerification: withVerification
952
+ }
953
+ });
954
+ },
955
+ {}
956
+ );
957
+ this.setExternalWallets(this.externalWallets);
958
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
959
+ });
960
+ }
961
+ /**
962
+ * Sets the user id associated with the `ParaCore` instance.
963
+ * @param userId - User id to set.
964
+ */
965
+ setUserId(userId) {
966
+ return __async(this, null, function* () {
967
+ this.userId = userId;
968
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_USER_ID, userId);
969
+ });
970
+ }
971
+ /**
972
+ * Sets the wallets associated with the `ParaCore` instance.
973
+ * @param wallets - Wallets to set.
974
+ */
975
+ setWallets(wallets) {
976
+ return __async(this, null, function* () {
977
+ this.wallets = wallets;
978
+ if (this.platformUtils.secureStorage) {
979
+ yield this.platformUtils.secureStorage.set(constants.LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
980
+ return;
981
+ }
982
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
983
+ });
984
+ }
985
+ /**
986
+ * Sets the external wallets associated with the `ParaCore` instance.
987
+ * @param externalWallets - External wallets to set.
988
+ */
989
+ setExternalWallets(externalWallets) {
990
+ return __async(this, null, function* () {
991
+ this.externalWallets = externalWallets;
992
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
993
+ });
994
+ }
995
+ /**
996
+ * Sets the login encryption key pair associated with the `ParaCore` instance.
997
+ * @param keyPair - Encryption key pair generated from loginEncryptionKey.
998
+ */
999
+ setLoginEncryptionKeyPair(keyPair) {
1000
+ return __async(this, null, function* () {
1001
+ if (!keyPair) {
1002
+ keyPair = yield (0, import_utils.getAsymmetricKeyPair)(this.ctx);
1003
+ }
1004
+ this.loginEncryptionKeyPair = keyPair;
1005
+ yield this.sessionStorageSetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR, JSON.stringify(keyPair));
1006
+ });
1007
+ }
1008
+ deleteLoginEncryptionKeyPair() {
1009
+ return __async(this, null, function* () {
1010
+ this.loginEncryptionKeyPair = void 0;
1011
+ yield this.sessionStorageRemoveItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Gets the userId associated with the `ParaCore` instance.
1016
+ * @returns - userId associated with the `ParaCore` instance.
1017
+ */
1018
+ getUserId() {
1019
+ return this.userId;
1020
+ }
1021
+ getAuthInfo() {
1022
+ return this.authInfo;
1023
+ }
1024
+ /**
1025
+ * Gets the email associated with the `ParaCore` instance.
1026
+ * @returns - email associated with the `ParaCore` instance.
1027
+ */
1028
+ getEmail() {
1029
+ return this.email;
1030
+ }
1031
+ /**
1032
+ * Gets the formatted phone number associated with the `ParaCore` instance.
1033
+ * @returns - formatted phone number associated with the `ParaCore` instance.
1034
+ */
1035
+ getPhoneNumber() {
1036
+ return this.phone;
1037
+ }
1038
+ /**
1039
+ * Gets the farcaster username associated with the `ParaCore` instance.
1040
+ * @returns - farcaster username associated with the `ParaCore` instance.
1041
+ */
1042
+ getFarcasterUsername() {
1043
+ return this.farcasterUsername;
1044
+ }
1045
+ setCurrentWalletIds(_0) {
1046
+ return __async(this, arguments, function* (currentWalletIds, {
1047
+ needsWallet = false,
1048
+ sessionLookupId,
1049
+ newDeviceSessionLookupId
1050
+ } = {}) {
1051
+ this.currentWalletIds = currentWalletIds;
1052
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_CURRENT_WALLET_IDS, JSON.stringify(this.currentWalletIds));
1053
+ if (sessionLookupId) {
1054
+ yield this.ctx.client.setCurrentWalletIds(
1055
+ this.getUserId(),
1056
+ this.currentWalletIds,
1057
+ needsWallet,
1058
+ sessionLookupId,
1059
+ newDeviceSessionLookupId
1060
+ );
1061
+ }
1062
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.WALLETS_CHANGE_EVENT, null);
1063
+ });
1064
+ }
1065
+ /**
1066
+ * Fetches the most recent OAuth account metadata for the signed-in user.
1067
+ * If applicable, this will include the user's most recent metadata from their Google, Apple, Facebook, X, Discord, Farcaster, or Telegram account, the last time they signed in to your app.
1068
+ * @deprecated use `para.getLinkedAccounts({ withMetadata: true })` instead.
1069
+ * @returns {Promise<AccountMetadata>} the user's account metadata.
1070
+ */
1071
+ getAccountMetadata() {
1072
+ return __async(this, null, function* () {
1073
+ if (!(yield this.isSessionActive()) || !this.userId) {
1074
+ throw new Error("no signed-in user");
1075
+ }
1076
+ const { partnerId } = yield this.touchSession();
1077
+ const { accountMetadata } = yield this.ctx.client.getAccountMetadata(this.userId, partnerId);
1078
+ return accountMetadata;
1079
+ });
1080
+ }
1081
+ /**
1082
+ * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
1083
+ * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
1084
+ * @param {string} [walletId] the wallet ID to validate.
1085
+ * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1086
+ * @returns {string} the wallet ID originally passed, or the one found.
1087
+ */
1088
+ findWalletId(walletId, filter = {}) {
1089
+ if (walletId) {
1090
+ this.assertIsValidWalletId(walletId, filter);
1091
+ } else {
1092
+ for (const id of [...this.currentWalletIdsUnique, ...Object.keys(this.wallets)]) {
1093
+ if (this.isWalletUsable(id, filter)) {
1094
+ walletId = id;
1095
+ break;
1096
+ }
1097
+ }
1098
+ if (!walletId) {
1099
+ throw new Error(`no valid wallet id found`);
1100
+ }
1101
+ }
1102
+ return walletId;
1103
+ }
1104
+ /**
1105
+ * Retrieves a wallet with the given address, if present.
1106
+ * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
1107
+ * @param {string} [walletId] the wallet ID to validate.
1108
+ * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1109
+ * @returns {string} the wallet ID originally passed, or the one found.
1110
+ */
1111
+ findWalletByAddress(address, filter) {
1112
+ if (this.externalWallets[address]) {
1113
+ return this.externalWallets[address];
1114
+ }
1115
+ let wallet;
1116
+ Object.entries(this.currentWalletIds).forEach(([type, walletIds]) => {
1117
+ const pregenWalletIds = Object.keys(this.wallets).filter(
1118
+ (id) => this.wallets[id].type === type && this.isPregenWalletClaimable(this.wallets[id])
1119
+ );
1120
+ [...walletIds, ...pregenWalletIds].forEach((id) => {
1121
+ if (address.toLowerCase() === this.getDisplayAddress(id, { addressType: type }).toLowerCase()) {
1122
+ wallet = this.wallets[id];
1123
+ }
1124
+ });
1125
+ });
1126
+ if (!wallet) {
1127
+ throw new Error(`wallet with address ${address} not found`);
1128
+ }
1129
+ this.assertIsValidWalletId(wallet.id, filter);
1130
+ return wallet;
1131
+ }
1132
+ findWallet(idOrAddress, overrideType, filter = {}) {
1133
+ var _a, _c, _d;
1134
+ if (!this.isExternalWalletAuth) {
1135
+ if (!idOrAddress && Object.keys(this.externalWallets).length > 0) {
1136
+ return Object.values(this.externalWallets)[0];
1137
+ }
1138
+ }
1139
+ if ((_a = this.externalWallets) == null ? void 0 : _a[idOrAddress]) {
1140
+ return this.externalWallets[idOrAddress];
1141
+ }
1142
+ try {
1143
+ const walletId = this.findWalletId(idOrAddress, filter);
1144
+ if (walletId && !!this.wallets[walletId]) {
1145
+ const _b = this.wallets[walletId], { signer: _signer } = _b, wallet = __objRest(_b, ["signer"]);
1146
+ const type = (_d = overrideType != null ? overrideType : (_c = this.currentWalletIdsArray.find(([id]) => id === walletId)) == null ? void 0 : _c[1]) != null ? _d : wallet.type;
1147
+ return __spreadProps(__spreadValues({}, wallet), {
1148
+ type
1149
+ });
1150
+ }
1151
+ } catch (e) {
1152
+ return void 0;
1153
+ }
1154
+ }
1155
+ get availableWallets() {
1156
+ var _a;
1157
+ return [
1158
+ ...[...this.currentWalletIdsArray, ...__privateGet(this, _ParaCore_instances, guestWalletIdsArray_get)].map(([address, type]) => [address, type, false]).map(([id, type]) => {
1159
+ const wallet = this.findWallet(id, type);
1160
+ if (!wallet) return null;
1161
+ return {
1162
+ id: wallet.id,
1163
+ type,
1164
+ address: this.getDisplayAddress(id, { addressType: type }),
1165
+ name: wallet.name
1166
+ };
1167
+ }).filter((obj) => obj !== null),
1168
+ ...Object.values((_a = this.externalWallets) != null ? _a : {})
1169
+ ];
1170
+ }
1171
+ /**
1172
+ * Retrieves all usable wallets with the provided type (`'EVM' | 'COSMOS' | 'SOLANA'`)
1173
+ * @param {string} type the wallet type to filter by.
1174
+ * @returns {Wallet[]} an array of matching wallets.
1175
+ */
1176
+ getWalletsByType(type) {
1177
+ return Object.values(this.wallets).filter((w) => this.isWalletUsable(w.id, { type: [type] }));
1178
+ }
1179
+ assertIsValidWalletId(walletId, condition = {}) {
1180
+ this.isWalletUsable(walletId, condition, true);
1181
+ }
1182
+ assertIsValidWalletType(type, walletTypes) {
1183
+ return __async(this, null, function* () {
1184
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1185
+ if (!type || !import_user_management_client.WALLET_TYPES.includes(type) || !(walletTypes != null ? walletTypes : supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
1186
+ throw new Error(`wallet type ${type} is not supported`);
1187
+ }
1188
+ return type;
1189
+ });
1190
+ }
1191
+ getMissingTypes() {
1192
+ return __async(this, null, function* () {
1193
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1194
+ return supportedWalletTypes.filter(
1195
+ ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !import_utils2.WalletSchemeTypeMap[w.scheme][t])
1196
+ ).map(({ type }) => type);
1197
+ });
1198
+ }
1199
+ getTypesToCreate(types) {
1200
+ return __async(this, null, function* () {
1201
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1202
+ return (0, import_utils2.getSchemes)(types != null ? types : yield this.getMissingTypes()).map((scheme) => {
1203
+ switch (scheme) {
1204
+ case "ED25519":
1205
+ return "SOLANA";
1206
+ default:
1207
+ return supportedWalletTypes.some(({ type, optional }) => type === "COSMOS" && !optional) ? "COSMOS" : "EVM";
1208
+ }
1209
+ });
1210
+ });
1211
+ }
1212
+ getPartnerURL() {
1213
+ return __async(this, null, function* () {
1214
+ try {
1215
+ const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1216
+ return portalUrl;
1217
+ } catch (e) {
1218
+ if (this.isPartnerOptional) {
1219
+ return void 0;
1220
+ }
1221
+ throw e;
1222
+ }
1223
+ });
1224
+ }
1225
+ /**
1226
+ * URL of the portal, which can be associated with a partner id
1227
+ * @param partnerId: string - id of the partner to get the portal URL for
1228
+ * @returns - portal URL
1229
+ */
1230
+ getPortalURL() {
1231
+ return __async(this, null, function* () {
1232
+ return (yield this.getPartnerURL()) || (0, import_utils2.getPortalBaseURL)(this.ctx);
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Gets the private key for the given wallet.
1237
+ * @param {string } [walletId] id of the wallet to get the private key for. Will default to the first wallet if not provided.
1238
+ * @returns - the private key string.
1239
+ */
1240
+ getPrivateKey(walletId) {
1241
+ return __async(this, null, function* () {
1242
+ const wallets = Object.values(this.wallets);
1243
+ const wallet = walletId ? this.wallets[walletId] : wallets == null ? void 0 : wallets[0];
1244
+ if (!wallet) {
1245
+ throw new Error("wallet not found");
1246
+ }
1247
+ if (wallet.scheme !== "DKLS") {
1248
+ throw new Error("invalid wallet scheme");
1249
+ }
1250
+ return yield this.platformUtils.getPrivateKey(
1251
+ this.ctx,
1252
+ this.userId,
1253
+ wallet.id,
1254
+ wallet.signer,
1255
+ this.retrieveSessionCookie()
1256
+ );
1257
+ });
1258
+ }
1259
+ /**
1260
+ * Fetches the wallets associated with the user.
1261
+ * @returns {WalletEntity[]} wallets that were fetched.
1262
+ */
1263
+ fetchWallets() {
1264
+ return __async(this, null, function* () {
1265
+ const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
1266
+ return res.data.wallets.filter(
1267
+ (wallet) => !!wallet.address && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported((0, import_utils2.entityToWallet)(wallet)))
1268
+ );
1269
+ });
1270
+ }
1271
+ populateWalletAddresses() {
1272
+ return __async(this, null, function* () {
1273
+ const res = yield this.ctx.client.getWallets(this.userId, true);
1274
+ const wallets = res.data.wallets;
1275
+ wallets.forEach((entity) => {
1276
+ if (this.wallets[entity.id]) {
1277
+ this.wallets[entity.id] = __spreadValues(__spreadValues({}, (0, import_utils2.entityToWallet)(entity)), this.wallets[entity.id]);
1278
+ }
1279
+ });
1280
+ yield this.setWallets(this.wallets);
1281
+ });
1282
+ }
1283
+ populatePregenWalletAddresses() {
1284
+ return __async(this, null, function* () {
1285
+ const res = yield this.getPregenWallets();
1286
+ res.forEach((entity) => {
1287
+ if (this.wallets[entity.id]) {
1288
+ this.wallets[entity.id] = __spreadValues(__spreadValues({}, (0, import_utils2.entityToWallet)(entity)), this.wallets[entity.id]);
1289
+ }
1290
+ });
1291
+ yield this.setWallets(this.wallets);
1292
+ });
1293
+ }
1294
+ /**
1295
+ * Logs in or creates a new user using an external wallet address.
1296
+ * @param {Object} opts the options object
1297
+ * @param {string} opts.address the external wallet address to use for identification.
1298
+ * @param {TWalletType} opts.type type of external wallet to use for identification.
1299
+ * @param {string} opts.provider the name of the provider for the external wallet.
1300
+ */
1301
+ loginExternalWallet(_a) {
1302
+ return __async(this, null, function* () {
1303
+ var _b = _a, {
1304
+ externalWallet
1305
+ } = _b, urlOptions = __objRest(_b, [
1306
+ "externalWallet"
1307
+ ]);
1308
+ const externalWallets = Array.isArray(externalWallet) ? externalWallet : [externalWallet];
1309
+ if (this.externalWalletConnectionOnly || externalWallets.every((wallet) => wallet.isConnectionOnly)) {
1310
+ yield this.setExternalWallet(
1311
+ externalWallets.map((wallet) => __spreadProps(__spreadValues({}, wallet), {
1312
+ withFullParaAuth: false
1313
+ }))
1314
+ );
1315
+ return Promise.resolve({
1316
+ userId: constants.EXTERNAL_WALLET_CONNECTION_ONLY_USER_ID
1317
+ });
1318
+ }
1319
+ if (Array.isArray(externalWallet)) {
1320
+ throw new Error(
1321
+ "Cannot authenticate multiple external wallets at once. To connect multiple wallets at once, use CONNECTION_ONLY mode."
1322
+ );
1323
+ }
1324
+ this.requireApiKey();
1325
+ const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet });
1326
+ if (!externalWallet.withFullParaAuth && externalWallet.withVerification) {
1327
+ yield this.touchSession(true);
1328
+ }
1329
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1330
+ });
1331
+ }
1332
+ verifyExternalWallet(_c) {
1333
+ return __async(this, null, function* () {
1334
+ var _d = _c, {
1335
+ externalWallet,
1336
+ signedMessage,
1337
+ cosmosPublicKeyHex,
1338
+ cosmosSigner
1339
+ } = _d, urlOptions = __objRest(_d, [
1340
+ "externalWallet",
1341
+ "signedMessage",
1342
+ "cosmosPublicKeyHex",
1343
+ "cosmosSigner"
1344
+ ]);
1345
+ const serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1346
+ externalWallet,
1347
+ signedMessage,
1348
+ cosmosPublicKeyHex,
1349
+ cosmosSigner
1350
+ });
1351
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1352
+ });
1353
+ }
1354
+ verifyExternalWalletLink(opts) {
1355
+ return __async(this, null, function* () {
1356
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EXTERNAL_WALLET"]);
1357
+ if (!accountLinkInProgress.externalWallet) {
1358
+ throw new Error("no external wallet account link in progress");
1359
+ }
1360
+ const accounts = yield this.verifyLink(__spreadValues({
1361
+ accountLinkInProgress,
1362
+ externalWallet: accountLinkInProgress.externalWallet
1363
+ }, opts));
1364
+ return accounts;
1365
+ });
1366
+ }
1367
+ /**
1368
+ * Validates the response received from an attempted Telegram login for authenticity, then
1369
+ * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
1370
+ * @param authResponse - the response JSON object received from the Telegram widget.
1371
+ * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1372
+ */
1373
+ verifyTelegramProcess(_e) {
1374
+ return __async(this, null, function* () {
1375
+ var _f = _e, {
1376
+ telegramAuthResponse,
1377
+ isLinkAccount
1378
+ } = _f, urlOptions = __objRest(_f, [
1379
+ "telegramAuthResponse",
1380
+ "isLinkAccount"
1381
+ ]);
1382
+ try {
1383
+ switch (isLinkAccount) {
1384
+ case false: {
1385
+ const serverAuthState = yield this.ctx.client.verifyTelegram(telegramAuthResponse);
1386
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1387
+ }
1388
+ case true: {
1389
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "TELEGRAM");
1390
+ const accounts = yield this.verifyLink({
1391
+ accountLinkInProgress,
1392
+ telegramAuthResponse
1393
+ });
1394
+ return accounts;
1395
+ }
1396
+ }
1397
+ } catch (e) {
1398
+ throw new Error(e.message);
1399
+ }
1400
+ });
1401
+ }
1402
+ verifyTelegram(opts) {
1403
+ return __async(this, null, function* () {
1404
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1405
+ });
1406
+ }
1407
+ verifyTelegramLink(opts) {
1408
+ return __async(this, null, function* () {
1409
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
1410
+ });
1411
+ }
1412
+ /**
1413
+ * Performs 2FA verification.
1414
+ * @param {Object} opts the options object
1415
+ * @param {string} opts.email the email to use for performing a 2FA verification.
1416
+ * @param {string} opts.verificationCode the verification code to received via 2FA.
1417
+ * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
1418
+ */
1419
+ verify2fa(_0) {
1420
+ return __async(this, arguments, function* ({ auth, verificationCode }) {
1421
+ const res = yield this.ctx.client.verify2FA(auth, verificationCode);
1422
+ return {
1423
+ initiatedAt: res.data.initiatedAt,
1424
+ status: res.data.status,
1425
+ userId: res.data.userId,
1426
+ wallets: res.data.wallets
1427
+ };
1428
+ });
1429
+ }
1430
+ /**
1431
+ * Sets up two-factor authentication for the current user.
1432
+ * @returns {string} uri - uri to use for setting up 2FA
1433
+ * */
1434
+ setup2fa() {
1435
+ return __async(this, null, function* () {
1436
+ const userId = this.assertUserId();
1437
+ const res = yield this.ctx.client.setup2FA(userId);
1438
+ return res;
1439
+ });
1440
+ }
1441
+ /**
1442
+ * Enables 2FA.
1443
+ * @param {Object} opts the options object
1444
+ * @param {string} opts.verificationCode - the verification code received via 2FA.
1445
+ */
1446
+ enable2fa(_0) {
1447
+ return __async(this, arguments, function* ({ verificationCode }) {
1448
+ const userId = this.assertUserId();
1449
+ yield this.ctx.client.enable2FA(userId, verificationCode);
1450
+ });
1451
+ }
1452
+ /**
1453
+ * Resend a verification email for the current user.
1454
+ */
1455
+ resendVerificationCode(_0) {
1456
+ return __async(this, arguments, function* ({
1457
+ type: reason = "SIGNUP"
1458
+ }) {
1459
+ let type, linkedAccountId;
1460
+ switch (reason) {
1461
+ case "SIGNUP":
1462
+ {
1463
+ const authInfo = this.assertIsAuthSet(["email", "phone"]);
1464
+ type = authInfo.authType.toUpperCase();
1465
+ }
1466
+ break;
1467
+ case "LINK_ACCOUNT":
1468
+ {
1469
+ const accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]);
1470
+ linkedAccountId = accountLinkInProgress.id;
1471
+ type = accountLinkInProgress.type;
1472
+ }
1473
+ break;
1474
+ }
1475
+ const userId = this.assertUserId();
1476
+ if (type !== "EMAIL" && type !== "PHONE") {
1477
+ throw new Error("invalid auth type for verification code");
1478
+ }
1479
+ yield this.ctx.client.resendVerificationCode(__spreadValues({
1480
+ userId,
1481
+ type,
1482
+ linkedAccountId
1483
+ }, this.getVerificationEmailProps()));
1484
+ });
1485
+ }
1486
+ /**
1487
+ * Checks if the current session is active.
1488
+ * @returns `true` if active, `false` otherwise
1489
+ */
1490
+ isSessionActive() {
1491
+ return __async(this, null, function* () {
1492
+ if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1493
+ return true;
1494
+ }
1495
+ const { isAuthenticated, verifiedExternalWalletAddresses } = yield this.touchSession();
1496
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1497
+ if (!verifiedExternalWalletAddresses) {
1498
+ return false;
1499
+ }
1500
+ const externalAddresses = Object.values(this.externalWallets).map((w) => w.id);
1501
+ return externalAddresses.every((address) => verifiedExternalWalletAddresses.includes(address));
1502
+ }
1503
+ return !!isAuthenticated;
1504
+ });
1505
+ }
1506
+ /**
1507
+ * Checks if a session is active and a wallet exists.
1508
+ * @returns `true` if active, `false` otherwise
1509
+ **/
1510
+ isFullyLoggedIn() {
1511
+ return __async(this, null, function* () {
1512
+ if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1513
+ return true;
1514
+ }
1515
+ if (this.isGuestMode) {
1516
+ return true;
1517
+ }
1518
+ const isSessionActive = yield this.isSessionActive();
1519
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1520
+ return isSessionActive;
1521
+ }
1522
+ return isSessionActive && (this.isNoWalletConfig || this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true));
1523
+ });
1524
+ }
1525
+ get isGuestMode() {
1526
+ return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1527
+ ({ userId, partnerId }) => {
1528
+ var _a;
1529
+ return partnerId === ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1530
+ }
1531
+ );
1532
+ }
1533
+ supportedAuthMethods(auth) {
1534
+ return __async(this, null, function* () {
1535
+ const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
1536
+ const authMethods = /* @__PURE__ */ new Set();
1537
+ for (const type of supportedAuthMethods) {
1538
+ switch (type) {
1539
+ case "PASSWORD":
1540
+ authMethods.add(import_user_management_client.AuthMethod.PASSWORD);
1541
+ break;
1542
+ case "BIOMETRIC":
1543
+ authMethods.add(import_user_management_client.AuthMethod.PASSKEY);
1544
+ break;
1545
+ }
1546
+ }
1547
+ return authMethods;
1548
+ });
1549
+ }
1550
+ /**
1551
+ * Get hints associated with the users stored biometrics.
1552
+ * @deprecated
1553
+ * @returns Array containing useragents and AAGuids for stored biometrics
1554
+ */
1555
+ getUserBiometricLocationHints() {
1556
+ return __async(this, null, function* () {
1557
+ const { auth } = this.assertIsAuthSet();
1558
+ return yield this.ctx.client.getBiometricLocationHints(auth);
1559
+ });
1560
+ }
1561
+ /**
1562
+ * Waits for the session to be active.
1563
+ **/
1564
+ waitForSignup(_0) {
1565
+ return __async(this, arguments, function* ({
1566
+ isCanceled = () => false,
1567
+ onCancel,
1568
+ onPoll
1569
+ }) {
1570
+ const startedAt = Date.now();
1571
+ return new Promise((resolve, reject) => {
1572
+ (() => __async(this, null, function* () {
1573
+ yield this.touchSession();
1574
+ if (!this.isExternalWalletAuth) {
1575
+ this.externalWallets = {};
1576
+ }
1577
+ while (true) {
1578
+ try {
1579
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1580
+ onCancel == null ? void 0 : onCancel();
1581
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.ACCOUNT_CREATION_EVENT, false, "failed to sign up user");
1582
+ return reject("canceled");
1583
+ }
1584
+ yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
1585
+ if (yield this.isSessionActive()) {
1586
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.ACCOUNT_CREATION_EVENT, true);
1587
+ return resolve(true);
1588
+ }
1589
+ onPoll == null ? void 0 : onPoll();
1590
+ } catch (err) {
1591
+ console.error(err);
1592
+ onPoll == null ? void 0 : onPoll();
1593
+ }
1594
+ }
1595
+ }))();
1596
+ });
1597
+ });
1598
+ }
1599
+ waitForWalletCreation() {
1600
+ return __async(this, arguments, function* ({
1601
+ isCanceled = () => false,
1602
+ onCancel
1603
+ } = {}) {
1604
+ yield this.waitForSignup({ isCanceled, onCancel });
1605
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1606
+ const pregenWallets = yield this.getPregenWallets();
1607
+ let recoverySecret, walletIds = {};
1608
+ if (pregenWallets.length > 0) {
1609
+ recoverySecret = yield this.claimPregenWallets();
1610
+ walletIds = supportedWalletTypes.reduce((acc, { type }) => {
1611
+ var _a;
1612
+ return __spreadProps(__spreadValues({}, acc), {
1613
+ [type]: [(_a = pregenWallets.find((w) => !!import_utils2.WalletSchemeTypeMap[w.scheme][type])) == null ? void 0 : _a.id]
1614
+ });
1615
+ }, {});
1616
+ }
1617
+ const created = yield this.createWalletPerType();
1618
+ recoverySecret = recoverySecret != null ? recoverySecret : created.recoverySecret;
1619
+ walletIds = __spreadValues(__spreadValues({}, walletIds), created.walletIds);
1620
+ const resp = { walletIds, recoverySecret };
1621
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.ACCOUNT_SETUP_EVENT, resp);
1622
+ return resp;
1623
+ });
1624
+ }
1625
+ /**
1626
+ * Initiates a Farcaster login attempt and returns the URL for the user to connect.
1627
+ * You can create a QR code with this URI that works with Farcaster's mobile app.
1628
+ * @return {string} the Farcaster connect URI
1629
+ */
1630
+ getFarcasterConnectUri() {
1631
+ return __async(this, arguments, function* ({ appScheme } = {}) {
1632
+ const { connect_uri: connectUri } = yield this.ctx.client.initializeFarcasterLogin({ appScheme });
1633
+ return connectUri;
1634
+ });
1635
+ }
1636
+ /**
1637
+ * Awaits the response from a user's attempt to log in with Farcaster.
1638
+ * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
1639
+ * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
1640
+ */
1641
+ verifyFarcasterProcess(_g) {
1642
+ return __async(this, null, function* () {
1643
+ var _h = _g, {
1644
+ isCanceled = () => false,
1645
+ onConnectUri,
1646
+ onCancel,
1647
+ onPoll,
1648
+ isLinkAccount
1649
+ } = _h, urlOptions = __objRest(_h, [
1650
+ "isCanceled",
1651
+ "onConnectUri",
1652
+ "onCancel",
1653
+ "onPoll",
1654
+ "isLinkAccount"
1655
+ ]);
1656
+ let accountLinkInProgress;
1657
+ if (isLinkAccount) {
1658
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
1659
+ }
1660
+ if (onConnectUri) {
1661
+ const connectUri = yield this.getFarcasterConnectUri();
1662
+ onConnectUri(connectUri);
1663
+ }
1664
+ return new Promise((resolve, reject) => {
1665
+ (() => __async(this, null, function* () {
1666
+ const startedAt = Date.now();
1667
+ while (true) {
1668
+ try {
1669
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1670
+ onCancel == null ? void 0 : onCancel();
1671
+ return reject("CANCELED");
1672
+ }
1673
+ yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
1674
+ switch (isLinkAccount) {
1675
+ case false:
1676
+ {
1677
+ const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
1678
+ if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
1679
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1680
+ return resolve(authState);
1681
+ }
1682
+ }
1683
+ break;
1684
+ case true: {
1685
+ const result = yield this.verifyLink({
1686
+ accountLinkInProgress
1687
+ });
1688
+ if ("isConflict" in result) {
1689
+ throw new Error(import_types.AccountLinkError.Conflict);
1690
+ }
1691
+ return resolve(result);
1692
+ }
1693
+ }
1694
+ onPoll == null ? void 0 : onPoll();
1695
+ } catch (e) {
1696
+ if (!isLinkAccount || e.message === import_types.AccountLinkError.Conflict) {
1697
+ return reject(e.message);
1698
+ }
1699
+ }
1700
+ }
1701
+ }))();
1702
+ });
1703
+ });
1704
+ }
1705
+ verifyFarcaster(opts) {
1706
+ return __async(this, null, function* () {
1707
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1708
+ });
1709
+ }
1710
+ verifyFarcasterLink(opts) {
1711
+ return __async(this, null, function* () {
1712
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
1713
+ });
1714
+ }
1715
+ getOAuthUrl(opts) {
1716
+ return __async(this, null, function* () {
1717
+ return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, opts);
1718
+ });
1719
+ }
1720
+ /**
1721
+ * Awaits the response from a user's attempt to log in with OAuth.
1722
+ * If successful, this returns the user's email address and indicates whether the user already exists.
1723
+ *
1724
+ * @param {Object} opts the options object.
1725
+ * @param {Window} [opts.popupWindow] the popup window being used for login.
1726
+ * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
1727
+ */
1728
+ verifyOAuthProcess(_k) {
1729
+ return __async(this, null, function* () {
1730
+ var _l = _k, {
1731
+ method,
1732
+ appScheme,
1733
+ isCanceled = () => false,
1734
+ onCancel,
1735
+ onPoll,
1736
+ onOAuthUrl,
1737
+ isLinkAccount
1738
+ } = _l, urlOptions = __objRest(_l, [
1739
+ "method",
1740
+ "appScheme",
1741
+ "isCanceled",
1742
+ "onCancel",
1743
+ "onPoll",
1744
+ "onOAuthUrl",
1745
+ "isLinkAccount"
1746
+ ]);
1747
+ let sessionLookupId, accountLinkInProgress;
1748
+ if (onOAuthUrl) {
1749
+ if (isLinkAccount) {
1750
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
1751
+ sessionLookupId = (yield this.touchSession()).sessionLookupId;
1752
+ } else {
1753
+ sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
1754
+ }
1755
+ const oAuthUrl = yield __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, { method, appScheme, sessionLookupId, accountLinkInProgress });
1756
+ onOAuthUrl(oAuthUrl);
1757
+ } else {
1758
+ ({ sessionLookupId } = yield this.touchSession());
1759
+ }
1760
+ const startedAt = Date.now();
1761
+ return new Promise((resolve, reject) => {
1762
+ (() => __async(this, null, function* () {
1763
+ while (true) {
1764
+ try {
1765
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1766
+ onCancel == null ? void 0 : onCancel();
1767
+ return reject(import_types.AccountLinkError.Canceled);
1768
+ }
1769
+ yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
1770
+ switch (isLinkAccount) {
1771
+ case false:
1772
+ {
1773
+ const serverAuthState = yield this.ctx.client.verifyOAuth();
1774
+ if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
1775
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1776
+ return resolve(authState);
1777
+ }
1778
+ }
1779
+ break;
1780
+ case true: {
1781
+ const accounts = yield this.verifyLink({ accountLinkInProgress });
1782
+ return resolve(accounts);
1783
+ }
1784
+ }
1785
+ onPoll == null ? void 0 : onPoll();
1786
+ } catch (err) {
1787
+ if (isLinkAccount && err.message === import_types.AccountLinkError.Conflict) {
1788
+ return reject(err.message);
1789
+ }
1790
+ onPoll == null ? void 0 : onPoll();
1791
+ }
1792
+ }
1793
+ }))();
1794
+ });
1795
+ });
1796
+ }
1797
+ verifyOAuth(opts) {
1798
+ return __async(this, null, function* () {
1799
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1800
+ });
1801
+ }
1802
+ verifyOAuthLink(opts) {
1803
+ return __async(this, null, function* () {
1804
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
1805
+ });
1806
+ }
1807
+ /**
1808
+ * Waits for the session to be active and sets up the user.
1809
+ *
1810
+ * @param {Object} opts the options object
1811
+ * @param {Window} [opts.popupWindow] the popup window being used for login.
1812
+ * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
1813
+ * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
1814
+ **/
1815
+ waitForLogin() {
1816
+ return __async(this, arguments, function* ({
1817
+ isCanceled = () => false,
1818
+ onCancel,
1819
+ onPoll,
1820
+ skipSessionRefresh = false
1821
+ } = {}) {
1822
+ const startedAt = Date.now();
1823
+ return new Promise((resolve, reject) => {
1824
+ (() => __async(this, null, function* () {
1825
+ var _a;
1826
+ if (!this.isExternalWalletAuth) {
1827
+ this.externalWallets = {};
1828
+ }
1829
+ while (true) {
1830
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1831
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
1832
+ onCancel == null ? void 0 : onCancel();
1833
+ return reject("canceled");
1834
+ }
1835
+ yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
1836
+ try {
1837
+ let session = yield this.touchSession();
1838
+ if (!session.isAuthenticated) {
1839
+ onPoll == null ? void 0 : onPoll();
1840
+ continue;
1841
+ }
1842
+ session = yield this.userSetupAfterLogin();
1843
+ const needsWallet = (_a = session.needsWallet) != null ? _a : false;
1844
+ if (!needsWallet) {
1845
+ if (this.currentWalletIdsArray.length === 0) {
1846
+ onPoll == null ? void 0 : onPoll();
1847
+ continue;
1848
+ }
1849
+ }
1850
+ const fetchedWallets = yield this.fetchWallets();
1851
+ const tempSharesRes = yield this.getTransmissionKeyShares();
1852
+ if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
1853
+ yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
1854
+ yield this.claimPregenWallets();
1855
+ const resp = {
1856
+ needsWallet: needsWallet || Object.values(this.wallets).length === 0,
1857
+ partnerId: session.partnerId
1858
+ };
1859
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGIN_EVENT, resp);
1860
+ return resolve(resp);
1861
+ }
1862
+ onPoll == null ? void 0 : onPoll();
1863
+ } catch (err) {
1864
+ console.error(err);
1865
+ onPoll == null ? void 0 : onPoll();
1866
+ }
1867
+ }
1868
+ }))();
1869
+ });
1870
+ });
1871
+ }
1872
+ /**
1873
+ * Updates the session with the user management server, possibly
1874
+ * opening a popup to refresh the session.
1875
+ *
1876
+ * @param {Object} opts the options object.
1877
+ * @param {boolean} [shouldOpenPopup] - if `true`, the running device will open a popup to reauthenticate the user.
1878
+ * @returns a URL for the user to reauthenticate.
1879
+ **/
1880
+ refreshSession() {
1881
+ return __async(this, arguments, function* ({
1882
+ shouldOpenPopup = false
1883
+ } = {}) {
1884
+ const { sessionId } = yield this.touchSession(true);
1885
+ if (!this.loginEncryptionKeyPair) {
1886
+ yield this.setLoginEncryptionKeyPair();
1887
+ }
1888
+ const link = yield this.getLoginUrl({
1889
+ sessionId
1890
+ });
1891
+ if (shouldOpenPopup) {
1892
+ this.platformUtils.openPopup(link);
1893
+ }
1894
+ return link;
1895
+ });
1896
+ }
1897
+ /**
1898
+ * Call this method after login to ensure that the user ID is set
1899
+ * internally.
1900
+ **/
1901
+ userSetupAfterLogin() {
1902
+ return __async(this, null, function* () {
1903
+ const session = yield this.touchSession();
1904
+ yield this.setUserId(session.userId);
1905
+ if (session.currentWalletIds && session.currentWalletIds !== this.currentWalletIds)
1906
+ yield this.setCurrentWalletIds(session.currentWalletIds, {
1907
+ sessionLookupId: this.isPortal() ? session.sessionLookupId : void 0
1908
+ });
1909
+ return session;
1910
+ });
1911
+ }
1912
+ /**
1913
+ * Get transmission shares associated with session.
1914
+ * @param {Object} opts the options object.
1915
+ * @param {boolean} opts.isForNewDevice - true if this device is registering.
1916
+ * @returns - transmission keyshares.
1917
+ **/
1918
+ getTransmissionKeyShares() {
1919
+ return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
1920
+ const session = yield this.touchSession();
1921
+ const sessionLookupId = isForNewDevice ? `${session.sessionLookupId}-new-device` : session.sessionLookupId;
1922
+ return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
1923
+ });
1924
+ }
1925
+ /**
1926
+ * Call this method after login to perform setup.
1927
+ * @param {Object} opts the options object.
1928
+ * @param {any[]} opts.temporaryShares optional temporary shares to use for decryption.
1929
+ * @param {boolean} [opts.skipSessionRefresh] - whether or not to skip refreshing the session.
1930
+ **/
1931
+ setupAfterLogin() {
1932
+ return __async(this, arguments, function* ({
1933
+ temporaryShares,
1934
+ skipSessionRefresh = false
1935
+ } = {}) {
1936
+ if (!temporaryShares) {
1937
+ temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
1938
+ }
1939
+ temporaryShares.forEach((share) => {
1940
+ const signer = (0, import_utils.decryptWithPrivateKey)(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
1941
+ this.wallets[share.walletId] = {
1942
+ id: share.walletId,
1943
+ signer
1944
+ };
1945
+ });
1946
+ yield this.deleteLoginEncryptionKeyPair();
1947
+ yield this.populateWalletAddresses();
1948
+ yield this.touchSession(!skipSessionRefresh);
1949
+ });
1950
+ }
1951
+ /**
1952
+ * Distributes a new wallet recovery share.
1953
+ * @param {Object} opts the options object.
1954
+ * @param {string} opts.walletId the wallet to distribute the recovery share for.
1955
+ * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
1956
+ * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
1957
+ * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
1958
+ * @returns {string} the recovery share.
1959
+ **/
1960
+ distributeNewWalletShare(_0) {
1961
+ return __async(this, arguments, function* ({
1962
+ walletId,
1963
+ userShare,
1964
+ skipBiometricShareCreation = false,
1965
+ forceRefresh = false
1966
+ }) {
1967
+ let userSigner = userShare;
1968
+ if (!userSigner) {
1969
+ userSigner = this.wallets[walletId].signer;
1970
+ }
1971
+ const recoveryShare = skipBiometricShareCreation ? yield (0, import_recovery.sendRecoveryForShare)({
1972
+ ctx: this.ctx,
1973
+ userId: this.userId,
1974
+ walletId,
1975
+ userSigner,
1976
+ emailProps: this.getBackupKitEmailProps(),
1977
+ forceRefresh
1978
+ }) : yield (0, import_shareDistribution.distributeNewShare)({
1979
+ ctx: this.ctx,
1980
+ userId: this.userId,
1981
+ walletId,
1982
+ userShare: userSigner,
1983
+ emailProps: this.getBackupKitEmailProps()
1984
+ });
1985
+ return recoveryShare;
1986
+ });
1987
+ }
1988
+ waitForWalletAddress(walletId) {
1989
+ return __async(this, null, function* () {
1990
+ let maxPolls = 0;
1991
+ while (true) {
1992
+ try {
1993
+ if (maxPolls === 10) {
1994
+ break;
1995
+ }
1996
+ ++maxPolls;
1997
+ const res = yield this.ctx.client.getWallets(this.userId);
1998
+ const wallet = res.data.wallets.find((w) => w.id === walletId);
1999
+ if (wallet && wallet.address) {
2000
+ return;
2001
+ }
2002
+ yield new Promise((resolve) => setTimeout(resolve, constants.SHORT_POLLING_INTERVAL_MS));
2003
+ } catch (err) {
2004
+ console.error(err);
2005
+ }
2006
+ }
2007
+ throw new Error("timed out waiting for wallet address");
2008
+ });
2009
+ }
2010
+ /**
2011
+ * Waits for a pregen wallet address to be created.
2012
+ *
2013
+ * @param pregenIdentifier - the identifier of the user the pregen wallet is associated with.
2014
+ * @param walletId - the wallet id
2015
+ * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
2016
+ * @returns - recovery share.
2017
+ **/
2018
+ waitForPregenWalletAddress(walletId) {
2019
+ return __async(this, null, function* () {
2020
+ let maxPolls = 0;
2021
+ while (true) {
2022
+ try {
2023
+ if (maxPolls === 10) {
2024
+ break;
2025
+ }
2026
+ ++maxPolls;
2027
+ const res = yield this.getPregenWallets();
2028
+ const wallet = res.find((w) => w.id === walletId);
2029
+ if (wallet && wallet.address) {
2030
+ return;
2031
+ }
2032
+ yield new Promise((resolve) => setTimeout(resolve, constants.SHORT_POLLING_INTERVAL_MS));
2033
+ } catch (err) {
2034
+ console.error(err);
2035
+ }
2036
+ }
2037
+ throw new Error("timed out waiting for wallet address");
2038
+ });
2039
+ }
2040
+ /**
2041
+ * Creates several new wallets with the desired types. If no types are provided, this method
2042
+ * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
2043
+ * object that are not already present. This is automatically called upon account creation to ensure that
2044
+ * the user has a wallet of each required type.
2045
+ *
2046
+ * @param {Object} [opts] the options object.
2047
+ * @param {boolean} [opts.skipDistribute] if `true`, the wallets' recovery share will not be distributed.
2048
+ * @param {TWalletType[]} [opts.types] the types of wallets to create.
2049
+ * @returns {Object} the wallets created, their ids, and the recovery secret.
2050
+ **/
2051
+ createWalletPerType() {
2052
+ return __async(this, arguments, function* ({
2053
+ skipDistribute = false,
2054
+ types
2055
+ } = {}) {
2056
+ const wallets = [];
2057
+ const walletIds = {};
2058
+ let recoverySecret;
2059
+ for (const type of yield this.getTypesToCreate(types)) {
2060
+ const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
2061
+ wallets.push(wallet);
2062
+ (0, import_utils2.getEquivalentTypes)(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
2063
+ walletIds[t] = [wallet.id];
2064
+ });
2065
+ if (recoveryShare) {
2066
+ recoverySecret = recoveryShare;
2067
+ }
2068
+ }
2069
+ return { wallets, walletIds, recoverySecret };
2070
+ });
2071
+ }
2072
+ /**
2073
+ * Refresh the current user share for a wallet.
2074
+ *
2075
+ * @param {Object} opts the options object.
2076
+ * @param {string} opts.walletId the wallet id to refresh.
2077
+ * @param {string} opts.share the current user share.
2078
+ * @param {string} [opts.oldPartnerId] the current partner id.
2079
+ * @param {string} [opts.newPartnerId] the new partner id to set, if any.
2080
+ * @param {string} [opts.keyShareProtocolId]
2081
+ * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
2082
+ * @returns {Object} the new user share and recovery secret.
2083
+ **/
2084
+ refreshShare(_0) {
2085
+ return __async(this, arguments, function* ({
2086
+ walletId,
2087
+ share,
2088
+ oldPartnerId,
2089
+ newPartnerId,
2090
+ keyShareProtocolId,
2091
+ redistributeBackupEncryptedShares
2092
+ }) {
2093
+ const { signer, protocolId } = yield this.platformUtils.refresh(
2094
+ this.ctx,
2095
+ this.retrieveSessionCookie(),
2096
+ this.userId,
2097
+ walletId,
2098
+ share,
2099
+ oldPartnerId,
2100
+ newPartnerId,
2101
+ keyShareProtocolId
2102
+ );
2103
+ const recoverySecret = yield (0, import_shareDistribution.distributeNewShare)({
2104
+ ctx: this.ctx,
2105
+ userId: this.userId,
2106
+ walletId,
2107
+ userShare: signer,
2108
+ ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
2109
+ emailProps: this.getBackupKitEmailProps(),
2110
+ partnerId: newPartnerId,
2111
+ protocolId
2112
+ });
2113
+ return { signer, recoverySecret, protocolId };
2114
+ });
2115
+ }
2116
+ /**
2117
+ * Creates a new wallet.
2118
+ * @param {Object} opts the options object.
2119
+ * @param {TWalletType} opts.type the type of wallet to create.
2120
+ * @param {boolean} opts.skipDistribute - if true, recovery share will not be distributed.
2121
+ * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2122
+ **/
2123
+ createWallet() {
2124
+ return __async(this, arguments, function* ({
2125
+ type: _type,
2126
+ skipDistribute = false
2127
+ } = {}) {
2128
+ var _a, _b;
2129
+ this.requireApiKey();
2130
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2131
+ const walletType = yield this.assertIsValidWalletType(
2132
+ _type != null ? _type : (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
2133
+ );
2134
+ let signer;
2135
+ let wallet;
2136
+ let keygenRes;
2137
+ switch (walletType) {
2138
+ case "SOLANA": {
2139
+ keygenRes = yield this.platformUtils.ed25519Keygen(
2140
+ this.ctx,
2141
+ this.userId,
2142
+ this.retrieveSessionCookie(),
2143
+ this.getBackupKitEmailProps()
2144
+ );
2145
+ break;
2146
+ }
2147
+ default: {
2148
+ keygenRes = yield this.platformUtils.keygen(
2149
+ this.ctx,
2150
+ this.userId,
2151
+ walletType,
2152
+ null,
2153
+ this.retrieveSessionCookie(),
2154
+ this.getBackupKitEmailProps()
2155
+ );
2156
+ break;
2157
+ }
2158
+ }
2159
+ const walletId = keygenRes.walletId;
2160
+ signer = keygenRes.signer;
2161
+ this.wallets[walletId] = {
2162
+ id: walletId,
2163
+ signer,
2164
+ scheme: walletType === "SOLANA" ? "ED25519" : "DKLS",
2165
+ type: walletType
2166
+ };
2167
+ wallet = this.wallets[walletId];
2168
+ yield this.waitForWalletAddress(wallet.id);
2169
+ yield this.populateWalletAddresses();
2170
+ let recoveryShare = null;
2171
+ if (!skipDistribute) {
2172
+ recoveryShare = yield (0, import_shareDistribution.distributeNewShare)({
2173
+ ctx: this.ctx,
2174
+ userId: this.userId,
2175
+ walletId: wallet.id,
2176
+ userShare: signer,
2177
+ emailProps: this.getBackupKitEmailProps()
2178
+ });
2179
+ }
2180
+ yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
2181
+ [walletType]: [.../* @__PURE__ */ new Set([...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId])]
2182
+ }));
2183
+ const walletNoSigner = __spreadValues({}, wallet);
2184
+ delete walletNoSigner.signer;
2185
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.WALLET_CREATED, {
2186
+ wallet: walletNoSigner,
2187
+ recoverySecret: recoveryShare
2188
+ });
2189
+ return [wallet, recoveryShare];
2190
+ });
2191
+ }
2192
+ createPregenWallet(opts) {
2193
+ return __async(this, null, function* () {
2194
+ return yield __privateMethod(this, _ParaCore_instances, createPregenWallet_fn).call(this, opts);
2195
+ });
2196
+ }
2197
+ /**
2198
+ * Creates new pregenerated wallets for each desired type.
2199
+ * If no types are provided, this method will create one for each of the non-optional types
2200
+ * specified in the instance's `supportedWalletTypes` array that are not already present.
2201
+ * @param {Object} opts the options object.
2202
+ * @param {string} opts.pregenIdentifier the identifier to associate each wallet with.
2203
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType - either `'EMAIL'` or `'PHONE'`.
2204
+ * @param {TWalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
2205
+ * @returns {Wallet[]} an array containing the created wallets.
2206
+ **/
2207
+ createPregenWalletPerType(_0) {
2208
+ return __async(this, arguments, function* ({
2209
+ types,
2210
+ pregenId
2211
+ }) {
2212
+ const wallets = [];
2213
+ for (const type of yield this.getTypesToCreate(types)) {
2214
+ const wallet = yield this.createPregenWallet({ type, pregenId });
2215
+ wallets.push(wallet);
2216
+ }
2217
+ return wallets;
2218
+ });
2219
+ }
2220
+ /**
2221
+ * Claims a pregenerated wallet.
2222
+ * @param {Object} opts the options object.
2223
+ * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
2224
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the identifier of the user claiming the wallet
2225
+ * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2226
+ **/
2227
+ claimPregenWallets() {
2228
+ return __async(this, arguments, function* ({
2229
+ pregenId
2230
+ } = {}) {
2231
+ var _a;
2232
+ this.requireApiKey();
2233
+ const pregenWallets = pregenId ? yield this.getPregenWallets({ pregenId }) : yield this.getPregenWallets();
2234
+ if (pregenWallets.length === 0) {
2235
+ return void 0;
2236
+ }
2237
+ const missingWallets = pregenWallets.filter((wallet) => !this.wallets[wallet.id]);
2238
+ if (missingWallets.length > 0) {
2239
+ throw new Error(
2240
+ `Cannot claim pregen wallets because wallet data is missing. Please call setUserShare first to load the wallet data for the following wallet IDs: ${missingWallets.map((w) => w.id).join(", ")}`
2241
+ );
2242
+ }
2243
+ let newRecoverySecret;
2244
+ const { walletIds } = yield this.ctx.client.claimPregenWallets({
2245
+ userId: this.userId,
2246
+ walletIds: pregenWallets.map((w) => w.id)
2247
+ });
2248
+ for (const walletId of walletIds) {
2249
+ const wallet = this.wallets[walletId];
2250
+ let refreshedShare;
2251
+ if (wallet.scheme === "ED25519") {
2252
+ const distributeRes = yield (0, import_shareDistribution.distributeNewShare)({
2253
+ ctx: this.ctx,
2254
+ userId: this.userId,
2255
+ walletId: wallet.id,
2256
+ userShare: this.wallets[wallet.id].signer,
2257
+ emailProps: this.getBackupKitEmailProps(),
2258
+ partnerId: wallet.partnerId
2259
+ });
2260
+ if (distributeRes.length > 0) {
2261
+ newRecoverySecret = distributeRes;
2262
+ }
2263
+ } else {
2264
+ refreshedShare = yield this.refreshShare({
2265
+ walletId: wallet.id,
2266
+ share: this.wallets[wallet.id].signer,
2267
+ oldPartnerId: wallet.partnerId,
2268
+ newPartnerId: wallet.partnerId,
2269
+ redistributeBackupEncryptedShares: true
2270
+ });
2271
+ if (refreshedShare.recoverySecret) {
2272
+ newRecoverySecret = refreshedShare.recoverySecret;
2273
+ }
2274
+ }
2275
+ this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
2276
+ signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
2277
+ userId: this.userId,
2278
+ pregenIdentifier: void 0,
2279
+ pregenIdentifierType: void 0
2280
+ });
2281
+ const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
2282
+ delete walletNoSigner.signer;
2283
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.PREGEN_WALLET_CLAIMED, {
2284
+ wallet: walletNoSigner,
2285
+ recoverySecret: newRecoverySecret
2286
+ });
2287
+ }
2288
+ yield this.setWallets(this.wallets);
2289
+ return newRecoverySecret;
2290
+ });
2291
+ }
2292
+ /**
2293
+ * Updates the identifier for a pregen wallet.
2294
+ * @param {Object} opts the options object.
2295
+ * @param {string} opts.walletId the pregen wallet ID
2296
+ * @param {string} opts.newPregenIdentifier the new identtifier
2297
+ * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
2298
+ **/
2299
+ updatePregenWalletIdentifier(_0) {
2300
+ return __async(this, arguments, function* ({
2301
+ walletId,
2302
+ newPregenId
2303
+ }) {
2304
+ this.requireApiKey();
2305
+ const [newPregenIdentifierType, newPregenIdentifier] = (0, import_user_management_client.toPregenTypeAndId)(newPregenId);
2306
+ yield this.ctx.client.updatePregenWallet(walletId, {
2307
+ pregenIdentifier: newPregenIdentifier,
2308
+ pregenIdentifierType: newPregenIdentifierType
2309
+ });
2310
+ if (!!this.wallets[walletId]) {
2311
+ this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
2312
+ pregenIdentifier: newPregenIdentifier,
2313
+ pregenIdentifierType: newPregenIdentifierType
2314
+ });
2315
+ yield this.setWallets(this.wallets);
2316
+ }
2317
+ });
2318
+ }
2319
+ /**
2320
+ * Checks if a pregen Wallet exists for the given identifier with the current partner.
2321
+ * @param {Object} opts the options object.
2322
+ * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
2323
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
2324
+ * @returns {boolean} whether the pregen wallet exists
2325
+ **/
2326
+ hasPregenWallet(_0) {
2327
+ return __async(this, arguments, function* ({ pregenId }) {
2328
+ this.requireApiKey();
2329
+ const [pregenIdentifierType, pregenIdentifier] = (0, import_user_management_client.toPregenTypeAndId)(pregenId);
2330
+ const wallets = yield this.getPregenWallets({ pregenId });
2331
+ const wallet = wallets.find(
2332
+ (w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType
2333
+ );
2334
+ if (!wallet) {
2335
+ return false;
2336
+ }
2337
+ return true;
2338
+ });
2339
+ }
2340
+ /**
2341
+ * Get pregen wallets for the given identifier.
2342
+ * @param {Object} opts the options object.
2343
+ * @param {string} opts.pregenIdentifier - the identifier of the user claiming the wallet
2344
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType - type of the identifier of the user claiming the wallet
2345
+ * @returns {Promise<WalletEntity[]>} the array of found wallets
2346
+ **/
2347
+ getPregenWallets() {
2348
+ return __async(this, arguments, function* ({ pregenId } = {}) {
2349
+ this.requireApiKey();
2350
+ const res = yield this.ctx.client.getPregenWallets(
2351
+ pregenId ? (0, import_user_management_client.toPregenIds)(pregenId) : this.pregenIds,
2352
+ this.isPortal(),
2353
+ this.userId
2354
+ );
2355
+ return res.wallets.filter((w) => this.isWalletSupported((0, import_utils2.entityToWallet)(w)));
2356
+ });
2357
+ }
2358
+ createGuestWallets() {
2359
+ return __async(this, null, function* () {
2360
+ let error;
2361
+ if (__privateGet(this, _isCreateGuestWalletsPending)) {
2362
+ error = new Error("Guest wallets creation already in progress");
2363
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, null, error.message);
2364
+ throw error;
2365
+ }
2366
+ if (this.isGuestMode) {
2367
+ error = new Error("Guest wallets already created");
2368
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, null, error.message);
2369
+ throw error;
2370
+ }
2371
+ try {
2372
+ __privateSet(this, _isCreateGuestWalletsPending, true);
2373
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2374
+ const wallets = [];
2375
+ const guestId = (0, import_utils2.newUuid)();
2376
+ for (const type of yield this.getTypesToCreate(
2377
+ supportedWalletTypes.filter(({ optional }) => !optional).map(({ type: type2 }) => type2)
2378
+ )) {
2379
+ const wallet = yield __privateMethod(this, _ParaCore_instances, createPregenWallet_fn).call(this, { type, pregenId: { guestId } });
2380
+ wallets.push(wallet);
2381
+ }
2382
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, wallets);
2383
+ __privateSet(this, _isCreateGuestWalletsPending, false);
2384
+ return wallets;
2385
+ } catch (e) {
2386
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, null, error == null ? void 0 : error.message);
2387
+ __privateSet(this, _isCreateGuestWalletsPending, false);
2388
+ throw error;
2389
+ }
2390
+ });
2391
+ }
2392
+ encodeWalletBase64(wallet) {
2393
+ const walletJson = JSON.stringify(wallet);
2394
+ const base64Wallet = Buffer.from(walletJson).toString("base64");
2395
+ return base64Wallet;
2396
+ }
2397
+ /**
2398
+ * Encodes the current wallets encoded in Base 64.
2399
+ * @returns {string} the encoded wallet string
2400
+ **/
2401
+ getUserShare() {
2402
+ if (Object.values(this.wallets).length === 0) {
2403
+ return null;
2404
+ }
2405
+ return Object.values(this.wallets).map((wallet) => this.encodeWalletBase64(wallet)).join("-");
2406
+ }
2407
+ /**
2408
+ * Sets the current wallets from a Base 64 string.
2409
+ * @param {string} base64Wallet the encoded wallet string
2410
+ **/
2411
+ setUserShare(base64Wallets) {
2412
+ return __async(this, null, function* () {
2413
+ if (!base64Wallets) {
2414
+ return;
2415
+ }
2416
+ const base64WalletsSplit = base64Wallets.split("-");
2417
+ for (const base64Wallet of base64WalletsSplit) {
2418
+ const walletJson = Buffer.from(base64Wallet, "base64").toString();
2419
+ const wallet = (0, import_utils2.migrateWallet)(JSON.parse(walletJson));
2420
+ this.wallets[wallet.id] = wallet;
2421
+ yield this.setWallets(this.wallets);
2422
+ }
2423
+ });
2424
+ }
2425
+ getTransactionReviewUrl(transactionId, timeoutMs) {
2426
+ return __async(this, null, function* () {
2427
+ return this.constructPortalUrl("txReview", {
2428
+ pathId: transactionId,
2429
+ params: {
2430
+ email: this.email,
2431
+ timeoutMs: timeoutMs == null ? void 0 : timeoutMs.toString()
2432
+ }
2433
+ });
2434
+ });
2435
+ }
2436
+ getOnRampTransactionUrl(_m) {
2437
+ return __async(this, null, function* () {
2438
+ var _n = _m, {
2439
+ purchaseId,
2440
+ providerKey
2441
+ } = _n, walletParams = __objRest(_n, [
2442
+ "purchaseId",
2443
+ "providerKey"
2444
+ ]);
2445
+ const { sessionId } = yield this.touchSession();
2446
+ const [key, identifier] = (0, import_user_management_client.extractWalletRef)(walletParams);
2447
+ return this.constructPortalUrl("onRamp", {
2448
+ pathId: purchaseId,
2449
+ sessionId,
2450
+ params: {
2451
+ [key]: identifier,
2452
+ providerKey,
2453
+ currentWalletIds: JSON.stringify(this.currentWalletIds)
2454
+ }
2455
+ });
2456
+ });
2457
+ }
2458
+ /**
2459
+ * Signs a message using one of the current wallets.
2460
+ *
2461
+ * If you want to sign the keccak256 hash of a message, hash the
2462
+ * message first and then pass in the base64 encoded hash.
2463
+ * @param {Object} opts the options object.
2464
+ * @param {string} opts.walletId the id of the wallet to sign with.
2465
+ * @param {string} opts.messageBase64 the base64 encoding of exact message that should be signed
2466
+ * @param {number} [opts.timeout] optional timeout in milliseconds. If not present, defaults to 30 seconds.
2467
+ * @param {string} [opts.cosmosSignDocBase64] the Cosmos `SignDoc` in base64, if applicable
2468
+ **/
2469
+ signMessage(_0) {
2470
+ return __async(this, arguments, function* ({
2471
+ walletId,
2472
+ messageBase64,
2473
+ timeoutMs = 3e4,
2474
+ cosmosSignDocBase64,
2475
+ isCanceled = () => false,
2476
+ onCancel,
2477
+ onPoll
2478
+ }) {
2479
+ this.assertIsValidWalletId(walletId);
2480
+ const wallet = this.wallets[walletId];
2481
+ let signerId = this.userId;
2482
+ if (wallet.partnerId && !wallet.userId) {
2483
+ signerId = wallet.partnerId;
2484
+ }
2485
+ let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2486
+ let timeStart = Date.now();
2487
+ if (signRes.pendingTransactionId) {
2488
+ this.platformUtils.openPopup(
2489
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2490
+ { type: cosmosSignDocBase64 ? import_types.PopupType.SIGN_TRANSACTION_REVIEW : import_types.PopupType.SIGN_MESSAGE_REVIEW }
2491
+ );
2492
+ } else {
2493
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_MESSAGE_EVENT, signRes);
2494
+ return signRes;
2495
+ }
2496
+ while (true) {
2497
+ if (isCanceled() || Date.now() - timeStart > timeoutMs) {
2498
+ onCancel == null ? void 0 : onCancel();
2499
+ break;
2500
+ }
2501
+ yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2502
+ try {
2503
+ yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2504
+ } catch (err) {
2505
+ const error = new import_errors.TransactionReviewDenied();
2506
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2507
+ throw error;
2508
+ }
2509
+ signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2510
+ if (signRes.pendingTransactionId) {
2511
+ onPoll == null ? void 0 : onPoll();
2512
+ continue;
2513
+ } else {
2514
+ break;
2515
+ }
2516
+ }
2517
+ if (signRes.pendingTransactionId) {
2518
+ const error = new import_errors.TransactionReviewTimeout(
2519
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
2520
+ signRes.pendingTransactionId
2521
+ );
2522
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2523
+ throw error;
2524
+ }
2525
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_MESSAGE_EVENT, signRes);
2526
+ return signRes;
2527
+ });
2528
+ }
2529
+ signMessageInner(_0) {
2530
+ return __async(this, arguments, function* ({
2531
+ wallet,
2532
+ signerId,
2533
+ messageBase64,
2534
+ cosmosSignDocBase64
2535
+ }) {
2536
+ let signRes;
2537
+ switch (wallet.scheme) {
2538
+ case "ED25519":
2539
+ signRes = yield this.platformUtils.ed25519Sign(
2540
+ this.ctx,
2541
+ signerId,
2542
+ wallet.id,
2543
+ wallet.signer,
2544
+ messageBase64,
2545
+ this.retrieveSessionCookie()
2546
+ );
2547
+ break;
2548
+ default:
2549
+ signRes = yield this.platformUtils.signMessage(
2550
+ this.ctx,
2551
+ signerId,
2552
+ wallet.id,
2553
+ wallet.signer,
2554
+ messageBase64,
2555
+ this.retrieveSessionCookie(),
2556
+ wallet.scheme === "DKLS",
2557
+ cosmosSignDocBase64
2558
+ );
2559
+ break;
2560
+ }
2561
+ return signRes;
2562
+ });
2563
+ }
2564
+ /**
2565
+ * Signs a transaction.
2566
+ * @param {Object} opts the options object.
2567
+ * @param {string} opts.walletId the id of the wallet to sign with.
2568
+ * @param {string} opts.rlpEncodedTxBase64 the transaction to sign, in RLP base64 encoding
2569
+ * @param {string} [opts.chainId] the EVM chain id of the chain the transaction is being sent on, if applicable
2570
+ * @param {number} [opts.timeoutMs] the amount of time to wait for the user to sign the transaction, in milliseconds
2571
+ **/
2572
+ signTransaction(_0) {
2573
+ return __async(this, arguments, function* ({
2574
+ walletId,
2575
+ rlpEncodedTxBase64,
2576
+ chainId,
2577
+ timeoutMs = 3e4,
2578
+ isCanceled = () => false,
2579
+ onCancel,
2580
+ onPoll
2581
+ }) {
2582
+ this.assertIsValidWalletId(walletId);
2583
+ const wallet = this.wallets[walletId];
2584
+ let signerId = this.userId;
2585
+ if (wallet.partnerId && !wallet.userId) {
2586
+ signerId = wallet.partnerId;
2587
+ }
2588
+ let signRes = yield this.platformUtils.signTransaction(
2589
+ this.ctx,
2590
+ signerId,
2591
+ walletId,
2592
+ this.wallets[walletId].signer,
2593
+ rlpEncodedTxBase64,
2594
+ chainId,
2595
+ this.retrieveSessionCookie(),
2596
+ wallet.scheme === "DKLS"
2597
+ );
2598
+ let timeStart = Date.now();
2599
+ if (signRes.pendingTransactionId) {
2600
+ this.platformUtils.openPopup(
2601
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2602
+ { type: import_types.PopupType.SIGN_TRANSACTION_REVIEW }
2603
+ );
2604
+ } else {
2605
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
2606
+ return signRes;
2607
+ }
2608
+ while (true) {
2609
+ if (isCanceled() || Date.now() - timeStart > timeoutMs) {
2610
+ onCancel == null ? void 0 : onCancel();
2611
+ break;
2612
+ }
2613
+ yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2614
+ try {
2615
+ yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2616
+ } catch (err) {
2617
+ const error = new import_errors.TransactionReviewDenied();
2618
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2619
+ throw error;
2620
+ }
2621
+ signRes = yield this.platformUtils.signTransaction(
2622
+ this.ctx,
2623
+ signerId,
2624
+ walletId,
2625
+ this.wallets[walletId].signer,
2626
+ rlpEncodedTxBase64,
2627
+ chainId,
2628
+ this.retrieveSessionCookie(),
2629
+ wallet.scheme === "DKLS"
2630
+ );
2631
+ if (signRes.pendingTransactionId) {
2632
+ onPoll == null ? void 0 : onPoll();
2633
+ continue;
2634
+ } else {
2635
+ break;
2636
+ }
2637
+ }
2638
+ if (signRes.pendingTransactionId) {
2639
+ const error = new import_errors.TransactionReviewTimeout(
2640
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
2641
+ signRes.pendingTransactionId
2642
+ );
2643
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2644
+ throw error;
2645
+ }
2646
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
2647
+ return signRes;
2648
+ });
2649
+ }
2650
+ isProviderModalDisabled() {
2651
+ return !!this.disableProviderModal;
2652
+ }
2653
+ /**
2654
+ * Starts a on-ramp or off-ramp transaction and returns the Para Portal link for the user to finalize and complete it.
2655
+ * @param {Object} opts the options object
2656
+ * @param {OnRampPurchaseCreateParams} opts.params the transaction settings.
2657
+ * @param {boolean} opts.shouldOpenPopup if `true`, a popup window with the link will be opened.
2658
+ * @param {string} opts.walletId the wallet ID to use for the transaction, where funds will be sent or withdrawn.
2659
+ * @param {string} opts.externalWalletAddress the external wallet address to send funds to or withdraw funds from, if using an external wallet.
2660
+ **/
2661
+ initiateOnRampTransaction(options) {
2662
+ return __async(this, null, function* () {
2663
+ var _b;
2664
+ const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
2665
+ const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
2666
+ userId: this.userId,
2667
+ params: __spreadProps(__spreadValues({}, params), {
2668
+ address: (_b = walletParams.externalWalletAddress) != null ? _b : this.getDisplayAddress(walletParams.walletId, { addressType: params.walletType })
2669
+ })
2670
+ }, walletParams));
2671
+ const portalUrl = yield this.getOnRampTransactionUrl(__spreadValues({
2672
+ purchaseId: onRampPurchase.id,
2673
+ providerKey: onRampPurchase.providerKey
2674
+ }, walletParams));
2675
+ if (shouldOpenPopup) {
2676
+ this.platformUtils.openPopup(portalUrl, { type: import_types.PopupType.ON_RAMP_TRANSACTION });
2677
+ }
2678
+ return { onRampPurchase, portalUrl };
2679
+ });
2680
+ }
2681
+ /**
2682
+ * Returns `true` if session was successfully kept alive, `false` otherwise.
2683
+ **/
2684
+ keepSessionAlive() {
2685
+ return __async(this, null, function* () {
2686
+ try {
2687
+ yield this.ctx.client.keepSessionAlive(this.userId);
2688
+ return true;
2689
+ } catch (err) {
2690
+ return false;
2691
+ }
2692
+ });
2693
+ }
2694
+ /**
2695
+ * Serialize the current session for import by another Para instance.
2696
+ * @param {boolean} excludeSigners - whether or not to exclude the signer from the exported wallets.
2697
+ * @returns {string} the serialized session
2698
+ */
2699
+ exportSession({ excludeSigners = false } = {}) {
2700
+ const sessionInfo = {
2701
+ authInfo: __privateGet(this, _authInfo),
2702
+ userId: this.userId,
2703
+ wallets: structuredClone(this.wallets),
2704
+ currentWalletIds: this.currentWalletIds,
2705
+ sessionCookie: this.retrieveSessionCookie(),
2706
+ externalWallets: this.externalWallets
2707
+ };
2708
+ if (excludeSigners) {
2709
+ for (const wallet of Object.values(sessionInfo.wallets)) {
2710
+ delete wallet.signer;
2711
+ }
2712
+ }
2713
+ return Buffer.from(JSON.stringify(sessionInfo)).toString("base64");
2714
+ }
2715
+ /**
2716
+ * Imports a session serialized by another Para instance.
2717
+ * @param {string} serializedInstanceBase64 the serialized session
2718
+ */
2719
+ importSession(serializedInstanceBase64) {
2720
+ return __async(this, null, function* () {
2721
+ var _a, _b;
2722
+ const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
2723
+ const sessionInfo = (0, import_utils2.jsonParse)(serializedInstance);
2724
+ const authInfo = (_a = sessionInfo.authInfo) != null ? _a : __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, sessionInfo);
2725
+ yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
2726
+ yield this.setUserId(sessionInfo.userId);
2727
+ yield this.setWallets(sessionInfo.wallets);
2728
+ yield this.setExternalWallets(sessionInfo.externalWallets || {});
2729
+ for (const walletId of Object.keys(this.wallets)) {
2730
+ if (!this.wallets[walletId].userId) {
2731
+ this.wallets[walletId].userId = this.userId;
2732
+ }
2733
+ }
2734
+ if (Object.keys(sessionInfo.currentWalletIds).length !== 0) {
2735
+ yield this.setCurrentWalletIds(sessionInfo.currentWalletIds);
2736
+ } else {
2737
+ const currentWalletIds = {};
2738
+ for (const walletId of Object.keys(sessionInfo.wallets)) {
2739
+ currentWalletIds[sessionInfo.wallets[walletId].type] = [
2740
+ ...(_b = currentWalletIds[sessionInfo.wallets[walletId].type]) != null ? _b : [],
2741
+ walletId
2742
+ ];
2743
+ }
2744
+ yield this.setCurrentWalletIds(currentWalletIds);
2745
+ }
2746
+ this.persistSessionCookie(sessionInfo.sessionCookie);
2747
+ });
2748
+ }
2749
+ /**
2750
+ * Retrieves a token to verify the current session.
2751
+ * @returns {Promise<string>} the ID
2752
+ **/
2753
+ getVerificationToken() {
2754
+ return __async(this, null, function* () {
2755
+ const { sessionLookupId } = yield this.touchSession();
2756
+ return sessionLookupId;
2757
+ });
2758
+ }
2759
+ issueJwt() {
2760
+ return __async(this, arguments, function* ({ keyIndex = 0 } = {}) {
2761
+ const res = yield this.ctx.client.issueJwt({ keyIndex });
2762
+ return res;
2763
+ });
2764
+ }
2765
+ /**
2766
+ * Logs the user out.
2767
+ * @param {Object} opts the options object.
2768
+ * @param {boolean} opts.clearPregenWallets if `true`, will remove all pregen wallets from storage
2769
+ **/
2770
+ logout() {
2771
+ return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
2772
+ yield this.ctx.client.logout();
2773
+ yield this.clearStorage();
2774
+ if (!clearPregenWallets) {
2775
+ Object.entries(this.wallets).forEach(([id, wallet]) => {
2776
+ if (!wallet.pregenIdentifier) {
2777
+ delete this.wallets[id];
2778
+ }
2779
+ });
2780
+ yield this.setWallets(this.wallets);
2781
+ } else {
2782
+ this.wallets = {};
2783
+ }
2784
+ this.currentWalletIds = {};
2785
+ this.externalWallets = {};
2786
+ this.loginEncryptionKeyPair = void 0;
2787
+ __privateSet(this, _authInfo, void 0);
2788
+ this.accountLinkInProgress = void 0;
2789
+ this.userId = void 0;
2790
+ this.sessionCookie = void 0;
2791
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGOUT_EVENT, null);
2792
+ });
2793
+ }
2794
+ get toStringAdditions() {
2795
+ return {};
2796
+ }
2797
+ /**
2798
+ * Converts to a string, removing sensitive data when logging this class.
2799
+ *
2800
+ * Doesn't work for all types of logging.
2801
+ **/
2802
+ toString() {
2803
+ var _a, _b, _c;
2804
+ const redactedWallets = Object.keys(this.wallets).reduce(
2805
+ (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
2806
+ [walletId]: __spreadProps(__spreadValues({}, this.wallets[walletId]), {
2807
+ signer: this.wallets[walletId].signer ? "[REDACTED]" : void 0
2808
+ })
2809
+ }),
2810
+ {}
2811
+ );
2812
+ const redactedExternalWallets = Object.keys(this.externalWallets).reduce(
2813
+ (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
2814
+ [walletId]: __spreadProps(__spreadValues({}, this.externalWallets[walletId]), {
2815
+ signer: this.externalWallets[walletId].signer ? "[REDACTED]" : void 0
2816
+ })
2817
+ }),
2818
+ {}
2819
+ );
2820
+ const obj = __spreadProps(__spreadValues({
2821
+ partnerId: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id,
2822
+ supportedWalletTypes: (_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes,
2823
+ cosmosPrefix: (_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix,
2824
+ authInfo: __privateGet(this, _authInfo),
2825
+ isGuestMode: this.isGuestMode,
2826
+ userId: this.userId,
2827
+ pregenIds: this.pregenIds,
2828
+ currentWalletIds: this.currentWalletIds,
2829
+ guestWalletIds: __privateGet(this, _ParaCore_instances, guestWalletIds_get),
2830
+ wallets: redactedWallets,
2831
+ externalWallets: redactedExternalWallets,
2832
+ loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
2833
+ isReady: this.isReady
2834
+ }, this.toStringAdditions), {
2835
+ ctx: {
2836
+ apiKey: this.ctx.apiKey,
2837
+ disableWorkers: this.ctx.disableWorkers,
2838
+ disableWebSockets: this.ctx.disableWebSockets,
2839
+ env: this.ctx.env,
2840
+ offloadMPCComputationURL: this.ctx.offloadMPCComputationURL,
2841
+ useLocalFiles: this.ctx.useLocalFiles,
2842
+ useDKLS: this.ctx.useDKLS,
2843
+ cosmosPrefix: this.ctx.cosmosPrefix
2844
+ }
2845
+ });
2846
+ return `Para ${JSON.stringify(obj, null, 2)}`;
2847
+ }
2848
+ devLog(...s) {
2849
+ if (this.ctx.env === import_types.Environment.DEV || this.ctx.env === import_types.Environment.SANDBOX) {
2850
+ console.log(...s);
2851
+ }
2852
+ }
2853
+ getNewCredentialAndUrl() {
2854
+ return __async(this, arguments, function* ({
2855
+ authMethod = "PASSKEY",
2856
+ isForNewDevice = false,
2857
+ portalTheme,
2858
+ shorten = false
2859
+ } = {}) {
2860
+ this.assertIsAuthSet();
2861
+ let credentialId, urlType;
2862
+ switch (authMethod) {
2863
+ case "PASSKEY":
2864
+ ({
2865
+ data: { id: credentialId }
2866
+ } = yield this.ctx.client.addSessionPublicKey(this.userId, {
2867
+ status: import_user_management_client.PublicKeyStatus.PENDING,
2868
+ type: import_user_management_client.PublicKeyType.WEB
2869
+ }));
2870
+ urlType = "createAuth";
2871
+ break;
2872
+ case "PASSWORD":
2873
+ ({
2874
+ data: { id: credentialId }
2875
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2876
+ status: import_user_management_client.PasswordStatus.PENDING
2877
+ }));
2878
+ urlType = "createPassword";
2879
+ break;
2880
+ }
2881
+ const url = this.isNativePasskey && urlType === "createAuth" ? void 0 : yield this.constructPortalUrl(urlType, {
2882
+ isForNewDevice,
2883
+ pathId: credentialId,
2884
+ portalTheme,
2885
+ shorten
2886
+ });
2887
+ return __spreadValues({ credentialId }, url ? { url } : {});
2888
+ });
2889
+ }
2890
+ /**
2891
+ * Returns a Para Portal URL for logging in with a WebAuth passkey or a password.
2892
+ * @param {Object} opts the options object
2893
+ * @param {String} opts.auth - the user auth to sign up or log in with, in the form ` { email: string } | { phone: `+${number}` } `
2894
+ * @param {boolean} opts.useShortUrls - whether to shorten the generated portal URLs
2895
+ * @param {Theme} opts.portalTheme the Para Portal theme to apply to the password creation URL, if other than the default theme
2896
+ * @returns {SignUpOrLogInResponse} an object in the form of either: `{ stage: 'verify' }` or `{ stage: 'login'; passkeyUrl?: string; passwordUrl?: string; biometricHints?: BiometricLocationHint[] }`
2897
+ */
2898
+ getLoginUrl(_0) {
2899
+ return __async(this, arguments, function* ({
2900
+ authMethod = "PASSKEY",
2901
+ shorten = false,
2902
+ portalTheme,
2903
+ sessionId
2904
+ }) {
2905
+ if (!sessionId) {
2906
+ sessionId = (yield this.touchSession()).sessionLookupId;
2907
+ }
2908
+ this.assertIsAuthSet();
2909
+ let urlType;
2910
+ switch (authMethod) {
2911
+ case "PASSKEY":
2912
+ urlType = "loginAuth";
2913
+ break;
2914
+ case "PASSWORD":
2915
+ urlType = "loginPassword";
2916
+ break;
2917
+ default:
2918
+ throw new Error(`invalid authentication method: '${authMethod}'`);
2919
+ }
2920
+ return this.constructPortalUrl(urlType, {
2921
+ sessionId,
2922
+ shorten,
2923
+ portalTheme
2924
+ });
2925
+ });
2926
+ }
2927
+ signUpOrLogIn(_o) {
2928
+ return __async(this, null, function* () {
2929
+ var _p = _o, { auth } = _p, urlOptions = __objRest(_p, ["auth"]);
2930
+ const serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
2931
+ const authInfo = serverAuthState.auth;
2932
+ if (this.fetchPregenWalletsOverride && (0, import_user_management_client.isPregenAuth)(authInfo)) {
2933
+ const { userShare } = yield this.fetchPregenWalletsOverride({ pregenId: authInfo });
2934
+ if (userShare) {
2935
+ yield this.setUserShare(userShare);
2936
+ }
2937
+ }
2938
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2939
+ });
2940
+ }
2941
+ verifyNewAccount(_q) {
2942
+ return __async(this, null, function* () {
2943
+ var _r = _q, {
2944
+ verificationCode
2945
+ } = _r, urlOptions = __objRest(_r, [
2946
+ "verificationCode"
2947
+ ]);
2948
+ this.assertIsAuthSet(["email", "phone"]);
2949
+ const userId = this.assertUserId();
2950
+ const serverAuthState = yield this.ctx.client.verifyNewAccount(userId, {
2951
+ verificationCode
2952
+ });
2953
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2954
+ });
2955
+ }
2956
+ getLinkedAccounts() {
2957
+ return __async(this, arguments, function* ({
2958
+ withMetadata = false
2959
+ } = {}) {
2960
+ const userId = this.assertUserId();
2961
+ const { accounts } = yield this.ctx.client.getLinkedAccounts({ userId, withMetadata });
2962
+ return __spreadValues({
2963
+ userId
2964
+ }, accounts);
2965
+ });
2966
+ }
2967
+ linkAccount(opts) {
2968
+ return __async(this, null, function* () {
2969
+ const { supportedAccountLinks = [...import_user_management_client.LINKED_ACCOUNT_TYPES] } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2970
+ let type, identifier, externalWallet, isPermitted;
2971
+ switch (true) {
2972
+ case "auth" in opts:
2973
+ {
2974
+ const authInfo = (0, import_user_management_client.extractAuthInfo)(opts.auth, { isRequired: true });
2975
+ if (authInfo.auth === this.authInfo.auth) {
2976
+ throw new Error(import_types.AccountLinkError.Conflict);
2977
+ }
2978
+ type = authInfo.authType.toUpperCase();
2979
+ identifier = authInfo.identifier;
2980
+ isPermitted = supportedAccountLinks.includes(type);
2981
+ }
2982
+ break;
2983
+ case "externalWallet" in opts:
2984
+ {
2985
+ externalWallet = opts.externalWallet;
2986
+ type = "EXTERNAL_WALLET";
2987
+ isPermitted = supportedAccountLinks.includes("EXTERNAL_WALLET") || supportedAccountLinks.includes(externalWallet.providerId);
2988
+ }
2989
+ break;
2990
+ case "type" in opts:
2991
+ {
2992
+ type = opts.type;
2993
+ if (type === "X") {
2994
+ type = "TWITTER";
2995
+ }
2996
+ isPermitted = supportedAccountLinks.includes(type);
2997
+ }
2998
+ break;
2999
+ default:
3000
+ throw new Error("Invalid parameters for linking account, must pass `auth` or `type` or `externalWallet");
3001
+ }
3002
+ if (!isPermitted) {
3003
+ throw new Error(`Account linking for type '${type}' is not supported by the current API key configuration`);
3004
+ }
3005
+ const userId = this.assertUserId();
3006
+ const result = yield this.ctx.client.linkAccount(__spreadValues(__spreadValues({
3007
+ userId,
3008
+ type
3009
+ }, identifier ? { identifier } : {}), externalWallet ? { externalWallet } : {}));
3010
+ if ("isConflict" in result) {
3011
+ throw new Error(import_types.AccountLinkError.Conflict);
3012
+ }
3013
+ const { linkedAccountId, signatureVerificationMessage } = result;
3014
+ this.accountLinkInProgress = __spreadValues(__spreadValues({
3015
+ id: linkedAccountId,
3016
+ type,
3017
+ isComplete: false
3018
+ }, identifier ? { identifier } : {}), signatureVerificationMessage && externalWallet ? {
3019
+ externalWallet: __spreadProps(__spreadValues({}, externalWallet), {
3020
+ signatureVerificationMessage
3021
+ })
3022
+ } : {});
3023
+ return this.accountLinkInProgress;
3024
+ });
3025
+ }
3026
+ unlinkAccount(_0) {
3027
+ return __async(this, arguments, function* ({
3028
+ linkedAccountId
3029
+ }) {
3030
+ if (!linkedAccountId) {
3031
+ throw new Error("No linked account ID provided");
3032
+ }
3033
+ const userId = this.assertUserId();
3034
+ const accounts = yield this.ctx.client.unlinkAccount({ linkedAccountId, userId });
3035
+ return accounts;
3036
+ });
3037
+ }
3038
+ verifyLink() {
3039
+ return __async(this, arguments, function* (_s = {}) {
3040
+ var _t = _s, {
3041
+ accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3042
+ } = _t, opts = __objRest(_t, [
3043
+ "accountLinkInProgress"
3044
+ ]);
3045
+ try {
3046
+ const userId = this.assertUserId(), result = yield this.ctx.client.verifyLink(__spreadValues({
3047
+ linkedAccountId: accountLinkInProgress.id,
3048
+ userId
3049
+ }, opts));
3050
+ if ("isConflict" in result) {
3051
+ throw new Error(import_types.AccountLinkError.Conflict);
3052
+ }
3053
+ this.accountLinkInProgress = void 0;
3054
+ return result.accounts;
3055
+ } catch (e) {
3056
+ throw new Error(e.message === import_types.AccountLinkError.Conflict ? import_types.AccountLinkError.Conflict : e.message);
3057
+ }
3058
+ });
3059
+ }
3060
+ verifyEmailOrPhoneLink(_0) {
3061
+ return __async(this, arguments, function* ({
3062
+ verificationCode
3063
+ }) {
3064
+ const accounts = yield this.verifyLink({
3065
+ accountLinkInProgress: __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]),
3066
+ verificationCode
3067
+ });
3068
+ return accounts;
3069
+ });
3070
+ }
3071
+ };
3072
+ _authInfo = new WeakMap();
3073
+ _partner = new WeakMap();
3074
+ _ParaCore_instances = new WeakSet();
3075
+ assertPartner_fn = function() {
3076
+ return __async(this, null, function* () {
3077
+ var _a, _b;
3078
+ if (!__privateGet(this, _partner)) {
3079
+ yield this.touchSession();
3080
+ }
3081
+ if (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== __privateGet(this, _partner).cosmosPrefix) {
3082
+ this.ctx.cosmosPrefix = (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix;
3083
+ }
3084
+ return __privateGet(this, _partner);
3085
+ });
3086
+ };
3087
+ guestWalletIds_get = function() {
3088
+ var _a, _b, _c;
3089
+ if (!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes)) {
3090
+ return {};
3091
+ }
3092
+ const guestId = (_c = (_b = this.pregenIds) == null ? void 0 : _b.GUEST_ID) == null ? void 0 : _c[0];
3093
+ return !!guestId ? Object.entries(this.wallets).reduce((acc, [id, wallet]) => {
3094
+ if (wallet.isPregen && !wallet.userId && wallet.pregenIdentifierType === "GUEST_ID" && wallet.pregenIdentifier === guestId) {
3095
+ return __spreadValues(__spreadValues({}, acc), (0, import_utils2.getEquivalentTypes)(wallet.type).filter((type) => __privateGet(this, _partner).supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
3096
+ var _a2;
3097
+ return __spreadProps(__spreadValues({}, acc2), { [eqType]: [.../* @__PURE__ */ new Set([...(_a2 = acc2[eqType]) != null ? _a2 : [], id])] });
3098
+ }, {}));
3099
+ }
3100
+ return acc;
3101
+ }, {}) : {};
3102
+ };
3103
+ guestWalletIdsArray_get = function() {
3104
+ return Object.entries(__privateGet(this, _ParaCore_instances, guestWalletIds_get)).reduce((acc, [type, ids]) => {
3105
+ return [...acc, ...ids.map((id) => [id, type])];
3106
+ }, []);
3107
+ };
3108
+ toAuthInfo_fn = function({
3109
+ email,
3110
+ phone,
3111
+ countryCode,
3112
+ farcasterUsername,
3113
+ telegramUserId,
3114
+ externalWalletAddress
3115
+ }) {
3116
+ let auth;
3117
+ switch (true) {
3118
+ case !!email:
3119
+ auth = { email };
3120
+ break;
3121
+ case !!phone:
3122
+ {
3123
+ const validPhone = (0, import_utils2.formatPhoneNumber)(phone, countryCode);
3124
+ if (validPhone) auth = { phone: (0, import_utils2.formatPhoneNumber)(phone, countryCode) };
3125
+ }
3126
+ break;
3127
+ case !!farcasterUsername:
3128
+ auth = { farcasterUsername };
3129
+ break;
3130
+ case !!telegramUserId:
3131
+ auth = { telegramUserId };
3132
+ break;
3133
+ case !!externalWalletAddress:
3134
+ auth = { externalWalletAddress };
3135
+ break;
3136
+ }
3137
+ return (0, import_user_management_client.extractAuthInfo)(auth);
3138
+ };
3139
+ setAuthInfo_fn = function(authInfo) {
3140
+ return __async(this, null, function* () {
3141
+ __privateSet(this, _authInfo, authInfo);
3142
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_AUTH_INFO, JSON.stringify(authInfo));
3143
+ yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_EMAIL);
3144
+ yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_PHONE);
3145
+ yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_COUNTRY_CODE);
3146
+ yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_FARCASTER_USERNAME);
3147
+ yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_TELEGRAM_USER_ID);
3148
+ });
3149
+ };
3150
+ getPartner_fn = function(partnerId) {
3151
+ return __async(this, null, function* () {
3152
+ if (this.isPartnerOptional && !partnerId) {
3153
+ return void 0;
3154
+ }
3155
+ const res = yield this.ctx.client.getPartner(partnerId);
3156
+ __privateSet(this, _partner, res.data.partner);
3157
+ return __privateGet(this, _partner);
3158
+ });
3159
+ };
3160
+ assertIsLinkingAccount_fn = function(types) {
3161
+ if (!this.accountLinkInProgress || this.accountLinkInProgress.isComplete) {
3162
+ throw new Error("no account linking in progress");
3163
+ }
3164
+ if (types && !types.includes(this.accountLinkInProgress.type)) {
3165
+ throw new Error(
3166
+ `account linking in progress for type ${this.accountLinkInProgress.type}, expected one of ${types.join(", ")}`
3167
+ );
3168
+ }
3169
+ return this.accountLinkInProgress;
3170
+ };
3171
+ assertIsLinkingAccountOrStart_fn = function(type) {
3172
+ return __async(this, null, function* () {
3173
+ if (this.accountLinkInProgress && !this.accountLinkInProgress.isComplete) {
3174
+ return __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, [type]);
3175
+ }
3176
+ return yield this.linkAccount({ type });
3177
+ });
3178
+ };
3179
+ getOAuthUrl_fn = function(_i) {
3180
+ return __async(this, null, function* () {
3181
+ var _j = _i, {
3182
+ method,
3183
+ appScheme,
3184
+ accountLinkInProgress
3185
+ } = _j, params = __objRest(_j, [
3186
+ "method",
3187
+ "appScheme",
3188
+ "accountLinkInProgress"
3189
+ ]);
3190
+ var _a;
3191
+ const sessionLookupId = (_a = params.sessionLookupId) != null ? _a : yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3192
+ return (0, import_utils2.constructUrl)({
3193
+ base: (0, import_userManagementClient.getBaseOAuthUrl)(this.ctx.env),
3194
+ path: `/auth/${method}`,
3195
+ params: __spreadValues({
3196
+ apiKey: this.ctx.apiKey,
3197
+ sessionLookupId,
3198
+ appScheme
3199
+ }, accountLinkInProgress ? {
3200
+ linkedAccountId: this.accountLinkInProgress.id
3201
+ } : {})
3202
+ });
3203
+ });
3204
+ };
3205
+ createPregenWallet_fn = function(opts) {
3206
+ return __async(this, null, function* () {
3207
+ var _a, _b;
3208
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3209
+ const { type: _type = (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type, pregenId } = opts;
3210
+ this.requireApiKey();
3211
+ const walletType = yield this.assertIsValidWalletType(
3212
+ _type != null ? _type : (_b = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
3213
+ );
3214
+ const [pregenIdentifierType, pregenIdentifier] = (0, import_user_management_client.toPregenTypeAndId)(pregenId);
3215
+ let keygenRes;
3216
+ switch (walletType) {
3217
+ case "SOLANA":
3218
+ keygenRes = yield this.platformUtils.ed25519PreKeygen(
3219
+ this.ctx,
3220
+ pregenIdentifier,
3221
+ pregenIdentifierType,
3222
+ this.retrieveSessionCookie()
3223
+ );
3224
+ break;
3225
+ default:
3226
+ keygenRes = yield this.platformUtils.preKeygen(
3227
+ this.ctx,
3228
+ void 0,
3229
+ pregenIdentifier,
3230
+ pregenIdentifierType,
3231
+ walletType,
3232
+ null,
3233
+ this.retrieveSessionCookie()
3234
+ );
3235
+ break;
3236
+ }
3237
+ const { signer, walletId } = keygenRes;
3238
+ this.wallets[walletId] = {
3239
+ id: walletId,
3240
+ signer,
3241
+ scheme: walletType === "SOLANA" ? "ED25519" : "DKLS",
3242
+ type: walletType,
3243
+ isPregen: true,
3244
+ pregenIdentifier,
3245
+ pregenIdentifierType
3246
+ };
3247
+ yield this.waitForPregenWalletAddress(walletId);
3248
+ yield this.populatePregenWalletAddresses();
3249
+ return this.wallets[walletId];
3250
+ });
3251
+ };
3252
+ _isCreateGuestWalletsPending = new WeakMap();
3253
+ prepareAuthState_fn = function(_0) {
3254
+ return __async(this, arguments, function* (serverAuthState, opts = {}) {
3255
+ if (!opts.sessionLookupId && serverAuthState.stage === "login") {
3256
+ opts.sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3257
+ }
3258
+ const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
3259
+ const authInfo = __spreadValues(__spreadValues({}, (0, import_user_management_client.extractAuthInfo)(auth, { isRequired: true })), Object.fromEntries(
3260
+ Object.entries({
3261
+ displayName,
3262
+ pfpUrl,
3263
+ username,
3264
+ externalWallet
3265
+ }).filter(([_, v]) => !!v)
3266
+ ));
3267
+ yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
3268
+ yield this.assertIsAuthSet();
3269
+ if (!!externalWallet) {
3270
+ yield this.setExternalWallet([externalWallet]);
3271
+ }
3272
+ if (!!userId) {
3273
+ yield this.setUserId(userId);
3274
+ }
3275
+ let authState;
3276
+ switch (serverAuthState.stage) {
3277
+ case "verify":
3278
+ authState = serverAuthState;
3279
+ break;
3280
+ case "login":
3281
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3282
+ authState = serverAuthState;
3283
+ break;
3284
+ }
3285
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), { sessionLookupId: opts.sessionLookupId }));
3286
+ break;
3287
+ case "signup":
3288
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3289
+ authState = serverAuthState;
3290
+ break;
3291
+ }
3292
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareSignUpState_fn).call(this, serverAuthState, opts);
3293
+ break;
3294
+ }
3295
+ return authState;
3296
+ });
3297
+ };
3298
+ prepareLogin_fn = function() {
3299
+ return __async(this, null, function* () {
3300
+ yield this.logout();
3301
+ const { sessionLookupId } = yield this.touchSession(true);
3302
+ if (!this.loginEncryptionKeyPair) {
3303
+ yield this.setLoginEncryptionKeyPair();
3304
+ }
3305
+ return sessionLookupId;
3306
+ });
3307
+ };
3308
+ prepareLoginState_fn = function(_0, _1) {
3309
+ return __async(this, arguments, function* (loginState, {
3310
+ useShortUrls: shorten = false,
3311
+ portalTheme,
3312
+ sessionLookupId
3313
+ }) {
3314
+ const _a = loginState, { loginAuthMethods } = _a, authState = __objRest(_a, ["loginAuthMethods"]);
3315
+ const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD);
3316
+ return __spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
3317
+ isPasskeySupported
3318
+ }), isPasskeyPossible ? {
3319
+ passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
3320
+ passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
3321
+ sessionId: sessionLookupId,
3322
+ newDevice: {
3323
+ sessionId: sessionLookupId,
3324
+ encryptionKey: (0, import_utils.getPublicKeyHex)(this.loginEncryptionKeyPair)
3325
+ },
3326
+ shorten,
3327
+ portalTheme
3328
+ })
3329
+ } : {}), isPasswordPossible ? {
3330
+ passwordUrl: yield this.constructPortalUrl("loginPassword", {
3331
+ sessionId: sessionLookupId,
3332
+ shorten,
3333
+ portalTheme,
3334
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
3335
+ })
3336
+ } : {});
3337
+ });
3338
+ };
3339
+ prepareSignUpState_fn = function(_0, _1) {
3340
+ return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
3341
+ const _a = serverSignupState, { signupAuthMethods } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
3342
+ const isPasskeySupported = yield this.isPasskeySupported();
3343
+ const [isPasskey, isPassword] = [
3344
+ signupAuthMethods.includes(import_user_management_client.AuthMethod.PASSKEY),
3345
+ signupAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD) || !isPasskeySupported
3346
+ ];
3347
+ if (!isPasskey && !isPassword) {
3348
+ throw new Error(
3349
+ "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys or passwords in your Developer Portal settings."
3350
+ );
3351
+ }
3352
+ const signupState = __spreadProps(__spreadValues({}, authState), { isPasskeySupported });
3353
+ if (isPasskey) {
3354
+ const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
3355
+ authMethod: "PASSKEY",
3356
+ shorten
3357
+ });
3358
+ if (passkeyUrl) signupState.passkeyUrl = passkeyUrl;
3359
+ signupState.passkeyId = passkeyId;
3360
+ }
3361
+ if (isPassword) {
3362
+ const { url: passwordUrl, credentialId: passwordId } = yield this.getNewCredentialAndUrl({
3363
+ authMethod: "PASSWORD",
3364
+ portalTheme,
3365
+ shorten
3366
+ });
3367
+ signupState.passwordUrl = passwordUrl;
3368
+ signupState.passwordId = passwordId;
3369
+ }
3370
+ return signupState;
3371
+ });
3372
+ };
3373
+ _ParaCore.version = constants.PARA_CORE_VERSION;
3374
+ let ParaCore = _ParaCore;
3375
+ // Annotate the CommonJS export names for ESM import in node:
3376
+ 0 && (module.exports = {
3377
+ ParaCore
3378
+ });