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