@getpara/core-sdk 1.2.0 → 1.3.0

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