@getpara/core-sdk 1.7.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/cjs/ParaCore.js +2964 -0
  2. package/dist/cjs/PlatformUtils.js +15 -0
  3. package/dist/cjs/StorageUtils.js +15 -0
  4. package/dist/cjs/constants.js +75 -0
  5. package/dist/cjs/cryptography/utils.js +350 -0
  6. package/dist/cjs/errors.js +51 -0
  7. package/dist/cjs/external/mpcComputationClient.js +62 -0
  8. package/dist/cjs/external/userManagementClient.js +106 -0
  9. package/dist/cjs/index.js +75 -4008
  10. package/dist/cjs/shares/KeyContainer.js +89 -0
  11. package/dist/cjs/shares/recovery.js +127 -0
  12. package/dist/cjs/shares/shareDistribution.js +104 -0
  13. package/dist/cjs/transmission/transmissionUtils.js +93 -0
  14. package/dist/cjs/types/config.js +43 -0
  15. package/dist/cjs/types/events.js +40 -0
  16. package/dist/cjs/types/index.js +50 -0
  17. package/dist/cjs/types/onRamps.js +33 -0
  18. package/dist/cjs/types/params.js +15 -0
  19. package/dist/cjs/types/popup.js +35 -0
  20. package/dist/cjs/types/recovery.js +34 -0
  21. package/dist/cjs/types/theme.js +15 -0
  22. package/dist/cjs/types/wallet.js +31 -0
  23. package/dist/cjs/utils/events.js +45 -0
  24. package/dist/cjs/utils/formatting.js +120 -0
  25. package/dist/cjs/utils/index.js +31 -0
  26. package/dist/cjs/utils/listeners.js +80 -0
  27. package/dist/cjs/utils/onRamps.js +64 -0
  28. package/dist/cjs/utils/polling.js +58 -0
  29. package/dist/cjs/utils/url.js +103 -0
  30. package/dist/cjs/utils/wallet.js +130 -0
  31. package/dist/esm/ParaCore.js +2913 -0
  32. package/dist/esm/PlatformUtils.js +0 -0
  33. package/dist/esm/StorageUtils.js +0 -0
  34. package/dist/esm/chunk-UICEQADR.js +68 -0
  35. package/dist/esm/constants.js +37 -0
  36. package/dist/esm/cryptography/utils.js +282 -0
  37. package/dist/esm/errors.js +27 -0
  38. package/dist/esm/external/mpcComputationClient.js +30 -0
  39. package/dist/esm/external/userManagementClient.js +71 -0
  40. package/dist/esm/index.js +54 -3968
  41. package/dist/esm/shares/KeyContainer.js +57 -0
  42. package/dist/esm/shares/recovery.js +74 -0
  43. package/dist/esm/shares/shareDistribution.js +64 -0
  44. package/dist/esm/transmission/transmissionUtils.js +42 -0
  45. package/dist/esm/types/config.js +20 -0
  46. package/dist/esm/types/events.js +18 -0
  47. package/dist/esm/types/index.js +21 -0
  48. package/dist/esm/types/onRamps.js +11 -0
  49. package/dist/esm/types/params.js +0 -0
  50. package/dist/esm/types/popup.js +13 -0
  51. package/dist/esm/types/recovery.js +12 -0
  52. package/dist/esm/types/theme.js +0 -0
  53. package/dist/esm/types/wallet.js +9 -0
  54. package/dist/esm/utils/events.js +11 -0
  55. package/dist/esm/utils/formatting.js +80 -0
  56. package/dist/esm/utils/index.js +6 -0
  57. package/dist/esm/utils/listeners.js +47 -0
  58. package/dist/esm/utils/onRamps.js +40 -0
  59. package/dist/esm/utils/polling.js +18 -0
  60. package/dist/esm/utils/url.js +77 -0
  61. package/dist/esm/utils/wallet.js +87 -0
  62. package/dist/types/ParaCore.d.ts +2 -1
  63. package/dist/types/index.d.ts +1 -1
  64. package/dist/types/types/params.d.ts +4 -0
  65. package/package.json +5 -5
  66. package/dist/cjs/index.js.br +0 -0
  67. package/dist/cjs/index.js.gz +0 -0
  68. package/dist/esm/index.js.br +0 -0
  69. package/dist/esm/index.js.gz +0 -0
package/dist/esm/index.js CHANGED
@@ -1,3984 +1,80 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __typeError = (msg) => {
8
- throw TypeError(msg);
9
- };
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
- var __objRest = (source, exclude) => {
24
- var target = {};
25
- for (var prop in source)
26
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
27
- target[prop] = source[prop];
28
- if (source != null && __getOwnPropSymbols)
29
- for (var prop of __getOwnPropSymbols(source)) {
30
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
31
- target[prop] = source[prop];
32
- }
33
- return target;
34
- };
35
- var __export = (target, all) => {
36
- for (var name in all)
37
- __defProp(target, name, { get: all[name], enumerable: true });
38
- };
39
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
40
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
41
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
42
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
43
- var __async = (__this, __arguments, generator) => {
44
- return new Promise((resolve, reject) => {
45
- var fulfilled = (value) => {
46
- try {
47
- step(generator.next(value));
48
- } catch (e) {
49
- reject(e);
50
- }
51
- };
52
- var rejected = (value) => {
53
- try {
54
- step(generator.throw(value));
55
- } catch (e) {
56
- reject(e);
57
- }
58
- };
59
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
60
- step((generator = generator.apply(__this, __arguments)).next());
61
- });
62
- };
63
-
64
- // src/ParaCore.ts
65
- import { Buffer as NodeBuffer } from "buffer";
1
+ import "./chunk-UICEQADR.js";
2
+ import { ParaCore } from "./ParaCore.js";
66
3
  import {
67
4
  AuthMethod,
68
- PublicKeyStatus,
69
- PublicKeyType,
70
- WalletType as WalletType2,
71
- WalletScheme as WalletScheme2,
72
- OAuthMethod,
73
- extractWalletRef,
74
- PasswordStatus,
75
- extractAuthInfo
76
- } from "@getpara/user-management-client";
77
- import forge3 from "node-forge";
78
-
79
- // src/cryptography/utils.ts
80
- import base64url from "base64url";
81
- import forge from "node-forge";
82
-
83
- // src/utils/events.ts
84
- function dispatchEvent(type, data, error) {
85
- typeof window !== "undefined" && !!window.dispatchEvent && window.dispatchEvent(
86
- new CustomEvent(type, { detail: __spreadValues({ data }, error && { error: new Error(error) }) })
87
- );
88
- }
89
-
90
- // src/utils/formatting.ts
91
- import { toBech32 } from "@cosmjs/encoding";
92
- import { sha256 } from "@noble/hashes/sha256";
93
- import { ripemd160 } from "@noble/hashes/ripemd160";
94
- import elliptic from "elliptic";
95
- import parsePhoneNumberFromString from "libphonenumber-js";
96
- var secp256k1 = new elliptic.ec("secp256k1");
97
- function hexStringToBase64(hexString) {
98
- if (hexString.substring(0, 2) === "0x") {
99
- hexString = hexString.substring(2);
100
- }
101
- return Buffer.from(hexString, "hex").toString("base64");
102
- }
103
- function hexToSignature(hexSig) {
104
- return {
105
- r: `0x${hexSig.slice(2, 66)}`,
106
- s: `0x${hexSig.slice(66, 130)}`,
107
- v: BigInt(hexSig.slice(130, 132))
108
- };
109
- }
110
- function hexToUint8Array(hex) {
111
- if (hex.startsWith("0x")) {
112
- hex = hex.slice(2);
113
- }
114
- return new Uint8Array(Buffer.from(hex, "hex"));
115
- }
116
- function hexToDecimal(hex) {
117
- if (hex.startsWith("0x")) {
118
- hex = hex.slice(2);
119
- }
120
- return `${parseInt(hex, 16)}`;
121
- }
122
- function decimalToHex(decimal) {
123
- return `0x${parseInt(decimal).toString(16)}`;
124
- }
125
- function compressPubkey(pubkey) {
126
- switch (pubkey.length) {
127
- case 33:
128
- return pubkey;
129
- case 65:
130
- return Uint8Array.from(secp256k1.keyFromPublic(pubkey).getPublic(true, "array"));
131
- default:
132
- throw new Error("Invalid pubkey length");
133
- }
134
- }
135
- function rawSecp256k1PubkeyToRawAddress(pubkeyData) {
136
- if (pubkeyData.length !== 33) {
137
- throw new Error(`Invalid Secp256k1 pubkey length (compressed): ${pubkeyData.length}`);
138
- }
139
- return ripemd160(sha256(pubkeyData));
140
- }
141
- function getCosmosAddress(publicKey, prefix) {
142
- const uncompressedPublicKey = new Uint8Array(
143
- Buffer.from(publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey, "hex")
144
- );
145
- const compressedPublicKey = compressPubkey(uncompressedPublicKey);
146
- return toBech32(prefix, rawSecp256k1PubkeyToRawAddress(compressedPublicKey));
147
- }
148
- function truncateAddress(str, addressType, { prefix = addressType === "COSMOS" ? "cosmos" : void 0 } = {}) {
149
- const headLength = (addressType === "COSMOS" ? prefix.length : addressType === "SOLANA" ? 0 : 2) + 4;
150
- return `${str.slice(0, headLength)}...${str.slice(-4)}`;
151
- }
152
- function stringToPhoneNumber(str) {
153
- var _a;
154
- return (_a = parsePhoneNumberFromString(str)) == null ? void 0 : _a.formatInternational().replace(/[^\d+]/g, "");
155
- }
156
- function normalizePhoneNumber(countryCode, number) {
157
- return stringToPhoneNumber(`${countryCode[0] !== "+" ? "+" : ""}${countryCode}${number}`);
158
- }
159
-
160
- // src/utils/onRamps.ts
161
- function toAssetInfoArray(data) {
162
- const result = [];
163
- Object.keys(data).forEach((walletType) => {
164
- const networks = data[walletType];
165
- Object.keys(networks).forEach((network) => {
166
- const assets = networks[network];
167
- Object.keys(assets).forEach((asset) => {
168
- const providerInfo = assets[asset];
169
- result.push([walletType, network, asset, providerInfo]);
170
- });
171
- });
172
- });
173
- return result;
174
- }
175
- function getOnRampNetworks(data, { walletType, allowed } = {}) {
176
- return [
177
- ...new Set(
178
- toAssetInfoArray(data).filter(([type, network]) => (!walletType || type === walletType) && (!allowed || allowed.includes(network))).map(([_, network]) => network)
179
- )
180
- ];
181
- }
182
- function getOnRampAssets(data, {
183
- walletType,
184
- network,
185
- allowed
186
- } = {}) {
187
- return [
188
- ...new Set(
189
- toAssetInfoArray(data).filter(
190
- ([t, n, a]) => (!walletType || t === walletType) && (!network || n === network) && (!Array.isArray(allowed) || allowed.includes(a))
191
- ).map(([, , asset]) => asset)
192
- )
193
- ];
194
- }
195
-
196
- // src/utils/polling.ts
197
- function waitUntilTrue(condition, timeoutMs, intervalMs) {
198
- return __async(this, null, function* () {
199
- const start = Date.now();
200
- while (Date.now() - start < timeoutMs) {
201
- if (yield condition()) {
202
- return true;
203
- }
204
- yield new Promise((resolve) => setTimeout(resolve, intervalMs));
205
- }
206
- return false;
207
- });
208
- }
209
-
210
- // src/types/config.ts
211
- var Environment = /* @__PURE__ */ ((Environment2) => {
212
- Environment2["DEV"] = "DEV";
213
- Environment2["SANDBOX"] = "SANDBOX";
214
- Environment2["BETA"] = "BETA";
215
- Environment2["PROD"] = "PROD";
216
- Environment2["DEVELOPMENT"] = "BETA";
217
- Environment2["PRODUCTION"] = "PROD";
218
- return Environment2;
219
- })(Environment || {});
220
- var EnabledFlow = /* @__PURE__ */ ((EnabledFlow2) => {
221
- EnabledFlow2["BUY"] = "BUY";
222
- EnabledFlow2["RECEIVE"] = "RECEIVE";
223
- EnabledFlow2["WITHDRAW"] = "WITHDRAW";
224
- return EnabledFlow2;
225
- })(EnabledFlow || {});
226
-
227
- // src/types/wallet.ts
228
- var PregenIdentifierType = /* @__PURE__ */ ((PregenIdentifierType2) => {
229
- PregenIdentifierType2["EMAIL"] = "EMAIL";
230
- PregenIdentifierType2["PHONE"] = "PHONE";
231
- return PregenIdentifierType2;
232
- })(PregenIdentifierType || {});
233
-
234
- // src/types/onRamps.ts
235
- var OnRampMethod = /* @__PURE__ */ ((OnRampMethod2) => {
236
- OnRampMethod2["ACH"] = "ACH";
237
- OnRampMethod2["DEBIT"] = "Debit";
238
- OnRampMethod2["CREDIT"] = "Credit";
239
- OnRampMethod2["APPLE_PAY"] = "Apple Pay";
240
- return OnRampMethod2;
241
- })(OnRampMethod || {});
242
-
243
- // src/types/popup.ts
244
- var PopupType = /* @__PURE__ */ ((PopupType2) => {
245
- PopupType2["SIGN_TRANSACTION_REVIEW"] = "SIGN_TRANSACTION_REVIEW";
246
- PopupType2["SIGN_MESSAGE_REVIEW"] = "SIGN_MESSAGE_REVIEW";
247
- PopupType2["LOGIN_PASSKEY"] = "LOGIN_PASSKEY";
248
- PopupType2["CREATE_PASSKEY"] = "CREATE_PASSKEY";
249
- PopupType2["OAUTH"] = "OAUTH";
250
- PopupType2["ON_RAMP_TRANSACTION"] = "ON_RAMP_TRANSACTION";
251
- return PopupType2;
252
- })(PopupType || {});
253
-
254
- // src/types/recovery.ts
255
- var RecoveryStatus = /* @__PURE__ */ ((RecoveryStatus3) => {
256
- RecoveryStatus3["INITIATED"] = "INITIATED";
257
- RecoveryStatus3["READY"] = "READY";
258
- RecoveryStatus3["EXPIRED"] = "EXPIRED";
259
- RecoveryStatus3["FINISHED"] = "FINISHED";
260
- RecoveryStatus3["CANCELLED"] = "CANCELLED";
261
- return RecoveryStatus3;
262
- })(RecoveryStatus || {});
263
-
264
- // src/types/events.ts
265
- var EVENT_PREFIX = "para";
266
- var ParaEvent = ((ParaEvent2) => {
267
- ParaEvent2["LOGIN_EVENT"] = `${EVENT_PREFIX}Login`;
268
- ParaEvent2["ACCOUNT_CREATION_EVENT"] = `${EVENT_PREFIX}AccountCreation`;
269
- ParaEvent2["ACCOUNT_SETUP_EVENT"] = `${EVENT_PREFIX}AccountSetup`;
270
- ParaEvent2["LOGOUT_EVENT"] = `${EVENT_PREFIX}Logout`;
271
- ParaEvent2["SIGN_MESSAGE_EVENT"] = `${EVENT_PREFIX}SignMessage`;
272
- ParaEvent2["SIGN_TRANSACTION_EVENT"] = `${EVENT_PREFIX}SignTransaction`;
273
- ParaEvent2["EXTERNAL_WALLET_CHANGE_EVENT"] = `${EVENT_PREFIX}ExternalWalletChange`;
274
- ParaEvent2["WALLETS_CHANGE_EVENT"] = `${EVENT_PREFIX}WalletsChange`;
275
- ParaEvent2["WALLET_CREATED"] = `${EVENT_PREFIX}WalletCreated`;
276
- ParaEvent2["PREGEN_WALLET_CLAIMED"] = `${EVENT_PREFIX}PregenWalletClaimed`;
277
- return ParaEvent2;
278
- })(ParaEvent || {});
279
-
280
- // src/utils/url.ts
281
- function getPortalDomain(env, isE2E) {
282
- if (isE2E) {
283
- return `localhost`;
284
- }
285
- switch (env) {
286
- case "DEV" /* DEV */:
287
- return "localhost";
288
- case "SANDBOX" /* SANDBOX */:
289
- return "app.sandbox.usecapsule.com";
290
- case "BETA" /* BETA */:
291
- return "app.beta.usecapsule.com";
292
- case "PROD" /* PROD */:
293
- return "app.usecapsule.com";
294
- default:
295
- throw new Error(`env: ${env} not supported`);
296
- }
297
- }
298
- function getPortalBaseURL({ env, isE2E }, useLocalIp, isForWasm) {
299
- if (isE2E) {
300
- if (isForWasm) {
301
- return `https://app.sandbox.usecapsule.com`;
302
- }
303
- return `http://localhost:3003`;
304
- }
305
- const domain = getPortalDomain(env);
306
- if (env === "DEV" /* DEV */) {
307
- if (useLocalIp) {
308
- return `http://127.0.0.1:3003`;
309
- }
310
- return `http://${domain}:3003`;
311
- }
312
- return `https://${domain}`;
313
- }
314
- function getParaConnectDomain(env) {
315
- switch (env) {
316
- case "DEV" /* DEV */:
317
- return "localhost";
318
- case "SANDBOX" /* SANDBOX */:
319
- return "connect.sandbox.getpara.com";
320
- case "BETA" /* BETA */:
321
- return "connect.beta.getpara.com";
322
- case "PROD" /* PROD */:
323
- return "connect.getpara.com";
324
- default:
325
- throw new Error(`env: ${env} not supported`);
326
- }
327
- }
328
- function getParaConnectBaseUrl({ env }, useLocalIp) {
329
- const domain = getParaConnectDomain(env);
330
- if (env === "DEV" /* DEV */) {
331
- if (useLocalIp) {
332
- return `http://127.0.0.1:3008`;
333
- }
334
- return `http://${domain}:3008`;
335
- }
336
- return `https://${domain}`;
337
- }
338
- function constructUrl({
339
- base,
340
- path,
341
- params = {}
342
- }) {
343
- const url = new URL(path, base);
344
- Object.entries(params).forEach(([key, value]) => {
345
- if (!!value && value !== "undefined" && value !== "null") url.searchParams.set(key, value.toString());
346
- });
347
- return url.toString();
348
- }
349
-
350
- // src/utils/wallet.ts
351
- import { WalletScheme, WalletType } from "@getpara/user-management-client";
352
- var WalletSchemeTypeMap = {
353
- [WalletScheme.DKLS]: {
354
- [WalletType.EVM]: true,
355
- [WalletType.COSMOS]: true
356
- },
357
- [WalletScheme.CGGMP]: {
358
- [WalletType.EVM]: true,
359
- [WalletType.COSMOS]: true
360
- },
361
- [WalletScheme.ED25519]: {
362
- [WalletType.SOLANA]: true
363
- }
364
- };
365
- function isPregenIdentifierMatch(a, b, type) {
366
- if (!a || !b) {
367
- return false;
368
- }
369
- switch (type) {
370
- case "EMAIL":
371
- return a.toLowerCase() === b.toLowerCase();
372
- case "PHONE":
373
- return stringToPhoneNumber(a) === stringToPhoneNumber(b);
374
- case "CUSTOM_ID":
375
- return a === b;
376
- default:
377
- return a.replace(/^@/g, "").toLowerCase() === b.replace(/^@/g, "").toLowerCase();
378
- }
379
- }
380
- function isWalletSupported(types, wallet) {
381
- return types.some((walletType) => {
382
- var _a;
383
- return !!((_a = WalletSchemeTypeMap[wallet == null ? void 0 : wallet.scheme]) == null ? void 0 : _a[walletType]);
384
- });
385
- }
386
- function getSchemes(types) {
387
- return Object.keys(WalletSchemeTypeMap).filter((scheme) => {
388
- if (scheme === WalletScheme.CGGMP) {
389
- return false;
390
- }
391
- return (Array.isArray(types) ? types : Object.keys(types)).some((type) => WalletSchemeTypeMap[scheme][type]);
392
- });
393
- }
394
- function getWalletTypes(schemes) {
395
- return [
396
- ...new Set(
397
- schemes.reduce((acc, scheme) => {
398
- return [...acc, ...Object.keys(WalletSchemeTypeMap[scheme]).filter((type) => WalletSchemeTypeMap[scheme][type])];
399
- }, [])
400
- )
401
- ];
402
- }
403
- function getEquivalentTypes(types) {
404
- return getWalletTypes(getSchemes((Array.isArray(types) ? types : [types]).map((t) => WalletType[t])));
405
- }
406
- function entityToWallet(w) {
407
- return __spreadProps(__spreadValues({}, w), {
408
- scheme: w.scheme,
409
- type: w.type,
410
- pregenIdentifierType: w.pregenIdentifierType
411
- });
412
- }
413
- function migrateWallet(obj) {
414
- if (["USER", "PREGEN"].includes(obj.type)) {
415
- obj.isPregen = obj.type === "PREGEN";
416
- obj.type = obj.scheme === WalletScheme.ED25519 ? WalletType.SOLANA : WalletType.EVM;
417
- }
418
- if (!!obj.scheme && !obj.type) {
419
- obj.type = obj.scheme === WalletScheme.ED25519 ? WalletType.SOLANA : WalletType.EVM;
420
- }
421
- return obj;
422
- }
423
-
424
- // src/cryptography/utils.ts
425
- var rsa = forge.pki.rsa;
426
- var RSA_ENCRYPTION_SCHEME = "RSA-OAEP";
427
- var CONSTANT_IV = "794241bc819a125a7b78ea313decc0bc";
428
- var CONSTANT_IV_AES = new Uint8Array([23, 66, 157, 146, 179, 158, 117, 120, 184, 73, 123, 81]);
429
- function getSHA256HashHex(str) {
430
- const md = forge.md.sha256.create();
431
- md.update(str);
432
- return md.digest().toHex();
433
- }
434
- function getPublicKeyHex(keyPair) {
435
- const pem = forge.pki.publicKeyToRSAPublicKeyPem(keyPair.publicKey);
436
- return Buffer.from(pem, "utf-8").toString("hex");
437
- }
438
- function publicKeyFromHex(publicKeyHex) {
439
- const pem = publicKeyHexToPem(publicKeyHex);
440
- return forge.pki.publicKeyFromPem(pem);
441
- }
442
- function publicKeyHexToPem(publicKeyHex) {
443
- return Buffer.from(publicKeyHex, "hex").toString("utf-8");
444
- }
445
- function encodePrivateKeyToPemHex(keyPair) {
446
- const pem = forge.pki.privateKeyToPem(keyPair.privateKey);
447
- return Buffer.from(pem, "utf-8").toString("hex");
448
- }
449
- function decodePrivateKeyPemHex(privateKeyPemHex) {
450
- const pem = Buffer.from(privateKeyPemHex, "hex").toString("utf-8");
451
- return forge.pki.privateKeyFromPem(pem);
452
- }
453
- function encryptPrivateKey(keyPair, key) {
454
- return __async(this, null, function* () {
455
- const privateKeyPemHex = encodePrivateKeyToPemHex(keyPair);
456
- const cryptoKey = yield window.crypto.subtle.importKey(
457
- "raw",
458
- Buffer.from(key, "base64"),
459
- {
460
- name: "AES-GCM",
461
- length: 256
462
- },
463
- true,
464
- ["encrypt", "decrypt"]
465
- );
466
- const encodedPlaintext = new TextEncoder().encode(privateKeyPemHex);
467
- const ciphertext = yield window.crypto.subtle.encrypt(
468
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
469
- cryptoKey,
470
- encodedPlaintext
471
- );
472
- return Buffer.from(ciphertext).toString("base64");
473
- });
474
- }
475
- function decryptPrivateKey(encryptedPrivateKeyPemHex, key) {
476
- return __async(this, null, function* () {
477
- const secretKey = yield crypto.subtle.importKey(
478
- "raw",
479
- Buffer.from(key, "base64"),
480
- {
481
- name: "AES-GCM",
482
- length: 256
483
- },
484
- true,
485
- ["encrypt", "decrypt"]
486
- );
487
- const cleartext = yield crypto.subtle.decrypt(
488
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
489
- secretKey,
490
- Buffer.from(encryptedPrivateKeyPemHex, "base64")
491
- );
492
- const privateKeyPemHex = new TextDecoder().decode(cleartext);
493
- const privateKey = decodePrivateKeyPemHex(privateKeyPemHex);
494
- return privateKey;
495
- });
496
- }
497
- function getAsymmetricKeyPair(ctx, seedValue) {
498
- return __async(this, null, function* () {
499
- const prng = forge.random.createInstance();
500
- if (seedValue) {
501
- prng.seedFileSync = (_n) => seedValue;
502
- prng.seedFile = (_n, cb) => {
503
- cb(null, seedValue);
504
- };
505
- }
506
- const options = {
507
- bits: 2048,
508
- e: 65537,
509
- prng
510
- };
511
- if (!ctx.disableWorkers) {
512
- options.workLoad = 100;
513
- options.workers = seedValue ? 1 : -1;
514
- const workerRes = yield fetch(`${getPortalBaseURL(ctx)}/static/js/prime.worker.min.js`);
515
- const workerBlob = new Blob([yield workerRes.text()], { type: "application/javascript" });
516
- options.workerScript = URL.createObjectURL(workerBlob);
517
- }
518
- return new Promise(
519
- (resolve, reject) => rsa.generateKeyPair(options, (err, keypair) => {
520
- if (err) {
521
- reject(err);
522
- }
523
- resolve(keypair);
524
- })
525
- );
526
- });
527
- }
528
- function getPublicKeyFromSignature(ctx, userHandle) {
529
- return __async(this, null, function* () {
530
- const encodedUserHandle = base64url.encode(userHandle);
531
- const keyPair = yield getAsymmetricKeyPair(ctx, encodedUserHandle);
532
- return getPublicKeyHex(keyPair);
533
- });
534
- }
535
- function symmetricKeyEncryptMessage(message) {
536
- const key = forge.random.getBytesSync(16);
537
- const cipher = forge.cipher.createCipher("AES-CBC", key);
538
- cipher.start({ iv: CONSTANT_IV });
539
- cipher.update(forge.util.createBuffer(message));
540
- cipher.finish();
541
- const encryptedMessageHex = cipher.output.toHex();
542
- return { key, encryptedMessageHex };
543
- }
544
- function decipherEncryptedMessageHex(key, encryptedMessageHex) {
545
- const decipher = forge.cipher.createDecipher("AES-CBC", key);
546
- decipher.start({ iv: CONSTANT_IV });
547
- decipher.update(forge.util.createBuffer(forge.util.hexToBytes(encryptedMessageHex)));
548
- decipher.finish();
549
- return decipher.output.toString();
550
- }
551
- function decryptWithKeyPair(keyPair, encryptedMessageHex, encryptedKeyHex) {
552
- const encryptedKey = Buffer.from(encryptedKeyHex, "hex").toString("utf-8");
553
- const key = keyPair.privateKey.decrypt(encryptedKey, RSA_ENCRYPTION_SCHEME);
554
- return decipherEncryptedMessageHex(key, encryptedMessageHex);
555
- }
556
- function decryptWithPrivateKey(privateKey, encryptedMessageHex, encryptedKeyHex) {
557
- const encryptedKey = Buffer.from(encryptedKeyHex, "hex").toString("utf-8");
558
- const key = privateKey.decrypt(encryptedKey, RSA_ENCRYPTION_SCHEME);
559
- return decipherEncryptedMessageHex(key, encryptedMessageHex);
560
- }
561
- function decryptWithDerivedPrivateKey(_0, _1) {
562
- return __async(this, arguments, function* (ctx, {
563
- seedValue,
564
- encryptedMessageHex,
565
- encryptedKeyHex
566
- }) {
567
- const keyPair = yield getAsymmetricKeyPair(ctx, seedValue);
568
- return decryptWithPrivateKey(keyPair.privateKey, encryptedMessageHex, encryptedKeyHex);
569
- });
570
- }
571
- function getDerivedPrivateKeyAndDecrypt(ctx, seedValue, encryptedShares) {
572
- return __async(this, null, function* () {
573
- return Promise.all(
574
- encryptedShares.map((share) => __async(this, null, function* () {
575
- return {
576
- walletId: share.walletId,
577
- walletScheme: share.walletScheme,
578
- partnerId: share.partnerId,
579
- signer: yield decryptWithDerivedPrivateKey(ctx, {
580
- seedValue,
581
- encryptedMessageHex: share.encryptedShare,
582
- encryptedKeyHex: share.encryptedKey
583
- }),
584
- protocolId: share.protocolId
585
- };
586
- }))
587
- );
588
- });
589
- }
590
- function decryptPrivateKeyAndDecryptShare(encryptionKey, encryptedShares, encryptedPrivateKey) {
591
- return __async(this, null, function* () {
592
- let privateKey;
593
- try {
594
- privateKey = yield decryptPrivateKey(encryptedPrivateKey, encryptionKey);
595
- } catch (e) {
596
- }
597
- try {
598
- privateKey = yield decryptPrivateKeyWithPassword(encryptedPrivateKey, encryptionKey);
599
- } catch (e) {
600
- }
601
- if (!privateKey) {
602
- throw new Error("Could not decrypt private key");
603
- }
604
- return encryptedShares.map((share) => ({
605
- walletId: share.walletId,
606
- walletScheme: share.walletScheme,
607
- partnerId: share.partnerId,
608
- signer: decryptWithPrivateKey(privateKey, share.encryptedShare, share.encryptedKey),
609
- protocolId: share.protocolId
610
- }));
611
- });
612
- }
613
- function encryptWithDerivedPublicKey(publicKeyHex, message) {
614
- const { key, encryptedMessageHex } = symmetricKeyEncryptMessage(message);
615
- const publicKeyPem = publicKeyHexToPem(publicKeyHex);
616
- const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
617
- const encryptedKey = publicKey.encrypt(key, RSA_ENCRYPTION_SCHEME);
618
- const encryptedKeyHex = Buffer.from(encryptedKey, "utf-8").toString("hex");
619
- return { encryptedMessageHex, encryptedKeyHex };
620
- }
621
- function hashPasswordWithSalt(password) {
622
- const salt = generateSalt();
623
- const saltedPassword = salt + password;
624
- const hash = getSHA256HashHex(saltedPassword);
625
- return { salt, hash };
626
- }
627
- function generateSalt(length = 16) {
628
- return forge.util.bytesToHex(forge.random.getBytesSync(length));
629
- }
630
- function deriveCryptoKeyFromPassword(hashedPassword) {
631
- return __async(this, null, function* () {
632
- const keyBuffer = Buffer.from(hashedPassword, "hex");
633
- return yield window.crypto.subtle.importKey(
634
- "raw",
635
- keyBuffer,
636
- {
637
- name: "AES-GCM",
638
- length: 256
639
- },
640
- true,
641
- ["encrypt", "decrypt"]
642
- );
643
- });
644
- }
645
- function encryptPrivateKeyWithPassword(keyPair, hashedPassword) {
646
- return __async(this, null, function* () {
647
- const cryptoKey = yield deriveCryptoKeyFromPassword(hashedPassword);
648
- const privateKeyPemHex = encodePrivateKeyToPemHex(keyPair);
649
- const encodedPlaintext = new TextEncoder().encode(privateKeyPemHex);
650
- const ciphertext = yield window.crypto.subtle.encrypt(
651
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
652
- cryptoKey,
653
- encodedPlaintext
654
- );
655
- return Buffer.from(ciphertext).toString("base64");
656
- });
657
- }
658
- function decryptPrivateKeyWithPassword(encryptedPrivateKeyPemHex, hashedPassword) {
659
- return __async(this, null, function* () {
660
- const secretKey = yield crypto.subtle.importKey(
661
- "raw",
662
- Buffer.from(hashedPassword, "hex"),
663
- {
664
- name: "AES-GCM",
665
- length: 256
666
- },
667
- true,
668
- ["encrypt", "decrypt"]
669
- );
670
- const cleartext = yield crypto.subtle.decrypt(
671
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
672
- secretKey,
673
- Buffer.from(encryptedPrivateKeyPemHex, "base64")
674
- );
675
- const privateKeyPemHex = new TextDecoder().decode(cleartext);
676
- const privateKey = decodePrivateKeyPemHex(privateKeyPemHex);
677
- return privateKey;
678
- });
679
- }
680
-
681
- // src/external/userManagementClient.ts
682
- import Client from "@getpara/user-management-client";
683
- function getBaseOAuthUrl(env) {
684
- switch (env) {
685
- case "DEV" /* DEV */:
686
- return "http://localhost:8080/";
687
- case "SANDBOX" /* SANDBOX */:
688
- return "https://api.sandbox.usecapsule.com/";
689
- case "BETA" /* BETA */:
690
- return "https://api.beta.usecapsule.com/";
691
- case "PROD" /* PROD */:
692
- return "https://api.usecapsule.com/";
693
- default:
694
- throw new Error(`unsupported env: ${env}`);
695
- }
696
- }
697
- function getBaseUrl(env) {
698
- switch (env) {
699
- case "DEV" /* DEV */:
700
- return "http://localhost:8080/";
701
- case "SANDBOX" /* SANDBOX */:
702
- return "https://api.sandbox.getpara.com/";
703
- case "BETA" /* BETA */:
704
- return "https://api.beta.getpara.com/";
705
- case "PROD" /* PROD */:
706
- return "https://api.getpara.com/";
707
- default:
708
- throw new Error(`unsupported env: ${env}`);
709
- }
710
- }
711
- function getBaseMPCNetworkUrl(env, useWebsocket) {
712
- const prefix = useWebsocket ? "ws" : "http";
713
- switch (env) {
714
- case "DEV" /* DEV */:
715
- return `${prefix}://localhost:3000`;
716
- case "SANDBOX" /* SANDBOX */:
717
- return `${prefix}s://mpc-network.sandbox.getpara.com`;
718
- case "BETA" /* BETA */:
719
- return `${prefix}s://mpc-network.beta.getpara.com`;
720
- case "PROD" /* PROD */:
721
- return `${prefix}s://mpc-network.prod.getpara.com`;
722
- default:
723
- throw new Error(`unsupported env: ${env}`);
724
- }
725
- }
726
- function initClient({
727
- env,
728
- version,
729
- apiKey,
730
- partnerId,
731
- useFetchAdapter = false,
732
- retrieveSessionCookie,
733
- persistSessionCookie
734
- }) {
735
- return new Client({
736
- userManagementHost: getBaseUrl(env),
737
- version: ["DEV" /* DEV */, "SANDBOX" /* SANDBOX */].includes(env) ? "dev" : version,
738
- apiKey,
739
- partnerId,
740
- opts: { useFetchAdapter },
741
- retrieveSessionCookie,
742
- persistSessionCookie
743
- });
744
- }
745
-
746
- // src/external/mpcComputationClient.ts
747
- var mpcComputationClient_exports = {};
748
- __export(mpcComputationClient_exports, {
749
- initClient: () => initClient2
750
- });
751
- import axios from "axios";
752
- function initClient2(baseURL, useAdapter) {
753
- const client = axios.create({ baseURL });
754
- if (useAdapter) {
755
- client.defaults.adapter = function(config) {
756
- return fetch(config.baseURL + config.url, {
757
- method: config.method,
758
- headers: config.headers,
759
- body: config.data,
760
- credentials: config.withCredentials ? "include" : void 0
761
- }).then(
762
- (response) => response.text().then((text) => ({
763
- data: text,
764
- status: response.status,
765
- statusText: response.statusText,
766
- headers: response.headers,
767
- config,
768
- request: fetch
769
- }))
770
- ).catch(function(reason) {
771
- throw reason;
772
- });
773
- };
774
- }
775
- return client;
776
- }
777
-
778
- // src/shares/shareDistribution.ts
779
- import { EncryptorType as EncryptorType2, KeyShareType as KeyShareType2 } from "@getpara/user-management-client";
780
-
781
- // src/shares/recovery.ts
782
- import { EncryptorType, KeyShareType } from "@getpara/user-management-client";
783
-
784
- // src/shares/KeyContainer.ts
785
- import { Encrypt as ECIESEncrypt, Decrypt as ECIESDecrypt } from "@celo/utils/lib/ecies.js";
786
- import * as eutil from "ethereumjs-util";
787
- import * as forge2 from "node-forge";
788
- var KeyContainer = class _KeyContainer {
789
- constructor(walletId, keyshare, address) {
790
- this.walletId = walletId;
791
- this.keyshare = keyshare;
792
- this.address = address;
793
- this.backupDecryptionKey = Buffer.from(forge2.random.getBytesSync(32), "binary").toString("hex");
794
- }
795
- static buildFrom(serializedContainer) {
796
- try {
797
- const parsedObject = JSON.parse(serializedContainer);
798
- return Object.assign(new _KeyContainer("", "", ""), parsedObject);
799
- } catch (e) {
800
- const container = new _KeyContainer("", "", "");
801
- container.backupDecryptionKey = serializedContainer.split("|")[0];
802
- return container;
803
- }
804
- }
805
- getPublicEncryptionKey() {
806
- return Buffer.from(eutil.privateToPublic(Buffer.from(this.backupDecryptionKey, "hex")));
807
- }
808
- getPublicEncryptionKeyHex() {
809
- return this.getPublicEncryptionKey().toString("hex");
810
- }
811
- encryptForSelf(backup) {
812
- try {
813
- const pubkey = this.getPublicEncryptionKey();
814
- const data = ECIESEncrypt(pubkey, Buffer.from(backup, "ucs2")).toString("base64");
815
- return data;
816
- } catch (error) {
817
- throw Error("Error encrypting backup");
818
- }
819
- }
820
- static encryptWithPublicKey(publicKey, backup) {
821
- try {
822
- const data = ECIESEncrypt(publicKey, Buffer.from(backup, "ucs2")).toString("base64");
823
- return data;
824
- } catch (error) {
825
- throw Error("Error encrypting backup");
826
- }
827
- }
828
- decrypt(encryptedBackup) {
829
- try {
830
- const buf = Buffer.from(encryptedBackup, "base64");
831
- const data = ECIESDecrypt(Buffer.from(this.backupDecryptionKey, "hex"), buf);
832
- return Buffer.from(data.buffer).toString("ucs2");
833
- } catch (error) {
834
- throw Error("Error decrypting backup");
835
- }
836
- }
837
- };
838
-
839
- // src/shares/recovery.ts
840
- function sendRecoveryForShare(_0) {
841
- return __async(this, arguments, function* ({
842
- ctx,
843
- userId,
844
- walletId,
845
- otherEncryptedShares = [],
846
- userSigner,
847
- ignoreRedistributingBackupEncryptedShare = false,
848
- emailProps = {},
849
- forceRefresh = false
850
- }) {
851
- if (ignoreRedistributingBackupEncryptedShare) {
852
- yield ctx.client.uploadUserKeyShares(
853
- userId,
854
- otherEncryptedShares.map((share) => __spreadValues({
855
- walletId
856
- }, share))
857
- );
858
- return "";
859
- }
860
- let userBackupKeyShareOptsArr;
861
- let recoveryPrivateKeyContainer;
862
- const { recoveryPublicKeys } = yield ctx.client.getRecoveryPublicKeys(userId);
863
- if (forceRefresh || !(recoveryPublicKeys == null ? void 0 : recoveryPublicKeys.length)) {
864
- recoveryPrivateKeyContainer = new KeyContainer(walletId, "", "");
865
- const { recoveryPublicKeys: recoveryPublicKeys2 } = yield ctx.client.persistRecoveryPublicKeys(userId, [
866
- recoveryPrivateKeyContainer.getPublicEncryptionKeyHex()
867
- ]);
868
- const encryptedUserBackup = recoveryPrivateKeyContainer.encryptForSelf(userSigner);
869
- userBackupKeyShareOptsArr = [
870
- {
871
- walletId,
872
- encryptedShare: encryptedUserBackup,
873
- type: KeyShareType.USER,
874
- encryptor: EncryptorType.RECOVERY,
875
- recoveryPublicKeyId: recoveryPublicKeys2[0].id
876
- }
877
- ];
878
- } else {
879
- userBackupKeyShareOptsArr = recoveryPublicKeys.map((recoveryPublicKey) => {
880
- const { id: recoveryPublicKeyId, publicKey } = recoveryPublicKey;
881
- const encryptedUserBackup = KeyContainer.encryptWithPublicKey(Buffer.from(publicKey, "hex"), userSigner);
882
- return {
883
- walletId,
884
- encryptedShare: encryptedUserBackup,
885
- type: KeyShareType.USER,
886
- encryptor: EncryptorType.RECOVERY,
887
- recoveryPublicKeyId
888
- };
889
- });
890
- }
891
- yield ctx.client.uploadUserKeyShares(userId, [
892
- ...otherEncryptedShares.map((share) => __spreadValues({
893
- walletId
894
- }, share)),
895
- ...ignoreRedistributingBackupEncryptedShare ? [] : userBackupKeyShareOptsArr
896
- ]);
897
- yield ctx.client.distributeParaShare(__spreadValues({
898
- userId,
899
- walletId,
900
- useDKLS: ctx.useDKLS
901
- }, emailProps));
902
- return recoveryPrivateKeyContainer ? JSON.stringify(recoveryPrivateKeyContainer) : "";
903
- });
904
- }
905
-
906
- // src/shares/shareDistribution.ts
907
- function distributeNewShare(_0) {
908
- return __async(this, arguments, function* ({
909
- ctx,
910
- userId,
911
- walletId,
912
- userShare,
913
- ignoreRedistributingBackupEncryptedShare = false,
914
- emailProps = {},
915
- partnerId,
916
- protocolId
917
- }) {
918
- const publicKeysRes = yield ctx.client.getSessionPublicKeys(userId);
919
- const biometricEncryptedShares = publicKeysRes.data.keys.map((key) => {
920
- if (!key.publicKey) {
921
- return;
922
- }
923
- const { encryptedMessageHex, encryptedKeyHex } = encryptWithDerivedPublicKey(key.sigDerivedPublicKey, userShare);
924
- return {
925
- encryptedShare: encryptedMessageHex,
926
- encryptedKey: encryptedKeyHex,
927
- type: KeyShareType2.USER,
928
- encryptor: EncryptorType2.BIOMETRICS,
929
- biometricPublicKey: key.sigDerivedPublicKey,
930
- partnerId,
931
- protocolId
932
- };
933
- }).filter(Boolean);
934
- const passwords = yield ctx.client.getPasswords({ userId });
935
- const passwordEncryptedShares = passwords.map((password) => {
936
- if (password.status === "PENDING") {
937
- return;
938
- }
939
- const { encryptedMessageHex, encryptedKeyHex } = encryptWithDerivedPublicKey(password.sigDerivedPublicKey, userShare);
940
- return {
941
- encryptedShare: encryptedMessageHex,
942
- encryptedKey: encryptedKeyHex,
943
- type: KeyShareType2.USER,
944
- encryptor: EncryptorType2.PASSWORD,
945
- passwordId: password.id,
946
- partnerId,
947
- protocolId
948
- };
949
- }).filter(Boolean);
950
- const allEncryptedShares = [...biometricEncryptedShares, ...passwordEncryptedShares];
951
- return yield sendRecoveryForShare({
952
- ctx,
953
- userId,
954
- walletId,
955
- otherEncryptedShares: allEncryptedShares,
956
- userSigner: userShare,
957
- ignoreRedistributingBackupEncryptedShare,
958
- emailProps
959
- });
960
- });
961
- }
962
-
963
- // src/transmission/transmissionUtils.ts
964
- import { Encrypt as ECIESEncrypt2, Decrypt as ECIESDecrypt2 } from "@celo/utils/lib/ecies.js";
965
- import { Buffer as Buffer2 } from "buffer";
966
- import * as eutil2 from "ethereumjs-util";
967
- import { randomBytes } from "crypto";
968
- function upload(message, userManagementClient) {
969
- return __async(this, null, function* () {
970
- let secret;
971
- let publicKeyUint8Array;
972
- while (true) {
973
- try {
974
- secret = randomBytes(32).toString("hex");
975
- publicKeyUint8Array = eutil2.privateToPublic(Buffer2.from(secret, "hex"));
976
- break;
977
- } catch (e) {
978
- continue;
979
- }
980
- }
981
- const pubkey = Buffer2.from(publicKeyUint8Array);
982
- const data = ECIESEncrypt2(pubkey, Buffer2.from(message, "ucs2")).toString("base64");
983
- const {
984
- data: { id }
985
- } = yield userManagementClient.tempTrasmissionInit(data);
986
- return encodeURIComponent(id + "|" + secret);
987
- });
988
- }
989
- function retrieve(uriEncodedMessage, userManagementClient) {
990
- return __async(this, null, function* () {
991
- const [id, secret] = decodeURIComponent(uriEncodedMessage).split("|");
992
- const response = yield userManagementClient.tempTrasmission(id);
993
- const data = response.data.message;
994
- const buf = Buffer2.from(data, "base64");
995
- const res = Buffer2.from(ECIESDecrypt2(Buffer2.from(secret, "hex"), buf).buffer).toString("ucs2");
996
- return res;
997
- });
998
- }
999
-
1000
- // src/errors.ts
1001
- var TransactionReviewError = class extends Error {
1002
- constructor(transactionReviewUrl) {
1003
- super("transaction review error");
1004
- this.name = "TransactionReviewError";
1005
- this.transactionReviewUrl = transactionReviewUrl;
1006
- }
1007
- };
1008
- var TransactionReviewDenied = class extends Error {
1009
- constructor() {
1010
- super("transaction review has been denied by the user");
1011
- this.name = "TransactionReviewDenied";
1012
- }
1013
- };
1014
- var TransactionReviewTimeout = class extends Error {
1015
- constructor(transactionReviewUrl, pendingTransactionId) {
1016
- super("transaction review has timed out");
1017
- this.name = "TransactionReviewTimeout";
1018
- this.transactionReviewUrl = transactionReviewUrl;
1019
- this.pendingTransactionId = pendingTransactionId;
1020
- }
1021
- };
1022
-
1023
- // src/constants.ts
1024
- var PARA_CORE_VERSION = '1.7.1';
1025
- var PREFIX = "@CAPSULE/";
1026
- var LOCAL_STORAGE_EMAIL = `${PREFIX}e-mail`;
1027
- var LOCAL_STORAGE_PHONE = `${PREFIX}phone`;
1028
- var LOCAL_STORAGE_COUNTRY_CODE = `${PREFIX}countryCode`;
1029
- var LOCAL_STORAGE_FARCASTER_USERNAME = `${PREFIX}farcasterUsername`;
1030
- var LOCAL_STORAGE_TELEGRAM_USER_ID = `${PREFIX}telegramUserId`;
1031
- var LOCAL_STORAGE_EXTERNAL_WALLET_USER_ID = `${PREFIX}externalWalletUserId`;
1032
- var LOCAL_STORAGE_USER_ID = `${PREFIX}userId`;
1033
- var LOCAL_STORAGE_ED25519_WALLETS = `${PREFIX}ed25519Wallets`;
1034
- var LOCAL_STORAGE_WALLETS = `${PREFIX}wallets`;
1035
- var LOCAL_STORAGE_EXTERNAL_WALLETS = `${PREFIX}externalWallets`;
1036
- var LOCAL_STORAGE_CURRENT_WALLET_IDS = `${PREFIX}currentWalletIds`;
1037
- var LOCAL_STORAGE_SESSION_COOKIE = `${PREFIX}sessionCookie`;
1038
- var SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR = `${PREFIX}loginEncryptionKeyPair`;
1039
- var POLLING_INTERVAL_MS = 2e3;
1040
- var SHORT_POLLING_INTERVAL_MS = 1e3;
1041
-
1042
- // src/utils/listeners.ts
1043
- function storageListener(e) {
1044
- if (!e.url.includes(window.location.origin)) {
1045
- return;
1046
- }
1047
- if (e.key === LOCAL_STORAGE_EXTERNAL_WALLETS) {
1048
- this.updateExternalWalletsFromStorage();
1049
- }
1050
- if (e.key === SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR) {
1051
- this.updateLoginEncryptionKeyPairFromStorage();
1052
- }
1053
- if (e.key === LOCAL_STORAGE_SESSION_COOKIE) {
1054
- this.updateSessionCookieFromStorage();
1055
- }
1056
- if (e.key === LOCAL_STORAGE_CURRENT_WALLET_IDS) {
1057
- this.updateWalletIdsFromStorage();
1058
- }
1059
- if (e.key === LOCAL_STORAGE_WALLETS || e.key === LOCAL_STORAGE_ED25519_WALLETS) {
1060
- this.updateWalletsFromStorage();
1061
- }
1062
- if (e.key === LOCAL_STORAGE_EMAIL) {
1063
- this.updateEmailFromStorage();
1064
- }
1065
- if (e.key === LOCAL_STORAGE_COUNTRY_CODE) {
1066
- this.updateCountryCodeFromStorage();
1067
- }
1068
- if (e.key === LOCAL_STORAGE_PHONE) {
1069
- this.updatePhoneFromStorage();
1070
- }
1071
- if (e.key === LOCAL_STORAGE_USER_ID) {
1072
- this.updateUserIdFromStorage();
1073
- }
1074
- if (e.key === LOCAL_STORAGE_TELEGRAM_USER_ID) {
1075
- this.updateTelegramUserIdFromStorage();
1076
- }
1077
- }
1078
- function setupListeners() {
1079
- if (typeof window !== "undefined" && window.addEventListener && window.location) {
1080
- window.removeEventListener("storage", storageListener.bind(this));
1081
- window.addEventListener("storage", storageListener.bind(this));
1082
- }
1083
- }
1084
-
1085
- // src/ParaCore.ts
1086
- if (typeof global !== "undefined") {
1087
- global.Buffer = global.Buffer || NodeBuffer;
1088
- } else if (typeof window !== "undefined") {
1089
- window.Buffer = window.Buffer || NodeBuffer;
1090
- window.global = window.global || window;
1091
- } else {
1092
- self.Buffer = self.Buffer || NodeBuffer;
1093
- self.global = self.global || self;
1094
- }
1095
- var { pki, jsbn } = forge3;
1096
- var _supportedWalletTypes, _supportedWalletTypesOpt;
1097
- var _ParaCore = class _ParaCore {
1098
- /**
1099
- * Constructs a new `ParaCore` instance.
1100
- * @param env - `Environment` to use.
1101
- * @param apiKey - API key to use.
1102
- * @param opts - Additional constructor options; see `ConstructorOpts`.
1103
- * @returns - A new ParaCore instance.
1104
- */
1105
- constructor(env, apiKey, opts) {
1106
- this.isAwaitingAccountCreation = false;
1107
- this.isAwaitingLogin = false;
1108
- this.isAwaitingFarcaster = false;
1109
- this.isAwaitingOAuth = false;
1110
- /**
1111
- * 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.
1112
- */
1113
- this.currentWalletIds = {};
1114
- __privateAdd(this, _supportedWalletTypes);
1115
- __privateAdd(this, _supportedWalletTypesOpt);
1116
- this.localStorageGetItem = (key) => {
1117
- return this.platformUtils.localStorage.get(key);
1118
- };
1119
- this.localStorageSetItem = (key, value) => {
1120
- return this.platformUtils.localStorage.set(key, value);
1121
- };
1122
- this.sessionStorageGetItem = (key) => {
1123
- return this.platformUtils.sessionStorage.get(key);
1124
- };
1125
- this.sessionStorageSetItem = (key, value) => {
1126
- return this.platformUtils.sessionStorage.set(key, value);
1127
- };
1128
- this.sessionStorageRemoveItem = (key) => {
1129
- return this.platformUtils.sessionStorage.removeItem(key);
1130
- };
1131
- this.retrieveSessionCookie = () => {
1132
- return this.sessionCookie;
1133
- };
1134
- /**
1135
- * Remove all local storage and prefixed session storage.
1136
- * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
1137
- */
1138
- this.clearStorage = (type = "all") => __async(this, null, function* () {
1139
- const isAll = type === "all";
1140
- (isAll || type === "local") && this.platformUtils.localStorage.clear(PREFIX);
1141
- (isAll || type === "session") && this.platformUtils.sessionStorage.clear(PREFIX);
1142
- if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
1143
- this.platformUtils.secureStorage.clear(PREFIX);
1144
- }
1145
- });
1146
- this.initializeFromStorage = () => {
1147
- this.updateEmailFromStorage();
1148
- this.updateCountryCodeFromStorage();
1149
- this.updatePhoneFromStorage();
1150
- this.updateUserIdFromStorage();
1151
- this.updateTelegramUserIdFromStorage();
1152
- this.updateWalletsFromStorage();
1153
- this.updateWalletIdsFromStorage();
1154
- this.updateSessionCookieFromStorage();
1155
- this.updateLoginEncryptionKeyPairFromStorage();
1156
- this.updateExternalWalletsFromStorage();
1157
- };
1158
- this.updateTelegramUserIdFromStorage = () => {
1159
- this.telegramUserId = this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID) || void 0;
1160
- };
1161
- this.updateUserIdFromStorage = () => {
1162
- this.userId = this.localStorageGetItem(LOCAL_STORAGE_USER_ID) || void 0;
1163
- };
1164
- this.updatePhoneFromStorage = () => {
1165
- this.phone = this.localStorageGetItem(LOCAL_STORAGE_PHONE) || void 0;
1166
- };
1167
- this.updateCountryCodeFromStorage = () => {
1168
- this.countryCode = this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE) || void 0;
1169
- };
1170
- this.updateEmailFromStorage = () => {
1171
- this.email = this.localStorageGetItem(LOCAL_STORAGE_EMAIL) || void 0;
1172
- };
1173
- this.updateWalletsFromStorage = () => __async(this, null, function* () {
1174
- var _a;
1175
- const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1176
- const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
1177
- const fromJson = JSON.parse(_currentWalletIds);
1178
- return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1179
- const wallet = Object.values(this.wallets).find(
1180
- (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1181
- );
1182
- return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1183
- }, {}) : fromJson;
1184
- })();
1185
- this.setCurrentWalletIds(currentWalletIds);
1186
- const stringWallets = this.platformUtils.secureStorage ? this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS) : this.localStorageGetItem(LOCAL_STORAGE_WALLETS);
1187
- const _wallets = JSON.parse(stringWallets || "{}");
1188
- const stringEd25519Wallets = this.platformUtils.secureStorage ? this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
1189
- const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
1190
- const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
1191
- return __spreadProps(__spreadValues({}, res), {
1192
- [key]: migrateWallet(_wallets[key])
1193
- });
1194
- }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
1195
- return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {});
1196
- }, {}));
1197
- this.setWallets(wallets);
1198
- });
1199
- this.updateWalletIdsFromStorage = () => {
1200
- var _a;
1201
- const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1202
- const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
1203
- const fromJson = JSON.parse(_currentWalletIds);
1204
- return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1205
- const wallet = Object.values(this.wallets).find(
1206
- (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1207
- );
1208
- return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1209
- }, {}) : fromJson;
1210
- })();
1211
- this.setCurrentWalletIds(currentWalletIds);
1212
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1213
- this.findWalletId(void 0, { forbidPregen: true });
1214
- }
1215
- };
1216
- this.updateSessionCookieFromStorage = () => {
1217
- this.sessionCookie = this.localStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE) || void 0;
1218
- };
1219
- this.updateLoginEncryptionKeyPairFromStorage = () => {
1220
- const loginEncryptionKey = this.sessionStorageGetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1221
- if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
1222
- this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
1223
- }
1224
- };
1225
- this.updateExternalWalletsFromStorage = () => {
1226
- const stringExternalWallets = this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);
1227
- const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1228
- this.setExternalWallets(_externalWallets);
1229
- };
1230
- /**
1231
- * Creates several new wallets with the desired types. If no types are provided, this method
1232
- * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
1233
- * object that are not already present. This is automatically called upon account creation to ensure that
1234
- * the user has a wallet of each required type.
1235
- *
1236
- * @deprecated alias for `createWalletPerType`
1237
- **/
1238
- this.createWalletPerMissingType = this.createWalletPerType;
1239
- if (!opts) opts = {};
1240
- let isE2E = false;
1241
- if (env === "E2E") {
1242
- isE2E = true;
1243
- env = "SANDBOX" /* SANDBOX */;
1244
- }
1245
- this.emailPrimaryColor = opts.emailPrimaryColor;
1246
- this.emailTheme = opts.emailTheme;
1247
- this.homepageUrl = opts.homepageUrl;
1248
- this.supportUrl = opts.supportUrl;
1249
- this.xUrl = opts.xUrl;
1250
- this.githubUrl = opts.githubUrl;
1251
- this.linkedinUrl = opts.linkedinUrl;
1252
- this.portalBackgroundColor = opts.portalBackgroundColor;
1253
- this.portalPrimaryButtonColor = opts.portalPrimaryButtonColor;
1254
- this.portalTextColor = opts.portalTextColor;
1255
- this.portalPrimaryButtonTextColor = opts.portalPrimaryButtonTextColor;
1256
- this.portalTheme = opts.portalTheme;
1257
- this.platformUtils = this.getPlatformUtils();
1258
- this.disableProviderModal = this.platformUtils.disableProviderModal;
1259
- if (opts.useStorageOverrides) {
1260
- this.localStorageGetItem = opts.localStorageGetItemOverride;
1261
- this.localStorageSetItem = opts.localStorageSetItemOverride;
1262
- this.sessionStorageGetItem = opts.sessionStorageGetItemOverride;
1263
- this.sessionStorageSetItem = opts.sessionStorageSetItemOverride;
1264
- this.sessionStorageRemoveItem = opts.sessionStorageRemoveItemOverride;
1265
- this.clearStorage = opts.clearStorageOverride;
1266
- }
1267
- if (opts.useSessionStorage) {
1268
- this.localStorageGetItem = this.sessionStorageGetItem;
1269
- this.localStorageSetItem = this.sessionStorageSetItem;
1270
- }
1271
- this.persistSessionCookie = (cookie) => {
1272
- this.sessionCookie = cookie;
1273
- (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
1274
- LOCAL_STORAGE_SESSION_COOKIE,
1275
- cookie
1276
- );
1277
- };
1278
- this.ctx = {
1279
- env,
1280
- apiKey,
1281
- client: initClient({
1282
- env,
1283
- version: _ParaCore.version,
1284
- apiKey,
1285
- partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
1286
- useFetchAdapter: !!opts.disableWorkers,
1287
- retrieveSessionCookie: this.retrieveSessionCookie,
1288
- persistSessionCookie: this.persistSessionCookie
1289
- }),
1290
- disableWorkers: opts.disableWorkers,
1291
- offloadMPCComputationURL: opts.offloadMPCComputationURL,
1292
- useLocalFiles: opts.useLocalFiles,
1293
- useDKLS: opts.useDKLSForCreation || !opts.offloadMPCComputationURL,
1294
- disableWebSockets: !!opts.disableWebSockets,
1295
- wasmOverride: opts.wasmOverride,
1296
- cosmosPrefix: this.cosmosPrefix,
1297
- isE2E
1298
- };
1299
- if (opts.offloadMPCComputationURL) {
1300
- this.ctx.mpcComputationClient = initClient2(opts.offloadMPCComputationURL, opts.disableWorkers);
1301
- }
1302
- try {
1303
- __privateSet(this, _supportedWalletTypes, opts.supportedWalletTypes ? (() => {
1304
- if (Object.values(opts.supportedWalletTypes).every(
1305
- (config) => !!config && typeof config === "object" && config.optional
1306
- )) {
1307
- throw new Error("at least one wallet type must be non-optional");
1308
- }
1309
- if (!Object.keys(opts.supportedWalletTypes).every((type) => Object.values(WalletType2).includes(type))) {
1310
- throw new Error("unsupported wallet type");
1311
- }
1312
- __privateSet(this, _supportedWalletTypesOpt, opts.supportedWalletTypes);
1313
- return Object.entries(opts.supportedWalletTypes).reduce((acc, [key, value]) => {
1314
- var _a;
1315
- if (!value) {
1316
- return acc;
1317
- }
1318
- if (key === WalletType2.COSMOS && typeof value === "object" && !!value.prefix) {
1319
- this.cosmosPrefix = value.prefix;
1320
- }
1321
- return [...acc, { type: key, optional: value === true ? false : (_a = value.optional) != null ? _a : false }];
1322
- }, []);
1323
- })() : void 0);
1324
- } catch (e) {
1325
- __privateSet(this, _supportedWalletTypes, void 0);
1326
- }
1327
- if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
1328
- return;
1329
- }
1330
- this.initializeFromStorage();
1331
- setupListeners.bind(this)();
1332
- }
1333
- get isEmail() {
1334
- return !!this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.telegramUserId && !this.externalWalletWithParaAuth;
1335
- }
1336
- get isPhone() {
1337
- return !!this.phone && !!this.countryCode && !this.email && !this.farcasterUsername && !this.telegramUserId && !this.externalWalletWithParaAuth;
1338
- }
1339
- get isFarcaster() {
1340
- return !!this.farcasterUsername && !this.email && !this.phone && !this.countryCode && !this.telegramUserId && !this.externalWalletWithParaAuth;
1341
- }
1342
- get isTelegram() {
1343
- return !!this.telegramUserId && !this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.externalWalletWithParaAuth;
1344
- }
1345
- get externalWalletWithParaAuth() {
1346
- const externalWallets = Object.values(this.externalWallets);
1347
- return externalWallets.find((w) => w.isExternalWithParaAuth);
1348
- }
1349
- get isExternalWalletAuth() {
1350
- return !!this.externalWalletWithParaAuth && !this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.telegramUserId;
1351
- }
1352
- get currentWalletIdsArray() {
1353
- return this.supportedWalletTypes.reduce((acc, { type }) => {
1354
- var _a;
1355
- return [
1356
- ...acc,
1357
- ...((_a = this.currentWalletIds[type]) != null ? _a : []).map((id) => {
1358
- return [id, type];
1359
- })
1360
- ];
1361
- }, []);
1362
- }
1363
- get currentWalletIdsUnique() {
1364
- return [...new Set(Object.values(this.currentWalletIds).flat())];
1365
- }
1366
- /**
1367
- * A map of pre-generated wallet identifiers that can be claimed in the current instance.
1368
- */
1369
- get pregenIds() {
1370
- return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
1371
- var _a, _b;
1372
- if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
1373
- return acc;
1374
- }
1375
- return __spreadProps(__spreadValues({}, acc), {
1376
- [wallet.pregenIdentifierType]: [
1377
- .../* @__PURE__ */ new Set([...(_b = acc[wallet.pregenIdentifierType]) != null ? _b : [], wallet.pregenIdentifier])
1378
- ]
1379
- });
1380
- }, {}));
1381
- }
1382
- /**
1383
- * Whether the instance has multiple wallets connected.
1384
- */
1385
- get isMultiWallet() {
1386
- return this.currentWalletIdsArray.length > 1;
1387
- }
1388
- get supportedWalletTypes() {
1389
- var _a;
1390
- return (_a = __privateGet(this, _supportedWalletTypes)) != null ? _a : [];
1391
- }
1392
- get isWalletTypeEnabled() {
1393
- return this.supportedWalletTypes.reduce((acc, { type }) => {
1394
- return __spreadProps(__spreadValues({}, acc), { [type]: true });
1395
- }, {});
1396
- }
1397
- convertBigInt(bigInt) {
1398
- const convertedBigInt = new jsbn.BigInteger(null);
1399
- convertedBigInt.data = bigInt.data;
1400
- convertedBigInt.s = bigInt.s;
1401
- convertedBigInt.t = bigInt.t;
1402
- return convertedBigInt;
1403
- }
1404
- convertEncryptionKeyPair(jsonKeyPair) {
1405
- return {
1406
- privateKey: pki.setRsaPrivateKey(
1407
- this.convertBigInt(jsonKeyPair.privateKey.n),
1408
- this.convertBigInt(jsonKeyPair.privateKey.e),
1409
- this.convertBigInt(jsonKeyPair.privateKey.d),
1410
- this.convertBigInt(jsonKeyPair.privateKey.p),
1411
- this.convertBigInt(jsonKeyPair.privateKey.q),
1412
- this.convertBigInt(jsonKeyPair.privateKey.dP),
1413
- this.convertBigInt(jsonKeyPair.privateKey.dQ),
1414
- this.convertBigInt(jsonKeyPair.privateKey.qInv)
1415
- ),
1416
- publicKey: pki.setRsaPublicKey(
1417
- this.convertBigInt(jsonKeyPair.publicKey.n),
1418
- this.convertBigInt(jsonKeyPair.publicKey.e)
1419
- )
1420
- };
1421
- }
1422
- isPortal(envOverride) {
1423
- var _a;
1424
- if (typeof window === "undefined") return false;
1425
- return !!((_a = window.location) == null ? void 0 : _a.host) && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
1426
- }
1427
- isParaConnect() {
1428
- var _a;
1429
- if (typeof window === "undefined") return false;
1430
- return !!((_a = window.location) == null ? void 0 : _a.host) && getParaConnectBaseUrl(this.ctx).includes(window.location.host);
1431
- }
1432
- requireApiKey() {
1433
- if (!this.ctx.apiKey) {
1434
- throw new Error(
1435
- `in order to create a wallet or user with Para, you
1436
- must provide an API key to the Para instance`
1437
- );
1438
- }
1439
- }
1440
- isWalletSupported(wallet) {
1441
- var _a, _b;
1442
- return !__privateGet(this, _supportedWalletTypes) || isWalletSupported((_b = (_a = this.supportedWalletTypes) == null ? void 0 : _a.map(({ type }) => type)) != null ? _b : [], wallet);
1443
- }
1444
- isWalletOwned(wallet) {
1445
- 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;
1446
- }
1447
- isPregenWalletUnclaimed(wallet) {
1448
- 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));
1449
- }
1450
- isPregenWalletClaimable(wallet) {
1451
- return this.isWalletSupported(wallet) && this.isPregenWalletUnclaimed(wallet) && (!["EMAIL", "PHONE", "TELEGRAM"].includes(wallet == null ? void 0 : wallet.pregenIdentifierType) || isPregenIdentifierMatch(
1452
- (wallet == null ? void 0 : wallet.pregenIdentifierType) === "EMAIL" ? this.email : (wallet == null ? void 0 : wallet.pregenIdentifierType) === "TELEGRAM" ? this.telegramUserId : this.getPhoneNumber(),
1453
- wallet == null ? void 0 : wallet.pregenIdentifier,
1454
- wallet == null ? void 0 : wallet.pregenIdentifierType
1455
- ));
1456
- }
1457
- isWalletUsable(walletId, { type: types, scheme: schemes, forbidPregen = false } = {}, throwError = false) {
1458
- var _a;
1459
- let error;
1460
- if ((_a = this.externalWallets) == null ? void 0 : _a[walletId]) {
1461
- return true;
1462
- }
1463
- if (!this.wallets[walletId]) {
1464
- error = `wallet with id ${walletId} does not exist`;
1465
- } else {
1466
- const wallet = this.wallets[walletId];
1467
- const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
1468
- if (forbidPregen && isUnclaimed) {
1469
- error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
1470
- } else if (!isOwned && !isUnclaimed) {
1471
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
1472
- } else if (!this.isWalletSupported(wallet)) {
1473
- 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(", ")}`;
1474
- } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
1475
- var _a2, _b;
1476
- return (_b = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b.includes(walletId);
1477
- }))) {
1478
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} cannot be selected`;
1479
- } else if (schemes && !schemes.includes(wallet == null ? void 0 : wallet.scheme)) {
1480
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and scheme ${wallet == null ? void 0 : wallet.scheme} cannot be selected`;
1481
- }
1482
- }
1483
- if (error) {
1484
- if (throwError) {
1485
- throw new Error(error);
1486
- }
1487
- return false;
1488
- }
1489
- return true;
1490
- }
1491
- /**
1492
- * Returns the formatted address for the desired wallet ID, depending on your app settings.
1493
- * @param {string} walletId the ID of the wallet address to display.
1494
- * @param {object} options additional options for formatting the address.
1495
- * @param {boolean} options.truncate whether to truncate the address.
1496
- * @param {WalletType} options.addressType the type of address to display.
1497
- * @returns the formatted address
1498
- */
1499
- getDisplayAddress(walletId, options = {}) {
1500
- var _a;
1501
- if (this.externalWallets[walletId]) {
1502
- const wallet2 = this.externalWallets[walletId];
1503
- return options.truncate ? truncateAddress(wallet2.address, wallet2.type, { prefix: this.cosmosPrefix }) : wallet2.address;
1504
- }
1505
- const wallet = this.findWallet(walletId, options.addressType);
1506
- if (!wallet) {
1507
- return void 0;
1508
- }
1509
- let str;
1510
- switch (wallet.type) {
1511
- case WalletType2.COSMOS:
1512
- str = getCosmosAddress(wallet.publicKey, (_a = this.cosmosPrefix) != null ? _a : "cosmos");
1513
- break;
1514
- default:
1515
- str = wallet.address;
1516
- break;
1517
- }
1518
- return options.truncate ? truncateAddress(str, wallet.type, { prefix: this.cosmosPrefix }) : str;
1519
- }
1520
- /**
1521
- * Returns a unique hash for a wallet suitable for use as an identicon seed.
1522
- * @param {string} walletId the ID of the wallet.
1523
- * @param {boolean} options.addressType used to format the hash for another wallet type.
1524
- * @returns the identicon hash string
1525
- */
1526
- getIdenticonHash(walletId, overrideType) {
1527
- if (this.externalWallets[walletId]) {
1528
- const wallet2 = this.externalWallets[walletId];
1529
- return `${wallet2.id}-${wallet2.address}-${wallet2.type}`;
1530
- }
1531
- const wallet = this.findWallet(walletId, overrideType);
1532
- return wallet ? `${wallet.id}-${wallet.address}-${wallet.type}` : void 0;
1533
- }
1534
- getWallets() {
1535
- return this.wallets;
1536
- }
1537
- getAddress(walletId) {
1538
- var _a, _b, _c;
1539
- 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;
1540
- }
1541
- constructPortalUrl(_0) {
1542
- return __async(this, arguments, function* (type, opts = {}) {
1543
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1544
- const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : yield this.getPortalURL(opts.partnerId);
1545
- let path;
1546
- switch (type) {
1547
- case "createPassword": {
1548
- path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
1549
- break;
1550
- }
1551
- case "createAuth": {
1552
- path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
1553
- break;
1554
- }
1555
- case "loginPassword": {
1556
- path = "/web/passwords/login";
1557
- break;
1558
- }
1559
- case "loginAuth": {
1560
- path = "/web/biometrics/login";
1561
- break;
1562
- }
1563
- case "txReview": {
1564
- path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
1565
- break;
1566
- }
1567
- case "onRamp": {
1568
- path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
1569
- break;
1570
- }
1571
- default: {
1572
- throw new Error(`invalid URL type ${type}`);
1573
- }
1574
- }
1575
- const [isCreate, isLogin, isOnRamp] = [
1576
- ["createAuth", "createPassword"].includes(type),
1577
- ["loginAuth", "loginPassword"].includes(type),
1578
- type === "onRamp"
1579
- ];
1580
- const partner = opts.partnerId ? (_a = (yield this.ctx.client.getPartner(opts.partnerId)).data) == null ? void 0 : _a.partner : void 0;
1581
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues({
1582
- apiKey: this.ctx.apiKey,
1583
- partnerId: opts.partnerId,
1584
- portalFont: ((_b = opts.theme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
1585
- portalBorderRadius: ((_d = opts.theme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
1586
- portalThemeMode: ((_f = opts.theme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
1587
- portalAccentColor: ((_h = opts.theme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
1588
- portalForegroundColor: ((_j = opts.theme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
1589
- 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),
1590
- portalPrimaryButtonColor: this.portalPrimaryButtonColor,
1591
- portalTextColor: this.portalTextColor,
1592
- portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
1593
- isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0,
1594
- supportedWalletTypes: __privateGet(this, _supportedWalletTypesOpt) ? JSON.stringify(__privateGet(this, _supportedWalletTypesOpt)) : void 0
1595
- }, 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" ? {
1596
- // Using id here since we store the bech32 address for cosmos in the address field of the wallet
1597
- externalWalletAddress: (_n = this.externalWalletWithParaAuth) == null ? void 0 : _n.id
1598
- } : {}) : {}), isLogin || isOnRamp ? { sessionId: opts.sessionId } : {}), isLogin ? {
1599
- encryptionKey: opts.loginEncryptionPublicKey,
1600
- newDeviceSessionLookupId: opts.newDeviceSessionId,
1601
- newDeviceEncryptionKey: opts.newDeviceEncryptionKey,
1602
- pregenIds: JSON.stringify(this.pregenIds),
1603
- displayName: opts.displayName,
1604
- pfpUrl: opts.pfpUrl
1605
- } : {}), opts.params || {});
1606
- return constructUrl({ base, path, params });
1607
- });
1608
- }
1609
- touchSession(regenerate = false) {
1610
- return __async(this, null, function* () {
1611
- const res = yield this.ctx.client.touchSession(regenerate);
1612
- this.setSupportedWalletTypes(res.data.supportedWalletTypes, res.data.cosmosPrefix);
1613
- return res;
1614
- });
1615
- }
1616
- setSupportedWalletTypes(supportedWalletTypes, cosmosPrefix) {
1617
- if (supportedWalletTypes && !__privateGet(this, _supportedWalletTypes)) {
1618
- __privateSet(this, _supportedWalletTypes, supportedWalletTypes);
1619
- Object.keys(this.currentWalletIds).forEach((type) => {
1620
- var _a;
1621
- if (!((_a = __privateGet(this, _supportedWalletTypes)) == null ? void 0 : _a.some(({ type: supportedType }) => supportedType === type))) {
1622
- delete this.currentWalletIds[type];
1623
- }
1624
- });
1625
- }
1626
- if (cosmosPrefix && !this.cosmosPrefix) {
1627
- this.cosmosPrefix = cosmosPrefix;
1628
- }
1629
- }
1630
- getVerificationEmailProps() {
1631
- return {
1632
- brandColor: this.emailPrimaryColor,
1633
- theme: this.emailTheme,
1634
- supportUrl: this.supportUrl,
1635
- homepageUrl: this.homepageUrl,
1636
- xUrl: this.xUrl,
1637
- githubUrl: this.githubUrl,
1638
- linkedinUrl: this.linkedinUrl
1639
- };
1640
- }
1641
- getBackupKitEmailProps() {
1642
- return {
1643
- brandColor: this.emailPrimaryColor,
1644
- theme: this.emailTheme,
1645
- homepageUrl: this.homepageUrl,
1646
- xUrl: this.xUrl,
1647
- linkedinUrl: this.linkedinUrl,
1648
- githubUrl: this.githubUrl,
1649
- supportUrl: this.supportUrl
1650
- };
1651
- }
1652
- /**
1653
- * Initialize storage relating to a `ParaCore` instance.
1654
- *
1655
- * Init only needs to be called for storage that is async.
1656
- */
1657
- init() {
1658
- return __async(this, null, function* () {
1659
- var _a;
1660
- this.email = (yield this.localStorageGetItem(LOCAL_STORAGE_EMAIL)) || void 0;
1661
- this.countryCode = (yield this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE)) || void 0;
1662
- this.phone = (yield this.localStorageGetItem(LOCAL_STORAGE_PHONE)) || void 0;
1663
- this.userId = (yield this.localStorageGetItem(LOCAL_STORAGE_USER_ID)) || void 0;
1664
- this.telegramUserId = (yield this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID)) || void 0;
1665
- const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_WALLETS);
1666
- const _wallets = JSON.parse(stringWallets || "{}");
1667
- const stringEd25519Wallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
1668
- const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
1669
- const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
1670
- return __spreadProps(__spreadValues({}, res), {
1671
- [key]: migrateWallet(_wallets[key])
1672
- });
1673
- }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
1674
- return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {});
1675
- }, {}));
1676
- yield this.setWallets(wallets);
1677
- const _currentWalletIds = (_a = yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1678
- const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
1679
- const fromJson = JSON.parse(_currentWalletIds);
1680
- return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1681
- const wallet = Object.values(this.wallets).find(
1682
- (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1683
- );
1684
- return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1685
- }, {}) : fromJson;
1686
- })();
1687
- yield this.setCurrentWalletIds(currentWalletIds);
1688
- this.sessionCookie = (yield this.localStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1689
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1690
- this.findWalletId(void 0, { forbidPregen: true });
1691
- }
1692
- const loginEncryptionKey = yield this.sessionStorageGetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1693
- if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
1694
- this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
1695
- }
1696
- const stringExternalWallets = yield this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);
1697
- const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1698
- yield this.setExternalWallets(_externalWallets);
1699
- setupListeners.bind(this)();
1700
- yield this.touchSession();
1701
- });
1702
- }
1703
- /**
1704
- * Sets the email associated with the `ParaCore` instance.
1705
- * @param email - Email to set.
1706
- */
1707
- setEmail(email) {
1708
- return __async(this, null, function* () {
1709
- this.email = email;
1710
- yield this.localStorageSetItem(LOCAL_STORAGE_EMAIL, email);
1711
- });
1712
- }
1713
- /**
1714
- * Sets the Telegram user ID associated with the `ParaCore` instance.
1715
- * @param telegramUserId - Telegram user ID to set.
1716
- */
1717
- setTelegramUserId(telegramUserId) {
1718
- return __async(this, null, function* () {
1719
- this.telegramUserId = telegramUserId;
1720
- yield this.localStorageSetItem(LOCAL_STORAGE_TELEGRAM_USER_ID, telegramUserId);
1721
- });
1722
- }
1723
- /**
1724
- * Sets the phone number associated with the `ParaCore` instance.
1725
- * @param phone - Phone number to set.
1726
- * @param countryCode - Country Code to set.
1727
- */
1728
- setPhoneNumber(phone, countryCode) {
1729
- return __async(this, null, function* () {
1730
- this.phone = phone;
1731
- this.countryCode = countryCode;
1732
- yield this.localStorageSetItem(LOCAL_STORAGE_PHONE, phone);
1733
- yield this.localStorageSetItem(LOCAL_STORAGE_COUNTRY_CODE, countryCode);
1734
- });
1735
- }
1736
- /**
1737
- * Sets the farcaster username associated with the `ParaCore` instance.
1738
- * @param farcasterUsername - Farcaster Username to set.
1739
- */
1740
- setFarcasterUsername(farcasterUsername) {
1741
- return __async(this, null, function* () {
1742
- this.farcasterUsername = farcasterUsername;
1743
- yield this.localStorageSetItem(LOCAL_STORAGE_FARCASTER_USERNAME, farcasterUsername);
1744
- });
1745
- }
1746
- /**
1747
- * Sets the external wallet address and type associated with the `ParaCore` instance.
1748
- * @param externalAddress - External wallet address to set.
1749
- * @param externalType - Type of external wallet to set.
1750
- */
1751
- setExternalWallet(_0) {
1752
- return __async(this, arguments, function* ({ address, type, provider, addressBech32, withFullParaAuth }) {
1753
- this.externalWallets = {
1754
- [address]: {
1755
- id: address,
1756
- address: addressBech32 != null ? addressBech32 : address,
1757
- type,
1758
- name: provider,
1759
- isExternal: true,
1760
- isExternalWithParaAuth: withFullParaAuth,
1761
- signer: ""
1762
- }
1763
- };
1764
- this.setExternalWallets(this.externalWallets);
1765
- dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1766
- });
1767
- }
1768
- /**
1769
- * Sets the user id associated with the `ParaCore` instance.
1770
- * @param userId - User id to set.
1771
- */
1772
- setUserId(userId) {
1773
- return __async(this, null, function* () {
1774
- this.userId = userId;
1775
- yield this.localStorageSetItem(LOCAL_STORAGE_USER_ID, userId);
1776
- });
1777
- }
1778
- /**
1779
- * Sets the wallets associated with the `ParaCore` instance.
1780
- * @param wallets - Wallets to set.
1781
- */
1782
- setWallets(wallets) {
1783
- return __async(this, null, function* () {
1784
- this.wallets = wallets;
1785
- if (this.platformUtils.secureStorage) {
1786
- yield this.platformUtils.secureStorage.set(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1787
- return;
1788
- }
1789
- yield this.localStorageSetItem(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1790
- });
1791
- }
1792
- /**
1793
- * Sets the external wallets associated with the `ParaCore` instance.
1794
- * @param externalWallets - External wallets to set.
1795
- */
1796
- setExternalWallets(externalWallets) {
1797
- return __async(this, null, function* () {
1798
- this.externalWallets = externalWallets;
1799
- yield this.localStorageSetItem(LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1800
- });
1801
- }
1802
- /**
1803
- * Sets the login encryption key pair associated with the `ParaCore` instance.
1804
- * @param keyPair - Encryption key pair generated from loginEncryptionKey.
1805
- */
1806
- setLoginEncryptionKeyPair(keyPair) {
1807
- return __async(this, null, function* () {
1808
- if (!keyPair) {
1809
- keyPair = yield getAsymmetricKeyPair(this.ctx);
1810
- }
1811
- this.loginEncryptionKeyPair = keyPair;
1812
- yield this.sessionStorageSetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR, JSON.stringify(keyPair));
1813
- });
1814
- }
1815
- deleteLoginEncryptionKeyPair() {
1816
- return __async(this, null, function* () {
1817
- this.loginEncryptionKeyPair = void 0;
1818
- yield this.sessionStorageRemoveItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1819
- });
1820
- }
1821
- /**
1822
- * Gets the userId associated with the `ParaCore` instance.
1823
- * @returns - userId associated with the `ParaCore` instance.
1824
- */
1825
- getUserId() {
1826
- return this.userId;
1827
- }
1828
- /**
1829
- * Gets the email associated with the `ParaCore` instance.
1830
- * @returns - email associated with the `ParaCore` instance.
1831
- */
1832
- getEmail() {
1833
- return this.email;
1834
- }
1835
- /**
1836
- * Gets the phone object associated with the `ParaCore` instance.
1837
- * @returns - phone object with phone number and country code associated with the `ParaCore` instance.
1838
- */
1839
- getPhone() {
1840
- return { phone: this.phone, countryCode: this.countryCode };
1841
- }
1842
- /**
1843
- * Gets the formatted phone number associated with the `ParaCore` instance.
1844
- * @returns - formatted phone number associated with the `ParaCore` instance.
1845
- */
1846
- getPhoneNumber() {
1847
- if (!this.phone || !this.countryCode) {
1848
- return void 0;
1849
- }
1850
- return normalizePhoneNumber(this.countryCode, this.phone);
1851
- }
1852
- /**
1853
- * Gets the farcaster username associated with the `ParaCore` instance.
1854
- * @returns - farcaster username associated with the `ParaCore` instance.
1855
- */
1856
- getFarcasterUsername() {
1857
- return this.farcasterUsername;
1858
- }
1859
- setCurrentWalletIds(_0) {
1860
- return __async(this, arguments, function* (currentWalletIds, {
1861
- needsWallet = false,
1862
- sessionLookupId,
1863
- newDeviceSessionLookupId
1864
- } = {}) {
1865
- this.currentWalletIds = currentWalletIds;
1866
- yield this.localStorageSetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS, JSON.stringify(this.currentWalletIds));
1867
- if (sessionLookupId) {
1868
- yield this.ctx.client.setCurrentWalletIds(
1869
- this.getUserId(),
1870
- this.currentWalletIds,
1871
- needsWallet,
1872
- sessionLookupId,
1873
- newDeviceSessionLookupId
1874
- );
1875
- }
1876
- dispatchEvent(ParaEvent.WALLETS_CHANGE_EVENT, null);
1877
- });
1878
- }
1879
- /**
1880
- * Fetches the most recent OAuth account metadata for the signed-in user.
1881
- * 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.
1882
- * @returns {Promise<AccountMetadata>} the user's account metadata.
1883
- */
1884
- getAccountMetadata() {
1885
- return __async(this, null, function* () {
1886
- if (!(yield this.isSessionActive()) || !this.userId) {
1887
- throw new Error("no signed-in user");
1888
- }
1889
- const {
1890
- data: { partnerId }
1891
- } = yield this.touchSession();
1892
- const { accountMetadata } = yield this.ctx.client.getAccountMetadata(this.userId, partnerId);
1893
- return accountMetadata;
1894
- });
1895
- }
1896
- /**
1897
- * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
1898
- * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
1899
- * @param {string} [walletId] the wallet ID to validate.
1900
- * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1901
- * @returns {string} the wallet ID originally passed, or the one found.
1902
- */
1903
- findWalletId(walletId, filter = {}) {
1904
- if (walletId) {
1905
- this.assertIsValidWalletId(walletId, filter);
1906
- } else {
1907
- for (const id of [...this.currentWalletIdsUnique, ...Object.keys(this.wallets)]) {
1908
- if (this.isWalletUsable(id, filter)) {
1909
- walletId = id;
1910
- break;
1911
- }
1912
- }
1913
- if (!walletId) {
1914
- throw new Error(`no valid wallet id found`);
1915
- }
1916
- }
1917
- return walletId;
1918
- }
1919
- /**
1920
- * Retrieves a wallet with the given address, if present.
1921
- * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
1922
- * @param {string} [walletId] the wallet ID to validate.
1923
- * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1924
- * @returns {string} the wallet ID originally passed, or the one found.
1925
- */
1926
- findWalletByAddress(address, filter) {
1927
- if (this.externalWallets[address]) {
1928
- return this.externalWallets[address];
1929
- }
1930
- let wallet;
1931
- Object.entries(this.currentWalletIds).forEach(([type, walletIds]) => {
1932
- const pregenWalletIds = Object.keys(this.wallets).filter(
1933
- (id) => this.wallets[id].type === type && this.isPregenWalletClaimable(this.wallets[id])
1934
- );
1935
- [...walletIds, ...pregenWalletIds].forEach((id) => {
1936
- if (address.toLowerCase() === this.getDisplayAddress(id, { addressType: type }).toLowerCase()) {
1937
- wallet = this.wallets[id];
1938
- }
1939
- });
1940
- });
1941
- if (!wallet) {
1942
- throw new Error(`wallet with address ${address} not found`);
1943
- }
1944
- this.assertIsValidWalletId(wallet.id, filter);
1945
- return wallet;
1946
- }
1947
- findWallet(idOrAddress, overrideType, filter = {}) {
1948
- var _a, _c, _d;
1949
- if (!this.isExternalWalletAuth && !idOrAddress && Object.keys(this.externalWallets).length > 0) {
1950
- return Object.values(this.externalWallets)[0];
1951
- }
1952
- if ((_a = this.externalWallets) == null ? void 0 : _a[idOrAddress]) {
1953
- return this.externalWallets[idOrAddress];
1954
- }
1955
- try {
1956
- const walletId = this.findWalletId(idOrAddress, filter);
1957
- if (walletId && !!this.wallets[walletId]) {
1958
- const _b = this.wallets[walletId], { signer: _signer } = _b, wallet = __objRest(_b, ["signer"]);
1959
- const type = (_d = overrideType != null ? overrideType : (_c = this.currentWalletIdsArray.find(([id]) => id === walletId)) == null ? void 0 : _c[1]) != null ? _d : wallet.type;
1960
- return __spreadProps(__spreadValues({}, wallet), {
1961
- type: WalletType2[type]
1962
- });
1963
- }
1964
- } catch (e) {
1965
- return void 0;
1966
- }
1967
- }
1968
- get availableWallets() {
1969
- var _a;
1970
- return [
1971
- ...this.currentWalletIdsArray.map(([address, type]) => [address, type, false]).map(([id, type]) => {
1972
- const wallet = this.findWallet(id, type);
1973
- if (!wallet) return null;
1974
- return {
1975
- id: wallet.id,
1976
- type,
1977
- address: this.getDisplayAddress(id, { addressType: type }),
1978
- name: wallet.name
1979
- };
1980
- }).filter((obj) => obj !== null),
1981
- ...Object.values((_a = this.externalWallets) != null ? _a : {})
1982
- ];
1983
- }
1984
- /**
1985
- * Retrieves all usable wallets with the provided type (`'EVM' | 'COSMOS' | 'SOLANA'`)
1986
- * @param {string} type the wallet type to filter by.
1987
- * @returns {Wallet[]} an array of matching wallets.
1988
- */
1989
- getWalletsByType(type) {
1990
- return Object.values(this.wallets).filter((w) => this.isWalletUsable(w.id, { type: [type] }));
1991
- }
1992
- assertIsValidWalletId(walletId, condition = {}) {
1993
- this.isWalletUsable(walletId, condition, true);
1994
- }
1995
- assertIsValidWalletType(type, walletTypes) {
1996
- return __async(this, null, function* () {
1997
- if (!__privateGet(this, _supportedWalletTypes)) {
1998
- yield this.touchSession();
1999
- }
2000
- if (!type || !Object.values(WalletType2).includes(type) || !(walletTypes != null ? walletTypes : this.supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
2001
- throw new Error(`wallet type ${type} is not supported`);
2002
- }
2003
- return type;
2004
- });
2005
- }
2006
- getMissingTypes() {
2007
- return __async(this, null, function* () {
2008
- if (!__privateGet(this, _supportedWalletTypes)) {
2009
- yield this.touchSession();
2010
- }
2011
- return this.supportedWalletTypes.filter(
2012
- ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !WalletSchemeTypeMap[w.scheme][t])
2013
- ).map(({ type }) => type);
2014
- });
2015
- }
2016
- getTypesToCreate(types) {
2017
- return __async(this, null, function* () {
2018
- if (!__privateGet(this, _supportedWalletTypes)) {
2019
- yield this.touchSession();
2020
- }
2021
- return getSchemes(types != null ? types : yield this.getMissingTypes()).map((scheme) => {
2022
- switch (scheme) {
2023
- case WalletScheme2.ED25519:
2024
- return WalletType2.SOLANA;
2025
- default:
2026
- return this.supportedWalletTypes.some(({ type, optional }) => type === WalletType2.COSMOS && !optional) ? WalletType2.COSMOS : WalletType2.EVM;
2027
- }
2028
- });
2029
- });
2030
- }
2031
- getPartnerURL(partnerId) {
2032
- return __async(this, null, function* () {
2033
- const res = yield this.ctx.client.getPartner(partnerId);
2034
- return res.data.partner.portalUrl;
2035
- });
2036
- }
2037
- /**
2038
- * URL of the portal, which can be associated with a partner id
2039
- * @param partnerId: string - id of the partner to get the portal URL for
2040
- * @returns - portal URL
2041
- */
2042
- getPortalURL(partnerId) {
2043
- return __async(this, null, function* () {
2044
- return partnerId && (yield this.getPartnerURL(partnerId)) || getPortalBaseURL(this.ctx);
2045
- });
2046
- }
2047
- getWebAuthURLForCreate(_a) {
2048
- return __async(this, null, function* () {
2049
- var _b = _a, {
2050
- webAuthId
2051
- } = _b, options = __objRest(_b, [
2052
- "webAuthId"
2053
- ]);
2054
- return this.constructPortalUrl("createAuth", __spreadProps(__spreadValues({}, options), { pathId: webAuthId }));
2055
- });
2056
- }
2057
- getPasswordURLForCreate(_c) {
2058
- return __async(this, null, function* () {
2059
- var _d = _c, {
2060
- passwordId
2061
- } = _d, options = __objRest(_d, [
2062
- "passwordId"
2063
- ]);
2064
- return this.constructPortalUrl("createPassword", __spreadProps(__spreadValues({}, options), {
2065
- pathId: passwordId
2066
- }));
2067
- });
2068
- }
2069
- getShortUrl(compressedUrl) {
2070
- return constructUrl({
2071
- base: getPortalBaseURL(this.ctx),
2072
- path: `/short/${compressedUrl}`
2073
- });
2074
- }
2075
- shortenLoginLink(link) {
2076
- return __async(this, null, function* () {
2077
- const url = yield upload(link, this.ctx.client);
2078
- return this.getShortUrl(url);
2079
- });
2080
- }
2081
- /**
2082
- * Generates a URL for registering a new WebAuth passkey.
2083
- * @param {GetWebAuthUrlForLoginParams} opts the options object
2084
- * @returns - the URL for creating a new passkey
2085
- */
2086
- getWebAuthURLForLogin(opts) {
2087
- return __async(this, null, function* () {
2088
- return this.constructPortalUrl("loginAuth", opts);
2089
- });
2090
- }
2091
- /**
2092
- * Generates a URL for registering a new user password.
2093
- * @param {GetWebAuthUrlForLoginParams} opts the options object
2094
- * @returns - the URL for creating a new password
2095
- */
2096
- getPasswordURLForLogin(opts) {
2097
- return __async(this, null, function* () {
2098
- return this.constructPortalUrl("loginPassword", opts);
2099
- });
2100
- }
2101
- /**
2102
- * Generates a URL for registering a new WebAuth passkey for a phone number.
2103
- * @param {Omit<GetWebAuthUrlForLoginParams, 'authType'>} opts the options object
2104
- * @returns - web auth url
2105
- */
2106
- getWebAuthURLForLoginForPhone(opts) {
2107
- return __async(this, null, function* () {
2108
- return this.constructPortalUrl("loginAuth", __spreadValues({
2109
- authType: "phone"
2110
- }, opts));
2111
- });
2112
- }
2113
- /**
2114
- * Gets the private key for the given wallet.
2115
- * @param {string } [walletId] id of the wallet to get the private key for. Will default to the first wallet if not provided.
2116
- * @returns - the private key string.
2117
- */
2118
- getPrivateKey(walletId) {
2119
- return __async(this, null, function* () {
2120
- const wallets = Object.values(this.wallets);
2121
- const wallet = walletId ? this.wallets[walletId] : wallets == null ? void 0 : wallets[0];
2122
- if (!wallet) {
2123
- throw new Error("wallet not found");
2124
- }
2125
- if (wallet.scheme !== WalletScheme2.DKLS) {
2126
- throw new Error("invalid wallet scheme");
2127
- }
2128
- return yield this.platformUtils.getPrivateKey(
2129
- this.ctx,
2130
- this.userId,
2131
- wallet.id,
2132
- wallet.signer,
2133
- this.retrieveSessionCookie()
2134
- );
2135
- });
2136
- }
2137
- /**
2138
- * Fetches the wallets associated with the user.
2139
- * @returns {WalletEntity[]} wallets that were fetched.
2140
- */
2141
- fetchWallets() {
2142
- return __async(this, null, function* () {
2143
- const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
2144
- return res.data.wallets.filter(
2145
- (wallet) => !!wallet.address && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported(entityToWallet(wallet)))
2146
- );
2147
- });
2148
- }
2149
- populateWalletAddresses() {
2150
- return __async(this, null, function* () {
2151
- const res = yield this.ctx.client.getWallets(this.userId, true);
2152
- const wallets = res.data.wallets;
2153
- wallets.forEach((entity) => {
2154
- if (this.wallets[entity.id]) {
2155
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
2156
- }
2157
- });
2158
- yield this.setWallets(this.wallets);
2159
- });
2160
- }
2161
- populatePregenWalletAddresses() {
2162
- return __async(this, null, function* () {
2163
- const res = yield this.getPregenWallets();
2164
- res.forEach((entity) => {
2165
- if (this.wallets[entity.id]) {
2166
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
2167
- }
2168
- });
2169
- yield this.setWallets(this.wallets);
2170
- });
2171
- }
2172
- /**
2173
- * Checks if a user exists for an email address.
2174
- * @param {Object} opts the options object
2175
- * @param {string} opts.email the email to check.
2176
- * @returns true if user exists, false otherwise.
2177
- */
2178
- checkIfUserExists(_0) {
2179
- return __async(this, arguments, function* ({ email }) {
2180
- const res = yield this.ctx.client.checkUserExists({ email });
2181
- return res.data.exists;
2182
- });
2183
- }
2184
- /**
2185
- * Checks if a user exists for a phone number.
2186
- * @param {Object} opts the options object
2187
- * @param {string} opts.phone - phone number to check.
2188
- * @param {string} opts.countryCode - the country code.
2189
- * @returns true if user exists, false otherwise.
2190
- */
2191
- checkIfUserExistsByPhone(_0) {
2192
- return __async(this, arguments, function* ({ phone, countryCode }) {
2193
- const res = yield this.ctx.client.checkUserExists({ phone, countryCode });
2194
- return res.data.exists;
2195
- });
2196
- }
2197
- /**
2198
- * Creates a new user.
2199
- * @param {Object} opts the options object
2200
- * @param {string} opts.email the email to use.
2201
- */
2202
- createUser(_0) {
2203
- return __async(this, arguments, function* ({ email }) {
2204
- this.requireApiKey();
2205
- yield this.setEmail(email);
2206
- const { userId } = yield this.ctx.client.createUser(__spreadValues({
2207
- email: this.email
2208
- }, this.getVerificationEmailProps()));
2209
- yield this.setUserId(userId);
2210
- });
2211
- }
2212
- /**
2213
- * Creates a new user with a phone number.
2214
- * @param {Object} opts the options object
2215
- * @param {string} opts.phone - the phone number to use for creating the user.
2216
- * @param {string} opts.countryCode - the country code to use for creating the user.
2217
- */
2218
- createUserByPhone(_0) {
2219
- return __async(this, arguments, function* ({ phone, countryCode }) {
2220
- this.requireApiKey();
2221
- yield this.setPhoneNumber(phone, countryCode);
2222
- const { userId } = yield this.ctx.client.createUser({
2223
- phone: this.phone,
2224
- countryCode: this.countryCode
2225
- });
2226
- yield this.setUserId(userId);
2227
- });
2228
- }
2229
- /**
2230
- * Logs in or creates a new user using an external wallet address.
2231
- * @param {Object} opts the options object
2232
- * @param {string} opts.address the external wallet address to use for identification.
2233
- * @param {WalletType} opts.type type of external wallet to use for identification.
2234
- * @param {string} opts.provider the name of the provider for the external wallet.
2235
- */
2236
- externalWalletLogin(wallet) {
2237
- return __async(this, null, function* () {
2238
- this.requireApiKey();
2239
- const res = yield this.ctx.client.externalWalletLogin({
2240
- externalAddress: wallet.address,
2241
- type: wallet.type,
2242
- externalWalletProvider: wallet.provider,
2243
- // If the wallet isn't using full Para auth we want to track the login here
2244
- shouldTrackUser: !wallet.withFullParaAuth
2245
- });
2246
- yield this.setExternalWallet(wallet);
2247
- yield this.setUserId(res.userId);
2248
- return res;
2249
- });
2250
- }
2251
- /**
2252
- * Returns whether or not the user is connected with only an external wallet, not an external wallet with Para auth.
2253
- */
2254
- isUsingExternalWallet() {
2255
- return !this.isExternalWalletAuth && !!Object.keys(this.externalWallets).length;
2256
- }
2257
- /**
2258
- * Passes the email code obtained from the user for verification.
2259
- * @param {Object} opts the options object
2260
- * @param {string} verificationCode the six-digit code to check
2261
- * @returns {string} the web auth url for creating a new credential
2262
- */
2263
- verifyEmail(_0) {
2264
- return __async(this, arguments, function* ({ verificationCode }) {
2265
- yield this.ctx.client.verifyEmail(this.userId, { verificationCode });
2266
- return this.getSetUpBiometricsURL();
2267
- });
2268
- }
2269
- verifyExternalWallet(_0) {
2270
- return __async(this, arguments, function* ({
2271
- address,
2272
- signedMessage,
2273
- cosmosPublicKeyHex,
2274
- cosmosSigner
2275
- }) {
2276
- yield this.ctx.client.verifyExternalWallet(this.userId, { address, signedMessage, cosmosPublicKeyHex, cosmosSigner });
2277
- return this.getSetUpBiometricsURL({ authType: "externalWallet" });
2278
- });
2279
- }
2280
- /**
2281
- * Passes the phone code obtained from the user for verification.
2282
- * @param {Object} opts the options object
2283
- * @param {string} verificationCode the six-digit code to check
2284
- * @returns {string} the web auth url for creating a new credential
2285
- */
2286
- verifyPhone(_0) {
2287
- return __async(this, arguments, function* ({ verificationCode }) {
2288
- yield this.ctx.client.verifyPhone(this.userId, { verificationCode });
2289
- return this.getSetUpBiometricsURLForPhone();
2290
- });
2291
- }
2292
- /**
2293
- * Validates the response received from an attempted Telegram login for authenticity, then
2294
- * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
2295
- * @param authResponse - the response JSON object received from the Telegram widget.
2296
- * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
2297
- */
2298
- verifyTelegram(authObject) {
2299
- return __async(this, null, function* () {
2300
- const res = yield this.ctx.client.verifyTelegram(authObject);
2301
- if (res.isValid) {
2302
- yield this.setUserId(res.userId);
2303
- yield this.setTelegramUserId(res.telegramUserId);
2304
- yield this.touchSession(true);
2305
- if (!this.loginEncryptionKeyPair) {
2306
- yield this.setLoginEncryptionKeyPair();
2307
- }
2308
- }
2309
- return res;
2310
- });
2311
- }
2312
- /**
2313
- * Performs 2FA verification.
2314
- * @param {Object} opts the options object
2315
- * @param {string} opts.email the email to use for performing a 2FA verification.
2316
- * @param {string} opts.verificationCode the verification code to received via 2FA.
2317
- * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2318
- */
2319
- verify2FA(_0) {
2320
- return __async(this, arguments, function* ({ email, verificationCode }) {
2321
- const res = yield this.ctx.client.verify2FA(email, verificationCode);
2322
- return {
2323
- initiatedAt: res.data.initiatedAt,
2324
- status: res.data.status,
2325
- userId: res.data.userId,
2326
- wallets: res.data.wallets
2327
- };
2328
- });
2329
- }
2330
- /**
2331
- * Performs 2FA verification.
2332
- * @param {Object} opts the options object
2333
- * @param {string} opts.phone the phone number
2334
- * @param {string} opts.countryCode - the country code
2335
- * @param {string} opts.verificationCode - verification code to received via 2FA.
2336
- * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2337
- */
2338
- verify2FAForPhone(_0) {
2339
- return __async(this, arguments, function* ({
2340
- phone,
2341
- countryCode,
2342
- verificationCode
2343
- }) {
2344
- const res = yield this.ctx.client.verify2FAForPhone(phone, countryCode, verificationCode);
2345
- return {
2346
- initiatedAt: res.data.initiatedAt,
2347
- status: res.data.status,
2348
- userId: res.data.userId,
2349
- wallets: res.data.wallets
2350
- };
2351
- });
2352
- }
2353
- /**
2354
- * Sets up two-factor authentication for the current user.
2355
- * @returns {string} uri - uri to use for setting up 2FA
2356
- * */
2357
- setup2FA() {
2358
- return __async(this, null, function* () {
2359
- const res = yield this.ctx.client.setup2FA(this.userId);
2360
- return {
2361
- uri: res.data.uri
2362
- };
2363
- });
2364
- }
2365
- /**
2366
- * Enables 2FA.
2367
- * @param {Object} opts the options object
2368
- * @param {string} opts.verificationCode - the verification code received via 2FA.
2369
- */
2370
- enable2FA(_0) {
2371
- return __async(this, arguments, function* ({ verificationCode }) {
2372
- yield this.ctx.client.enable2FA(this.userId, verificationCode);
2373
- });
2374
- }
2375
- /**
2376
- * Determines if 2FA has been set up.
2377
- * @returns {Object} `{ isSetup: boolean }` - true if 2FA is setup, false otherwise
2378
- */
2379
- check2FAStatus() {
2380
- return __async(this, null, function* () {
2381
- if (!this.userId) {
2382
- return { isSetup: false };
2383
- }
2384
- const res = yield this.ctx.client.check2FAStatus(this.userId);
2385
- return {
2386
- isSetup: res.data.isSetup
2387
- };
2388
- });
2389
- }
2390
- /**
2391
- * Resend a verification email for the current user.
2392
- */
2393
- resendVerificationCode() {
2394
- return __async(this, null, function* () {
2395
- yield this.ctx.client.resendVerificationCode(__spreadValues({
2396
- userId: this.userId
2397
- }, this.getVerificationEmailProps()));
2398
- });
2399
- }
2400
- /**
2401
- * Resend a verification SMS for the current user.
2402
- */
2403
- resendVerificationCodeByPhone() {
2404
- return __async(this, null, function* () {
2405
- yield this.ctx.client.resendVerificationCodeByPhone({
2406
- userId: this.userId
2407
- });
2408
- });
2409
- }
2410
- /**
2411
- * Returns a URL for setting up a new WebAuth passkey.
2412
- * @param {Object} opts the options object
2413
- * @param {string} opts.authType - the auth type to use
2414
- * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2415
- * @returns {string} the URL
2416
- */
2417
- getSetUpBiometricsURL() {
2418
- return __async(this, arguments, function* ({
2419
- authType = "email",
2420
- isForNewDevice = false
2421
- } = {}) {
2422
- const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2423
- status: PublicKeyStatus.PENDING,
2424
- type: PublicKeyType.WEB
2425
- });
2426
- return this.getWebAuthURLForCreate({
2427
- authType,
2428
- isForNewDevice,
2429
- webAuthId: res.data.id,
2430
- partnerId: res.data.partnerId
2431
- });
2432
- });
2433
- }
2434
- /**
2435
- * Returns a URL for setting up a new WebAuth passkey for a phone number.
2436
- * @param {Object} opts the options object
2437
- * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2438
- * @returns {string} the URL
2439
- */
2440
- getSetUpBiometricsURLForPhone() {
2441
- return __async(this, arguments, function* ({
2442
- isForNewDevice = false
2443
- } = {}) {
2444
- const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2445
- status: PublicKeyStatus.PENDING,
2446
- type: PublicKeyType.WEB
2447
- });
2448
- return this.getWebAuthURLForCreate({
2449
- authType: "phone",
2450
- isForNewDevice,
2451
- webAuthId: res.data.id,
2452
- partnerId: res.data.partnerId
2453
- });
2454
- });
2455
- }
2456
- /**
2457
- * Returns a URL for setting up a new password.
2458
- * @param {Object} opts the options object
2459
- * @param {string} opts.authType - the auth type to use
2460
- * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2461
- * @param {Theme} [opts.theme] the portal theme to use in place of the partner's default
2462
- * @returns {string} the URL
2463
- */
2464
- getSetupPasswordURL() {
2465
- return __async(this, arguments, function* ({
2466
- authType = "email",
2467
- isForNewDevice = false,
2468
- theme
2469
- } = {}) {
2470
- const res = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2471
- status: PasswordStatus.PENDING
2472
- });
2473
- return this.getPasswordURLForCreate({
2474
- authType,
2475
- isForNewDevice,
2476
- passwordId: res.data.id,
2477
- partnerId: res.data.partnerId,
2478
- theme
2479
- });
2480
- });
2481
- }
2482
- /**
2483
- * Checks if the current session is active.
2484
- * @returns `true` if active, `false` otherwise
2485
- */
2486
- isSessionActive() {
2487
- return __async(this, null, function* () {
2488
- if (this.isUsingExternalWallet()) {
2489
- return true;
2490
- }
2491
- const res = yield this.touchSession();
2492
- return !!res.data.isAuthenticated;
2493
- });
2494
- }
2495
- /**
2496
- * Checks if a session is active and a wallet exists.
2497
- * @returns `true` if active, `false` otherwise
2498
- **/
2499
- isFullyLoggedIn() {
2500
- return __async(this, null, function* () {
2501
- if (this.isUsingExternalWallet()) {
2502
- return true;
2503
- }
2504
- const isSessionActive = yield this.isSessionActive();
2505
- return isSessionActive && this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true);
2506
- });
2507
- }
2508
- supportedAuthMethods(auth) {
2509
- return __async(this, null, function* () {
2510
- const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
2511
- const authMethods = /* @__PURE__ */ new Set();
2512
- for (const type of supportedAuthMethods) {
2513
- switch (type) {
2514
- case "PASSWORD":
2515
- authMethods.add(AuthMethod.PASSWORD);
2516
- break;
2517
- case "BIOMETRIC":
2518
- authMethods.add(AuthMethod.PASSKEY);
2519
- break;
2520
- }
2521
- }
2522
- return authMethods;
2523
- });
2524
- }
2525
- /**
2526
- * Get hints associated with the users stored biometrics.
2527
- * @returns Array containing useragents and AAGuids for stored biometrics
2528
- */
2529
- getUserBiometricLocationHints() {
2530
- return __async(this, null, function* () {
2531
- var _a;
2532
- if (!this.email && !this.phone && !this.farcasterUsername && !this.telegramUserId && !this.isExternalWalletAuth) {
2533
- throw new Error(
2534
- "one of email, phone, farcaster username, telegram user id or external wallet with Para auth are required to get biometric location hints"
2535
- );
2536
- }
2537
- return yield this.ctx.client.getBiometricLocationHints({
2538
- email: this.email,
2539
- phone: this.phone,
2540
- countryCode: this.countryCode,
2541
- farcasterUsername: this.farcasterUsername,
2542
- telegramUserId: this.telegramUserId,
2543
- // Using id here since we store the bech32 address for cosmos in the address field of the wallet
2544
- externalWalletAddress: (_a = this.externalWalletWithParaAuth) == null ? void 0 : _a.id
2545
- });
2546
- });
2547
- }
2548
- setAuth(auth) {
2549
- return __async(this, null, function* () {
2550
- const authInfo = extractAuthInfo(auth);
2551
- if (!authInfo) {
2552
- return void 0;
2553
- }
2554
- switch (authInfo.authType) {
2555
- case "email":
2556
- yield this.setEmail(authInfo.identifier);
2557
- break;
2558
- case "phone":
2559
- yield this.setPhoneNumber(authInfo.auth.phone, authInfo.auth.countryCode);
2560
- break;
2561
- case "farcaster":
2562
- yield this.setFarcasterUsername(authInfo.identifier);
2563
- break;
2564
- case "telegram":
2565
- yield this.setTelegramUserId(authInfo.identifier);
2566
- break;
2567
- }
2568
- return authInfo;
2569
- });
2570
- }
2571
- /**
2572
- * Initiates a login.
2573
- * @param {Object} opts the options object
2574
- * @param {String} opts.email - the email to login with
2575
- * @param {boolean} opts.useShortURL - whether to shorten the link
2576
- * @returns - the WebAuth URL for logging in
2577
- **/
2578
- initiateUserLogin(_e) {
2579
- return __async(this, null, function* () {
2580
- var _f = _e, { useShortUrl = false } = _f, auth = __objRest(_f, ["useShortUrl"]);
2581
- const authInfo = yield this.setAuth(auth);
2582
- if (!authInfo) {
2583
- return;
2584
- }
2585
- const res = yield this.touchSession(true);
2586
- if (!this.loginEncryptionKeyPair) {
2587
- yield this.setLoginEncryptionKeyPair();
2588
- }
2589
- const webAuthLoginURL = yield this.getWebAuthURLForLogin({
2590
- authType: authInfo.authType,
2591
- sessionId: res.data.sessionId,
2592
- partnerId: res.data.partnerId,
2593
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2594
- });
2595
- if (!useShortUrl) {
2596
- return webAuthLoginURL;
2597
- }
2598
- return this.shortenLoginLink(webAuthLoginURL);
2599
- });
2600
- }
2601
- /**
2602
- * Initiates a login.
2603
- * @param email - the email to login with
2604
- * @returns - a set of supported auth methods for the user
2605
- **/
2606
- initiateUserLoginV2(auth) {
2607
- return __async(this, null, function* () {
2608
- const authInfo = yield this.setAuth(auth);
2609
- if (!authInfo) {
2610
- return;
2611
- }
2612
- yield this.touchSession(true);
2613
- if (!this.loginEncryptionKeyPair) {
2614
- yield this.setLoginEncryptionKeyPair();
2615
- }
2616
- return yield this.supportedAuthMethods(authInfo.auth);
2617
- });
2618
- }
2619
- /**
2620
- * Initiates a login.
2621
- * @param opts the options object
2622
- * @param opts.phone the phone number
2623
- * @param opts.countryCode the country code
2624
- * @param opts.useShortURL - whether to shorten the link
2625
- * @returns - the WebAuth URL for logging in
2626
- **/
2627
- initiateUserLoginForPhone(_g) {
2628
- return __async(this, null, function* () {
2629
- var _h = _g, {
2630
- useShortUrl = false
2631
- } = _h, auth = __objRest(_h, [
2632
- "useShortUrl"
2633
- ]);
2634
- yield this.setAuth(auth);
2635
- const res = yield this.touchSession(true);
2636
- if (!this.loginEncryptionKeyPair) {
2637
- yield this.setLoginEncryptionKeyPair();
2638
- }
2639
- const webAuthLoginURL = yield this.getWebAuthURLForLoginForPhone({
2640
- sessionId: res.data.sessionId,
2641
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair),
2642
- partnerId: res.data.partnerId
2643
- });
2644
- if (!useShortUrl) {
2645
- return webAuthLoginURL;
2646
- }
2647
- return this.shortenLoginLink(webAuthLoginURL);
2648
- });
2649
- }
2650
- /**
2651
- * Waits for the session to be active.
2652
- **/
2653
- waitForAccountCreation() {
2654
- return __async(this, arguments, function* ({ popupWindow } = {}) {
2655
- yield this.touchSession();
2656
- if (!this.isExternalWalletAuth) {
2657
- this.externalWallets = {};
2658
- }
2659
- this.isAwaitingAccountCreation = true;
2660
- while (this.isAwaitingAccountCreation) {
2661
- try {
2662
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2663
- if (yield this.isSessionActive()) {
2664
- this.isAwaitingAccountCreation = false;
2665
- dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, true);
2666
- return true;
2667
- } else {
2668
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2669
- this.isAwaitingAccountCreation = false;
2670
- return false;
2671
- }
2672
- }
2673
- } catch (err) {
2674
- console.error(err);
2675
- }
2676
- }
2677
- return false;
2678
- });
2679
- }
2680
- waitForPasskeyAndCreateWallet() {
2681
- return __async(this, arguments, function* ({
2682
- popupWindow
2683
- } = {}) {
2684
- yield this.waitForAccountCreation({ popupWindow });
2685
- const pregenWallets = yield this.getPregenWallets();
2686
- let recoverySecret, walletIds = {};
2687
- if (pregenWallets.length > 0) {
2688
- recoverySecret = yield this.claimPregenWallets();
2689
- walletIds = this.supportedWalletTypes.reduce((acc, { type }) => {
2690
- var _a;
2691
- return __spreadProps(__spreadValues({}, acc), {
2692
- [type]: [(_a = pregenWallets.find((w) => !!WalletSchemeTypeMap[w.scheme][type])) == null ? void 0 : _a.id]
2693
- });
2694
- }, {});
2695
- }
2696
- const created = yield this.createWalletPerType();
2697
- recoverySecret = recoverySecret != null ? recoverySecret : created.recoverySecret;
2698
- walletIds = __spreadValues(__spreadValues({}, walletIds), created.walletIds);
2699
- const resp = { walletIds, recoverySecret };
2700
- dispatchEvent(ParaEvent.ACCOUNT_SETUP_EVENT, resp);
2701
- return resp;
2702
- });
2703
- }
2704
- /**
2705
- * Initiates a Farcaster login attempt and return the URI for the user to connect.
2706
- * You can create a QR code with this URI that works with Farcaster's mobile app.
2707
- * @return {string} the Farcaster connect URI
2708
- */
2709
- getFarcasterConnectURL() {
2710
- return __async(this, null, function* () {
2711
- yield this.logout();
2712
- yield this.touchSession(true);
2713
- const {
2714
- data: { connect_uri }
2715
- } = yield this.ctx.client.initializeFarcasterLogin();
2716
- return connect_uri;
2717
- });
2718
- }
2719
- /**
2720
- * Awaits the response from a user's attempt to log in with Farcaster.
2721
- * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
2722
- * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
2723
- */
2724
- waitForFarcasterStatus() {
2725
- return __async(this, null, function* () {
2726
- this.isAwaitingFarcaster = true;
2727
- while (this.isAwaitingFarcaster) {
2728
- try {
2729
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2730
- const res = yield this.ctx.client.getFarcasterAuthStatus();
2731
- if (res.data.state === "completed") {
2732
- const { userId, userExists, username, pfpUrl } = res.data;
2733
- yield this.setUserId(userId);
2734
- yield this.setFarcasterUsername(username);
2735
- return {
2736
- userExists,
2737
- username,
2738
- pfpUrl
2739
- };
2740
- }
2741
- } catch (err) {
2742
- console.error(err);
2743
- this.isAwaitingFarcaster = false;
2744
- }
2745
- }
2746
- });
2747
- }
2748
- /**
2749
- * Generates a URL for the user to log in with OAuth using a desire method.
2750
- *
2751
- * @param {Object} opts the options object
2752
- * @param {OAuthMethod} opts.method the third-party service to use for OAuth.
2753
- * @param {string} [opts.deeplinkUrl] the deeplink to redirect to after the OAuth flow. This is for mobile only.
2754
- * @returns {string} the URL for the user to log in with OAuth.
2755
- */
2756
- getOAuthURL(_0) {
2757
- return __async(this, arguments, function* ({ method, deeplinkUrl }) {
2758
- yield this.logout();
2759
- const res = yield this.touchSession(true);
2760
- return constructUrl({
2761
- base: method === OAuthMethod.TELEGRAM ? getPortalBaseURL(this.ctx, true) : getBaseOAuthUrl(this.ctx.env),
2762
- path: `/auth/${method.toLowerCase()}`,
2763
- params: {
2764
- apiKey: this.ctx.apiKey,
2765
- sessionLookupId: res.data.sessionLookupId,
2766
- deeplinkUrl
2767
- }
2768
- });
2769
- });
2770
- }
2771
- /**
2772
- * Awaits the response from a user's attempt to log in with OAuth.
2773
- * If successful, this returns the user's email address and indicates whether the user already exists.
2774
- *
2775
- * @param {Object} opts the options object.
2776
- * @param {Window} [opts.popupWindow] the popup window being used for login.
2777
- * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
2778
- */
2779
- waitForOAuth() {
2780
- return __async(this, arguments, function* ({ popupWindow } = {}) {
2781
- this.isAwaitingOAuth = true;
2782
- while (this.isAwaitingOAuth) {
2783
- try {
2784
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2785
- return { isError: true, userExists: false };
2786
- }
2787
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2788
- if (this.isAwaitingOAuth) {
2789
- const res = yield this.touchSession();
2790
- if (res.data.userId) {
2791
- const { userId, email } = res.data;
2792
- if (!this.loginEncryptionKeyPair) {
2793
- yield this.setLoginEncryptionKeyPair();
2794
- }
2795
- yield this.setUserId(userId);
2796
- yield this.setEmail(email);
2797
- const userExists = yield this.checkIfUserExists({ email });
2798
- this.isAwaitingOAuth = false;
2799
- return {
2800
- userExists,
2801
- email
2802
- };
2803
- }
2804
- }
2805
- } catch (err) {
2806
- console.error(err);
2807
- }
2808
- }
2809
- return { userExists: false };
2810
- });
2811
- }
2812
- /**
2813
- * Waits for the session to be active and sets up the user.
2814
- *
2815
- * @param {Object} opts the options object
2816
- * @param {Window} [opts.popupWindow] the popup window being used for login.
2817
- * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2818
- * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2819
- **/
2820
- waitForLoginAndSetup() {
2821
- return __async(this, arguments, function* ({
2822
- popupWindow,
2823
- skipSessionRefresh = false
2824
- } = {}) {
2825
- var _a;
2826
- if (!this.isExternalWalletAuth) {
2827
- this.externalWallets = {};
2828
- }
2829
- this.isAwaitingLogin = true;
2830
- while (this.isAwaitingLogin) {
2831
- try {
2832
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2833
- if (!(yield this.isSessionActive())) {
2834
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2835
- const resp2 = { isComplete: false, isError: true };
2836
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2837
- return resp2;
2838
- }
2839
- continue;
2840
- }
2841
- const postLoginData = yield this.userSetupAfterLogin();
2842
- const needsWallet = (_a = postLoginData.data.needsWallet) != null ? _a : false;
2843
- if (!needsWallet) {
2844
- if (this.currentWalletIdsArray.length === 0) {
2845
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2846
- const resp2 = { isComplete: false, isError: true };
2847
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2848
- return resp2;
2849
- } else {
2850
- continue;
2851
- }
2852
- }
2853
- }
2854
- const fetchedWallets = yield this.fetchWallets();
2855
- const tempSharesRes = yield this.getTransmissionKeyShares();
2856
- if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
2857
- yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
2858
- yield this.claimPregenWallets();
2859
- const resp2 = {
2860
- isComplete: true,
2861
- needsWallet: needsWallet || Object.values(this.wallets).length === 0,
2862
- partnerId: postLoginData.data.partnerId
2863
- };
2864
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2);
2865
- return resp2;
2866
- }
2867
- } catch (err) {
2868
- console.error(err);
2869
- }
2870
- }
2871
- const resp = { isComplete: false };
2872
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp, "exitted login without setting up user");
2873
- return resp;
2874
- });
2875
- }
2876
- /**
2877
- * Updates the session with the user management server, possibly
2878
- * opening a popup to refresh the session.
2879
- *
2880
- * @param {Object} opts the options object.
2881
- * @param {boolean} [shouldOpenPopup] - if `true`, the running device will open a popup to reauthenticate the user.
2882
- * @returns a URL for the user to reauthenticate.
2883
- **/
2884
- refreshSession() {
2885
- return __async(this, arguments, function* ({ shouldOpenPopup = false } = {}) {
2886
- const res = yield this.touchSession(true);
2887
- if (!this.loginEncryptionKeyPair) {
2888
- yield this.setLoginEncryptionKeyPair();
2889
- }
2890
- const link = yield this.getWebAuthURLForLogin({
2891
- sessionId: res.data.sessionId,
2892
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2893
- });
2894
- if (shouldOpenPopup) {
2895
- this.platformUtils.openPopup(link);
2896
- }
2897
- return link;
2898
- });
2899
- }
2900
- /**
2901
- * Call this method after login to ensure that the user ID is set
2902
- * internally.
2903
- **/
2904
- userSetupAfterLogin() {
2905
- return __async(this, null, function* () {
2906
- const res = yield this.touchSession();
2907
- yield this.setUserId(res.data.userId);
2908
- if (res.data.currentWalletIds && res.data.currentWalletIds !== this.currentWalletIds)
2909
- yield this.setCurrentWalletIds(res.data.currentWalletIds, {
2910
- sessionLookupId: this.isPortal() ? res.data.sessionLookupId : void 0
2911
- });
2912
- return res;
2913
- });
2914
- }
2915
- /**
2916
- * Get transmission shares associated with session.
2917
- * @param {Object} opts the options object.
2918
- * @param {boolean} opts.isForNewDevice - true if this device is registering.
2919
- * @returns - transmission keyshares.
2920
- **/
2921
- getTransmissionKeyShares() {
2922
- return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
2923
- const res = yield this.touchSession();
2924
- const sessionLookupId = isForNewDevice ? `${res.data.sessionLookupId}-new-device` : res.data.sessionLookupId;
2925
- return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2926
- });
2927
- }
2928
- /**
2929
- * Call this method after login to perform setup.
2930
- * @param {Object} opts the options object.
2931
- * @param {any[]} opts.temporaryShares optional temporary shares to use for decryption.
2932
- * @param {boolean} [opts.skipSessionRefresh] - whether or not to skip refreshing the session.
2933
- **/
2934
- setupAfterLogin() {
2935
- return __async(this, arguments, function* ({
2936
- temporaryShares,
2937
- skipSessionRefresh = false
2938
- } = {}) {
2939
- if (!temporaryShares) {
2940
- temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2941
- }
2942
- temporaryShares.forEach((share) => {
2943
- const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
2944
- this.wallets[share.walletId] = {
2945
- id: share.walletId,
2946
- signer
2947
- };
2948
- });
2949
- yield this.deleteLoginEncryptionKeyPair();
2950
- yield this.populateWalletAddresses();
2951
- yield this.touchSession(!skipSessionRefresh);
2952
- });
2953
- }
2954
- /**
2955
- * Distributes a new wallet recovery share.
2956
- * @param {Object} opts the options object.
2957
- * @param {string} opts.walletId the wallet to distribute the recovery share for.
2958
- * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
2959
- * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
2960
- * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
2961
- * @returns {string} the recovery share.
2962
- **/
2963
- distributeNewWalletShare(_0) {
2964
- return __async(this, arguments, function* ({
2965
- walletId,
2966
- userShare,
2967
- skipBiometricShareCreation = false,
2968
- forceRefresh = false
2969
- }) {
2970
- let userSigner = userShare;
2971
- if (!userSigner) {
2972
- userSigner = this.wallets[walletId].signer;
2973
- }
2974
- const recoveryShare = skipBiometricShareCreation ? yield sendRecoveryForShare({
2975
- ctx: this.ctx,
2976
- userId: this.userId,
2977
- walletId,
2978
- userSigner,
2979
- emailProps: this.getBackupKitEmailProps(),
2980
- forceRefresh
2981
- }) : yield distributeNewShare({
2982
- ctx: this.ctx,
2983
- userId: this.userId,
2984
- walletId,
2985
- userShare: userSigner,
2986
- emailProps: this.getBackupKitEmailProps()
2987
- });
2988
- return recoveryShare;
2989
- });
2990
- }
2991
- waitForWalletAddress(walletId) {
2992
- return __async(this, null, function* () {
2993
- let maxPolls = 0;
2994
- while (true) {
2995
- try {
2996
- if (maxPolls === 10) {
2997
- break;
2998
- }
2999
- ++maxPolls;
3000
- const res = yield this.ctx.client.getWallets(this.userId);
3001
- const wallet = res.data.wallets.find((w) => w.id === walletId);
3002
- if (wallet && wallet.address) {
3003
- return;
3004
- }
3005
- yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
3006
- } catch (err) {
3007
- console.error(err);
3008
- }
3009
- }
3010
- throw new Error("timed out waiting for wallet address");
3011
- });
3012
- }
3013
- /**
3014
- * Waits for a pregen wallet address to be created.
3015
- *
3016
- * @param pregenIdentifier - the identifier of the user the pregen wallet is associated with.
3017
- * @param walletId - the wallet id
3018
- * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
3019
- * @returns - recovery share.
3020
- **/
3021
- waitForPregenWalletAddress(walletId) {
3022
- return __async(this, null, function* () {
3023
- let maxPolls = 0;
3024
- while (true) {
3025
- try {
3026
- if (maxPolls === 10) {
3027
- break;
3028
- }
3029
- ++maxPolls;
3030
- const res = yield this.getPregenWallets();
3031
- const wallet = res.find((w) => w.id === walletId);
3032
- if (wallet && wallet.address) {
3033
- return;
3034
- }
3035
- yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
3036
- } catch (err) {
3037
- console.error(err);
3038
- }
3039
- }
3040
- throw new Error("timed out waiting for wallet address");
3041
- });
3042
- }
3043
- /**
3044
- * Creates several new wallets with the desired types. If no types are provided, this method
3045
- * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
3046
- * object that are not already present. This is automatically called upon account creation to ensure that
3047
- * the user has a wallet of each required type.
3048
- *
3049
- * @param {Object} [opts] the options object.
3050
- * @param {boolean} [opts.skipDistribute] if `true`, the wallets' recovery share will not be distributed.
3051
- * @param {WalletType[]} [opts.types] the types of wallets to create.
3052
- * @returns {Object} the wallets created, their ids, and the recovery secret.
3053
- **/
3054
- createWalletPerType() {
3055
- return __async(this, arguments, function* ({
3056
- skipDistribute = false,
3057
- types
3058
- } = {}) {
3059
- const wallets = [];
3060
- const walletIds = {};
3061
- let recoverySecret;
3062
- for (const type of yield this.getTypesToCreate(types)) {
3063
- const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
3064
- wallets.push(wallet);
3065
- getEquivalentTypes(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
3066
- walletIds[t] = [wallet.id];
3067
- });
3068
- if (recoveryShare) {
3069
- recoverySecret = recoveryShare;
3070
- }
3071
- }
3072
- return { wallets, walletIds, recoverySecret };
3073
- });
3074
- }
3075
- /**
3076
- * Refresh the current user share for a wallet.
3077
- *
3078
- * @param {Object} opts the options object.
3079
- * @param {string} opts.walletId the wallet id to refresh.
3080
- * @param {string} opts.share the current user share.
3081
- * @param {string} [opts.oldPartnerId] the current partner id.
3082
- * @param {string} [opts.newPartnerId] the new partner id to set, if any.
3083
- * @param {string} [opts.keyShareProtocolId]
3084
- * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
3085
- * @returns {Object} the new user share and recovery secret.
3086
- **/
3087
- refreshShare(_0) {
3088
- return __async(this, arguments, function* ({
3089
- walletId,
3090
- share,
3091
- oldPartnerId,
3092
- newPartnerId,
3093
- keyShareProtocolId,
3094
- redistributeBackupEncryptedShares
3095
- }) {
3096
- const { signer, protocolId } = yield this.platformUtils.refresh(
3097
- this.ctx,
3098
- this.retrieveSessionCookie(),
3099
- this.userId,
3100
- walletId,
3101
- share,
3102
- oldPartnerId,
3103
- newPartnerId,
3104
- keyShareProtocolId
3105
- );
3106
- const recoverySecret = yield distributeNewShare({
3107
- ctx: this.ctx,
3108
- userId: this.userId,
3109
- walletId,
3110
- userShare: signer,
3111
- ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
3112
- emailProps: this.getBackupKitEmailProps(),
3113
- partnerId: newPartnerId,
3114
- protocolId
3115
- });
3116
- return { signer, recoverySecret, protocolId };
3117
- });
3118
- }
3119
- /**
3120
- * Creates a new wallet.
3121
- * @param {Object} opts the options object.
3122
- * @param {WalletType} opts.type the type of wallet to create.
3123
- * @param {boolean} opts.skipDistribute - if true, recovery share will not be distributed.
3124
- * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3125
- **/
3126
- createWallet() {
3127
- return __async(this, arguments, function* ({
3128
- type: _type,
3129
- skipDistribute = false
3130
- } = {}) {
3131
- var _a, _b;
3132
- this.requireApiKey();
3133
- const walletType = yield this.assertIsValidWalletType(
3134
- _type != null ? _type : (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
3135
- );
3136
- let signer;
3137
- let wallet;
3138
- let keygenRes;
3139
- switch (walletType) {
3140
- case WalletType2.SOLANA: {
3141
- keygenRes = yield this.platformUtils.ed25519Keygen(
3142
- this.ctx,
3143
- this.userId,
3144
- this.retrieveSessionCookie(),
3145
- this.getBackupKitEmailProps()
3146
- );
3147
- break;
3148
- }
3149
- default: {
3150
- keygenRes = yield this.platformUtils.keygen(
3151
- this.ctx,
3152
- this.userId,
3153
- walletType,
3154
- null,
3155
- this.retrieveSessionCookie(),
3156
- this.getBackupKitEmailProps()
3157
- );
3158
- break;
3159
- }
3160
- }
3161
- const walletId = keygenRes.walletId;
3162
- signer = keygenRes.signer;
3163
- this.wallets[walletId] = {
3164
- id: walletId,
3165
- signer,
3166
- scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
3167
- type: walletType
3168
- };
3169
- wallet = this.wallets[walletId];
3170
- yield this.waitForWalletAddress(wallet.id);
3171
- yield this.populateWalletAddresses();
3172
- let recoveryShare = null;
3173
- if (!skipDistribute) {
3174
- recoveryShare = yield distributeNewShare({
3175
- ctx: this.ctx,
3176
- userId: this.userId,
3177
- walletId: wallet.id,
3178
- userShare: signer,
3179
- emailProps: this.getBackupKitEmailProps()
3180
- });
3181
- }
3182
- yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
3183
- [walletType]: [...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId]
3184
- }));
3185
- const walletNoSigner = __spreadValues({}, wallet);
3186
- delete walletNoSigner.signer;
3187
- dispatchEvent(ParaEvent.WALLET_CREATED, {
3188
- wallet: walletNoSigner,
3189
- recoverySecret: recoveryShare
3190
- });
3191
- return [wallet, recoveryShare];
3192
- });
3193
- }
3194
- /**
3195
- * Creates a new pregenerated wallet.
3196
- *
3197
- * @param {Object} opts the options object.
3198
- * @param {string} opts.pregenIdentifier the identifier associated with the new wallet.
3199
- * @param {TPregenIdentifierType} [opts.pregenIdentifierType] the identifier type. Defaults to `EMAIL`.
3200
- * @param {WalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
3201
- * @returns {Wallet} the created wallet.
3202
- **/
3203
- createPregenWallet(opts) {
3204
- return __async(this, null, function* () {
3205
- var _a, _b;
3206
- const {
3207
- type: _type = (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type,
3208
- pregenIdentifier,
3209
- pregenIdentifierType = "EMAIL"
3210
- } = opts;
3211
- this.requireApiKey();
3212
- const walletType = yield this.assertIsValidWalletType(
3213
- _type != null ? _type : (_b = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
3214
- );
3215
- let keygenRes;
3216
- switch (walletType) {
3217
- case WalletType2.SOLANA:
3218
- keygenRes = yield this.platformUtils.ed25519PreKeygen(
3219
- this.ctx,
3220
- pregenIdentifier,
3221
- pregenIdentifierType,
3222
- this.retrieveSessionCookie()
3223
- );
3224
- break;
3225
- default:
3226
- keygenRes = yield this.platformUtils.preKeygen(
3227
- this.ctx,
3228
- void 0,
3229
- pregenIdentifier,
3230
- pregenIdentifierType,
3231
- walletType,
3232
- null,
3233
- this.retrieveSessionCookie()
3234
- );
3235
- break;
3236
- }
3237
- const { signer, walletId } = keygenRes;
3238
- this.wallets[walletId] = {
3239
- id: walletId,
3240
- signer,
3241
- scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
3242
- type: walletType,
3243
- isPregen: true,
3244
- pregenIdentifier,
3245
- pregenIdentifierType
3246
- };
3247
- yield this.waitForPregenWalletAddress(walletId);
3248
- yield this.populatePregenWalletAddresses();
3249
- return this.wallets[walletId];
3250
- });
3251
- }
3252
- /**
3253
- * Creates new pregenerated wallets for each desired type.
3254
- * If no types are provided, this method will create one for each of the non-optional types
3255
- * specified in the instance's `supportedWalletTypes` array that are not already present.
3256
- * @param {Object} opts the options object.
3257
- * @param {string} opts.pregenIdentifier the identifier to associate each wallet with.
3258
- * @param {TPregenIdentifierType} opts.pregenIdentifierType - either `'EMAIL'` or `'PHONE'`.
3259
- * @param {WalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
3260
- * @returns {Wallet[]} an array containing the created wallets.
3261
- **/
3262
- createPregenWalletPerType(_0) {
3263
- return __async(this, arguments, function* ({
3264
- types,
3265
- pregenIdentifier,
3266
- pregenIdentifierType = "EMAIL"
3267
- }) {
3268
- const wallets = [];
3269
- for (const type of yield this.getTypesToCreate(types)) {
3270
- const wallet = yield this.createPregenWallet({ type, pregenIdentifier, pregenIdentifierType });
3271
- wallets.push(wallet);
3272
- }
3273
- return wallets;
3274
- });
3275
- }
3276
- /**
3277
- * Claims a pregenerated wallet.
3278
- *
3279
- * @param {Object} opts the options object.
3280
- * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
3281
- * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the identifier of the user claiming the wallet
3282
- * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3283
- **/
3284
- claimPregenWallets() {
3285
- return __async(this, arguments, function* ({
3286
- pregenIdentifier,
3287
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3288
- } = {}) {
3289
- var _a;
3290
- this.requireApiKey();
3291
- const pregenWallets = pregenIdentifier && pregenIdentifierType ? yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType }) : yield this.getPregenWallets();
3292
- if (pregenWallets.length === 0) {
3293
- return void 0;
3294
- }
3295
- const missingWallets = pregenWallets.filter((wallet) => !this.wallets[wallet.id]);
3296
- if (missingWallets.length > 0) {
3297
- throw new Error(
3298
- `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(", ")}`
3299
- );
3300
- }
3301
- let newRecoverySecret;
3302
- const { walletIds } = yield this.ctx.client.claimPregenWallets({
3303
- userId: this.userId,
3304
- walletIds: pregenWallets.map((w) => w.id)
3305
- });
3306
- for (const walletId of walletIds) {
3307
- const wallet = this.wallets[walletId];
3308
- let refreshedShare;
3309
- if (wallet.scheme === WalletScheme2.ED25519) {
3310
- const distributeRes = yield distributeNewShare({
3311
- ctx: this.ctx,
3312
- userId: this.userId,
3313
- walletId: wallet.id,
3314
- userShare: this.wallets[wallet.id].signer,
3315
- emailProps: this.getBackupKitEmailProps(),
3316
- partnerId: wallet.partnerId
3317
- });
3318
- if (distributeRes.length > 0) {
3319
- newRecoverySecret = distributeRes;
3320
- }
3321
- } else {
3322
- refreshedShare = yield this.refreshShare({
3323
- walletId: wallet.id,
3324
- share: this.wallets[wallet.id].signer,
3325
- oldPartnerId: wallet.partnerId,
3326
- newPartnerId: wallet.partnerId,
3327
- redistributeBackupEncryptedShares: true
3328
- });
3329
- if (refreshedShare.recoverySecret) {
3330
- newRecoverySecret = refreshedShare.recoverySecret;
3331
- }
3332
- }
3333
- this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
3334
- signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
3335
- userId: this.userId,
3336
- pregenIdentifier: void 0,
3337
- pregenIdentifierType: void 0
3338
- });
3339
- const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
3340
- delete walletNoSigner.signer;
3341
- dispatchEvent(ParaEvent.PREGEN_WALLET_CLAIMED, {
3342
- wallet: walletNoSigner,
3343
- recoverySecret: newRecoverySecret
3344
- });
3345
- }
3346
- yield this.setWallets(this.wallets);
3347
- return newRecoverySecret;
3348
- });
3349
- }
3350
- /**
3351
- * Updates the identifier for a pregen wallet.
3352
- * @param {Object} opts the options object.
3353
- * @param {string} opts.walletId the pregen wallet ID
3354
- * @param {string} opts.newPregenIdentifier the new identtifier
3355
- * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
3356
- **/
3357
- updatePregenWalletIdentifier(_0) {
3358
- return __async(this, arguments, function* ({
3359
- walletId,
3360
- newPregenIdentifier,
3361
- newPregenIdentifierType
3362
- }) {
3363
- this.requireApiKey();
3364
- yield this.ctx.client.updatePregenWallet(walletId, {
3365
- pregenIdentifier: newPregenIdentifier,
3366
- pregenIdentifierType: newPregenIdentifierType
3367
- });
3368
- if (!!this.wallets[walletId]) {
3369
- this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3370
- pregenIdentifier: newPregenIdentifier,
3371
- pregenIdentifierType: newPregenIdentifierType
3372
- });
3373
- yield this.setWallets(this.wallets);
3374
- }
3375
- });
3376
- }
3377
- /**
3378
- * Checks if a pregen Wallet exists for the given identifier with the current partner.
3379
- * @param {Object} opts the options object.
3380
- * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
3381
- * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
3382
- * @returns {boolean} whether the pregen wallet exists
3383
- **/
3384
- hasPregenWallet(_0) {
3385
- return __async(this, arguments, function* ({
3386
- pregenIdentifier,
3387
- pregenIdentifierType
3388
- }) {
3389
- this.requireApiKey();
3390
- const res = yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType });
3391
- const wallet = res.find((w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType);
3392
- if (!wallet) {
3393
- return false;
3394
- }
3395
- return true;
3396
- });
3397
- }
3398
- /**
3399
- * Get pregen wallets for the given identifier.
3400
- * @param {Object} opts the options object.
3401
- * @param {string} opts.pregenIdentifier - the identifier of the user claiming the wallet
3402
- * @param {TPregenIdentifierType} opts.pregenIdentifierType - type of the identifier of the user claiming the wallet
3403
- * @returns {Promise<WalletEntity[]>} the array of found wallets
3404
- **/
3405
- getPregenWallets() {
3406
- return __async(this, arguments, function* ({
3407
- pregenIdentifier,
3408
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3409
- } = {}) {
3410
- this.requireApiKey();
3411
- const res = yield this.ctx.client.getPregenWallets(
3412
- pregenIdentifier && pregenIdentifierType ? { [pregenIdentifierType]: [pregenIdentifier] } : this.pregenIds,
3413
- this.isPortal(),
3414
- this.userId
3415
- );
3416
- return res.wallets.filter((w) => this.isWalletSupported(entityToWallet(w)));
3417
- });
3418
- }
3419
- encodeWalletBase64(wallet) {
3420
- const walletJson = JSON.stringify(wallet);
3421
- const base64Wallet = Buffer.from(walletJson).toString("base64");
3422
- return base64Wallet;
3423
- }
3424
- /**
3425
- * Encodes the current wallets encoded in Base 64.
3426
- * @returns {string} the encoded wallet string
3427
- **/
3428
- getUserShare() {
3429
- if (Object.values(this.wallets).length === 0) {
3430
- return null;
3431
- }
3432
- return Object.values(this.wallets).map((wallet) => this.encodeWalletBase64(wallet)).join("-");
3433
- }
3434
- /**
3435
- * Sets the current wallets from a Base 64 string.
3436
- * @param {string} base64Wallet the encoded wallet string
3437
- **/
3438
- setUserShare(base64Wallets) {
3439
- return __async(this, null, function* () {
3440
- if (!base64Wallets) {
3441
- return;
3442
- }
3443
- const base64WalletsSplit = base64Wallets.split("-");
3444
- for (const base64Wallet of base64WalletsSplit) {
3445
- const walletJson = Buffer.from(base64Wallet, "base64").toString();
3446
- const wallet = migrateWallet(JSON.parse(walletJson));
3447
- this.wallets[wallet.id] = wallet;
3448
- yield this.setWallets(this.wallets);
3449
- }
3450
- });
3451
- }
3452
- getTransactionReviewUrl(transactionId, timeoutMs) {
3453
- return __async(this, null, function* () {
3454
- const res = yield this.touchSession();
3455
- return this.constructPortalUrl("txReview", {
3456
- partnerId: res.data.partnerId,
3457
- pathId: transactionId,
3458
- params: {
3459
- email: this.email,
3460
- timeoutMs: timeoutMs == null ? void 0 : timeoutMs.toString()
3461
- }
3462
- });
3463
- });
3464
- }
3465
- getOnRampTransactionUrl(_i) {
3466
- return __async(this, null, function* () {
3467
- var _j = _i, {
3468
- purchaseId,
3469
- providerKey
3470
- } = _j, walletParams = __objRest(_j, [
3471
- "purchaseId",
3472
- "providerKey"
3473
- ]);
3474
- const res = yield this.touchSession();
3475
- const [key, identifier] = extractWalletRef(walletParams);
3476
- return this.constructPortalUrl("onRamp", {
3477
- partnerId: res.data.partnerId,
3478
- pathId: purchaseId,
3479
- sessionId: res.data.sessionId,
3480
- params: {
3481
- [key]: identifier,
3482
- providerKey,
3483
- currentWalletIds: JSON.stringify(this.currentWalletIds)
3484
- }
3485
- });
3486
- });
3487
- }
3488
- /**
3489
- * Signs a message using one of the current wallets.
3490
- *
3491
- * If you want to sign the keccak256 hash of a message, hash the
3492
- * message first and then pass in the base64 encoded hash.
3493
- * @param {Object} opts the options object.
3494
- * @param {string} opts.walletId the id of the wallet to sign with.
3495
- * @param {string} opts.messageBase64 the base64 encoding of exact message that should be signed
3496
- * @param {number} [opts.timeout] optional timeout in milliseconds. If not present, defaults to 30 seconds.
3497
- * @param {string} [opts.cosmosSignDocBase64] the Cosmos `SignDoc` in base64, if applicable
3498
- **/
3499
- signMessage(_0) {
3500
- return __async(this, arguments, function* ({
3501
- walletId,
3502
- messageBase64,
3503
- timeoutMs = 3e4,
3504
- cosmosSignDocBase64
3505
- }) {
3506
- this.assertIsValidWalletId(walletId);
3507
- const wallet = this.wallets[walletId];
3508
- let signerId = this.userId;
3509
- if (wallet.partnerId && !wallet.userId) {
3510
- signerId = wallet.partnerId;
3511
- }
3512
- let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3513
- let timeStart = Date.now();
3514
- if (signRes.pendingTransactionId) {
3515
- this.platformUtils.openPopup(
3516
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3517
- { type: cosmosSignDocBase64 ? "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ : "SIGN_MESSAGE_REVIEW" /* SIGN_MESSAGE_REVIEW */ }
3518
- );
3519
- } else {
3520
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3521
- return signRes;
3522
- }
3523
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3524
- while (true) {
3525
- if (Date.now() - timeStart > timeoutMs) {
3526
- break;
3527
- }
3528
- try {
3529
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3530
- } catch (err) {
3531
- const error = new TransactionReviewDenied();
3532
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3533
- throw error;
3534
- }
3535
- signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3536
- if (signRes.pendingTransactionId) {
3537
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3538
- } else {
3539
- break;
3540
- }
3541
- }
3542
- if (signRes.pendingTransactionId) {
3543
- const error = new TransactionReviewTimeout(
3544
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3545
- signRes.pendingTransactionId
3546
- );
3547
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3548
- throw error;
3549
- }
3550
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3551
- return signRes;
3552
- });
3553
- }
3554
- signMessageInner(_0) {
3555
- return __async(this, arguments, function* ({
3556
- wallet,
3557
- signerId,
3558
- messageBase64,
3559
- cosmosSignDocBase64
3560
- }) {
3561
- let signRes;
3562
- switch (wallet.scheme) {
3563
- case WalletScheme2.ED25519:
3564
- signRes = yield this.platformUtils.ed25519Sign(
3565
- this.ctx,
3566
- signerId,
3567
- wallet.id,
3568
- wallet.signer,
3569
- messageBase64,
3570
- this.retrieveSessionCookie()
3571
- );
3572
- break;
3573
- default:
3574
- signRes = yield this.platformUtils.signMessage(
3575
- this.ctx,
3576
- signerId,
3577
- wallet.id,
3578
- wallet.signer,
3579
- messageBase64,
3580
- this.retrieveSessionCookie(),
3581
- wallet.scheme === WalletScheme2.DKLS,
3582
- cosmosSignDocBase64
3583
- );
3584
- break;
3585
- }
3586
- return signRes;
3587
- });
3588
- }
3589
- /**
3590
- * Signs a transaction.
3591
- * @param {Object} opts the options object.
3592
- * @param {string} opts.walletId the id of the wallet to sign with.
3593
- * @param {string} opts.rlpEncodedTxBase64 the transaction to sign, in RLP base64 encoding
3594
- * @param {string} [opts.chainId] the EVM chain id of the chain the transaction is being sent on, if applicable
3595
- * @param {number} [opts.timeoutMs] the amount of time to wait for the user to sign the transaction, in milliseconds
3596
- **/
3597
- signTransaction(_0) {
3598
- return __async(this, arguments, function* ({
3599
- walletId,
3600
- rlpEncodedTxBase64,
3601
- chainId,
3602
- timeoutMs = 3e4
3603
- }) {
3604
- this.assertIsValidWalletId(walletId);
3605
- const wallet = this.wallets[walletId];
3606
- let signerId = this.userId;
3607
- if (wallet.partnerId && !wallet.userId) {
3608
- signerId = wallet.partnerId;
3609
- }
3610
- let signRes = yield this.platformUtils.signTransaction(
3611
- this.ctx,
3612
- signerId,
3613
- walletId,
3614
- this.wallets[walletId].signer,
3615
- rlpEncodedTxBase64,
3616
- chainId,
3617
- this.retrieveSessionCookie(),
3618
- wallet.scheme === WalletScheme2.DKLS
3619
- );
3620
- let timeStart = Date.now();
3621
- if (signRes.pendingTransactionId) {
3622
- this.platformUtils.openPopup(
3623
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3624
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3625
- );
3626
- } else {
3627
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3628
- return signRes;
3629
- }
3630
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3631
- while (true) {
3632
- if (Date.now() - timeStart > timeoutMs) {
3633
- break;
3634
- }
3635
- try {
3636
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3637
- } catch (err) {
3638
- const error = new TransactionReviewDenied();
3639
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3640
- throw error;
3641
- }
3642
- signRes = yield this.platformUtils.signTransaction(
3643
- this.ctx,
3644
- signerId,
3645
- walletId,
3646
- this.wallets[walletId].signer,
3647
- rlpEncodedTxBase64,
3648
- chainId,
3649
- this.retrieveSessionCookie(),
3650
- wallet.scheme === WalletScheme2.DKLS
3651
- );
3652
- if (signRes.pendingTransactionId) {
3653
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3654
- } else {
3655
- break;
3656
- }
3657
- }
3658
- if (signRes.pendingTransactionId) {
3659
- const error = new TransactionReviewTimeout(
3660
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3661
- signRes.pendingTransactionId
3662
- );
3663
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3664
- throw error;
3665
- }
3666
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3667
- return signRes;
3668
- });
3669
- }
3670
- /**
3671
- * @deprecated
3672
- * Sends a transaction.
3673
- * @param walletId - id of the wallet to send the transaction from.
3674
- * @param rlpEncodedTxBase64 - rlp encoded tx as base64 string
3675
- * @param chainId - chain id of the chain the transaction is being sent on.
3676
- **/
3677
- sendTransaction(_0) {
3678
- return __async(this, arguments, function* ({
3679
- walletId,
3680
- rlpEncodedTxBase64,
3681
- chainId
3682
- }) {
3683
- this.assertIsValidWalletId(walletId);
3684
- const wallet = this.wallets[walletId];
3685
- const signRes = yield this.platformUtils.sendTransaction(
3686
- this.ctx,
3687
- this.userId,
3688
- walletId,
3689
- this.wallets[walletId].signer,
3690
- rlpEncodedTxBase64,
3691
- chainId,
3692
- this.retrieveSessionCookie(),
3693
- wallet.scheme === WalletScheme2.DKLS
3694
- );
3695
- if (signRes.pendingTransactionId) {
3696
- this.platformUtils.openPopup(
3697
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3698
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3699
- );
3700
- const error = new TransactionReviewError(
3701
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId)
3702
- );
3703
- throw error;
3704
- }
3705
- return signRes;
3706
- });
3707
- }
3708
- isProviderModalDisabled() {
3709
- return !!this.disableProviderModal;
3710
- }
3711
- /**
3712
- * Starts a on-ramp or off-ramp transaction and returns the Para Portal link for the user to finalize and complete it.
3713
- * @param {Object} opts the options object
3714
- * @param {OnRampPurchaseCreateParams} opts.params the transaction settings.
3715
- * @param {boolean} opts.shouldOpenPopup if `true`, a popup window with the link will be opened.
3716
- * @param {string} opts.walletId the wallet ID to use for the transaction, where funds will be sent or withdrawn.
3717
- * @param {string} opts.externalWalletAddress the external wallet address to send funds to or withdraw funds from, if using an external wallet.
3718
- **/
3719
- initiateOnRampTransaction(options) {
3720
- return __async(this, null, function* () {
3721
- var _b;
3722
- const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
3723
- const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
3724
- userId: this.userId,
3725
- params: __spreadProps(__spreadValues({}, params), {
3726
- address: (_b = walletParams.externalWalletAddress) != null ? _b : this.getDisplayAddress(walletParams.walletId, { addressType: params.walletType })
3727
- })
3728
- }, walletParams));
3729
- const portalUrl = yield this.getOnRampTransactionUrl(__spreadValues({
3730
- purchaseId: onRampPurchase.id,
3731
- providerKey: onRampPurchase.providerKey
3732
- }, walletParams));
3733
- if (shouldOpenPopup) {
3734
- this.platformUtils.openPopup(portalUrl, { type: "ON_RAMP_TRANSACTION" /* ON_RAMP_TRANSACTION */ });
3735
- }
3736
- return { onRampPurchase, portalUrl };
3737
- });
3738
- }
3739
- /**
3740
- * Returns `true` if session was successfully kept alive, `false` otherwise.
3741
- **/
3742
- keepSessionAlive() {
3743
- return __async(this, null, function* () {
3744
- try {
3745
- yield this.ctx.client.keepSessionAlive(this.userId);
3746
- return true;
3747
- } catch (err) {
3748
- return false;
3749
- }
3750
- });
3751
- }
3752
- /**
3753
- * Serialize the current session for import by another Para instance.
3754
- * @param {boolean} excludeSigners - whether or not to exclude the signer from the exported wallets.
3755
- * @returns {string} the serialized session
3756
- */
3757
- exportSession({ excludeSigners } = {}) {
3758
- const sessionInfo = {
3759
- email: this.email,
3760
- userId: this.userId,
3761
- wallets: structuredClone(this.wallets),
3762
- currentWalletIds: this.currentWalletIds,
3763
- sessionCookie: this.sessionCookie,
3764
- phone: this.phone,
3765
- countryCode: this.countryCode,
3766
- telegramUserId: this.telegramUserId,
3767
- farcasterUsername: this.farcasterUsername,
3768
- externalWallets: this.externalWallets
3769
- };
3770
- if (excludeSigners) {
3771
- for (const wallet of Object.values(sessionInfo.wallets)) {
3772
- delete wallet.signer;
3773
- }
3774
- }
3775
- return Buffer.from(JSON.stringify(sessionInfo)).toString("base64");
3776
- }
3777
- /**
3778
- * Imports a session serialized by another Para instance.
3779
- * @param {string} serializedInstanceBase64 the serialized session
3780
- */
3781
- importSession(serializedInstanceBase64) {
3782
- return __async(this, null, function* () {
3783
- var _a;
3784
- const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3785
- const sessionInfo = JSON.parse(serializedInstance);
3786
- yield this.setEmail(sessionInfo.email);
3787
- yield this.setTelegramUserId(sessionInfo.telegramUserId);
3788
- yield this.setFarcasterUsername(sessionInfo.farcasterUsername);
3789
- yield this.setUserId(sessionInfo.userId);
3790
- yield this.setWallets(sessionInfo.wallets);
3791
- yield this.setExternalWallets(sessionInfo.externalWallets || {});
3792
- for (const walletId of Object.keys(this.wallets)) {
3793
- if (!this.wallets[walletId].userId) {
3794
- this.wallets[walletId].userId = this.userId;
3795
- }
3796
- }
3797
- if (Object.keys(sessionInfo.currentWalletIds).length !== 0) {
3798
- yield this.setCurrentWalletIds(sessionInfo.currentWalletIds);
3799
- } else {
3800
- const currentWalletIds = {};
3801
- for (const walletId of Object.keys(sessionInfo.wallets)) {
3802
- currentWalletIds[sessionInfo.wallets[walletId].type] = [
3803
- ...(_a = currentWalletIds[sessionInfo.wallets[walletId].type]) != null ? _a : [],
3804
- walletId
3805
- ];
3806
- }
3807
- yield this.setCurrentWalletIds(currentWalletIds);
3808
- }
3809
- this.persistSessionCookie(sessionInfo.sessionCookie);
3810
- yield this.setPhoneNumber(sessionInfo.phone, sessionInfo.countryCode);
3811
- });
3812
- }
3813
- exitAccountCreation() {
3814
- this.isAwaitingAccountCreation = false;
3815
- }
3816
- exitLogin() {
3817
- this.isAwaitingLogin = false;
3818
- }
3819
- exitFarcaster() {
3820
- this.isAwaitingFarcaster = false;
3821
- }
3822
- exitOAuth() {
3823
- this.isAwaitingOAuth = false;
3824
- }
3825
- exitLoops() {
3826
- this.exitAccountCreation();
3827
- this.exitLogin();
3828
- this.exitFarcaster();
3829
- this.exitOAuth();
3830
- }
3831
- /**
3832
- * Retrieves a token to verify the current session.
3833
- * @returns {Promise<string>} the ID
3834
- **/
3835
- getVerificationToken() {
3836
- return __async(this, null, function* () {
3837
- const { data } = yield this.touchSession();
3838
- return data.sessionLookupId;
3839
- });
3840
- }
3841
- /**
3842
- * Logs the user out.
3843
- * @param {Object} opts the options object.
3844
- * @param {boolean} opts.clearPregenWallets if `true`, will remove all pregen wallets from storage
3845
- **/
3846
- logout() {
3847
- return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3848
- yield this.ctx.client.logout();
3849
- yield this.clearStorage();
3850
- if (!clearPregenWallets) {
3851
- Object.entries(this.wallets).forEach(([id, wallet]) => {
3852
- if (!wallet.pregenIdentifier) {
3853
- delete this.wallets[id];
3854
- }
3855
- });
3856
- yield this.setWallets(this.wallets);
3857
- } else {
3858
- this.wallets = {};
3859
- }
3860
- this.currentWalletIds = {};
3861
- this.externalWallets = {};
3862
- this.loginEncryptionKeyPair = void 0;
3863
- this.email = void 0;
3864
- this.telegramUserId = void 0;
3865
- this.phone = void 0;
3866
- this.countryCode = void 0;
3867
- this.userId = void 0;
3868
- this.sessionCookie = void 0;
3869
- dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3870
- });
3871
- }
3872
- getSupportedCreateAuthMethods() {
3873
- return __async(this, null, function* () {
3874
- const res = yield this.touchSession();
3875
- const partnerId = res.data.partnerId;
3876
- const partnerRes = yield this.ctx.client.getPartner(partnerId);
3877
- let supportedAuthMethods = /* @__PURE__ */ new Set();
3878
- for (const authMethod of partnerRes.data.partner.supportedAuthMethods) {
3879
- supportedAuthMethods.add(AuthMethod[authMethod]);
3880
- }
3881
- return supportedAuthMethods;
3882
- });
3883
- }
3884
- /**
3885
- * Converts to a string, removing sensitive data when logging this class.
3886
- *
3887
- * Doesn't work for all types of logging.
3888
- **/
3889
- toString() {
3890
- const redactedWallets = Object.keys(this.wallets).reduce(
3891
- (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3892
- [walletId]: __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3893
- signer: this.wallets[walletId].signer ? "[REDACTED]" : void 0
3894
- })
3895
- }),
3896
- {}
3897
- );
3898
- const redactedExternalWallets = Object.keys(this.externalWallets).reduce(
3899
- (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3900
- [walletId]: __spreadProps(__spreadValues({}, this.externalWallets[walletId]), {
3901
- signer: this.externalWallets[walletId].signer ? "[REDACTED]" : void 0
3902
- })
3903
- }),
3904
- {}
3905
- );
3906
- const obj = {
3907
- supportedWalletTypes: this.supportedWalletTypes,
3908
- cosmosPrefix: this.cosmosPrefix,
3909
- email: this.email,
3910
- phone: this.phone,
3911
- countryCode: this.countryCode,
3912
- telegramUserId: this.telegramUserId,
3913
- farcasterUsername: this.farcasterUsername,
3914
- userId: this.userId,
3915
- pregenIds: this.pregenIds,
3916
- currentWalletIds: this.currentWalletIds,
3917
- wallets: redactedWallets,
3918
- externalWallets: redactedExternalWallets,
3919
- loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3920
- ctx: {
3921
- apiKey: this.ctx.apiKey,
3922
- disableWorkers: this.ctx.disableWorkers,
3923
- disableWebSockets: this.ctx.disableWebSockets,
3924
- env: this.ctx.env,
3925
- offloadMPCComputationURL: this.ctx.offloadMPCComputationURL,
3926
- useLocalFiles: this.ctx.useLocalFiles,
3927
- useDKLS: this.ctx.useDKLS,
3928
- cosmosPrefix: this.ctx.cosmosPrefix
3929
- }
3930
- };
3931
- return `Para ${JSON.stringify(obj, null, 2)}`;
3932
- }
3933
- };
3934
- _supportedWalletTypes = new WeakMap();
3935
- _supportedWalletTypesOpt = new WeakMap();
3936
- _ParaCore.version = PARA_CORE_VERSION;
3937
- var ParaCore = _ParaCore;
3938
-
3939
- // src/index.ts
3940
- import {
3941
- AuthMethod as AuthMethod2,
3942
- EmailTheme as EmailTheme2,
5
+ EmailTheme,
3943
6
  Network,
3944
- WalletType as WalletType3,
3945
- WalletScheme as WalletScheme3,
7
+ WalletType,
8
+ WalletScheme,
3946
9
  OnRampAsset,
3947
10
  OnRampPurchaseType,
3948
11
  OnRampProvider,
3949
12
  OnRampPurchaseStatus,
3950
- OAuthMethod as OAuthMethod2,
13
+ OAuthMethod,
3951
14
  NON_ED25519,
3952
15
  PREGEN_IDENTIFIER_TYPES
3953
16
  } from "@getpara/user-management-client";
3954
- var paraVersion = ParaCore.version;
17
+ import {
18
+ OnRampMethod,
19
+ PopupType,
20
+ PregenIdentifierType,
21
+ RecoveryStatus
22
+ } from "./types/index.js";
23
+ export * from "./types/events.js";
24
+ export * from "./types/config.js";
25
+ import { getPortalDomain, stringToPhoneNumber, entityToWallet } from "./utils/index.js";
26
+ import { PREFIX } from "./constants.js";
27
+ import { distributeNewShare } from "./shares/shareDistribution.js";
28
+ import { KeyContainer } from "./shares/KeyContainer.js";
29
+ import { getBaseUrl, initClient } from "./external/userManagementClient.js";
30
+ import * as mpcComputationClient from "./external/mpcComputationClient.js";
31
+ import {
32
+ decryptWithKeyPair,
33
+ decryptWithPrivateKey,
34
+ getAsymmetricKeyPair,
35
+ getPublicKeyHex,
36
+ encryptWithDerivedPublicKey,
37
+ encodePrivateKeyToPemHex,
38
+ getDerivedPrivateKeyAndDecrypt,
39
+ getPublicKeyFromSignature,
40
+ getSHA256HashHex,
41
+ encryptPrivateKey,
42
+ decryptPrivateKey,
43
+ decryptPrivateKeyAndDecryptShare,
44
+ hashPasswordWithSalt,
45
+ encryptPrivateKeyWithPassword,
46
+ decryptPrivateKeyWithPassword,
47
+ publicKeyFromHex
48
+ } from "./cryptography/utils.js";
49
+ export * from "./external/userManagementClient.js";
50
+ export * from "./errors.js";
51
+ export * from "./utils/formatting.js";
52
+ export * from "./utils/polling.js";
53
+ import { isWalletSupported } from "./utils/wallet.js";
54
+ import { getOnRampAssets, getOnRampNetworks, toAssetInfoArray } from "./utils/onRamps.js";
55
+ import { getPortalBaseURL } from "./utils/url.js";
56
+ import { retrieve } from "./transmission/transmissionUtils.js";
57
+ const paraVersion = ParaCore.version;
3955
58
  var src_default = ParaCore;
3956
59
  export {
3957
- AuthMethod2 as AuthMethod,
3958
- EmailTheme2 as EmailTheme,
3959
- EnabledFlow,
3960
- Environment,
60
+ AuthMethod,
61
+ EmailTheme,
3961
62
  KeyContainer,
3962
63
  NON_ED25519,
3963
64
  Network,
3964
- OAuthMethod2 as OAuthMethod,
65
+ OAuthMethod,
3965
66
  OnRampAsset,
3966
67
  OnRampMethod,
3967
68
  OnRampProvider,
3968
69
  OnRampPurchaseStatus,
3969
70
  OnRampPurchaseType,
3970
71
  PREGEN_IDENTIFIER_TYPES,
3971
- ParaEvent,
3972
72
  PopupType,
3973
73
  PregenIdentifierType,
3974
74
  RecoveryStatus,
3975
75
  PREFIX as STORAGE_PREFIX,
3976
- TransactionReviewDenied,
3977
- TransactionReviewError,
3978
- TransactionReviewTimeout,
3979
- WalletScheme3 as WalletScheme,
3980
- WalletType3 as WalletType,
3981
- decimalToHex,
76
+ WalletScheme,
77
+ WalletType,
3982
78
  decryptPrivateKey,
3983
79
  decryptPrivateKeyAndDecryptShare,
3984
80
  decryptPrivateKeyWithPassword,
@@ -3992,10 +88,7 @@ export {
3992
88
  encryptWithDerivedPublicKey,
3993
89
  entityToWallet,
3994
90
  getAsymmetricKeyPair,
3995
- getBaseMPCNetworkUrl,
3996
- getBaseOAuthUrl,
3997
91
  getBaseUrl,
3998
- getCosmosAddress,
3999
92
  getDerivedPrivateKeyAndDecrypt,
4000
93
  getOnRampAssets,
4001
94
  getOnRampNetworks,
@@ -4005,19 +98,12 @@ export {
4005
98
  getPublicKeyHex,
4006
99
  getSHA256HashHex,
4007
100
  hashPasswordWithSalt,
4008
- hexStringToBase64,
4009
- hexToDecimal,
4010
- hexToSignature,
4011
- hexToUint8Array,
4012
101
  initClient,
4013
102
  isWalletSupported,
4014
- mpcComputationClient_exports as mpcComputationClient,
4015
- normalizePhoneNumber,
103
+ mpcComputationClient,
4016
104
  paraVersion,
4017
105
  publicKeyFromHex,
4018
106
  stringToPhoneNumber,
4019
107
  toAssetInfoArray,
4020
- retrieve as transmissionUtilsRetrieve,
4021
- truncateAddress,
4022
- waitUntilTrue
108
+ retrieve as transmissionUtilsRetrieve
4023
109
  };