wallaby-cash 2.2.9 → 2.2.11

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.9";
806
+ const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
807
+ const currentPackageVersion = "2.2.11";
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) {
@@ -7011,6 +7031,7 @@ function objectToQueryParams(obj) {
7011
7031
 
7012
7032
  class Base {
7013
7033
  constructor(config) {
7034
+ var _a;
7014
7035
  const sanitizedConfig = sanitizeConfig(config);
7015
7036
  this.apiKey = sanitizedConfig.apiKey;
7016
7037
  this.baseUrl = sanitizedConfig.baseUrl;
@@ -7060,10 +7081,7 @@ class Base {
7060
7081
  }
7061
7082
  };
7062
7083
  this.api = new Api(httpClient);
7063
- this.api.http.setSecurityData({
7064
- 'x-api-key': config.apiKey,
7065
- 'x-client-jwt': config.clientAuthToken,
7066
- });
7084
+ this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_a = this.options) === null || _a === void 0 ? void 0 : _a.headers));
7067
7085
  }
7068
7086
  set setClientAuthToken(token) {
7069
7087
  this._initializeClientAuthToken(token);
@@ -7510,6 +7528,24 @@ const TransactionsRoutes = {
7510
7528
  },
7511
7529
  };
7512
7530
 
7531
+ const SwapRoutes = {
7532
+ getQuote: {
7533
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swap/quote`,
7534
+ method: exports.RequestMethod.Post,
7535
+ requiresAccessToken: true,
7536
+ },
7537
+ executeSwap: {
7538
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swap`,
7539
+ method: exports.RequestMethod.Post,
7540
+ requiresAccessToken: true,
7541
+ },
7542
+ getSwaps: {
7543
+ fullPath: ({ walletId }) => `/api/v1/wallets/${walletId}/swaps`,
7544
+ method: exports.RequestMethod.Get,
7545
+ requiresAccessToken: true,
7546
+ },
7547
+ };
7548
+
7513
7549
  /* eslint-disable no-useless-catch */
7514
7550
  /**
7515
7551
  * Web Authenticator Implementation
@@ -10453,7 +10489,7 @@ class WalletDataService extends Base {
10453
10489
  });
10454
10490
  }
10455
10491
  const response = await this.request(WalletRoutes.getMultiTokenBalances, {
10456
- payload: { assets: tokensAndAddressesList },
10492
+ payload: { tokensAndAddressesList },
10457
10493
  });
10458
10494
  return response;
10459
10495
  }
@@ -10541,10 +10577,20 @@ class WalletDataService extends Base {
10541
10577
  * Get all assets that exist in a certain wallet, by specifying a wallet ID
10542
10578
  * @param walletId Wallaby's wallet ID
10543
10579
  * @param { BasicQueryOptions } queryOptions Optional query options
10580
+ * @param { string } [queryOptions.search] - Search assets by name or symbol (minimum 3 characters)
10581
+ * @param { BlockchainName } [queryOptions.chainName] - Filter assets by blockchain name
10544
10582
  * @returns { GetUserAssetsByWalletIdData } Returns all assets belonging in a certain wallet ID
10545
10583
  */
10546
10584
  async getWalletAssets({ walletId, queryOptions }) {
10547
10585
  try {
10586
+ // Validate search parameter if provided
10587
+ if ((queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.search) !== undefined && queryOptions.search.length < 3) {
10588
+ throw new WallabyError({
10589
+ message: 'Search parameter must be at least 3 characters long',
10590
+ statusCode: 400,
10591
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
10592
+ });
10593
+ }
10548
10594
  const response = await this.request(WalletRoutes.getWalletAssets, {
10549
10595
  payload: {
10550
10596
  walletId,
@@ -11014,6 +11060,246 @@ class HttpApi extends Base {
11014
11060
  }
11015
11061
  }
11016
11062
 
11063
+ class Swap extends Base {
11064
+ constructor(config) {
11065
+ super(config);
11066
+ this.authService = new AuthService(config);
11067
+ this.walletService = new WalletService(config);
11068
+ }
11069
+ /**
11070
+ * Gets a swap quote between two assets (from/to), including fees, min output, and slippage limits.
11071
+ *
11072
+ * @public
11073
+ * @param {SwapQuoteRequest} request - The swap quote request parameters
11074
+ * @returns {Promise<SwapQuoteResponse>} A promise that resolves with the swap quote
11075
+ */
11076
+ async getQuote({ walletId, fromAsset, toAsset, fromAmount, toAmount }) {
11077
+ try {
11078
+ if (!walletId || !fromAsset || !toAsset) {
11079
+ throw new WallabyError({
11080
+ message: 'Missing required parameters: walletId, fromAsset, and toAsset are required',
11081
+ statusCode: 400,
11082
+ errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11083
+ });
11084
+ }
11085
+ if (!fromAmount && !toAmount) {
11086
+ throw new WallabyError({
11087
+ message: 'Either fromAmount or toAmount must be provided',
11088
+ statusCode: 400,
11089
+ errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11090
+ });
11091
+ }
11092
+ // Build path with walletId, but exclude it from request body
11093
+ const routePayload = { walletId };
11094
+ const requestBody = Object.assign(Object.assign({ fromAsset,
11095
+ toAsset }, (fromAmount && { fromAmount })), (toAmount && { toAmount }));
11096
+ const response = await this.request(Object.assign(Object.assign({}, SwapRoutes.getQuote), { fullPath: SwapRoutes.getQuote.fullPath(routePayload) }), {
11097
+ payload: requestBody,
11098
+ });
11099
+ return response;
11100
+ }
11101
+ catch (error) {
11102
+ logger.error('SDK::Swap::getQuote::error', error);
11103
+ throw error;
11104
+ }
11105
+ }
11106
+ /**
11107
+ * Executes a swap using a previously generated quote.
11108
+ *
11109
+ * @public
11110
+ * @param {ExecuteSwapRequest} request - The execute swap request parameters
11111
+ * @returns {Promise<ExecuteSwapResponse>} A promise that resolves with the swap execution response
11112
+ */
11113
+ async executeSwap({ walletId, quoteId, authenticationOptions }) {
11114
+ try {
11115
+ // Only attempt migration if we have password auth and V2 storage might be incomplete
11116
+ if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11117
+ try {
11118
+ await this.walletService.handleUpdateToV2({
11119
+ password: authenticationOptions.password,
11120
+ walletId: walletId,
11121
+ });
11122
+ }
11123
+ catch (error) {
11124
+ logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11125
+ throw new WallabyError({
11126
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11127
+ statusCode: 500,
11128
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11129
+ });
11130
+ }
11131
+ }
11132
+ const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11133
+ let swapResponse;
11134
+ // Build path with walletId, but exclude it from request body
11135
+ const routePayload = { walletId };
11136
+ if (readyForTransportSeedPhrase) {
11137
+ swapResponse = await this.request(Object.assign(Object.assign({}, SwapRoutes.executeSwap), { fullPath: SwapRoutes.executeSwap.fullPath(routePayload) }), {
11138
+ payload: {
11139
+ quoteId,
11140
+ message: signatureMessage.message,
11141
+ signature: signatureMessage.signature,
11142
+ clientAuthPubKey: deviceAuthPublicKey,
11143
+ encryptedSeed: readyForTransportSeedPhrase,
11144
+ },
11145
+ });
11146
+ }
11147
+ else if (hasShares) {
11148
+ swapResponse = await this.request(Object.assign(Object.assign({}, SwapRoutes.executeSwap), { fullPath: SwapRoutes.executeSwap.fullPath(routePayload) }), {
11149
+ payload: {
11150
+ quoteId,
11151
+ message: signatureMessage.message,
11152
+ signature: signatureMessage.signature,
11153
+ clientAuthPubKey: deviceAuthPublicKey,
11154
+ encryptedShares: sharesEncryptedWithWallabyPubKey,
11155
+ },
11156
+ });
11157
+ }
11158
+ else {
11159
+ throw new WallabyError({
11160
+ message: 'No valid seed option found on this device.',
11161
+ statusCode: 400,
11162
+ errorCode: exports.ErrorResponseCodes.sdk_no_valid_seed_option,
11163
+ });
11164
+ }
11165
+ return swapResponse;
11166
+ }
11167
+ catch (error) {
11168
+ logger.error('SDK::Swap::executeSwap::error', error);
11169
+ throw error;
11170
+ }
11171
+ }
11172
+ /**
11173
+ * Lists executed swap transactions for a given wallet, with optional date and pagination filters.
11174
+ *
11175
+ * @public
11176
+ * @param {GetSwapsRequest} request - The get swaps request parameters
11177
+ * @returns {Promise<GetSwapsResponse>} A promise that resolves with the list of swaps
11178
+ */
11179
+ async getSwaps({ walletId, queryParams }) {
11180
+ try {
11181
+ if (!walletId) {
11182
+ throw new WallabyError({
11183
+ message: 'Missing required parameter: walletId',
11184
+ statusCode: 400,
11185
+ errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
11186
+ });
11187
+ }
11188
+ // Build path with walletId
11189
+ const routePayload = { walletId };
11190
+ const response = await this.request(Object.assign(Object.assign({}, SwapRoutes.getSwaps), { fullPath: SwapRoutes.getSwaps.fullPath(routePayload) }), {
11191
+ queryParams: queryParams,
11192
+ });
11193
+ return response;
11194
+ }
11195
+ catch (error) {
11196
+ logger.error('SDK::Swap::getSwaps::error', error);
11197
+ throw error;
11198
+ }
11199
+ }
11200
+ /**
11201
+ * Prepares authentication data and encrypted payload for swap requests
11202
+ * @private
11203
+ */
11204
+ async prepareSwapAuth(authenticationOptions, walletId) {
11205
+ const { password, prfValue, user, clientSalt: authClientSalt } = authenticationOptions;
11206
+ const encryptedDevicePrivateKey = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey, {
11207
+ walletId,
11208
+ });
11209
+ if (!encryptedDevicePrivateKey) {
11210
+ throw new WallabyError({
11211
+ message: 'No private key was found on this device.',
11212
+ statusCode: 400,
11213
+ errorCode: exports.ErrorResponseCodes.sdk_private_key_not_found,
11214
+ });
11215
+ }
11216
+ // Get credentials key pair for device private key decryption
11217
+ const clientSalt = authClientSalt || user.clientSalt;
11218
+ const credentialsKeyPair = await this.cipher.getCredentialsKeyPair({
11219
+ authType: this.deviceAuthType,
11220
+ password,
11221
+ prfValue,
11222
+ salt: clientSalt,
11223
+ });
11224
+ // Decrypt device private key
11225
+ const decryptedDevicePrivateKey = await this.cipher.decrypt({
11226
+ cipherText: JSON.parse(encryptedDevicePrivateKey),
11227
+ decryptionKey: credentialsKeyPair.privateKey,
11228
+ });
11229
+ if (!decryptedDevicePrivateKey) {
11230
+ throw new WallabyError({
11231
+ message: 'Credentials are wrong, please pass the correct credentials.',
11232
+ statusCode: 400,
11233
+ errorCode: exports.ErrorResponseCodes.sdk_private_key_decryption_failed,
11234
+ });
11235
+ }
11236
+ const deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey);
11237
+ // Get signature message
11238
+ const signatureMessage = await this.authService.getSignature({
11239
+ publicKey: deviceAuthPublicKey,
11240
+ privateKey: decryptedDevicePrivateKey,
11241
+ }, this.deviceAuthType === exports.AuthType.Passkey ? exports.PasskeyChallengeType.AUTHENTICATION : undefined);
11242
+ // Prepare encrypted data (seed phrase or key shares)
11243
+ const sharesEncryptedWithWallabyPubKey = [];
11244
+ let readyForTransportSeedPhrase = undefined;
11245
+ const primaryKeyShare = await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare, { walletId });
11246
+ if (!primaryKeyShare) {
11247
+ // No primary share, try seed phrase
11248
+ const encryptedSeedPhrase = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase, {
11249
+ walletId,
11250
+ });
11251
+ if (!encryptedSeedPhrase) {
11252
+ throw new WallabyError({
11253
+ message: 'Your device does not have a seed phrase or an operating share to sign the transaction.',
11254
+ statusCode: 400,
11255
+ errorCode: exports.ErrorResponseCodes.sdk_seed_phrase_not_found,
11256
+ });
11257
+ }
11258
+ const parsedSeedPhrase = safeJsonParse(encryptedSeedPhrase);
11259
+ readyForTransportSeedPhrase = await this.cipher.prepareStoredDataForTransport({
11260
+ storedEncryptedData: parsedSeedPhrase,
11261
+ encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11262
+ wallabyPublicKey: user.wallabyAuthPubKey,
11263
+ options: {
11264
+ authType: this.deviceAuthType,
11265
+ password,
11266
+ prfValue,
11267
+ salt: clientSalt,
11268
+ },
11269
+ });
11270
+ }
11271
+ else {
11272
+ // Use primary key share
11273
+ const parsedPrimaryShare = safeJsonParse(primaryKeyShare);
11274
+ const readyForTransportShare = await this.cipher.prepareStoredDataForTransport({
11275
+ storedEncryptedData: parsedPrimaryShare,
11276
+ encryptedDevicePrivateKey: JSON.parse(encryptedDevicePrivateKey),
11277
+ wallabyPublicKey: user.wallabyAuthPubKey,
11278
+ options: {
11279
+ authType: this.deviceAuthType,
11280
+ password,
11281
+ prfValue,
11282
+ salt: clientSalt,
11283
+ },
11284
+ });
11285
+ sharesEncryptedWithWallabyPubKey.push(readyForTransportShare);
11286
+ }
11287
+ return Object.freeze({
11288
+ deviceAuthPublicKey,
11289
+ signatureMessage,
11290
+ readyForTransportSeedPhrase,
11291
+ sharesEncryptedWithWallabyPubKey,
11292
+ hasShares: sharesEncryptedWithWallabyPubKey.length > 0,
11293
+ });
11294
+ }
11295
+ }
11296
+ __decorate([
11297
+ WithLock('executeSwap'),
11298
+ __metadata("design:type", Function),
11299
+ __metadata("design:paramtypes", [Object]),
11300
+ __metadata("design:returntype", Promise)
11301
+ ], Swap.prototype, "executeSwap", null);
11302
+
11017
11303
  /**
11018
11304
  * Sanitizes a Sui object ID by removing any part of the string after '::'.
11019
11305
  *
@@ -11040,13 +11326,14 @@ class System extends Base {
11040
11326
  /**
11041
11327
  * @public
11042
11328
  * Get all supported chains
11043
- * @param {null}
11329
+ * @param {Object} [options] - Optional query parameters
11330
+ * @param {boolean} [options.supportSwaps] - When true, include only chains that support swaps
11044
11331
  * @returns {Array<Blockchain>} Array of supported chains
11045
11332
  */
11046
- async getSupportedBlockchains() {
11333
+ async getSupportedBlockchains(options) {
11047
11334
  try {
11048
11335
  const response = await this.request(SystemRoutes.getSupportedBlockchains, {
11049
- payload: {},
11336
+ queryParams: (options === null || options === void 0 ? void 0 : options.supportSwaps) !== undefined ? { supportSwaps: options.supportSwaps } : undefined,
11050
11337
  });
11051
11338
  return response.chains;
11052
11339
  }
@@ -11151,13 +11438,33 @@ class System extends Base {
11151
11438
  /**
11152
11439
  * @public
11153
11440
  * Get all supported assets configuration
11154
- * @param {null}
11441
+ * @param {Object} [options] - Optional query parameters
11442
+ * @param {boolean} [options.supportsSwaps] - When true, filter to assets that support swaps
11443
+ * @param {string} [options.search] - Search assets by name or symbol (minimum 3 characters)
11444
+ * @param {BlockchainName} [options.chainName] - Filter assets by blockchain name
11155
11445
  * @returns {Array<AssetConfig>} Array of supported tokens
11156
11446
  */
11157
- async getSupportedTokens() {
11447
+ async getSupportedTokens(options) {
11158
11448
  try {
11449
+ const queryParams = {};
11450
+ if ((options === null || options === void 0 ? void 0 : options.supportsSwaps) !== undefined) {
11451
+ queryParams.supportsSwaps = options.supportsSwaps;
11452
+ }
11453
+ if ((options === null || options === void 0 ? void 0 : options.search) !== undefined) {
11454
+ if (options.search.length < 3) {
11455
+ throw new WallabyError({
11456
+ message: 'Search parameter must be at least 3 characters long',
11457
+ statusCode: 400,
11458
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
11459
+ });
11460
+ }
11461
+ queryParams.search = options.search;
11462
+ }
11463
+ if ((options === null || options === void 0 ? void 0 : options.chainName) !== undefined) {
11464
+ queryParams.chainName = options.chainName;
11465
+ }
11159
11466
  const response = await this.request(SystemRoutes.getSupportedTokens, {
11160
- payload: {},
11467
+ queryParams: Object.keys(queryParams).length > 0 ? queryParams : undefined,
11161
11468
  });
11162
11469
  return response.assets;
11163
11470
  }
@@ -11346,7 +11653,7 @@ class Transactions extends Base {
11346
11653
  throw new WallabyError({
11347
11654
  message: 'No valid seed option found on this device.',
11348
11655
  statusCode: 400,
11349
- errorCode: 'sdk_no_valid_seed_option',
11656
+ errorCode: exports.ErrorResponseCodes.sdk_no_valid_seed_option,
11350
11657
  });
11351
11658
  }
11352
11659
  return transferResponse;
@@ -11413,6 +11720,7 @@ class Transactions extends Base {
11413
11720
  }
11414
11721
  const payload = Object.assign({ message,
11415
11722
  walletId,
11723
+ authenticationOptions,
11416
11724
  signature, clientAuthPubKey: deviceAuthPublicKey, ownerAddress,
11417
11725
  spenderAddress,
11418
11726
  chainName,
@@ -11638,6 +11946,7 @@ class Wallaby {
11638
11946
  this.auth = new AuthService(config);
11639
11947
  this.system = new System(config);
11640
11948
  this.transactions = new Transactions(config);
11949
+ this.swap = new Swap(config);
11641
11950
  this.merchants = new Merchants(config);
11642
11951
  this.httpApi = new HttpApi(config);
11643
11952
  }