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.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Storage keys adapter for Storage interface across different platforms.
3
+ *
4
+ * This sdk uses keys like "wsdk:version:key-name" but `SecureStore` doesn't allow colons in key names,
5
+ * Valid SecureStore key characters: alphanumeric, ".", "-", "_"
6
+ *
7
+ */
8
+ export declare const normalizeKey: (key: string) => string;
package/dist/index.cjs.js CHANGED
@@ -389,6 +389,7 @@ exports.ErrorResponseCodes = void 0;
389
389
  ErrorResponseCodes["sdk_missing_parameter"] = "sdk_missing_parameter";
390
390
  ErrorResponseCodes["sdk_invalid_parameter"] = "sdk_invalid_parameter";
391
391
  ErrorResponseCodes["sdk_wrong_password"] = "sdk_wrong_password";
392
+ ErrorResponseCodes["sdk_no_valid_seed_option"] = "sdk_no_valid_seed_option";
392
393
  // passkey errors
393
394
  ErrorResponseCodes["sdk_passkey_prf_not_available"] = "sdk_passkey_prf_not_available";
394
395
  ErrorResponseCodes["sdk_passkey_challenge_unavailable"] = "sdk_passkey_challenge_unavailable";
@@ -802,7 +803,17 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
802
803
  { type: 'public-key', alg: exports.PublicKeyCredentialAlgorithm.RS256 },
803
804
  { type: 'public-key', alg: exports.PublicKeyCredentialAlgorithm.ES256 },
804
805
  ];
805
- const currentPackageVersion = "2.2.8";
806
+ const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
807
+ const currentPackageVersion = "2.2.10";
808
+
809
+ /**
810
+ * Storage keys adapter for Storage interface across different platforms.
811
+ *
812
+ * This sdk uses keys like "wsdk:version:key-name" but `SecureStore` doesn't allow colons in key names,
813
+ * Valid SecureStore key characters: alphanumeric, ".", "-", "_"
814
+ *
815
+ */
816
+ const normalizeKey = (key) => key.replace(/:/g, '_');
806
817
 
807
818
  const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
808
819
 
@@ -5064,6 +5075,9 @@ class StorageService {
5064
5075
  else {
5065
5076
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5066
5077
  }
5078
+ if (!isWeb) {
5079
+ storageKey = normalizeKey(storageKey);
5080
+ }
5067
5081
  const item = await this.getItem(storageKey);
5068
5082
  if (!item) {
5069
5083
  logger.debug(`(404): Item with key ${storageKey} was not found in storage.`);
@@ -5097,6 +5111,9 @@ class StorageService {
5097
5111
  else {
5098
5112
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5099
5113
  }
5114
+ if (!isWeb) {
5115
+ storageKey = normalizeKey(storageKey);
5116
+ }
5100
5117
  let valueToStore;
5101
5118
  if (this._keysProtectedByMasterKey.includes(key)) {
5102
5119
  const wrappedByMasterKey = this.cipher.encryptWithMasterKey({ data: value });
@@ -5121,6 +5138,9 @@ class StorageService {
5121
5138
  else {
5122
5139
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5123
5140
  }
5141
+ if (!isWeb) {
5142
+ storageKey = normalizeKey(storageKey);
5143
+ }
5124
5144
  return await this.removeItem(storageKey);
5125
5145
  }
5126
5146
  setItem(key, value) {
@@ -7510,6 +7530,24 @@ const TransactionsRoutes = {
7510
7530
  },
7511
7531
  };
7512
7532
 
7533
+ const SwapRoutes = {
7534
+ getQuote: {
7535
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swap/quote`,
7536
+ method: exports.RequestMethod.Post,
7537
+ requiresAccessToken: true,
7538
+ },
7539
+ executeSwap: {
7540
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swap`,
7541
+ method: exports.RequestMethod.Post,
7542
+ requiresAccessToken: true,
7543
+ },
7544
+ getSwaps: {
7545
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swaps`,
7546
+ method: exports.RequestMethod.Get,
7547
+ requiresAccessToken: true,
7548
+ },
7549
+ };
7550
+
7513
7551
  /* eslint-disable no-useless-catch */
7514
7552
  /**
7515
7553
  * Web Authenticator Implementation
@@ -10453,7 +10491,7 @@ class WalletDataService extends Base {
10453
10491
  });
10454
10492
  }
10455
10493
  const response = await this.request(WalletRoutes.getMultiTokenBalances, {
10456
- payload: { assets: tokensAndAddressesList },
10494
+ payload: { tokensAndAddressesList },
10457
10495
  });
10458
10496
  return response;
10459
10497
  }
@@ -10541,10 +10579,20 @@ class WalletDataService extends Base {
10541
10579
  * Get all assets that exist in a certain wallet, by specifying a wallet ID
10542
10580
  * @param walletId Wallaby's wallet ID
10543
10581
  * @param { BasicQueryOptions } queryOptions Optional query options
10582
+ * @param { string } [queryOptions.search] - Search assets by name or symbol (minimum 3 characters)
10583
+ * @param { BlockchainName } [queryOptions.chainName] - Filter assets by blockchain name
10544
10584
  * @returns { GetUserAssetsByWalletIdData } Returns all assets belonging in a certain wallet ID
10545
10585
  */
10546
10586
  async getWalletAssets({ walletId, queryOptions }) {
10547
10587
  try {
10588
+ // Validate search parameter if provided
10589
+ if ((queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.search) !== undefined && queryOptions.search.length < 3) {
10590
+ throw new WallabyError({
10591
+ message: 'Search parameter must be at least 3 characters long',
10592
+ statusCode: 400,
10593
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
10594
+ });
10595
+ }
10548
10596
  const response = await this.request(WalletRoutes.getWalletAssets, {
10549
10597
  payload: {
10550
10598
  walletId,
@@ -11014,6 +11062,246 @@ class HttpApi extends Base {
11014
11062
  }
11015
11063
  }
11016
11064
 
11065
+ class Swap extends Base {
11066
+ constructor(config) {
11067
+ super(config);
11068
+ this.authService = new AuthService(config);
11069
+ this.walletService = new WalletService(config);
11070
+ }
11071
+ /**
11072
+ * Gets a swap quote between two assets (from/to), including fees, min output, and slippage limits.
11073
+ *
11074
+ * @public
11075
+ * @param {SwapQuoteRequest} request - The swap quote request parameters
11076
+ * @returns {Promise<SwapQuoteResponse>} A promise that resolves with the swap quote
11077
+ */
11078
+ async getQuote({ walletId, fromAsset, toAsset, fromAmount, toAmount }) {
11079
+ try {
11080
+ if (!walletId || !fromAsset || !toAsset) {
11081
+ throw new WallabyError({
11082
+ message: 'Missing required parameters: walletId, fromAsset, and toAsset are required',
11083
+ statusCode: 400,
11084
+ errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11085
+ });
11086
+ }
11087
+ if (!fromAmount && !toAmount) {
11088
+ throw new WallabyError({
11089
+ message: 'Either fromAmount or toAmount must be provided',
11090
+ statusCode: 400,
11091
+ errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11092
+ });
11093
+ }
11094
+ // Build path with walletId, but exclude it from request body
11095
+ const routePayload = { walletId };
11096
+ const requestBody = Object.assign(Object.assign({ fromAsset,
11097
+ toAsset }, (fromAmount && { fromAmount })), (toAmount && { toAmount }));
11098
+ const response = await this.request(Object.assign(Object.assign({}, SwapRoutes.getQuote), { fullPath: SwapRoutes.getQuote.fullPath(routePayload) }), {
11099
+ payload: requestBody,
11100
+ });
11101
+ return response;
11102
+ }
11103
+ catch (error) {
11104
+ logger.error('SDK::Swap::getQuote::error', error);
11105
+ throw error;
11106
+ }
11107
+ }
11108
+ /**
11109
+ * Executes a swap using a previously generated quote.
11110
+ *
11111
+ * @public
11112
+ * @param {ExecuteSwapRequest} request - The execute swap request parameters
11113
+ * @returns {Promise<ExecuteSwapResponse>} A promise that resolves with the swap execution response
11114
+ */
11115
+ async executeSwap({ walletId, quoteId, authenticationOptions }) {
11116
+ try {
11117
+ // Only attempt migration if we have password auth and V2 storage might be incomplete
11118
+ if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11119
+ try {
11120
+ await this.walletService.handleUpdateToV2({
11121
+ password: authenticationOptions.password,
11122
+ walletId: walletId,
11123
+ });
11124
+ }
11125
+ catch (error) {
11126
+ logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11127
+ throw new WallabyError({
11128
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11129
+ statusCode: 500,
11130
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11131
+ });
11132
+ }
11133
+ }
11134
+ const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11135
+ let swapResponse;
11136
+ // Build path with walletId, but exclude it from request body
11137
+ const routePayload = { walletId };
11138
+ if (readyForTransportSeedPhrase) {
11139
+ swapResponse = await this.request(Object.assign(Object.assign({}, SwapRoutes.executeSwap), { fullPath: SwapRoutes.executeSwap.fullPath(routePayload) }), {
11140
+ payload: {
11141
+ quoteId,
11142
+ message: signatureMessage.message,
11143
+ signature: signatureMessage.signature,
11144
+ clientAuthPubKey: deviceAuthPublicKey,
11145
+ encryptedSeed: readyForTransportSeedPhrase,
11146
+ },
11147
+ });
11148
+ }
11149
+ else if (hasShares) {
11150
+ swapResponse = await this.request(Object.assign(Object.assign({}, SwapRoutes.executeSwap), { fullPath: SwapRoutes.executeSwap.fullPath(routePayload) }), {
11151
+ payload: {
11152
+ quoteId,
11153
+ message: signatureMessage.message,
11154
+ signature: signatureMessage.signature,
11155
+ clientAuthPubKey: deviceAuthPublicKey,
11156
+ encryptedShares: sharesEncryptedWithWallabyPubKey,
11157
+ },
11158
+ });
11159
+ }
11160
+ else {
11161
+ throw new WallabyError({
11162
+ message: 'No valid seed option found on this device.',
11163
+ statusCode: 400,
11164
+ errorCode: exports.ErrorResponseCodes.sdk_no_valid_seed_option,
11165
+ });
11166
+ }
11167
+ return swapResponse;
11168
+ }
11169
+ catch (error) {
11170
+ logger.error('SDK::Swap::executeSwap::error', error);
11171
+ throw error;
11172
+ }
11173
+ }
11174
+ /**
11175
+ * Lists executed swap transactions for a given wallet, with optional date and pagination filters.
11176
+ *
11177
+ * @public
11178
+ * @param {GetSwapsRequest} request - The get swaps request parameters
11179
+ * @returns {Promise<GetSwapsResponse>} A promise that resolves with the list of swaps
11180
+ */
11181
+ async getSwaps({ walletId, queryParams }) {
11182
+ try {
11183
+ if (!walletId) {
11184
+ throw new WallabyError({
11185
+ message: 'Missing required parameter: walletId',
11186
+ statusCode: 400,
11187
+ errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11188
+ });
11189
+ }
11190
+ // Build path with walletId
11191
+ const routePayload = { walletId };
11192
+ const response = await this.request(Object.assign(Object.assign({}, SwapRoutes.getSwaps), { fullPath: SwapRoutes.getSwaps.fullPath(routePayload) }), {
11193
+ queryParams: queryParams,
11194
+ });
11195
+ return response;
11196
+ }
11197
+ catch (error) {
11198
+ logger.error('SDK::Swap::getSwaps::error', error);
11199
+ throw error;
11200
+ }
11201
+ }
11202
+ /**
11203
+ * Prepares authentication data and encrypted payload for swap requests
11204
+ * @private
11205
+ */
11206
+ async prepareSwapAuth(authenticationOptions, walletId) {
11207
+ const { password, prfValue, user, clientSalt: authClientSalt } = authenticationOptions;
11208
+ const encryptedDevicePrivateKey = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey, {
11209
+ walletId,
11210
+ });
11211
+ if (!encryptedDevicePrivateKey) {
11212
+ throw new WallabyError({
11213
+ message: 'No private key was found on this device.',
11214
+ statusCode: 400,
11215
+ errorCode: exports.ErrorResponseCodes.sdk_private_key_not_found,
11216
+ });
11217
+ }
11218
+ // Get credentials key pair for device private key decryption
11219
+ const clientSalt = authClientSalt || user.clientSalt;
11220
+ const credentialsKeyPair = await this.cipher.getCredentialsKeyPair({
11221
+ authType: this.deviceAuthType,
11222
+ password,
11223
+ prfValue,
11224
+ salt: clientSalt,
11225
+ });
11226
+ // Decrypt device private key
11227
+ const decryptedDevicePrivateKey = await this.cipher.decrypt({
11228
+ cipherText: JSON.parse(encryptedDevicePrivateKey),
11229
+ decryptionKey: credentialsKeyPair.privateKey,
11230
+ });
11231
+ if (!decryptedDevicePrivateKey) {
11232
+ throw new WallabyError({
11233
+ message: 'Credentials are wrong, please pass the correct credentials.',
11234
+ statusCode: 400,
11235
+ errorCode: exports.ErrorResponseCodes.sdk_private_key_decryption_failed,
11236
+ });
11237
+ }
11238
+ const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
11239
+ // Get signature message
11240
+ const signatureMessage = await this.authService.getSignature({
11241
+ publicKey: deviceAuthPublicKey,
11242
+ privateKey: decryptedDevicePrivateKey,
11243
+ }, this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined);
11244
+ // Prepare encrypted data (seed phrase or key shares)
11245
+ const sharesEncryptedWithWallabyPubKey = [];
11246
+ let readyForTransportSeedPhrase = undefined;
11247
+ const primaryKeyShare = await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare, { walletId });
11248
+ if (!primaryKeyShare) {
11249
+ // No primary share, try seed phrase
11250
+ const encryptedSeedPhrase = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase, {
11251
+ walletId,
11252
+ });
11253
+ if (!encryptedSeedPhrase) {
11254
+ throw new WallabyError({
11255
+ message: 'Your device does not have a seed phrase or an operating share to sign the transaction.',
11256
+ statusCode: 400,
11257
+ errorCode: exports.ErrorResponseCodes.sdk_seed_phrase_not_found,
11258
+ });
11259
+ }
11260
+ const parsedSeedPhrase = safeJsonParse(encryptedSeedPhrase);
11261
+ readyForTransportSeedPhrase = await this.cipher.prepareStoredDataForTransport({
11262
+ storedEncryptedData: parsedSeedPhrase,
11263
+ encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11264
+ wallabyPublicKey: user.wallabyAuthPubKey,
11265
+ options: {
11266
+ authType: this.deviceAuthType,
11267
+ password,
11268
+ prfValue,
11269
+ salt: clientSalt,
11270
+ },
11271
+ });
11272
+ }
11273
+ else {
11274
+ // Use primary key share
11275
+ const parsedPrimaryShare = safeJsonParse(primaryKeyShare);
11276
+ const readyForTransportShare = await this.cipher.prepareStoredDataForTransport({
11277
+ storedEncryptedData: parsedPrimaryShare,
11278
+ encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11279
+ wallabyPublicKey: user.wallabyAuthPubKey,
11280
+ options: {
11281
+ authType: this.deviceAuthType,
11282
+ password,
11283
+ prfValue,
11284
+ salt: clientSalt,
11285
+ },
11286
+ });
11287
+ sharesEncryptedWithWallabyPubKey.push(readyForTransportShare);
11288
+ }
11289
+ return Object.freeze({
11290
+ deviceAuthPublicKey,
11291
+ signatureMessage,
11292
+ readyForTransportSeedPhrase,
11293
+ sharesEncryptedWithWallabyPubKey,
11294
+ hasShares: sharesEncryptedWithWallabyPubKey.length > 0,
11295
+ });
11296
+ }
11297
+ }
11298
+ __decorate([
11299
+ WithLock('executeSwap'),
11300
+ __metadata("design:type", Function),
11301
+ __metadata("design:paramtypes", [Object]),
11302
+ __metadata("design:returntype", Promise)
11303
+ ], Swap.prototype, "executeSwap", null);
11304
+
11017
11305
  /**
11018
11306
  * Sanitizes a Sui object ID by removing any part of the string after '::'.
11019
11307
  *
@@ -11040,13 +11328,14 @@ class System extends Base {
11040
11328
  /**
11041
11329
  * @public
11042
11330
  * Get all supported chains
11043
- * @param {null}
11331
+ * @param {Object} [options] - Optional query parameters
11332
+ * @param {boolean} [options.supportSwaps] - When true, include only chains that support swaps
11044
11333
  * @returns {Array<Blockchain>} Array of supported chains
11045
11334
  */
11046
- async getSupportedBlockchains() {
11335
+ async getSupportedBlockchains(options) {
11047
11336
  try {
11048
11337
  const response = await this.request(SystemRoutes.getSupportedBlockchains, {
11049
- payload: {},
11338
+ queryParams: (options === null || options === void 0 ? void 0 : options.supportSwaps) !== undefined ? { supportSwaps: options.supportSwaps } : undefined,
11050
11339
  });
11051
11340
  return response.chains;
11052
11341
  }
@@ -11151,13 +11440,33 @@ class System extends Base {
11151
11440
  /**
11152
11441
  * @public
11153
11442
  * Get all supported assets configuration
11154
- * @param {null}
11443
+ * @param {Object} [options] - Optional query parameters
11444
+ * @param {boolean} [options.supportsSwaps] - When true, filter to assets that support swaps
11445
+ * @param {string} [options.search] - Search assets by name or symbol (minimum 3 characters)
11446
+ * @param {BlockchainName} [options.chainName] - Filter assets by blockchain name
11155
11447
  * @returns {Array<AssetConfig>} Array of supported tokens
11156
11448
  */
11157
- async getSupportedTokens() {
11449
+ async getSupportedTokens(options) {
11158
11450
  try {
11451
+ const queryParams = {};
11452
+ if ((options === null || options === void 0 ? void 0 : options.supportsSwaps) !== undefined) {
11453
+ queryParams.supportsSwaps = options.supportsSwaps;
11454
+ }
11455
+ if ((options === null || options === void 0 ? void 0 : options.search) !== undefined) {
11456
+ if (options.search.length < 3) {
11457
+ throw new WallabyError({
11458
+ message: 'Search parameter must be at least 3 characters long',
11459
+ statusCode: 400,
11460
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
11461
+ });
11462
+ }
11463
+ queryParams.search = options.search;
11464
+ }
11465
+ if ((options === null || options === void 0 ? void 0 : options.chainName) !== undefined) {
11466
+ queryParams.chainName = options.chainName;
11467
+ }
11159
11468
  const response = await this.request(SystemRoutes.getSupportedTokens, {
11160
- payload: {},
11469
+ queryParams: Object.keys(queryParams).length > 0 ? queryParams : undefined,
11161
11470
  });
11162
11471
  return response.assets;
11163
11472
  }
@@ -11346,7 +11655,7 @@ class Transactions extends Base {
11346
11655
  throw new WallabyError({
11347
11656
  message: 'No valid seed option found on this device.',
11348
11657
  statusCode: 400,
11349
- errorCode: 'sdk_no_valid_seed_option',
11658
+ errorCode: exports.ErrorResponseCodes.sdk_no_valid_seed_option,
11350
11659
  });
11351
11660
  }
11352
11661
  return transferResponse;
@@ -11413,6 +11722,7 @@ class Transactions extends Base {
11413
11722
  }
11414
11723
  const payload = Object.assign({ message,
11415
11724
  walletId,
11725
+ authenticationOptions,
11416
11726
  signature, clientAuthPubKey: deviceAuthPublicKey, ownerAddress,
11417
11727
  spenderAddress,
11418
11728
  chainName,
@@ -11638,6 +11948,7 @@ class Wallaby {
11638
11948
  this.auth = new AuthService(config);
11639
11949
  this.system = new System(config);
11640
11950
  this.transactions = new Transactions(config);
11951
+ this.swap = new Swap(config);
11641
11952
  this.merchants = new Merchants(config);
11642
11953
  this.httpApi = new HttpApi(config);
11643
11954
  }