@dynamic-labs-wallet/core 1.1.63 → 1.1.65

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/index.cjs CHANGED
@@ -811,6 +811,145 @@ var _Logger;
811
811
  }
812
812
  }, _Logger._instance = new NoopLogger(), _Logger._context = {}, _Logger);
813
813
 
814
+ class WalletApiError extends Error {
815
+ constructor(status, message, code){
816
+ super(message);
817
+ this.name = 'WalletApiError';
818
+ this.status = status;
819
+ this.code = code;
820
+ }
821
+ }
822
+ const getResponseRecord = (error)=>{
823
+ var _error_response;
824
+ const data = (_error_response = error.response) == null ? void 0 : _error_response.data;
825
+ return data && typeof data === 'object' ? data : undefined;
826
+ };
827
+ // The Key Share Service returns its machine-readable cause under `error_code`; other
828
+ // backends use `code` or a bare `error`. Exported for callers that must skip handleAxiosError's own logging.
829
+ const extractServerErrorCode = (error)=>{
830
+ const record = getResponseRecord(error);
831
+ const candidates = [
832
+ record == null ? void 0 : record['code'],
833
+ record == null ? void 0 : record['error_code'],
834
+ record == null ? void 0 : record['error']
835
+ ];
836
+ return candidates.find((value)=>typeof value === 'string');
837
+ };
838
+ const INTERNAL_SERVER_ERROR_MESSAGE = 'Internal server error';
839
+ /**
840
+ * `status` for a request that never received an HTTP response at all — the
841
+ * client lost connectivity, the request was aborted, DNS/TLS failed, or CORS
842
+ * blocked it. 0 matches the XHR/`fetch` convention for "no response".
843
+ *
844
+ * This used to be reported as `500 Internal server error`, which made a
845
+ * client-side network failure indistinguishable from a backend fault: the
846
+ * "Backend 500s" monitor counted 1,395 events on a day when the API returned
847
+ * only 33 real 5xx responses.
848
+ */ const NETWORK_ERROR_STATUS = 0;
849
+ const NETWORK_ERROR_CODE = 'NETWORK_ERROR';
850
+ const NETWORK_ERROR_MESSAGE = 'Network error - no response received';
851
+ const STATUS_MESSAGES = {
852
+ 400: 'Invalid request',
853
+ 403: 'Forbidden',
854
+ 422: 'Unprocessable content',
855
+ 429: 'Rate limited',
856
+ 500: INTERNAL_SERVER_ERROR_MESSAGE
857
+ };
858
+ const MISSING_AUTH_MESSAGE = 'Authorization header or cookie missing';
859
+ // A 401 can mean the request carried no credentials, or carried credentials the
860
+ // backend rejected — the two need different messages. The Authorization header
861
+ // is readable so we can confirm its presence; the auth cookie is httpOnly, so we
862
+ // can only report whether cookie mode was enabled (`withCredentials`), not that a
863
+ // cookie was actually attached.
864
+ const getRequestCredentials = (error)=>{
865
+ var _error_config, _error_config1;
866
+ const requestHeaders = (_error_config = error.config) == null ? void 0 : _error_config.headers;
867
+ var _requestHeaders_Authorization;
868
+ const hasAuthorizationHeader = Boolean((_requestHeaders_Authorization = requestHeaders == null ? void 0 : requestHeaders['Authorization']) != null ? _requestHeaders_Authorization : requestHeaders == null ? void 0 : requestHeaders['authorization']);
869
+ const usesCookieAuth = Boolean((_error_config1 = error.config) == null ? void 0 : _error_config1.withCredentials);
870
+ return {
871
+ hasAuthorizationHeader,
872
+ usesCookieAuth
873
+ };
874
+ };
875
+ const resolveUnauthorizedMessage = (error)=>{
876
+ const { hasAuthorizationHeader, usesCookieAuth } = getRequestCredentials(error);
877
+ if (!hasAuthorizationHeader && !usesCookieAuth) {
878
+ return MISSING_AUTH_MESSAGE;
879
+ }
880
+ const credentialDescriptions = [];
881
+ if (hasAuthorizationHeader) {
882
+ credentialDescriptions.push('Authorization header present');
883
+ }
884
+ if (usesCookieAuth) {
885
+ credentialDescriptions.push('withCredentials enabled (cookie auth)');
886
+ }
887
+ return `Unauthorized (${credentialDescriptions.join(', ')})`;
888
+ };
889
+ const resolveStatusMessage = (status, error)=>{
890
+ if (status === 401) {
891
+ return resolveUnauthorizedMessage(error);
892
+ }
893
+ if (status && STATUS_MESSAGES[status]) {
894
+ return STATUS_MESSAGES[status];
895
+ }
896
+ return undefined;
897
+ };
898
+ const handleAxiosError = (error, message, context, /**
899
+ * Optional severity hint from the caller, for failures the caller knows are
900
+ * expected (e.g. a business-rule rejection). It can only *lower* severity to
901
+ * `warn` — a caller must not be able to escalate, and a genuine 5xx has to
902
+ * stay at `error` regardless of what the call site believes.
903
+ *
904
+ * Without this the hint that `logError` accepts was silently discarded for
905
+ * every AxiosError, which is the most common error type in the SDK.
906
+ */ options)=>{
907
+ var _error_config, _error_config1, _error_response, _error_response1, _error_response2;
908
+ const requestUrl = (_error_config = error.config) == null ? void 0 : _error_config.url;
909
+ const requestBaseUrl = (_error_config1 = error.config) == null ? void 0 : _error_config1.baseURL;
910
+ // The HTTP status MUST NOT be logged as a top-level `status` field: Datadog
911
+ // reserves `status` for the log level and its remapper turns a numeric value
912
+ // into `info`, silently burying every 4xx/5xx we emit here. `http.status_code`
913
+ // is Datadog's standard attribute, so the level survives and these logs join
914
+ // against edge/CDN logs on the same field.
915
+ const logPayload = _extends({
916
+ message,
917
+ error: (_error_response = error.response) == null ? void 0 : _error_response.data,
918
+ http: {
919
+ status_code: (_error_response1 = error.response) == null ? void 0 : _error_response1.status
920
+ }
921
+ }, requestBaseUrl && {
922
+ requestBaseUrl
923
+ }, requestUrl && {
924
+ requestUrl
925
+ }, {
926
+ context
927
+ });
928
+ const status = (_error_response2 = error.response) == null ? void 0 : _error_response2.status;
929
+ // A 429 (Too Many Requests) is a transient rate-limit signal, not a code or
930
+ // logic failure — and a request that never got a response is a client-side
931
+ // connectivity problem, not a server fault. Both are logged at `warn` so they
932
+ // don't pollute error dashboards or trigger PagerDuty. The 429 case covers
933
+ // both Cloudflare WAF blocks and application-level rate limiting.
934
+ const inferredLevel = status === 429 || status === undefined ? 'warn' : 'error';
935
+ // A 5xx is a server fault: no call site is entitled to downgrade it, however
936
+ // expected it believes the failure to be. The hint only applies below 500.
937
+ const isServerFault = status !== undefined && status >= 500;
938
+ const logLevel = (options == null ? void 0 : options.level) === 'warn' && !isServerFault ? 'warn' : inferredLevel;
939
+ Logger[logLevel]('[DynamicWaasWalletClient] Axios error: ', logPayload);
940
+ // No response at all: report it as such rather than laundering it into a 500.
941
+ if (status === undefined) {
942
+ throw new WalletApiError(NETWORK_ERROR_STATUS, NETWORK_ERROR_MESSAGE, NETWORK_ERROR_CODE);
943
+ }
944
+ var _resolveStatusMessage;
945
+ // Preserve the real status. Collapsing every unmapped code to 500 made a 404
946
+ // (backup not found) and a 504 (gateway timeout) both surface as
947
+ // "Internal server error", so neither the caller nor a monitor could tell a
948
+ // missing resource from an outage.
949
+ const resolvedMessage = (_resolveStatusMessage = resolveStatusMessage(status, error)) != null ? _resolveStatusMessage : `Request failed with status ${status}`;
950
+ throw new WalletApiError(status, resolvedMessage, extractServerErrorCode(error));
951
+ };
952
+
814
953
  /**
815
954
  * Thrown when a signMessage/signTransaction SSE stream ends with `consent_required` instead of
816
955
  * completing — the wallet belongs to a business account with an unmet signing-quorum requirement.
@@ -859,11 +998,19 @@ const getElapsedTime = (startTime)=>{
859
998
  * Reports a request that failed before any response (e.g. a dropped
860
999
  * connection) to `onError` and returns the error to reject with. Axios errors
861
1000
  * carry request config (incl. auth headers) on the error itself, so onError
862
- * only gets a fresh error with the message, never the raw error object.
1001
+ * only gets a fresh error with the message, HTTP status and backend code (the
1002
+ * 409 recovery predicates key off `code`), never the raw error object.
863
1003
  */ const reportRequestFailure = (err, onError)=>{
1004
+ var _err_response;
864
1005
  const error = err instanceof Error ? err : new Error(String(err));
1006
+ const status = err == null ? void 0 : (_err_response = err.response) == null ? void 0 : _err_response.status;
1007
+ const code = extractServerErrorCode(err);
865
1008
  try {
866
- onError == null ? void 0 : onError(new Error(error.message));
1009
+ onError == null ? void 0 : onError(Object.assign(new Error(error.message), _extends({}, status !== undefined && {
1010
+ status
1011
+ }, code && {
1012
+ code
1013
+ })));
867
1014
  } catch (observerError) {
868
1015
  Logger.warn('Event stream error observer threw', {
869
1016
  observerErrorType: observerError instanceof Error ? observerError.name : typeof observerError
@@ -921,6 +1068,46 @@ const getElapsedTime = (startTime)=>{
921
1068
  };
922
1069
  return pump();
923
1070
  };
1071
+ const parseJsonOrText = (text)=>{
1072
+ try {
1073
+ return JSON.parse(text);
1074
+ } catch (e) {
1075
+ return text;
1076
+ }
1077
+ };
1078
+ const SERVER_ERROR_CODE_KEYS = [
1079
+ 'code',
1080
+ 'error_code',
1081
+ 'error'
1082
+ ];
1083
+ // handleAxiosError logs `response.data` verbatim, so only the machine-readable code fields may survive.
1084
+ const pickServerErrorCodes = (body)=>{
1085
+ if (typeof body !== 'object' || body === null) return undefined;
1086
+ const record = body;
1087
+ return Object.fromEntries(SERVER_ERROR_CODE_KEYS.flatMap((key)=>typeof record[key] === 'string' ? [
1088
+ [
1089
+ key,
1090
+ record[key]
1091
+ ]
1092
+ ] : []));
1093
+ };
1094
+ /**
1095
+ * With `responseType: 'stream'` an error response's body is an unread stream, so the backend's
1096
+ * `code` never reaches `handleAxiosError`. Replaces it in place with its code fields only.
1097
+ */ const drainStreamErrorBody = async (err)=>{
1098
+ var _response_data;
1099
+ const response = err == null ? void 0 : err.response;
1100
+ if (!(response == null ? void 0 : (_response_data = response.data) == null ? void 0 : _response_data.getReader)) return;
1101
+ try {
1102
+ Object.assign(response, {
1103
+ data: pickServerErrorCodes(parseJsonOrText(await readStreamToText(response.data.getReader())))
1104
+ });
1105
+ } catch (readError) {
1106
+ Logger.warn('Could not read the error response body', {
1107
+ readError
1108
+ });
1109
+ }
1110
+ };
924
1111
  /**
925
1112
  * Creates a promise that resolves when a specific event is received from an event stream.
926
1113
  * Adds a timeout to prevent hanging and races the two promises.
@@ -998,7 +1185,10 @@ const getElapsedTime = (startTime)=>{
998
1185
  })(response);
999
1186
  })// Without onError, a caller that races the ceremony against it (the cached-room
1000
1187
  // sign path never awaits this promise) waits out its queue timeout instead.
1001
- .catch((err)=>reject(reportRequestFailure(err, onError)));
1188
+ .catch(async (err)=>{
1189
+ await drainStreamErrorBody(err);
1190
+ reject(reportRequestFailure(err, onError));
1191
+ });
1002
1192
  });
1003
1193
  // Add a timeout to prevent hanging
1004
1194
  let timeoutId;
@@ -1297,145 +1487,6 @@ const getElapsedTime = (startTime)=>{
1297
1487
  }
1298
1488
  }
1299
1489
 
1300
- class WalletApiError extends Error {
1301
- constructor(status, message, code){
1302
- super(message);
1303
- this.name = 'WalletApiError';
1304
- this.status = status;
1305
- this.code = code;
1306
- }
1307
- }
1308
- const getResponseRecord = (error)=>{
1309
- var _error_response;
1310
- const data = (_error_response = error.response) == null ? void 0 : _error_response.data;
1311
- return data && typeof data === 'object' ? data : undefined;
1312
- };
1313
- // The Key Share Service returns its machine-readable cause under `error_code`; other
1314
- // backends use `code` or a bare `error`. Exported for callers that must skip handleAxiosError's own logging.
1315
- const extractServerErrorCode = (error)=>{
1316
- const record = getResponseRecord(error);
1317
- const candidates = [
1318
- record == null ? void 0 : record['code'],
1319
- record == null ? void 0 : record['error_code'],
1320
- record == null ? void 0 : record['error']
1321
- ];
1322
- return candidates.find((value)=>typeof value === 'string');
1323
- };
1324
- const INTERNAL_SERVER_ERROR_MESSAGE = 'Internal server error';
1325
- /**
1326
- * `status` for a request that never received an HTTP response at all — the
1327
- * client lost connectivity, the request was aborted, DNS/TLS failed, or CORS
1328
- * blocked it. 0 matches the XHR/`fetch` convention for "no response".
1329
- *
1330
- * This used to be reported as `500 Internal server error`, which made a
1331
- * client-side network failure indistinguishable from a backend fault: the
1332
- * "Backend 500s" monitor counted 1,395 events on a day when the API returned
1333
- * only 33 real 5xx responses.
1334
- */ const NETWORK_ERROR_STATUS = 0;
1335
- const NETWORK_ERROR_CODE = 'NETWORK_ERROR';
1336
- const NETWORK_ERROR_MESSAGE = 'Network error - no response received';
1337
- const STATUS_MESSAGES = {
1338
- 400: 'Invalid request',
1339
- 403: 'Forbidden',
1340
- 422: 'Unprocessable content',
1341
- 429: 'Rate limited',
1342
- 500: INTERNAL_SERVER_ERROR_MESSAGE
1343
- };
1344
- const MISSING_AUTH_MESSAGE = 'Authorization header or cookie missing';
1345
- // A 401 can mean the request carried no credentials, or carried credentials the
1346
- // backend rejected — the two need different messages. The Authorization header
1347
- // is readable so we can confirm its presence; the auth cookie is httpOnly, so we
1348
- // can only report whether cookie mode was enabled (`withCredentials`), not that a
1349
- // cookie was actually attached.
1350
- const getRequestCredentials = (error)=>{
1351
- var _error_config, _error_config1;
1352
- const requestHeaders = (_error_config = error.config) == null ? void 0 : _error_config.headers;
1353
- var _requestHeaders_Authorization;
1354
- const hasAuthorizationHeader = Boolean((_requestHeaders_Authorization = requestHeaders == null ? void 0 : requestHeaders['Authorization']) != null ? _requestHeaders_Authorization : requestHeaders == null ? void 0 : requestHeaders['authorization']);
1355
- const usesCookieAuth = Boolean((_error_config1 = error.config) == null ? void 0 : _error_config1.withCredentials);
1356
- return {
1357
- hasAuthorizationHeader,
1358
- usesCookieAuth
1359
- };
1360
- };
1361
- const resolveUnauthorizedMessage = (error)=>{
1362
- const { hasAuthorizationHeader, usesCookieAuth } = getRequestCredentials(error);
1363
- if (!hasAuthorizationHeader && !usesCookieAuth) {
1364
- return MISSING_AUTH_MESSAGE;
1365
- }
1366
- const credentialDescriptions = [];
1367
- if (hasAuthorizationHeader) {
1368
- credentialDescriptions.push('Authorization header present');
1369
- }
1370
- if (usesCookieAuth) {
1371
- credentialDescriptions.push('withCredentials enabled (cookie auth)');
1372
- }
1373
- return `Unauthorized (${credentialDescriptions.join(', ')})`;
1374
- };
1375
- const resolveStatusMessage = (status, error)=>{
1376
- if (status === 401) {
1377
- return resolveUnauthorizedMessage(error);
1378
- }
1379
- if (status && STATUS_MESSAGES[status]) {
1380
- return STATUS_MESSAGES[status];
1381
- }
1382
- return undefined;
1383
- };
1384
- const handleAxiosError = (error, message, context, /**
1385
- * Optional severity hint from the caller, for failures the caller knows are
1386
- * expected (e.g. a business-rule rejection). It can only *lower* severity to
1387
- * `warn` — a caller must not be able to escalate, and a genuine 5xx has to
1388
- * stay at `error` regardless of what the call site believes.
1389
- *
1390
- * Without this the hint that `logError` accepts was silently discarded for
1391
- * every AxiosError, which is the most common error type in the SDK.
1392
- */ options)=>{
1393
- var _error_config, _error_config1, _error_response, _error_response1, _error_response2;
1394
- const requestUrl = (_error_config = error.config) == null ? void 0 : _error_config.url;
1395
- const requestBaseUrl = (_error_config1 = error.config) == null ? void 0 : _error_config1.baseURL;
1396
- // The HTTP status MUST NOT be logged as a top-level `status` field: Datadog
1397
- // reserves `status` for the log level and its remapper turns a numeric value
1398
- // into `info`, silently burying every 4xx/5xx we emit here. `http.status_code`
1399
- // is Datadog's standard attribute, so the level survives and these logs join
1400
- // against edge/CDN logs on the same field.
1401
- const logPayload = _extends({
1402
- message,
1403
- error: (_error_response = error.response) == null ? void 0 : _error_response.data,
1404
- http: {
1405
- status_code: (_error_response1 = error.response) == null ? void 0 : _error_response1.status
1406
- }
1407
- }, requestBaseUrl && {
1408
- requestBaseUrl
1409
- }, requestUrl && {
1410
- requestUrl
1411
- }, {
1412
- context
1413
- });
1414
- const status = (_error_response2 = error.response) == null ? void 0 : _error_response2.status;
1415
- // A 429 (Too Many Requests) is a transient rate-limit signal, not a code or
1416
- // logic failure — and a request that never got a response is a client-side
1417
- // connectivity problem, not a server fault. Both are logged at `warn` so they
1418
- // don't pollute error dashboards or trigger PagerDuty. The 429 case covers
1419
- // both Cloudflare WAF blocks and application-level rate limiting.
1420
- const inferredLevel = status === 429 || status === undefined ? 'warn' : 'error';
1421
- // A 5xx is a server fault: no call site is entitled to downgrade it, however
1422
- // expected it believes the failure to be. The hint only applies below 500.
1423
- const isServerFault = status !== undefined && status >= 500;
1424
- const logLevel = (options == null ? void 0 : options.level) === 'warn' && !isServerFault ? 'warn' : inferredLevel;
1425
- Logger[logLevel]('[DynamicWaasWalletClient] Axios error: ', logPayload);
1426
- // No response at all: report it as such rather than laundering it into a 500.
1427
- if (status === undefined) {
1428
- throw new WalletApiError(NETWORK_ERROR_STATUS, NETWORK_ERROR_MESSAGE, NETWORK_ERROR_CODE);
1429
- }
1430
- var _resolveStatusMessage;
1431
- // Preserve the real status. Collapsing every unmapped code to 500 made a 404
1432
- // (backup not found) and a 504 (gateway timeout) both surface as
1433
- // "Internal server error", so neither the caller nor a monitor could tell a
1434
- // missing resource from an outage.
1435
- const resolvedMessage = (_resolveStatusMessage = resolveStatusMessage(status, error)) != null ? _resolveStatusMessage : `Request failed with status ${status}`;
1436
- throw new WalletApiError(status, resolvedMessage, extractServerErrorCode(error));
1437
- };
1438
-
1439
1490
  const getRequiredExternalKeyShareId = (ks)=>{
1440
1491
  if (!ks.externalKeyShareId) {
1441
1492
  throw new Error(`Missing externalKeyShareId for key share (id: ${ks.id}, keygenId: ${ks.keygenId})`);
@@ -1450,7 +1501,7 @@ const getRequiredExternalKeyShareId = (ks)=>{
1450
1501
  * before it is posted and surfaces in Datadog exactly as the recovery path does.
1451
1502
  */ const assertDynamicLocationsHaveExternalKeyShareId = (locations)=>locations.filter((location)=>location.location === BackupLocation.DYNAMIC).forEach((location)=>getRequiredExternalKeyShareId(location));
1452
1503
 
1453
- var version = "1.1.63";
1504
+ var version = "1.1.65";
1454
1505
 
1455
1506
  /**
1456
1507
  * Reads the Authorization header off an axios request config, which stores
@@ -2710,6 +2761,16 @@ class DynamicApiClient extends BaseClient {
2710
2761
  this.throwGaslessApiError('SVM sponsorship failed', error);
2711
2762
  }
2712
2763
  }
2764
+ async getSvmSponsorAddress({ traceContext } = {}) {
2765
+ try {
2766
+ const { data } = await this.apiClient.get(`${this.sdkRoutePrefix}/${this.environmentId}/solana/sponsorAddress`, {
2767
+ headers: this.buildTraceHeaders(traceContext)
2768
+ });
2769
+ return data;
2770
+ } catch (error) {
2771
+ this.throwGaslessApiError('SVM sponsor address lookup failed', error);
2772
+ }
2773
+ }
2713
2774
  buildTraceHeaders(traceContext) {
2714
2775
  return {
2715
2776
  [DynamicRequestIdHeader]: uuid.v4().replace('-', ''),
@@ -2813,11 +2874,33 @@ class DynamicApiClient extends BaseClient {
2813
2874
  return data;
2814
2875
  }
2815
2876
  /**
2816
- * Signs Token-2022 confidential-transfer transactions in the enclave.
2817
- * Returns base64 serialized transactions in broadcast order — the caller
2818
- * broadcasts them to Solana itself.
2877
+ * Builds Token-2022 confidential-transfer transactions in the enclave.
2878
+ * Returns base64 unsigned transactions in broadcast order plus a binding
2879
+ * tag; sign them through `signConfidentialTransactions`.
2819
2880
  */ async signConfidentialTransfer({ walletId, request, traceContext }) {
2820
- const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/signConfidentialTransfer`, request, {
2881
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/buildConfidentialTransaction`, request, {
2882
+ headers: this.buildTraceHeaders(traceContext)
2883
+ });
2884
+ return data;
2885
+ }
2886
+ /**
2887
+ * Second half of the confidential-transfer ceremony: provisions one MPC
2888
+ * room per transaction and dispatches the enclave co-sign. Returns the
2889
+ * room ids for the client share to join.
2890
+ */ async signConfidentialTransactions({ walletId, request, mfaToken, elevatedAccessToken, traceContext }) {
2891
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/signConfidentialTransaction`, request, {
2892
+ headers: _extends({}, this.buildTraceHeaders(traceContext), {
2893
+ [DynamicMfaTokenHeader]: mfaToken,
2894
+ [DynamicElevatedAccessTokenHeader]: elevatedAccessToken
2895
+ })
2896
+ });
2897
+ return data;
2898
+ }
2899
+ /**
2900
+ * Decrypts a confidential token account's available and pending balances
2901
+ * inside the enclave, using the wallet's stored confidential seed.
2902
+ */ async getSvmConfidentialBalance({ walletId, request, traceContext }) {
2903
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/svmConfidentialBalance`, request, {
2821
2904
  headers: this.buildTraceHeaders(traceContext)
2822
2905
  });
2823
2906
  return data;