wallaby-cash 2.3.7-alpha.0 → 2.3.8

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.
package/dist/index.cjs.js CHANGED
@@ -4,12 +4,13 @@ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toString
4
4
 
5
5
  const algosdk = require('algosdk');
6
6
  const bip39 = require('bip39');
7
- const uuid = require('uuid');
8
7
  const log = require('loglevel');
9
8
  const cryptoJs = require('crypto-js');
10
9
  const jwtDecode = require('jwt-decode');
10
+ const lodash = require('lodash');
11
11
  const WebAuthn = require('@simplewebauthn/browser');
12
12
  const jsBase64 = require('js-base64');
13
+ const uuid = require('uuid');
13
14
 
14
15
  const _interopDefaultCompat = e => e && typeof e === 'object' && 'default' in e ? e : { default: e };
15
16
 
@@ -108,11 +109,10 @@ exports.TransportEnum = void 0;
108
109
  * @property {string} [errorCode] - Specific error code for categorizing the error.
109
110
  * @property {any} [data] - Additional data related to the error.
110
111
  * @property {number} [status] - Alias for statusCode for compatibility.
111
- * @property {NetworkDiagnosticResult} [networkDiagnostic] - Optional network diagnostic information for network-related errors.
112
112
  */
113
113
  class WallabyError extends Error {
114
114
  constructor(errorPayload) {
115
- const { message, statusCode, errorCode, data, cause, onError, networkDiagnostic } = errorPayload;
115
+ const { message, statusCode, errorCode, data, cause, onError } = errorPayload;
116
116
  super(message);
117
117
  this.name = 'WallabyError';
118
118
  this.status = statusCode;
@@ -120,7 +120,6 @@ class WallabyError extends Error {
120
120
  this.cause = cause;
121
121
  this.onError = onError;
122
122
  this.data = data;
123
- this.networkDiagnostic = networkDiagnostic;
124
123
  Error.captureStackTrace(this, WallabyError);
125
124
  }
126
125
  static isWallabyError(error) {
@@ -296,6 +295,7 @@ exports.LocalStorageItems = void 0;
296
295
  LocalStorageItems["EncryptedAlgorandSeedPhrase"] = "encrypted-algorand-seedPhrase";
297
296
  LocalStorageItems["EncryptedDevicePrivateKey"] = "encrypted-private-key";
298
297
  LocalStorageItems["ClientAuthPublicKey"] = "client-auth-pub-key";
298
+ LocalStorageItems["WallabyAuthPubKey"] = "wallaby-auth-pub-key";
299
299
  LocalStorageItems["ClientAuthToken"] = "republic-jwt";
300
300
  LocalStorageItems["PasskeyCredential"] = "pass-key-credential";
301
301
  LocalStorageItems["Blob"] = "blob";
@@ -400,12 +400,6 @@ exports.ErrorResponseCodes = void 0;
400
400
  ErrorResponseCodes["sdk_passkey_challenge_unavailable"] = "sdk_passkey_challenge_unavailable";
401
401
  ErrorResponseCodes["sdk_passkey_authentication_failed"] = "sdk_passkey_authentication_failed";
402
402
  ErrorResponseCodes["sdk_passkey_registration_failed"] = "sdk_passkey_registration_failed";
403
- // network diagnostic errors
404
- ErrorResponseCodes["sdk_network_offline"] = "sdk_network_offline";
405
- ErrorResponseCodes["sdk_network_connectivity"] = "sdk_network_connectivity";
406
- ErrorResponseCodes["sdk_network_likely_cors_or_auth"] = "sdk_network_likely_cors_or_auth";
407
- ErrorResponseCodes["sdk_network_fast_failure"] = "sdk_network_fast_failure";
408
- ErrorResponseCodes["sdk_network_unknown"] = "sdk_network_unknown";
409
403
  })(exports.ErrorResponseCodes || (exports.ErrorResponseCodes = {}));
410
404
 
411
405
  const UnknownError = {
@@ -562,12 +556,12 @@ const global$1 = (typeof global !== "undefined" ? global :
562
556
  var env = {};
563
557
 
564
558
  // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
565
- var performance$1 = global$1.performance || {};
566
- performance$1.now ||
567
- performance$1.mozNow ||
568
- performance$1.msNow ||
569
- performance$1.oNow ||
570
- performance$1.webkitNow ||
559
+ var performance = global$1.performance || {};
560
+ performance.now ||
561
+ performance.mozNow ||
562
+ performance.msNow ||
563
+ performance.oNow ||
564
+ performance.webkitNow ||
571
565
  function(){ return (new Date()).getTime() };
572
566
 
573
567
  var browser$1 = {
@@ -607,7 +601,7 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
607
601
  { type: 'public-key', alg: exports.PublicKeyCredentialAlgorithm.ES256 },
608
602
  ];
609
603
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
610
- const currentPackageVersion = "2.3.7-alpha.0" ;
604
+ const currentPackageVersion = "2.3.8" ;
611
605
 
612
606
  /**
613
607
  * Storage keys adapter for Storage interface across different platforms.
@@ -4939,6 +4933,43 @@ class StorageService {
4939
4933
  }
4940
4934
  throw new Error(`Unsupported seed phrase type: ${seedPhraseType}`);
4941
4935
  }
4936
+ /**
4937
+ *
4938
+ * Stores Wallaby auth public key to local storage
4939
+ * @param wallabyAuthPubKey
4940
+ */
4941
+ async setWallabyAuthPubKey(wallabyAuthPubKey) {
4942
+ await this.save(exports.V2KeyNames.WallabyAuthPubKey, wallabyAuthPubKey);
4943
+ }
4944
+ /**
4945
+ *
4946
+ * Fetches Wallaby auth public key from local storage
4947
+ * @returns { string | undefined } Wallaby Auth Public key or undefined.
4948
+ */
4949
+ async getWallabyAuthPubKey() {
4950
+ let wallabyAuthPubKey = await this.fetch(exports.V2KeyNames.WallabyAuthPubKey);
4951
+ if (wallabyAuthPubKey) {
4952
+ return wallabyAuthPubKey;
4953
+ }
4954
+ // Legacy key migration
4955
+ const legacyKey = `wallabyAuthPubKey_${this.userId}`;
4956
+ const legacyPubKey = await this.getItem(legacyKey);
4957
+ if (legacyPubKey) {
4958
+ wallabyAuthPubKey = legacyPubKey;
4959
+ }
4960
+ else {
4961
+ const v1Key = `${this.environment}-wallaby-auth-public-key-${this.userId}`;
4962
+ const v1PubKey = await this.getItem(v1Key);
4963
+ if (v1PubKey) {
4964
+ wallabyAuthPubKey = v1PubKey;
4965
+ }
4966
+ }
4967
+ if (wallabyAuthPubKey) {
4968
+ await this.setWallabyAuthPubKey(wallabyAuthPubKey);
4969
+ return wallabyAuthPubKey;
4970
+ }
4971
+ return undefined;
4972
+ }
4942
4973
  /**
4943
4974
  * @deprecated This function is only used in tests, and should not be used anywhere else.
4944
4975
  * Encrypts and stores device auth private key
@@ -6313,16 +6344,6 @@ class Api {
6313
6344
  * @secure
6314
6345
  */
6315
6346
  getEstimateFee: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/estimate-fee`, method: "GET", query: query, secure: true, format: "json" }, params)),
6316
- /**
6317
- * @description The sign and broadcast transaction API was designed and implemented specifically for uses cases where the caller has their own custom raw transaction that is not yet currently supported by Wallaby
6318
- *
6319
- * @tags Transactions, Raw, Transactions
6320
- * @name SignAndBroadcastRawTx
6321
- * @summary Sign and broadcast raw transaction API
6322
- * @request POST:/api/v1/transactions/sign-broadcast-rawtx
6323
- * @secure
6324
- */
6325
- signAndBroadcastRawTx: (data, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/sign-broadcast-rawtx`, method: "POST", body: data, secure: true, type: ContentType.Json, format: "json" }, params)),
6326
6347
  /**
6327
6348
  * No description
6328
6349
  *
@@ -6333,6 +6354,16 @@ class Api {
6333
6354
  * @secure
6334
6355
  */
6335
6356
  fetchTransactionByHashOrReference: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/status`, method: "GET", query: query, secure: true, format: "json" }, params)),
6357
+ /**
6358
+ * @description The sign and broadcast transaction API was designed and implemented specifically for uses cases where the caller has their own custom raw transaction that is not yet currently supported by Wallaby
6359
+ *
6360
+ * @tags Transactions, Raw, Transactions
6361
+ * @name SignAndBroadcastRawTx
6362
+ * @summary Sign and broadcast raw transaction API
6363
+ * @request POST:/api/v1/transactions/sign-broadcast-rawtx
6364
+ * @secure
6365
+ */
6366
+ signAndBroadcastRawTx: (data, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/sign-broadcast-rawtx`, method: "POST", body: data, secure: true, type: ContentType.Json, format: "json" }, params)),
6336
6367
  /**
6337
6368
  * No description
6338
6369
  *
@@ -6844,184 +6875,6 @@ function objectToQueryParams(obj) {
6844
6875
  return params.toString();
6845
6876
  }
6846
6877
 
6847
- var NetworkDiagnosticCategory;
6848
- (function (NetworkDiagnosticCategory) {
6849
- NetworkDiagnosticCategory["OfflineHint"] = "offline_hint";
6850
- NetworkDiagnosticCategory["LikelyCorsOrAuthOrExtension"] = "likely_cors_or_auth_or_extension";
6851
- NetworkDiagnosticCategory["ConnectivityOrDns"] = "connectivity_or_dns";
6852
- NetworkDiagnosticCategory["FastFailureHint"] = "fast_failure_hint";
6853
- NetworkDiagnosticCategory["UnknownNetwork"] = "unknown_network";
6854
- })(NetworkDiagnosticCategory || (NetworkDiagnosticCategory = {}));
6855
-
6856
- const HEALTH_CHECK_TIMEOUT_MS = 5000;
6857
- class NetworkDiagnostic {
6858
- /**
6859
- * Run comprehensive network diagnostics after a fetch failure.
6860
- * Combines multiple signals to determine the likely cause of the failure.
6861
- */
6862
- static async run(context) {
6863
- const { failedUrl, originalError } = context;
6864
- logger.info('Running network diagnostic', { failedUrl, originalError });
6865
- const signals = {
6866
- online: NetworkDiagnostic.getNavigatorOnline(),
6867
- healthCheck: 'unavailable',
6868
- failedRequestUrl: failedUrl,
6869
- };
6870
- const hints = [];
6871
- const resourceTiming = NetworkDiagnostic.getResourceTimingForUrl(failedUrl);
6872
- if (resourceTiming) {
6873
- signals.resourceTiming = {
6874
- nextHopProtocol: resourceTiming.nextHopProtocol,
6875
- duration: resourceTiming.duration,
6876
- transferSize: resourceTiming.transferSize,
6877
- };
6878
- if (resourceTiming.duration < 50) {
6879
- hints.push('Very fast failure may indicate a local blocker or extension.');
6880
- }
6881
- }
6882
- const healthUrl = NetworkDiagnostic.deriveHealthUrl(failedUrl);
6883
- signals.healthCheck = await NetworkDiagnostic.simpleHealthCheck(healthUrl);
6884
- const category = NetworkDiagnostic.determineCategory(signals);
6885
- const message = NetworkDiagnostic.getCategoryMessage(category);
6886
- return {
6887
- category,
6888
- message,
6889
- signals,
6890
- hints: hints.length > 0 ? hints : undefined,
6891
- };
6892
- }
6893
- /**
6894
- * Check if navigator.onLine is available and return its value.
6895
- */
6896
- static getNavigatorOnline() {
6897
- if (typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean') {
6898
- return navigator.onLine;
6899
- }
6900
- return 'unknown';
6901
- }
6902
- /**
6903
- * Get the PerformanceResourceTiming entry for the given URL.
6904
- * Returns the most recent entry if multiple matches exist.
6905
- */
6906
- static getResourceTimingForUrl(url) {
6907
- if (typeof performance === 'undefined' || typeof performance.getEntriesByType !== 'function') {
6908
- return undefined;
6909
- }
6910
- try {
6911
- const entries = performance.getEntriesByType('resource');
6912
- const matchingEntries = entries.filter((entry) => entry.name && entry.name.includes(url));
6913
- if (matchingEntries.length === 0) {
6914
- return undefined;
6915
- }
6916
- return matchingEntries[matchingEntries.length - 1];
6917
- }
6918
- catch (_a) {
6919
- return undefined;
6920
- }
6921
- }
6922
- /**
6923
- * Perform a simple no-cors health check to the `/healthz` endpoint.
6924
- * This uses mode: 'no-cors' to avoid CORS preflight and credential issues.
6925
- */
6926
- static async simpleHealthCheck(healthUrl) {
6927
- if (typeof fetch === 'undefined') {
6928
- return 'unavailable';
6929
- }
6930
- const controller = new AbortController();
6931
- const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);
6932
- try {
6933
- const response = await fetch(healthUrl, {
6934
- method: 'HEAD',
6935
- mode: 'no-cors',
6936
- cache: 'no-store',
6937
- signal: controller.signal,
6938
- });
6939
- if (response.type === 'opaque') {
6940
- return 'ok';
6941
- }
6942
- return 'failed';
6943
- }
6944
- catch (_a) {
6945
- return 'failed';
6946
- }
6947
- finally {
6948
- clearTimeout(timeoutId);
6949
- }
6950
- }
6951
- /**
6952
- * Derive the health check URL from the base URL origin and `/healthz`.
6953
- */
6954
- static deriveHealthUrl(baseUrl) {
6955
- try {
6956
- const url = new URL(baseUrl);
6957
- const origin = url.origin;
6958
- return `${origin}/healthz`;
6959
- }
6960
- catch (_a) {
6961
- return `${baseUrl}/healthz`;
6962
- }
6963
- }
6964
- /**
6965
- * Determine the diagnostic category based on collected signals.
6966
- * Order matters - checks are performed in priority order.
6967
- */
6968
- static determineCategory(signals) {
6969
- if (signals.online === false) {
6970
- return NetworkDiagnosticCategory.OfflineHint;
6971
- }
6972
- if (signals.healthCheck === 'ok') {
6973
- return NetworkDiagnosticCategory.LikelyCorsOrAuthOrExtension;
6974
- }
6975
- if (signals.resourceTiming && signals.resourceTiming.duration !== undefined && signals.resourceTiming.duration < 50) {
6976
- return NetworkDiagnosticCategory.FastFailureHint;
6977
- }
6978
- if (signals.healthCheck === 'failed') {
6979
- return NetworkDiagnosticCategory.ConnectivityOrDns;
6980
- }
6981
- return NetworkDiagnosticCategory.UnknownNetwork;
6982
- }
6983
- /**
6984
- * Get a user-facing message for the given diagnostic category.
6985
- */
6986
- static getCategoryMessage(category) {
6987
- switch (category) {
6988
- case NetworkDiagnosticCategory.OfflineHint:
6989
- return 'Device reports offline; check Wi-Fi or mobile data.';
6990
- case NetworkDiagnosticCategory.LikelyCorsOrAuthOrExtension:
6991
- return 'Reachability to the API is OK; the failure may be due to CORS, authentication headers, or a browser extension blocking authenticated requests.';
6992
- case NetworkDiagnosticCategory.ConnectivityOrDns:
6993
- return 'Cannot reach the API host; check DNS, VPN, firewall, or ISP filtering.';
6994
- case NetworkDiagnosticCategory.FastFailureHint:
6995
- return 'Very fast failure may indicate a local blocker or extension.';
6996
- case NetworkDiagnosticCategory.UnknownNetwork:
6997
- default:
6998
- return 'Network request failed; see diagnostic details.';
6999
- }
7000
- }
7001
- /**
7002
- * Check if an error is a network-layer failure candidate that should trigger diagnostics.
7003
- * Returns true for TypeErrors with fetch-related messages, or DOMException with NetworkError name.
7004
- */
7005
- static isNetworkFailureCandidate(error) {
7006
- if (!error)
7007
- return false;
7008
- if (error instanceof TypeError) {
7009
- const message = error.message.toLowerCase();
7010
- return (message.includes('failed to fetch') ||
7011
- message.includes('load failed') ||
7012
- message.includes('networkerror') ||
7013
- message.includes('network request failed'));
7014
- }
7015
- if (error instanceof Error && error.name === 'NetworkError') {
7016
- return true;
7017
- }
7018
- if (typeof DOMException !== 'undefined' && error instanceof DOMException && error.name === 'NetworkError') {
7019
- return true;
7020
- }
7021
- return false;
7022
- }
7023
- }
7024
-
7025
6878
  class Base {
7026
6879
  constructor(config) {
7027
6880
  var _a, _b;
@@ -7072,26 +6925,6 @@ class Base {
7072
6925
  if (error instanceof WallabyError) {
7073
6926
  throw error;
7074
6927
  }
7075
- // Handle network-level failures with diagnostics
7076
- if (NetworkDiagnostic.isNetworkFailureCandidate(error)) {
7077
- const fullUrl = `${this.baseUrl.replace(/\/api\/v1\/?$/, '')}${params.path || ''}`;
7078
- const diagnostic = await NetworkDiagnostic.run({
7079
- failedUrl: fullUrl,
7080
- originalError: error,
7081
- });
7082
- const errorCode = this.mapCategoryToErrorCode(diagnostic.category);
7083
- throw new WallabyError({
7084
- message: diagnostic.message,
7085
- statusCode: 0,
7086
- errorCode,
7087
- data: {
7088
- originalError: error,
7089
- networkDiagnostic: diagnostic,
7090
- },
7091
- cause: error.cause,
7092
- networkDiagnostic: diagnostic,
7093
- });
7094
- }
7095
6928
  // Wrap any other errors
7096
6929
  throw new WallabyError({
7097
6930
  message: error.message || 'Unknown error occurred',
@@ -7261,25 +7094,6 @@ class Base {
7261
7094
  name: error.name,
7262
7095
  error,
7263
7096
  });
7264
- if (NetworkDiagnostic.isNetworkFailureCandidate(error)) {
7265
- const diagnostic = await NetworkDiagnostic.run({
7266
- failedUrl: fullUrl,
7267
- originalError: error,
7268
- });
7269
- const errorCode = this.mapCategoryToErrorCode(diagnostic.category);
7270
- throw new WallabyError({
7271
- message: diagnostic.message,
7272
- statusCode: 0,
7273
- errorCode,
7274
- data: {
7275
- code: error.name,
7276
- originalError: error,
7277
- networkDiagnostic: diagnostic,
7278
- },
7279
- cause: error.cause,
7280
- networkDiagnostic: diagnostic,
7281
- });
7282
- }
7283
7097
  throw new WallabyError({
7284
7098
  message: error.message || 'Network request failed',
7285
7099
  statusCode: 0,
@@ -7292,20 +7106,6 @@ class Base {
7292
7106
  });
7293
7107
  }
7294
7108
  }
7295
- mapCategoryToErrorCode(category) {
7296
- switch (category) {
7297
- case NetworkDiagnosticCategory.OfflineHint:
7298
- return exports.ErrorResponseCodes.sdk_network_offline;
7299
- case NetworkDiagnosticCategory.ConnectivityOrDns:
7300
- return exports.ErrorResponseCodes.sdk_network_connectivity;
7301
- case NetworkDiagnosticCategory.LikelyCorsOrAuthOrExtension:
7302
- return exports.ErrorResponseCodes.sdk_network_likely_cors_or_auth;
7303
- case NetworkDiagnosticCategory.FastFailureHint:
7304
- return exports.ErrorResponseCodes.sdk_network_fast_failure;
7305
- default:
7306
- return exports.ErrorResponseCodes.sdk_network_unknown;
7307
- }
7308
- }
7309
7109
  async _getRequestHeaders() {
7310
7110
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7311
7111
  if (!isTest && jwtHasExpired(this.clientAuthToken)) {
@@ -7600,13 +7400,6 @@ const SwapRoutes = {
7600
7400
  },
7601
7401
  };
7602
7402
 
7603
- function omit(obj, keys) {
7604
- if (!obj)
7605
- return {};
7606
- const keysSet = new Set(keys);
7607
- return Object.fromEntries(Object.entries(obj).filter(([k]) => !keysSet.has(k)));
7608
- }
7609
-
7610
7403
  /* eslint-disable no-useless-catch */
7611
7404
  /**
7612
7405
  * Web Authenticator Implementation
@@ -7746,7 +7539,7 @@ class PasskeyService {
7746
7539
  this.authenticator = new Authenticator();
7747
7540
  }
7748
7541
  preparePasskeyRequestOptions(options) {
7749
- var _a, _b, _c, _d, _e, _f, _g, _h;
7542
+ var _a, _b, _c, _d, _e, _f;
7750
7543
  const prfExtensionEvaluation = ((_b = (_a = options.extensions) === null || _a === void 0 ? void 0 : _a.prf.eval) === null || _b === void 0 ? void 0 : _b.base64)
7751
7544
  ? decodeBase64URL(options.extensions.prf.eval.base64)
7752
7545
  : ((_d = (_c = options.extensions) === null || _c === void 0 ? void 0 : _c.prf.eval) === null || _d === void 0 ? void 0 : _d.first) instanceof ArrayBuffer
@@ -7754,13 +7547,11 @@ class PasskeyService {
7754
7547
  : typeof ((_f = (_e = options.extensions) === null || _e === void 0 ? void 0 : _e.prf.eval) === null || _f === void 0 ? void 0 : _f.first) === 'object'
7755
7548
  ? new Uint8Array(Object.values(options.extensions.prf.eval.first))
7756
7549
  : undefined;
7757
- const parsedOptions = Object.assign(Object.assign({}, options), { extensions: Object.assign(Object.assign({}, options.extensions), { prf: prfExtensionEvaluation !== undefined
7758
- ? {
7759
- eval: {
7760
- first: prfExtensionEvaluation,
7761
- },
7762
- }
7763
- : ((_h = (_g = options.extensions) === null || _g === void 0 ? void 0 : _g.prf) !== null && _h !== void 0 ? _h : {}) }) });
7550
+ const parsedOptions = Object.assign(Object.assign({}, options), { extensions: Object.assign(Object.assign({}, options.extensions), { prf: {
7551
+ eval: {
7552
+ first: prfExtensionEvaluation,
7553
+ },
7554
+ } }) });
7764
7555
  logger.log('SDK::PasskeyService::preparePasskeyRequestOptions::parsedOptions', !!parsedOptions);
7765
7556
  // While the authenticator still works with the prf and would return the response (if any),
7766
7557
  // the library `@simplewebauthn/browser` does not support the prf extension in its type intentionally.
@@ -7768,7 +7559,7 @@ class PasskeyService {
7768
7559
  return parsedOptions;
7769
7560
  }
7770
7561
  preparePasskeyCreationOptions(options) {
7771
- var _a, _b, _c, _d, _e, _f, _g, _h;
7562
+ var _a, _b, _c, _d, _e, _f;
7772
7563
  const prfExtensionEvaluation = ((_b = (_a = options.extensions) === null || _a === void 0 ? void 0 : _a.prf.eval) === null || _b === void 0 ? void 0 : _b.base64)
7773
7564
  ? decodeBase64URL(options.extensions.prf.eval.base64)
7774
7565
  : ((_d = (_c = options.extensions) === null || _c === void 0 ? void 0 : _c.prf.eval) === null || _d === void 0 ? void 0 : _d.first) instanceof ArrayBuffer
@@ -7776,8 +7567,12 @@ class PasskeyService {
7776
7567
  : typeof ((_f = (_e = options.extensions) === null || _e === void 0 ? void 0 : _e.prf.eval) === null || _f === void 0 ? void 0 : _f.first) === 'object'
7777
7568
  ? new Uint8Array(Object.values(options.extensions.prf.eval.first))
7778
7569
  : undefined;
7779
- const parsedOptions = Object.assign(Object.assign({}, options), { extensions: Object.assign(Object.assign({}, options.extensions), { prf: prfExtensionEvaluation !== undefined ? { eval: { first: prfExtensionEvaluation } } : ((_h = (_g = options.extensions) === null || _g === void 0 ? void 0 : _g.prf) !== null && _h !== void 0 ? _h : {}) }) });
7780
- logger.log('SDK::PasskeyService::preparePasskeyCreationOptions::parsedOptions', !!parsedOptions);
7570
+ const parsedOptions = Object.assign(Object.assign({}, options), { extensions: Object.assign(Object.assign({}, options.extensions), { prf: {
7571
+ eval: {
7572
+ first: prfExtensionEvaluation,
7573
+ },
7574
+ } }) });
7575
+ logger.log('SDK::PasskeyService::preparePasskeyRequestOptions::parsedOptions', !!parsedOptions);
7781
7576
  return parsedOptions;
7782
7577
  }
7783
7578
  /**
@@ -7792,10 +7587,7 @@ class PasskeyService {
7792
7587
  let passkeyCredential;
7793
7588
  let signInResponse;
7794
7589
  try {
7795
- const registrationChallengeResponse = await getSignature({
7796
- deviceAuthKeys: deviceKeyPair,
7797
- passkeyChallengeType: exports.PasskeyChallengeType.REGISTRATION,
7798
- });
7590
+ const registrationChallengeResponse = await getSignature(deviceKeyPair, exports.PasskeyChallengeType.REGISTRATION);
7799
7591
  if (!registrationChallengeResponse.registrationOptions)
7800
7592
  throw new WallabyError({
7801
7593
  message: 'Passkey challenge could not be retrieved, please try again later.',
@@ -7838,10 +7630,7 @@ class PasskeyService {
7838
7630
  catch (error) {
7839
7631
  logger.error('SDK::PasskeyService::addNewPasskey::error', error);
7840
7632
  if (error && error.code === AuthenticatorPreviouslyRegisteredError.error) {
7841
- const authenticationChallengeResponse = await getSignature({
7842
- deviceAuthKeys: deviceKeyPair,
7843
- passkeyChallengeType: exports.PasskeyChallengeType.AUTHENTICATION,
7844
- });
7633
+ const authenticationChallengeResponse = await getSignature(deviceKeyPair, exports.PasskeyChallengeType.AUTHENTICATION);
7845
7634
  if (!authenticationChallengeResponse.authenticationOptions)
7846
7635
  throw new WallabyError({
7847
7636
  message: 'Passkey challenge could not be retrieved, please try again later.',
@@ -7912,7 +7701,7 @@ class PasskeyService {
7912
7701
  errorCode: exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable,
7913
7702
  });
7914
7703
  const parsedOptions = this.preparePasskeyRequestOptions(challengeResponse.authenticationOptions);
7915
- const updatedOptions = Object.assign(Object.assign({}, challengeResponse.authenticationOptions), { extensions: Object.assign(Object.assign({}, omit(parsedOptions.extensions, ['credProps'])), { prf: {
7704
+ const updatedOptions = Object.assign(Object.assign({}, challengeResponse.authenticationOptions), { extensions: Object.assign(Object.assign({}, lodash.omit(parsedOptions.extensions, 'credProps')), { prf: {
7916
7705
  eval: {
7917
7706
  first: (_b = (_a = parsedOptions.extensions.prf) === null || _a === void 0 ? void 0 : _a.eval) === null || _b === void 0 ? void 0 : _b.first,
7918
7707
  },
@@ -8141,6 +7930,10 @@ class PasskeyService {
8141
7930
  key: exports.LocalStorageItems.AccessToken,
8142
7931
  value: authenticationResponse.accessToken,
8143
7932
  },
7933
+ {
7934
+ key: exports.LocalStorageItems.WallabyAuthPubKey,
7935
+ value: authenticationResponse.user.wallabyAuthPubKey,
7936
+ },
8144
7937
  ]);
8145
7938
  }
8146
7939
  /**
@@ -8349,14 +8142,13 @@ class AuthService extends Base {
8349
8142
  * @param { PasskeyChallengeType } passkeyChallengeType the type of passkey challenge to request, either for registration or authentication.
8350
8143
  * @returns the messaged, the hash, and the signature using the passed private key.
8351
8144
  */
8352
- async getSignature({ deviceAuthKeys, walletId, passkeyChallengeType, }) {
8145
+ async getSignature(deviceAuthKeys, passkeyChallengeType) {
8353
8146
  try {
8354
8147
  logger.debug('SDK::AuthService::getSignature::authType', this.deviceAuthType);
8355
8148
  const challengeType = passkeyChallengeType !== null && passkeyChallengeType !== void 0 ? passkeyChallengeType : exports.PasskeyChallengeType.REGISTRATION;
8356
8149
  logger.debug('SDK::AuthService::getSignature::challengeType', challengeType);
8357
8150
  const response = await this.request(AuthRoutes.signatureMessage, {
8358
8151
  payload: {
8359
- walletId,
8360
8152
  clientAuthPubKey: deviceAuthKeys.publicKey,
8361
8153
  passkeyChallengeType: challengeType,
8362
8154
  },
@@ -8387,10 +8179,7 @@ class AuthService extends Base {
8387
8179
  logger.info('key pair generated', !!deviceKeyPair);
8388
8180
  let authentication;
8389
8181
  try {
8390
- const signatureMessageResponse = await this.getSignature({
8391
- deviceAuthKeys: deviceKeyPair,
8392
- passkeyChallengeType: exports.PasskeyChallengeType.REGISTRATION,
8393
- });
8182
+ const signatureMessageResponse = await this.getSignature(deviceKeyPair, exports.PasskeyChallengeType.REGISTRATION);
8394
8183
  logger.info('signature has been generated', !!signatureMessageResponse);
8395
8184
  switch (this.deviceAuthType) {
8396
8185
  case exports.AuthType.Passkey:
@@ -8423,10 +8212,7 @@ class AuthService extends Base {
8423
8212
  // TODO Add passkey errors to the WallabyError ErrorResponseCodes
8424
8213
  if ((error && error.error === InvalidStateError.error) || error.code === AuthenticatorPreviouslyRegisteredError.error) {
8425
8214
  logger.info('SDK::AuthService::signUp::handling previously registered passkey error');
8426
- const newChallenge = await this.getSignature({
8427
- deviceAuthKeys: deviceKeyPair,
8428
- passkeyChallengeType: exports.PasskeyChallengeType.AUTHENTICATION,
8429
- });
8215
+ const newChallenge = await this.getSignature(deviceKeyPair, exports.PasskeyChallengeType.AUTHENTICATION);
8430
8216
  authentication = await this.passkeyService.authenticate({
8431
8217
  deviceKeyPair: { publicKey: deviceKeyPair.publicKey, decryptedPrivateKey: deviceKeyPair.privateKey },
8432
8218
  challengeResponse: newChallenge,
@@ -8463,7 +8249,10 @@ class AuthService extends Base {
8463
8249
  errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8464
8250
  });
8465
8251
  }
8466
- await this.localStorageService.save(exports.LocalStorageItems.AccessToken, authentication.accessToken);
8252
+ await this.localStorageService.saveInBulk([
8253
+ { key: exports.LocalStorageItems.AccessToken, value: authentication.accessToken },
8254
+ { key: exports.LocalStorageItems.WallabyAuthPubKey, value: authentication.user.wallabyAuthPubKey },
8255
+ ]);
8467
8256
  return Object.freeze(Object.assign(Object.assign({}, authentication), input));
8468
8257
  }
8469
8258
  catch (error) {
@@ -8539,9 +8328,7 @@ class AuthService extends Base {
8539
8328
  },
8540
8329
  credentialsKeyPair,
8541
8330
  });
8542
- const signatureMessage = await this.getSignature({
8543
- deviceAuthKeys: { publicKey: clientPublicKey, privateKey: decryptedClientAuthPrivKey },
8544
- });
8331
+ const signatureMessage = await this.getSignature({ publicKey: clientPublicKey, privateKey: decryptedClientAuthPrivKey });
8545
8332
  const authentication = await this.request(AuthRoutes.signIn, {
8546
8333
  payload: {
8547
8334
  externalUserId: this.userId,
@@ -8665,6 +8452,10 @@ class AuthService extends Base {
8665
8452
  key: exports.LocalStorageItems.AccessToken,
8666
8453
  value: authResponse.accessToken,
8667
8454
  },
8455
+ {
8456
+ key: exports.LocalStorageItems.WallabyAuthPubKey,
8457
+ value: authResponse.user.wallabyAuthPubKey,
8458
+ },
8668
8459
  ]);
8669
8460
  return authResponse;
8670
8461
  });
@@ -8749,16 +8540,12 @@ class WalletHandlersService extends Base {
8749
8540
  this.userId = config.userId;
8750
8541
  }
8751
8542
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
8752
- var _a, _b, _c, _d, _e;
8543
+ var _a, _b, _c, _d;
8753
8544
  try {
8754
- // Since users importing a wallet can be requesting to create a new record, walletId is not available yet.
8755
- // However the enclave needs a uuid to bind the ephemeral wallaby auth public key to it for the first request
8756
- // Using the reference as the fallback for the walletId in this case.
8757
- const { signature, message, wallabyAuthPubKey } = await this.authService.getSignature({
8758
- walletId: (_a = importWalletInput.walletId) !== null && _a !== void 0 ? _a : importWalletInput.reference,
8759
- deviceAuthKeys: { publicKey: deviceAuthKeys.publicKey, privateKey: deviceAuthKeys.privateKey },
8760
- passkeyChallengeType: this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined,
8761
- });
8545
+ const { signature, message } = await this.authService.getSignature({
8546
+ publicKey: deviceAuthKeys.publicKey,
8547
+ privateKey: deviceAuthKeys.privateKey,
8548
+ }, this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined);
8762
8549
  if ((importWalletInput.returnWalletOption === exports.ReturnWalletOption.ReturnOnlyEncryptedShares ||
8763
8550
  importWalletInput.returnWalletOption === exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed) &&
8764
8551
  !importWalletInput.keyShareOptions) {
@@ -8768,7 +8555,7 @@ class WalletHandlersService extends Base {
8768
8555
  errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
8769
8556
  });
8770
8557
  }
8771
- const { numberOfKeyShares, threshold } = (_b = importWalletInput.keyShareOptions) !== null && _b !== void 0 ? _b : {};
8558
+ const { numberOfKeyShares, threshold } = (_a = importWalletInput.keyShareOptions) !== null && _a !== void 0 ? _a : {};
8772
8559
  if (threshold && numberOfKeyShares && numberOfKeyShares < threshold) {
8773
8560
  throw new WallabyError({
8774
8561
  message: 'Number of shares must be greater than or equal to the threshold',
@@ -8778,11 +8565,10 @@ class WalletHandlersService extends Base {
8778
8565
  }
8779
8566
  const readyForTransportSeedPhrase = await this.cipher.encrypt({
8780
8567
  data: importWalletInput.seedPhrase,
8781
- encryptionKey: wallabyAuthPubKey,
8568
+ encryptionKey: importWalletInput.authenticationOptions.user.wallabyAuthPubKey,
8782
8569
  });
8783
8570
  const importWalletPayload = {
8784
- reference: importWalletInput.reference,
8785
- walletId: importWalletInput.walletId,
8571
+ reference: uuid.v4(),
8786
8572
  message,
8787
8573
  signature,
8788
8574
  encryptedSeed: readyForTransportSeedPhrase,
@@ -8791,7 +8577,7 @@ class WalletHandlersService extends Base {
8791
8577
  numShares: numberOfKeyShares !== null && numberOfKeyShares !== void 0 ? numberOfKeyShares : 0,
8792
8578
  threshold: threshold !== null && threshold !== void 0 ? threshold : 0,
8793
8579
  walletOwnershipType: exports.WalletOwnershipType.SingleOwner,
8794
- wallabyKeepsOne: (_d = (_c = importWalletInput.keyShareOptions) === null || _c === void 0 ? void 0 : _c.storeOneKeyShareWithWallaby) !== null && _d !== void 0 ? _d : false,
8580
+ wallabyKeepsOne: (_c = (_b = importWalletInput.keyShareOptions) === null || _b === void 0 ? void 0 : _b.storeOneKeyShareWithWallaby) !== null && _c !== void 0 ? _c : false,
8795
8581
  };
8796
8582
  const importWalletRequest = await this.request(WalletRoutes.importSeedPhraseV2, {
8797
8583
  payload: importWalletPayload,
@@ -8829,7 +8615,7 @@ class WalletHandlersService extends Base {
8829
8615
  }
8830
8616
  catch (error) {
8831
8617
  throw new WallabyError({
8832
- message: (_e = error.message) !== null && _e !== void 0 ? _e : 'Failed to handle importing the wallet',
8618
+ message: (_d = error.message) !== null && _d !== void 0 ? _d : 'Failed to handle importing the wallet',
8833
8619
  statusCode: error.statusCode,
8834
8620
  errorCode: error.errorCode,
8835
8621
  data: error.data,
@@ -8851,9 +8637,9 @@ class WalletHandlersService extends Base {
8851
8637
  var _a, _b, _c, _d, _e, _f;
8852
8638
  try {
8853
8639
  const { signature, message, hashedMessage } = await this.authService.getSignature({
8854
- deviceAuthKeys: { publicKey: deviceAuthKeys.publicKey, privateKey: deviceAuthKeys.privateKey },
8855
- passkeyChallengeType: exports.PasskeyChallengeType.AUTHENTICATION,
8856
- });
8640
+ publicKey: deviceAuthKeys.publicKey,
8641
+ privateKey: deviceAuthKeys.privateKey,
8642
+ }, exports.PasskeyChallengeType.AUTHENTICATION);
8857
8643
  if ((walletCreationInput.returnWalletOption === exports.ReturnWalletOption.ReturnOnlyEncryptedShares ||
8858
8644
  walletCreationInput.returnWalletOption === exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed) &&
8859
8645
  !walletCreationInput.keyShareOptions) {
@@ -9030,6 +8816,36 @@ class WalletHandlersService extends Base {
9030
8816
  });
9031
8817
  }
9032
8818
  }
8819
+ /**
8820
+ *
8821
+ * @param encryptedKeyShares - Encrypted key shares that are encrypted with the wallabyAuthPublicKey.
8822
+ * @param walletId - The ID of the wallet for which the seed phrase is being constructed.
8823
+ * @param deviceAuthKeys - The device authentication key pair used to sign the request.
8824
+ * @description This function constructs the seed phrase from encrypted key shares.
8825
+ * It retrieves the seed phrase by sending a request to the Wallaby API with the encrypted key shares.
8826
+ * The shares should be encrypted with the wallabyAuthPublicKey before passing them into this function.
8827
+ * @returns The function returns the encrypted seed phrase wrapped with client device public key.
8828
+ */
8829
+ async handleConstructingSeedPhraseFromShares({ encryptedKeyShares, walletId, deviceAuthKeys, }) {
8830
+ try {
8831
+ const { signature, message } = await this.authService.getSignature(deviceAuthKeys, exports.PasskeyChallengeType.AUTHENTICATION);
8832
+ const retrieveSeedPhraseResponse = await this.request(WalletRoutes.retrieveSeedPhrase, {
8833
+ payload: {
8834
+ walletId: walletId,
8835
+ signature,
8836
+ message,
8837
+ clientAuthPubKey: deviceAuthKeys.publicKey,
8838
+ recoveryPubKey: deviceAuthKeys.publicKey,
8839
+ encryptedShares: encryptedKeyShares,
8840
+ },
8841
+ });
8842
+ return retrieveSeedPhraseResponse.encryptedSeed;
8843
+ }
8844
+ catch (error) {
8845
+ logger.error('SDK::handleConstructingSeedPhraseFromShares::error', error);
8846
+ return Promise.reject(error);
8847
+ }
8848
+ }
9033
8849
  }
9034
8850
 
9035
8851
  class WalletService extends Base {
@@ -9139,6 +8955,7 @@ class WalletService extends Base {
9139
8955
  */
9140
8956
  async export({ walletId, authenticationOptions, exportOptions }) {
9141
8957
  try {
8958
+ const { user: { wallabyAuthPubKey }, } = authenticationOptions;
9142
8959
  if (!exportOptions.algorandSeedPhrase && !exportOptions.standardSeedPhrase && !exportOptions.keyShares) {
9143
8960
  throw new WallabyError({
9144
8961
  message: 'exportOptions must be provided with at least one of the following options: algorandSeedPhrase, standardSeedPhrase, keyShares',
@@ -9248,20 +9065,10 @@ class WalletService extends Base {
9248
9065
  });
9249
9066
  }
9250
9067
  const parsedPrimaryShare = safeJsonParse(encryptedPrimaryDeviceShare);
9251
- const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
9252
- const deviceAuthKeys = {
9253
- publicKey: deviceAuthPublicKey,
9254
- privateKey: decryptedDevicePrivateKey,
9255
- };
9256
- const { signature, message, wallabyAuthPubKey: ephemeralWallabyAuthPubKey, } = await this.authService.getSignature({
9257
- deviceAuthKeys,
9258
- walletId,
9259
- passkeyChallengeType: exports.PasskeyChallengeType.AUTHENTICATION,
9260
- });
9261
9068
  const wallabyBoundPrimaryShare = await this.cipher.prepareStoredDataForTransport({
9262
9069
  storedEncryptedData: parsedPrimaryShare,
9263
9070
  encryptedDevicePrivateKey: parsedDevicePrivateKey,
9264
- wallabyPublicKey: ephemeralWallabyAuthPubKey || authenticationOptions.user.wallabyAuthPubKey,
9071
+ wallabyPublicKey: wallabyAuthPubKey,
9265
9072
  options: {
9266
9073
  authType: this.deviceAuthType,
9267
9074
  password: authenticationOptions.password,
@@ -9269,18 +9076,17 @@ class WalletService extends Base {
9269
9076
  prfValue: authenticationOptions.prfValue,
9270
9077
  },
9271
9078
  });
9272
- const retrieveSeedPhraseResponse = await this.request(WalletRoutes.retrieveSeedPhrase, {
9273
- payload: {
9274
- walletId: walletId,
9275
- signature,
9276
- message,
9277
- clientAuthPubKey: deviceAuthKeys.publicKey,
9278
- recoveryPubKey: deviceAuthKeys.publicKey,
9279
- encryptedShares: [wallabyBoundPrimaryShare],
9079
+ const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
9080
+ const encryptedReconstructedSeedPhrase = await this.handlers.handleConstructingSeedPhraseFromShares({
9081
+ encryptedKeyShares: [wallabyBoundPrimaryShare],
9082
+ walletId,
9083
+ deviceAuthKeys: {
9084
+ publicKey: deviceAuthPublicKey,
9085
+ privateKey: decryptedDevicePrivateKey,
9280
9086
  },
9281
9087
  });
9282
9088
  decryptedSeedPhrase = await this.cipher.decrypt({
9283
- cipherText: retrieveSeedPhraseResponse.encryptedSeed,
9089
+ cipherText: encryptedReconstructedSeedPhrase,
9284
9090
  decryptionKey: decryptedDevicePrivateKey,
9285
9091
  });
9286
9092
  if (exportOptions.algorandSeedPhrase) {
@@ -9318,9 +9124,7 @@ class WalletService extends Base {
9318
9124
  * @returns {ImportWalletResponse} The wallet has been created successfully.
9319
9125
  */
9320
9126
  async import(input) {
9321
- var _a;
9322
9127
  try {
9323
- const requestReference = (_a = input.reference) !== null && _a !== void 0 ? _a : uuid.v4();
9324
9128
  const encryptedDevicePrivateKey = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);
9325
9129
  if (!encryptedDevicePrivateKey) {
9326
9130
  throw new WallabyError({
@@ -9351,7 +9155,7 @@ class WalletService extends Base {
9351
9155
  const importRequest = await this.handlers.handleImportWallet({
9352
9156
  publicKey: clientAuthPubKey,
9353
9157
  privateKey: decryptedDevicePrivateKey,
9354
- }, Object.assign(Object.assign({}, input), { reference: requestReference }));
9158
+ }, input);
9355
9159
  return importRequest;
9356
9160
  }
9357
9161
  catch (error) {
@@ -9365,15 +9169,11 @@ class WalletService extends Base {
9365
9169
  *
9366
9170
  * @param { RecoverWalletRequest } input - The request object containing the necessary parameters.
9367
9171
  * @returns { Promise<RecoverWalletResponse> } The response containing the recovered wallet details.
9368
- *
9369
- * @deprecated This function is deprecated and will be removed in the next major release. It only supports seed phrase recovery.
9370
- * Use `import` instead with the `RETURN_ONLY_ENCRYPTED_SEED_PHRASE` option to maintain the same behavior.
9371
9172
  */
9372
9173
  async recover(input) {
9373
9174
  var _a, _b;
9374
9175
  try {
9375
- const wallabyPublicKey = input.authenticationOptions.signatureMessageResponse.wallabyAuthPubKey ||
9376
- input.authenticationOptions.user.wallabyAuthPubKey;
9176
+ const wallabyPublicKey = input.authenticationOptions.user.wallabyAuthPubKey;
9377
9177
  const deviceAuthKeyPair = createIdentity();
9378
9178
  const credentialsKeyPair = await this.cipher.getCredentialsKeyPair({
9379
9179
  authType: this.deviceAuthType,
@@ -9413,37 +9213,27 @@ class WalletService extends Base {
9413
9213
  return recoverWithSeedPhraseResponse;
9414
9214
  }
9415
9215
  else if (input.decryptedShares) {
9416
- if (!input.decryptedShares.length) {
9216
+ const encryptedShares = await Promise.all(input.decryptedShares.map(async (decryptedShare) => {
9217
+ const encrypted = await this.cipher.encrypt({
9218
+ data: decryptedShare,
9219
+ encryptionKey: wallabyPublicKey,
9220
+ });
9221
+ return encrypted;
9222
+ }));
9223
+ if (!encryptedShares.length) {
9417
9224
  throw new WallabyError({
9418
9225
  message: 'Decrypted shares are required',
9419
9226
  statusCode: 400,
9420
9227
  errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
9421
9228
  });
9422
9229
  }
9423
- const { signature, message, wallabyAuthPubKey: ephemeralWallabyAuthPubKey, } = await this.authService.getSignature({
9230
+ const encryptedSeed = await this.handlers.handleConstructingSeedPhraseFromShares({
9231
+ encryptedKeyShares: encryptedShares,
9424
9232
  deviceAuthKeys: deviceAuthKeyPair,
9425
9233
  walletId: input.walletId,
9426
- passkeyChallengeType: exports.PasskeyChallengeType.AUTHENTICATION,
9427
- });
9428
- const transportEncryptionKey = ephemeralWallabyAuthPubKey || input.authenticationOptions.user.wallabyAuthPubKey;
9429
- const encryptedShares = await Promise.all(input.decryptedShares.map(async (decryptedShare) => {
9430
- return await this.cipher.encrypt({
9431
- data: decryptedShare,
9432
- encryptionKey: transportEncryptionKey,
9433
- });
9434
- }));
9435
- const retrieveSeedPhraseResponse = await this.request(WalletRoutes.retrieveSeedPhrase, {
9436
- payload: {
9437
- walletId: input.walletId,
9438
- signature,
9439
- message,
9440
- clientAuthPubKey: deviceAuthKeyPair.publicKey,
9441
- recoveryPubKey: deviceAuthKeyPair.publicKey,
9442
- encryptedShares,
9443
- },
9444
9234
  });
9445
9235
  const wallabyBoundRecoverySeedPhrase = await this.cipher.flipEncryptedData({
9446
- cipherText: retrieveSeedPhraseResponse.encryptedSeed,
9236
+ cipherText: encryptedSeed,
9447
9237
  decryptionKey: deviceAuthKeyPair.privateKey,
9448
9238
  encryptionKey: wallabyPublicKey,
9449
9239
  });
@@ -9501,9 +9291,17 @@ class WalletService extends Base {
9501
9291
  async retrieveShares({ walletId, authenticationOptions, deviceAuthKeys, }) {
9502
9292
  try {
9503
9293
  const signatureMessage = await this.authService.getSignature({
9504
- deviceAuthKeys: { publicKey: deviceAuthKeys.publicKey, privateKey: deviceAuthKeys.privateKey },
9505
- walletId,
9506
- });
9294
+ publicKey: deviceAuthKeys.publicKey,
9295
+ privateKey: deviceAuthKeys.privateKey,
9296
+ });
9297
+ // const response = await this.request<RetrieveSharesData>(WalletRoutes.retrieveShares, {
9298
+ // payload: {
9299
+ // walletId,
9300
+ // signature: signatureMessage.signature,
9301
+ // message: signatureMessage.message,
9302
+ // clientAuthPubKey: deviceAuthKeys.publicKey,
9303
+ // },
9304
+ // });
9507
9305
  const response = await this.api.wallets.retrieveShares({
9508
9306
  walletId: walletId,
9509
9307
  signature: signatureMessage.signature,
@@ -9684,7 +9482,6 @@ class WalletService extends Base {
9684
9482
  */
9685
9483
  async initAddNewDevice(input) {
9686
9484
  const { walletId, backupUrl, authenticationOptions } = input;
9687
- const wallabyPublicKey = authenticationOptions.signatureMessageResponse.wallabyAuthPubKey || authenticationOptions.user.wallabyAuthPubKey;
9688
9485
  const encryptedDevicePrivateKey = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);
9689
9486
  if (!encryptedDevicePrivateKey) {
9690
9487
  throw new WallabyError({
@@ -9745,7 +9542,7 @@ class WalletService extends Base {
9745
9542
  const wallabyBoundPrimaryShare = await this.cipher.prepareStoredDataForTransport({
9746
9543
  storedEncryptedData: parsedPrimaryShare,
9747
9544
  encryptedDevicePrivateKey: parsedEncryptedDevicePrivateKey,
9748
- wallabyPublicKey,
9545
+ wallabyPublicKey: authenticationOptions.user.wallabyAuthPubKey,
9749
9546
  options: {
9750
9547
  authType: this.deviceAuthType,
9751
9548
  password: authenticationOptions.password,
@@ -9804,11 +9601,22 @@ class WalletService extends Base {
9804
9601
  }
9805
9602
  const devicePublicKey = (_a = (await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey))) !== null && _a !== void 0 ? _a : publicKeyByPrivateKey(decryptedDevicePrivateKey);
9806
9603
  const signatureMessage = await this.authService.getSignature({
9807
- deviceAuthKeys: { publicKey: devicePublicKey, privateKey: decryptedDevicePrivateKey },
9808
- walletId: input.walletId,
9809
- passkeyChallengeType: exports.PasskeyChallengeType.REGISTRATION,
9810
- });
9811
- const wallabyPublicKey = signatureMessage.wallabyAuthPubKey || input.authenticationOptions.user.wallabyAuthPubKey;
9604
+ publicKey: devicePublicKey,
9605
+ privateKey: decryptedDevicePrivateKey,
9606
+ }, exports.PasskeyChallengeType.REGISTRATION);
9607
+ // const backUpResponse: AddNewDeviceResponse = await this.request(WalletRoutes.addNewDevice, {
9608
+ // payload: {
9609
+ // walletId: input.walletId,
9610
+ // message: signatureMessage.message,
9611
+ // signature: signatureMessage.signature,
9612
+ // clientAuthPubKey: devicePublicKey,
9613
+ // share: {
9614
+ // encrypted: input.encryptedShares[DEFAULT_BACKUP_SHARE_INDEX], // we only want to send the backup share to be rewrapped
9615
+ // wrappingPublicKey: input.authenticationOptions.user.wallabyAuthPubKey,
9616
+ // type: KeyTypeName.OwnerBackupDeviceShare,
9617
+ // },
9618
+ // },
9619
+ // });
9812
9620
  const backUpResponse = await this.api.wallets.addNewDevice({
9813
9621
  walletId: input.walletId,
9814
9622
  message: signatureMessage.message,
@@ -9816,7 +9624,7 @@ class WalletService extends Base {
9816
9624
  clientAuthPubKey: devicePublicKey,
9817
9625
  share: {
9818
9626
  encrypted: input.encryptedShares[DEFAULT_BACKUP_SHARE_INDEX], // we only want to send the backup share to be rewrapped
9819
- wrappingPublicKey: wallabyPublicKey,
9627
+ wrappingPublicKey: input.authenticationOptions.user.wallabyAuthPubKey,
9820
9628
  type: exports.KeyTypeName.OwnerBackupDeviceShare,
9821
9629
  },
9822
9630
  });
@@ -9824,8 +9632,7 @@ class WalletService extends Base {
9824
9632
  backUpResponse.share, // this is the backup share that is now rewrapped with the new device public key.
9825
9633
  {
9826
9634
  encrypted: input.encryptedShares[DEFAULT_PRIMARY_SHARE_INDEX],
9827
- wrappingPublicKey: input.authenticationOptions.signatureMessageResponse.wallabyAuthPubKey ||
9828
- input.authenticationOptions.user.wallabyAuthPubKey, // this is the primary share still wrapped from the QR code.
9635
+ wrappingPublicKey: input.authenticationOptions.user.wallabyAuthPubKey, // this is the primary share still wrapped from the QR code.
9829
9636
  type: exports.KeyTypeName.OwnerMainDeviceShare,
9830
9637
  },
9831
9638
  ];
@@ -9882,28 +9689,12 @@ class WalletService extends Base {
9882
9689
  });
9883
9690
  }
9884
9691
  const parsedDevicePrivateKey = safeJsonParse(devicePrivateKey);
9885
- const derivedCredentialsKeyPair = await this.cipher.getCredentialsKeyPair({
9886
- authType: this.deviceAuthType,
9887
- password: input.authenticationOptions.password,
9888
- salt: input.authenticationOptions.clientSalt,
9889
- prfValue: input.authenticationOptions.prfValue,
9890
- });
9891
- const decryptedDevicePrivateKey = await this.cipher.decrypt({
9892
- cipherText: parsedDevicePrivateKey,
9893
- decryptionKey: derivedCredentialsKeyPair.privateKey,
9894
- });
9895
- const devicePublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
9896
- const { signature, message, wallabyAuthPubKey: ephemeralWallabyAuthPubKey, } = await this.authService.getSignature({
9897
- deviceAuthKeys: { privateKey: decryptedDevicePrivateKey, publicKey: devicePublicKey },
9898
- walletId,
9899
- });
9900
- const wallabyPublicKey = ephemeralWallabyAuthPubKey || input.authenticationOptions.user.wallabyAuthPubKey;
9901
9692
  if (storedSeedPhrase) {
9902
9693
  const parsedStoredSeedPhrase = safeJsonParse(storedSeedPhrase);
9903
9694
  transportSeed = await this.cipher.prepareStoredDataForTransport({
9904
9695
  storedEncryptedData: parsedStoredSeedPhrase,
9905
9696
  encryptedDevicePrivateKey: parsedDevicePrivateKey,
9906
- wallabyPublicKey,
9697
+ wallabyPublicKey: input.authenticationOptions.user.wallabyAuthPubKey,
9907
9698
  options: {
9908
9699
  authType: this.deviceAuthType,
9909
9700
  password: input.authenticationOptions.password,
@@ -9917,7 +9708,7 @@ class WalletService extends Base {
9917
9708
  transportKeyShare = await this.cipher.prepareStoredDataForTransport({
9918
9709
  storedEncryptedData: parsedPrimaryKeyShare,
9919
9710
  encryptedDevicePrivateKey: parsedDevicePrivateKey,
9920
- wallabyPublicKey,
9711
+ wallabyPublicKey: input.authenticationOptions.user.wallabyAuthPubKey,
9921
9712
  options: {
9922
9713
  authType: this.deviceAuthType,
9923
9714
  password: input.authenticationOptions.password,
@@ -9933,6 +9724,21 @@ class WalletService extends Base {
9933
9724
  errorCode: 'sdk_private_key_not_found',
9934
9725
  });
9935
9726
  }
9727
+ const derivedCredentialsKeyPair = await this.cipher.getCredentialsKeyPair({
9728
+ authType: this.deviceAuthType,
9729
+ password: input.authenticationOptions.password,
9730
+ salt: input.authenticationOptions.clientSalt,
9731
+ prfValue: input.authenticationOptions.prfValue,
9732
+ });
9733
+ const decryptedDevicePrivateKey = await this.cipher.decrypt({
9734
+ cipherText: parsedDevicePrivateKey,
9735
+ decryptionKey: derivedCredentialsKeyPair.privateKey,
9736
+ });
9737
+ const devicePublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
9738
+ const { signature, message } = await this.authService.getSignature({
9739
+ privateKey: decryptedDevicePrivateKey,
9740
+ publicKey: devicePublicKey,
9741
+ });
9936
9742
  const response = await this.request(WalletRoutes.generateWalletAddresses, {
9937
9743
  payload: {
9938
9744
  walletId,
@@ -10124,8 +9930,8 @@ class WalletService extends Base {
10124
9930
  // During migration, we need to authenticate but avoid creating conflicting device keypairs
10125
9931
  const devicePublicKey = publicKeyByPrivateKey(decryptedPrivateKey);
10126
9932
  const signInSignatureMessage = await this.authService.getSignature({
10127
- deviceAuthKeys: { publicKey: devicePublicKey, privateKey: decryptedPrivateKey },
10128
- walletId,
9933
+ publicKey: devicePublicKey,
9934
+ privateKey: decryptedPrivateKey,
10129
9935
  });
10130
9936
  // this would ensure the stored public key is consistent with wallaby and can authenticate the user.
10131
9937
  const authResponse = await this.request(AuthRoutes.signIn, {
@@ -10151,6 +9957,7 @@ class WalletService extends Base {
10151
9957
  // Store authentication tokens
10152
9958
  await this.localStorageService.saveInBulk([
10153
9959
  { key: exports.LocalStorageItems.AccessToken, value: authResponse.accessToken },
9960
+ { key: exports.LocalStorageItems.WallabyAuthPubKey, value: authResponse.user.wallabyAuthPubKey },
10154
9961
  { key: exports.V2KeyNames.EncryptedStandardSeedPhrase, value: encryptedV2Seed, walletId },
10155
9962
  { key: exports.V2KeyNames.EncryptedDevicePrivateKey, value: encryptedV2PrivateKey },
10156
9963
  ]);
@@ -10251,11 +10058,9 @@ class WalletService extends Base {
10251
10058
  const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
10252
10059
  // Get signature message
10253
10060
  const signatureMessage = await this.authService.getSignature({
10254
- deviceAuthKeys: { publicKey: deviceAuthPublicKey, privateKey: decryptedDevicePrivateKey },
10255
- walletId,
10256
- passkeyChallengeType: exports.PasskeyChallengeType.AUTHENTICATION,
10257
- });
10258
- const wallabyPublicKey = signatureMessage.wallabyAuthPubKey || authenticationOptions.user.wallabyAuthPubKey;
10061
+ publicKey: deviceAuthPublicKey,
10062
+ privateKey: decryptedDevicePrivateKey,
10063
+ }, exports.PasskeyChallengeType.AUTHENTICATION);
10259
10064
  // Prepare encrypted data (seed phrase or key shares)
10260
10065
  const sharesEncryptedWithWallabyPubKey = [];
10261
10066
  let readyForTransportSeedPhrase = undefined;
@@ -10275,7 +10080,7 @@ class WalletService extends Base {
10275
10080
  readyForTransportSeedPhrase = await this.cipher.prepareStoredDataForTransport({
10276
10081
  storedEncryptedData: parsedSeedPhrase,
10277
10082
  encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
10278
- wallabyPublicKey,
10083
+ wallabyPublicKey: user.wallabyAuthPubKey,
10279
10084
  options: {
10280
10085
  authType: this.deviceAuthType,
10281
10086
  password,
@@ -10290,7 +10095,7 @@ class WalletService extends Base {
10290
10095
  const readyForTransportShare = await this.cipher.prepareStoredDataForTransport({
10291
10096
  storedEncryptedData: parsedPrimaryShare,
10292
10097
  encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
10293
- wallabyPublicKey,
10098
+ wallabyPublicKey: user.wallabyAuthPubKey,
10294
10099
  options: {
10295
10100
  authType: this.deviceAuthType,
10296
10101
  password,
@@ -10459,7 +10264,6 @@ class WalletService extends Base {
10459
10264
  seedPhrase: decryptedSeedPhrase,
10460
10265
  storeSeedPhrase: false,
10461
10266
  returnWalletOption: exports.ReturnWalletOption.ReturnOnlyEncryptedShares, // always only return the encrypted shares
10462
- walletId: input.walletId,
10463
10267
  keyShareOptions: {
10464
10268
  threshold: 2,
10465
10269
  numberOfKeyShares: 3,
@@ -10510,31 +10314,20 @@ class WalletService extends Base {
10510
10314
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10511
10315
  }
10512
10316
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
10513
- const deviceAuthKeys = {
10514
- publicKey: clientPublicKey,
10515
- privateKey: decryptedClientAuthPrivKey,
10516
- };
10517
- const { signature, message, wallabyAuthPubKey: ephemeralWallabyAuthPubKey, } = await this.authService.getSignature({
10518
- deviceAuthKeys,
10519
- walletId: input.walletId,
10520
- passkeyChallengeType: exports.PasskeyChallengeType.AUTHENTICATION,
10521
- });
10522
10317
  const flippedEncryptedPrimaryShare = await this.cipher.encrypt({
10523
10318
  data: decryptedPrimaryShare,
10524
- encryptionKey: ephemeralWallabyAuthPubKey || authentication.user.wallabyAuthPubKey,
10319
+ encryptionKey: authentication.user.wallabyAuthPubKey,
10525
10320
  });
10526
- const retrieveSeedPhraseResponse = await this.request(WalletRoutes.retrieveSeedPhrase, {
10527
- payload: {
10528
- walletId: input.walletId,
10529
- signature,
10530
- message,
10531
- clientAuthPubKey: deviceAuthKeys.publicKey,
10532
- recoveryPubKey: deviceAuthKeys.publicKey,
10533
- encryptedShares: [flippedEncryptedPrimaryShare],
10321
+ const reconstructedSeedPhrase = await this.handlers.handleConstructingSeedPhraseFromShares({
10322
+ walletId: input.walletId,
10323
+ encryptedKeyShares: [flippedEncryptedPrimaryShare],
10324
+ deviceAuthKeys: {
10325
+ publicKey: clientPublicKey,
10326
+ privateKey: decryptedClientAuthPrivKey,
10534
10327
  },
10535
10328
  });
10536
10329
  decryptedSeedPhrase = await this.cipher.decrypt({
10537
- cipherText: retrieveSeedPhraseResponse.encryptedSeed,
10330
+ cipherText: reconstructedSeedPhrase,
10538
10331
  decryptionKey: decryptedClientAuthPrivKey,
10539
10332
  });
10540
10333
  }
@@ -10641,7 +10434,7 @@ class WalletDataService extends Base {
10641
10434
  * Note: Either chainName or tokenStandard must be provided.
10642
10435
  * @returns { FetchBalanceData } Returns an array of the requested tokens balances.
10643
10436
  */
10644
- async getMultiTokenBalances({ walletId, tokensAndAddressesList, }) {
10437
+ async getMultiTokenBalances({ walletId, tokensAndAddressesList }) {
10645
10438
  try {
10646
10439
  if (!tokensAndAddressesList.length) {
10647
10440
  throw new WallabyError({
@@ -11229,17 +11022,18 @@ class Swap extends Base {
11229
11022
  this.walletService = new WalletService(config);
11230
11023
  }
11231
11024
  /**
11232
- * Gets a swap quote between two assets (from/to), including fees, min output, and slippage limits.
11025
+ * Gets a swap quote between two assets, including fees, min output, and slippage limits.
11233
11026
  *
11234
11027
  * @public
11235
11028
  * @param {SwapQuoteRequest} request - The swap quote request parameters
11236
11029
  * @returns {Promise<SwapQuoteResponse>} A promise that resolves with the swap quote
11237
11030
  */
11238
- async getQuote({ walletId, fromAsset, toAsset, fromAmount, toAmount }) {
11031
+ async getQuote(request) {
11239
11032
  try {
11240
- if (!walletId || !fromAsset || !toAsset) {
11033
+ const { walletId, fromAssetConfigId, toAssetConfigId, fromAmount, toAmount, slippage } = request;
11034
+ if (!walletId || !fromAssetConfigId || !toAssetConfigId) {
11241
11035
  throw new WallabyError({
11242
- message: 'Missing required parameters: walletId, fromAsset, and toAsset are required',
11036
+ message: 'Missing required parameters: walletId, fromAssetConfigId, and toAssetConfigId',
11243
11037
  statusCode: 400,
11244
11038
  errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11245
11039
  });
@@ -11251,10 +11045,16 @@ class Swap extends Base {
11251
11045
  errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11252
11046
  });
11253
11047
  }
11254
- // Build path with walletId, but exclude it from request body
11048
+ if (fromAmount && toAmount) {
11049
+ throw new WallabyError({
11050
+ message: 'Only one of fromAmount or toAmount may be provided, not both',
11051
+ statusCode: 400,
11052
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
11053
+ });
11054
+ }
11255
11055
  const routePayload = { walletId };
11256
- const requestBody = Object.assign(Object.assign({ fromAsset,
11257
- toAsset }, (fromAmount && { fromAmount })), (toAmount && { toAmount }));
11056
+ const requestBody = Object.assign(Object.assign(Object.assign({ fromAssetConfigId,
11057
+ toAssetConfigId }, (fromAmount && { fromAmount })), (toAmount && { toAmount })), (slippage != null && { slippage }));
11258
11058
  const response = await this.request(Object.assign(Object.assign({}, SwapRoutes.getQuote), { fullPath: SwapRoutes.getQuote.fullPath(routePayload) }), {
11259
11059
  payload: requestBody,
11260
11060
  });
@@ -11398,11 +11198,9 @@ class Swap extends Base {
11398
11198
  const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
11399
11199
  // Get signature message
11400
11200
  const signatureMessage = await this.authService.getSignature({
11401
- deviceAuthKeys: { publicKey: deviceAuthPublicKey, privateKey: decryptedDevicePrivateKey },
11402
- passkeyChallengeType: this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined,
11403
- walletId,
11404
- });
11405
- const wallabyPublicKey = signatureMessage.wallabyAuthPubKey || authenticationOptions.user.wallabyAuthPubKey;
11201
+ publicKey: deviceAuthPublicKey,
11202
+ privateKey: decryptedDevicePrivateKey,
11203
+ }, this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined);
11406
11204
  // Prepare encrypted data (seed phrase or key shares)
11407
11205
  const sharesEncryptedWithWallabyPubKey = [];
11408
11206
  let readyForTransportSeedPhrase = undefined;
@@ -11423,7 +11221,7 @@ class Swap extends Base {
11423
11221
  readyForTransportSeedPhrase = await this.cipher.prepareStoredDataForTransport({
11424
11222
  storedEncryptedData: parsedSeedPhrase,
11425
11223
  encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11426
- wallabyPublicKey,
11224
+ wallabyPublicKey: user.wallabyAuthPubKey,
11427
11225
  options: {
11428
11226
  authType: this.deviceAuthType,
11429
11227
  password,
@@ -11438,7 +11236,7 @@ class Swap extends Base {
11438
11236
  const readyForTransportShare = await this.cipher.prepareStoredDataForTransport({
11439
11237
  storedEncryptedData: parsedPrimaryShare,
11440
11238
  encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11441
- wallabyPublicKey,
11239
+ wallabyPublicKey: user.wallabyAuthPubKey,
11442
11240
  options: {
11443
11241
  authType: this.deviceAuthType,
11444
11242
  password,
@@ -11693,7 +11491,7 @@ class Transactions extends Base {
11693
11491
  * @param {BlockchainName} blockchain
11694
11492
  * @returns {FeeEstimateRequest}
11695
11493
  */
11696
- async estimateFee({ originAddress, recipientAddress, amount, transactionType, token, }) {
11494
+ async estimateFee({ originAddress, recipientAddress, amount, token, transactionType, }) {
11697
11495
  try {
11698
11496
  const response = await this.request(TransactionsRoutes.estimateFee, {
11699
11497
  queryParams: {
@@ -12036,11 +11834,9 @@ class Transactions extends Base {
12036
11834
  const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
12037
11835
  // Get signature message
12038
11836
  const signatureMessage = await this.authService.getSignature({
12039
- deviceAuthKeys: { publicKey: deviceAuthPublicKey, privateKey: decryptedDevicePrivateKey },
12040
- walletId,
12041
- passkeyChallengeType: this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined,
12042
- });
12043
- const wallabyPublicKey = signatureMessage.wallabyAuthPubKey || authenticationOptions.user.wallabyAuthPubKey;
11837
+ publicKey: deviceAuthPublicKey,
11838
+ privateKey: decryptedDevicePrivateKey,
11839
+ }, this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined);
12044
11840
  // Prepare encrypted data (seed phrase or key shares)
12045
11841
  const sharesEncryptedWithWallabyPubKey = [];
12046
11842
  let readyForTransportSeedPhrase = undefined;
@@ -12061,7 +11857,7 @@ class Transactions extends Base {
12061
11857
  readyForTransportSeedPhrase = await this.cipher.prepareStoredDataForTransport({
12062
11858
  storedEncryptedData: parsedSeedPhrase,
12063
11859
  encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
12064
- wallabyPublicKey,
11860
+ wallabyPublicKey: user.wallabyAuthPubKey,
12065
11861
  options: {
12066
11862
  authType: this.deviceAuthType,
12067
11863
  password,
@@ -12076,7 +11872,7 @@ class Transactions extends Base {
12076
11872
  const readyForTransportShare = await this.cipher.prepareStoredDataForTransport({
12077
11873
  storedEncryptedData: parsedPrimaryShare,
12078
11874
  encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
12079
- wallabyPublicKey,
11875
+ wallabyPublicKey: user.wallabyAuthPubKey,
12080
11876
  options: {
12081
11877
  authType: this.deviceAuthType,
12082
11878
  password,
@@ -12165,7 +11961,6 @@ exports.InvalidUserIdError = InvalidUserIdError;
12165
11961
  exports.InvalidUserIdLengthError = InvalidUserIdLengthError;
12166
11962
  exports.MalformedPubKeyCredParamsError = MalformedPubKeyCredParamsError;
12167
11963
  exports.NativeError = NativeError;
12168
- exports.NetworkDiagnostic = NetworkDiagnostic;
12169
11964
  exports.NoCredentialsError = NoCredentialsError;
12170
11965
  exports.NotAllowedError = NotAllowedError;
12171
11966
  exports.PasskeyErrorCodes = PasskeyErrorCodes;