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