wallaby-cash 2.2.8 → 2.2.10

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.d.ts CHANGED
@@ -2,6 +2,7 @@ import { WallabyConfig } from './types';
2
2
  import { AuthService, WalletService, WalletDataService, Utils, Merchants } from './lib';
3
3
  import { System } from './lib/system';
4
4
  import { Transactions } from './lib/transactions';
5
+ import { Swap } from './lib/swap';
5
6
  import { HttpApi } from './lib/api/api';
6
7
  export * from './types';
7
8
  export * from './eth-crypto-utils';
@@ -42,6 +43,11 @@ export declare class Wallaby {
42
43
  * The `transactions` domain contains all transactions calls to Wallaby's APIs.
43
44
  */
44
45
  readonly transactions: Transactions;
46
+ /**
47
+ * The `swap` domain contains all swap-related calls to Wallaby's APIs.
48
+ * @public
49
+ */
50
+ readonly swap: Swap;
45
51
  /**
46
52
  * The `merchants` domain contains all merchants admin calls.
47
53
  *
package/dist/index.esm.js CHANGED
@@ -362,6 +362,7 @@ var ErrorResponseCodes;
362
362
  ErrorResponseCodes["sdk_missing_parameter"] = "sdk_missing_parameter";
363
363
  ErrorResponseCodes["sdk_invalid_parameter"] = "sdk_invalid_parameter";
364
364
  ErrorResponseCodes["sdk_wrong_password"] = "sdk_wrong_password";
365
+ ErrorResponseCodes["sdk_no_valid_seed_option"] = "sdk_no_valid_seed_option";
365
366
  // passkey errors
366
367
  ErrorResponseCodes["sdk_passkey_prf_not_available"] = "sdk_passkey_prf_not_available";
367
368
  ErrorResponseCodes["sdk_passkey_challenge_unavailable"] = "sdk_passkey_challenge_unavailable";
@@ -775,7 +776,17 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
775
776
  { type: 'public-key', alg: PublicKeyCredentialAlgorithm.RS256 },
776
777
  { type: 'public-key', alg: PublicKeyCredentialAlgorithm.ES256 },
777
778
  ];
778
- const currentPackageVersion = "2.2.8";
779
+ const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
780
+ const currentPackageVersion = "2.2.10";
781
+
782
+ /**
783
+ * Storage keys adapter for Storage interface across different platforms.
784
+ *
785
+ * This sdk uses keys like "wsdk:version:key-name" but `SecureStore` doesn't allow colons in key names,
786
+ * Valid SecureStore key characters: alphanumeric, ".", "-", "_"
787
+ *
788
+ */
789
+ const normalizeKey = (key) => key.replace(/:/g, '_');
779
790
 
780
791
  const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
781
792
 
@@ -5037,6 +5048,9 @@ class StorageService {
5037
5048
  else {
5038
5049
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5039
5050
  }
5051
+ if (!isWeb) {
5052
+ storageKey = normalizeKey(storageKey);
5053
+ }
5040
5054
  const item = await this.getItem(storageKey);
5041
5055
  if (!item) {
5042
5056
  logger.debug(`(404): Item with key ${storageKey} was not found in storage.`);
@@ -5070,6 +5084,9 @@ class StorageService {
5070
5084
  else {
5071
5085
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5072
5086
  }
5087
+ if (!isWeb) {
5088
+ storageKey = normalizeKey(storageKey);
5089
+ }
5073
5090
  let valueToStore;
5074
5091
  if (this._keysProtectedByMasterKey.includes(key)) {
5075
5092
  const wrappedByMasterKey = this.cipher.encryptWithMasterKey({ data: value });
@@ -5094,6 +5111,9 @@ class StorageService {
5094
5111
  else {
5095
5112
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5096
5113
  }
5114
+ if (!isWeb) {
5115
+ storageKey = normalizeKey(storageKey);
5116
+ }
5097
5117
  return await this.removeItem(storageKey);
5098
5118
  }
5099
5119
  setItem(key, value) {
@@ -7483,6 +7503,24 @@ const TransactionsRoutes = {
7483
7503
  },
7484
7504
  };
7485
7505
 
7506
+ const SwapRoutes = {
7507
+ getQuote: {
7508
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swap/quote`,
7509
+ method: RequestMethod.Post,
7510
+ requiresAccessToken: true,
7511
+ },
7512
+ executeSwap: {
7513
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swap`,
7514
+ method: RequestMethod.Post,
7515
+ requiresAccessToken: true,
7516
+ },
7517
+ getSwaps: {
7518
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swaps`,
7519
+ method: RequestMethod.Get,
7520
+ requiresAccessToken: true,
7521
+ },
7522
+ };
7523
+
7486
7524
  /* eslint-disable no-useless-catch */
7487
7525
  /**
7488
7526
  * Web Authenticator Implementation
@@ -10426,7 +10464,7 @@ class WalletDataService extends Base {
10426
10464
  });
10427
10465
  }
10428
10466
  const response = await this.request(WalletRoutes.getMultiTokenBalances, {
10429
- payload: { assets: tokensAndAddressesList },
10467
+ payload: { tokensAndAddressesList },
10430
10468
  });
10431
10469
  return response;
10432
10470
  }
@@ -10514,10 +10552,20 @@ class WalletDataService extends Base {
10514
10552
  * Get all assets that exist in a certain wallet, by specifying a wallet ID
10515
10553
  * @param walletId Wallaby's wallet ID
10516
10554
  * @param { BasicQueryOptions } queryOptions Optional query options
10555
+ * @param { string } [queryOptions.search] - Search assets by name or symbol (minimum 3 characters)
10556
+ * @param { BlockchainName } [queryOptions.chainName] - Filter assets by blockchain name
10517
10557
  * @returns { GetUserAssetsByWalletIdData } Returns all assets belonging in a certain wallet ID
10518
10558
  */
10519
10559
  async getWalletAssets({ walletId, queryOptions }) {
10520
10560
  try {
10561
+ // Validate search parameter if provided
10562
+ if ((queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.search) !== undefined && queryOptions.search.length < 3) {
10563
+ throw new WallabyError({
10564
+ message: 'Search parameter must be at least 3 characters long',
10565
+ statusCode: 400,
10566
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
10567
+ });
10568
+ }
10521
10569
  const response = await this.request(WalletRoutes.getWalletAssets, {
10522
10570
  payload: {
10523
10571
  walletId,
@@ -10987,6 +11035,246 @@ class HttpApi extends Base {
10987
11035
  }
10988
11036
  }
10989
11037
 
11038
+ class Swap extends Base {
11039
+ constructor(config) {
11040
+ super(config);
11041
+ this.authService = new AuthService(config);
11042
+ this.walletService = new WalletService(config);
11043
+ }
11044
+ /**
11045
+ * Gets a swap quote between two assets (from/to), including fees, min output, and slippage limits.
11046
+ *
11047
+ * @public
11048
+ * @param {SwapQuoteRequest} request - The swap quote request parameters
11049
+ * @returns {Promise<SwapQuoteResponse>} A promise that resolves with the swap quote
11050
+ */
11051
+ async getQuote({ walletId, fromAsset, toAsset, fromAmount, toAmount }) {
11052
+ try {
11053
+ if (!walletId || !fromAsset || !toAsset) {
11054
+ throw new WallabyError({
11055
+ message: 'Missing required parameters: walletId, fromAsset, and toAsset are required',
11056
+ statusCode: 400,
11057
+ errorCode: ErrorResponseCodes.sdk_missing_parameter,
11058
+ });
11059
+ }
11060
+ if (!fromAmount && !toAmount) {
11061
+ throw new WallabyError({
11062
+ message: 'Either fromAmount or toAmount must be provided',
11063
+ statusCode: 400,
11064
+ errorCode: ErrorResponseCodes.sdk_missing_parameter,
11065
+ });
11066
+ }
11067
+ // Build path with walletId, but exclude it from request body
11068
+ const routePayload = { walletId };
11069
+ const requestBody = Object.assign(Object.assign({ fromAsset,
11070
+ toAsset }, (fromAmount && { fromAmount })), (toAmount && { toAmount }));
11071
+ const response = await this.request(Object.assign(Object.assign({}, SwapRoutes.getQuote), { fullPath: SwapRoutes.getQuote.fullPath(routePayload) }), {
11072
+ payload: requestBody,
11073
+ });
11074
+ return response;
11075
+ }
11076
+ catch (error) {
11077
+ logger.error('SDK::Swap::getQuote::error', error);
11078
+ throw error;
11079
+ }
11080
+ }
11081
+ /**
11082
+ * Executes a swap using a previously generated quote.
11083
+ *
11084
+ * @public
11085
+ * @param {ExecuteSwapRequest} request - The execute swap request parameters
11086
+ * @returns {Promise<ExecuteSwapResponse>} A promise that resolves with the swap execution response
11087
+ */
11088
+ async executeSwap({ walletId, quoteId, authenticationOptions }) {
11089
+ try {
11090
+ // Only attempt migration if we have password auth and V2 storage might be incomplete
11091
+ if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11092
+ try {
11093
+ await this.walletService.handleUpdateToV2({
11094
+ password: authenticationOptions.password,
11095
+ walletId: walletId,
11096
+ });
11097
+ }
11098
+ catch (error) {
11099
+ logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11100
+ throw new WallabyError({
11101
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11102
+ statusCode: 500,
11103
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
11104
+ });
11105
+ }
11106
+ }
11107
+ const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11108
+ let swapResponse;
11109
+ // Build path with walletId, but exclude it from request body
11110
+ const routePayload = { walletId };
11111
+ if (readyForTransportSeedPhrase) {
11112
+ swapResponse = await this.request(Object.assign(Object.assign({}, SwapRoutes.executeSwap), { fullPath: SwapRoutes.executeSwap.fullPath(routePayload) }), {
11113
+ payload: {
11114
+ quoteId,
11115
+ message: signatureMessage.message,
11116
+ signature: signatureMessage.signature,
11117
+ clientAuthPubKey: deviceAuthPublicKey,
11118
+ encryptedSeed: readyForTransportSeedPhrase,
11119
+ },
11120
+ });
11121
+ }
11122
+ else if (hasShares) {
11123
+ swapResponse = await this.request(Object.assign(Object.assign({}, SwapRoutes.executeSwap), { fullPath: SwapRoutes.executeSwap.fullPath(routePayload) }), {
11124
+ payload: {
11125
+ quoteId,
11126
+ message: signatureMessage.message,
11127
+ signature: signatureMessage.signature,
11128
+ clientAuthPubKey: deviceAuthPublicKey,
11129
+ encryptedShares: sharesEncryptedWithWallabyPubKey,
11130
+ },
11131
+ });
11132
+ }
11133
+ else {
11134
+ throw new WallabyError({
11135
+ message: 'No valid seed option found on this device.',
11136
+ statusCode: 400,
11137
+ errorCode: ErrorResponseCodes.sdk_no_valid_seed_option,
11138
+ });
11139
+ }
11140
+ return swapResponse;
11141
+ }
11142
+ catch (error) {
11143
+ logger.error('SDK::Swap::executeSwap::error', error);
11144
+ throw error;
11145
+ }
11146
+ }
11147
+ /**
11148
+ * Lists executed swap transactions for a given wallet, with optional date and pagination filters.
11149
+ *
11150
+ * @public
11151
+ * @param {GetSwapsRequest} request - The get swaps request parameters
11152
+ * @returns {Promise<GetSwapsResponse>} A promise that resolves with the list of swaps
11153
+ */
11154
+ async getSwaps({ walletId, queryParams }) {
11155
+ try {
11156
+ if (!walletId) {
11157
+ throw new WallabyError({
11158
+ message: 'Missing required parameter: walletId',
11159
+ statusCode: 400,
11160
+ errorCode: ErrorResponseCodes.sdk_missing_parameter,
11161
+ });
11162
+ }
11163
+ // Build path with walletId
11164
+ const routePayload = { walletId };
11165
+ const response = await this.request(Object.assign(Object.assign({}, SwapRoutes.getSwaps), { fullPath: SwapRoutes.getSwaps.fullPath(routePayload) }), {
11166
+ queryParams: queryParams,
11167
+ });
11168
+ return response;
11169
+ }
11170
+ catch (error) {
11171
+ logger.error('SDK::Swap::getSwaps::error', error);
11172
+ throw error;
11173
+ }
11174
+ }
11175
+ /**
11176
+ * Prepares authentication data and encrypted payload for swap requests
11177
+ * @private
11178
+ */
11179
+ async prepareSwapAuth(authenticationOptions, walletId) {
11180
+ const { password, prfValue, user, clientSalt: authClientSalt } = authenticationOptions;
11181
+ const encryptedDevicePrivateKey = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey, {
11182
+ walletId,
11183
+ });
11184
+ if (!encryptedDevicePrivateKey) {
11185
+ throw new WallabyError({
11186
+ message: 'No private key was found on this device.',
11187
+ statusCode: 400,
11188
+ errorCode: ErrorResponseCodes.sdk_private_key_not_found,
11189
+ });
11190
+ }
11191
+ // Get credentials key pair for device private key decryption
11192
+ const clientSalt = authClientSalt || user.clientSalt;
11193
+ const credentialsKeyPair = await this.cipher.getCredentialsKeyPair({
11194
+ authType: this.deviceAuthType,
11195
+ password,
11196
+ prfValue,
11197
+ salt: clientSalt,
11198
+ });
11199
+ // Decrypt device private key
11200
+ const decryptedDevicePrivateKey = await this.cipher.decrypt({
11201
+ cipherText: JSON.parse(encryptedDevicePrivateKey),
11202
+ decryptionKey: credentialsKeyPair.privateKey,
11203
+ });
11204
+ if (!decryptedDevicePrivateKey) {
11205
+ throw new WallabyError({
11206
+ message: 'Credentials are wrong, please pass the correct credentials.',
11207
+ statusCode: 400,
11208
+ errorCode: ErrorResponseCodes.sdk_private_key_decryption_failed,
11209
+ });
11210
+ }
11211
+ const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
11212
+ // Get signature message
11213
+ const signatureMessage = await this.authService.getSignature({
11214
+ publicKey: deviceAuthPublicKey,
11215
+ privateKey: decryptedDevicePrivateKey,
11216
+ }, this.deviceAuthType === AuthType.Passkey ? PasskeyChallengeType.AUTHENTICATION : undefined);
11217
+ // Prepare encrypted data (seed phrase or key shares)
11218
+ const sharesEncryptedWithWallabyPubKey = [];
11219
+ let readyForTransportSeedPhrase = undefined;
11220
+ const primaryKeyShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, { walletId });
11221
+ if (!primaryKeyShare) {
11222
+ // No primary share, try seed phrase
11223
+ const encryptedSeedPhrase = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, {
11224
+ walletId,
11225
+ });
11226
+ if (!encryptedSeedPhrase) {
11227
+ throw new WallabyError({
11228
+ message: 'Your device does not have a seed phrase or an operating share to sign the transaction.',
11229
+ statusCode: 400,
11230
+ errorCode: ErrorResponseCodes.sdk_seed_phrase_not_found,
11231
+ });
11232
+ }
11233
+ const parsedSeedPhrase = safeJsonParse(encryptedSeedPhrase);
11234
+ readyForTransportSeedPhrase = await this.cipher.prepareStoredDataForTransport({
11235
+ storedEncryptedData: parsedSeedPhrase,
11236
+ encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11237
+ wallabyPublicKey: user.wallabyAuthPubKey,
11238
+ options: {
11239
+ authType: this.deviceAuthType,
11240
+ password,
11241
+ prfValue,
11242
+ salt: clientSalt,
11243
+ },
11244
+ });
11245
+ }
11246
+ else {
11247
+ // Use primary key share
11248
+ const parsedPrimaryShare = safeJsonParse(primaryKeyShare);
11249
+ const readyForTransportShare = await this.cipher.prepareStoredDataForTransport({
11250
+ storedEncryptedData: parsedPrimaryShare,
11251
+ encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11252
+ wallabyPublicKey: user.wallabyAuthPubKey,
11253
+ options: {
11254
+ authType: this.deviceAuthType,
11255
+ password,
11256
+ prfValue,
11257
+ salt: clientSalt,
11258
+ },
11259
+ });
11260
+ sharesEncryptedWithWallabyPubKey.push(readyForTransportShare);
11261
+ }
11262
+ return Object.freeze({
11263
+ deviceAuthPublicKey,
11264
+ signatureMessage,
11265
+ readyForTransportSeedPhrase,
11266
+ sharesEncryptedWithWallabyPubKey,
11267
+ hasShares: sharesEncryptedWithWallabyPubKey.length > 0,
11268
+ });
11269
+ }
11270
+ }
11271
+ __decorate([
11272
+ WithLock('executeSwap'),
11273
+ __metadata("design:type", Function),
11274
+ __metadata("design:paramtypes", [Object]),
11275
+ __metadata("design:returntype", Promise)
11276
+ ], Swap.prototype, "executeSwap", null);
11277
+
10990
11278
  /**
10991
11279
  * Sanitizes a Sui object ID by removing any part of the string after '::'.
10992
11280
  *
@@ -11013,13 +11301,14 @@ class System extends Base {
11013
11301
  /**
11014
11302
  * @public
11015
11303
  * Get all supported chains
11016
- * @param {null}
11304
+ * @param {Object} [options] - Optional query parameters
11305
+ * @param {boolean} [options.supportSwaps] - When true, include only chains that support swaps
11017
11306
  * @returns {Array<Blockchain>} Array of supported chains
11018
11307
  */
11019
- async getSupportedBlockchains() {
11308
+ async getSupportedBlockchains(options) {
11020
11309
  try {
11021
11310
  const response = await this.request(SystemRoutes.getSupportedBlockchains, {
11022
- payload: {},
11311
+ queryParams: (options === null || options === void 0 ? void 0 : options.supportSwaps) !== undefined ? { supportSwaps: options.supportSwaps } : undefined,
11023
11312
  });
11024
11313
  return response.chains;
11025
11314
  }
@@ -11124,13 +11413,33 @@ class System extends Base {
11124
11413
  /**
11125
11414
  * @public
11126
11415
  * Get all supported assets configuration
11127
- * @param {null}
11416
+ * @param {Object} [options] - Optional query parameters
11417
+ * @param {boolean} [options.supportsSwaps] - When true, filter to assets that support swaps
11418
+ * @param {string} [options.search] - Search assets by name or symbol (minimum 3 characters)
11419
+ * @param {BlockchainName} [options.chainName] - Filter assets by blockchain name
11128
11420
  * @returns {Array<AssetConfig>} Array of supported tokens
11129
11421
  */
11130
- async getSupportedTokens() {
11422
+ async getSupportedTokens(options) {
11131
11423
  try {
11424
+ const queryParams = {};
11425
+ if ((options === null || options === void 0 ? void 0 : options.supportsSwaps) !== undefined) {
11426
+ queryParams.supportsSwaps = options.supportsSwaps;
11427
+ }
11428
+ if ((options === null || options === void 0 ? void 0 : options.search) !== undefined) {
11429
+ if (options.search.length < 3) {
11430
+ throw new WallabyError({
11431
+ message: 'Search parameter must be at least 3 characters long',
11432
+ statusCode: 400,
11433
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
11434
+ });
11435
+ }
11436
+ queryParams.search = options.search;
11437
+ }
11438
+ if ((options === null || options === void 0 ? void 0 : options.chainName) !== undefined) {
11439
+ queryParams.chainName = options.chainName;
11440
+ }
11132
11441
  const response = await this.request(SystemRoutes.getSupportedTokens, {
11133
- payload: {},
11442
+ queryParams: Object.keys(queryParams).length > 0 ? queryParams : undefined,
11134
11443
  });
11135
11444
  return response.assets;
11136
11445
  }
@@ -11319,7 +11628,7 @@ class Transactions extends Base {
11319
11628
  throw new WallabyError({
11320
11629
  message: 'No valid seed option found on this device.',
11321
11630
  statusCode: 400,
11322
- errorCode: 'sdk_no_valid_seed_option',
11631
+ errorCode: ErrorResponseCodes.sdk_no_valid_seed_option,
11323
11632
  });
11324
11633
  }
11325
11634
  return transferResponse;
@@ -11386,6 +11695,7 @@ class Transactions extends Base {
11386
11695
  }
11387
11696
  const payload = Object.assign({ message,
11388
11697
  walletId,
11698
+ authenticationOptions,
11389
11699
  signature, clientAuthPubKey: deviceAuthPublicKey, ownerAddress,
11390
11700
  spenderAddress,
11391
11701
  chainName,
@@ -11611,6 +11921,7 @@ class Wallaby {
11611
11921
  this.auth = new AuthService(config);
11612
11922
  this.system = new System(config);
11613
11923
  this.transactions = new Transactions(config);
11924
+ this.swap = new Swap(config);
11614
11925
  this.merchants = new Merchants(config);
11615
11926
  this.httpApi = new HttpApi(config);
11616
11927
  }