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

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