@getpara/core-sdk 1.7.1 → 1.9.0

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