@getpara/core-sdk 2.0.0-dev.0 → 2.0.0-dev.2

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