@getpara/core-sdk 1.8.0 → 2.0.0-alpha.3

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