@portal-hq/utils 4.4.0 → 4.5.1

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.
@@ -145,6 +145,21 @@ class KeychainAdapter {
145
145
  validateOperations() {
146
146
  throw new Error(`[Portal] KeychainAdapter method validateOperations() cannot be called directly. Please extend KeychainAdapter.`);
147
147
  }
148
+ getPresignatures(curve) {
149
+ throw new Error(`[Portal] KeychainAdapter method getPresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
150
+ }
151
+ insertPresignature(_curve, _presignature) {
152
+ throw new Error(`[Portal] KeychainAdapter method insertPresignature cannot be called directly. Please extend KeychainAdapter.`);
153
+ }
154
+ popOldestPresignature(curve) {
155
+ throw new Error(`[Portal] KeychainAdapter method popOldestPresignature(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
156
+ }
157
+ cleanupExpiredPresignatures(curve) {
158
+ throw new Error(`[Portal] KeychainAdapter method cleanupExpiredPresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
159
+ }
160
+ deletePresignatures(curve) {
161
+ throw new Error(`[Portal] KeychainAdapter method deletePresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
162
+ }
148
163
  }
149
164
  exports.KeychainAdapter = KeychainAdapter;
150
165
  var MpcStatuses;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.sdkLogger = exports.EvaluateTransactionOperationType = exports.HttpRequester = exports.PortalRequests = exports.HttpRequest = exports.parseRequest = exports.numberToHexString = exports.getClientPlatformVersion = exports.Events = exports.RpcErrorCodes = exports.ProviderRpcError = exports.PortalMpcError = exports.PortalErrorCodeTypes = exports.PortalErrorCodes = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = exports.Storage = exports.PortalRequestMethod = exports.PasswordStorage = exports.MpcStatuses = exports.KeychainAdapter = exports.convert = exports.convertCryptoToLocal = exports.convertLocalToCrypto = exports.DEFAULT_HOSTS = exports.NAMESPACE_TO_CURVE = exports.ALL_CHAIN_IDS = exports.BITCOIN_CHAIN_IDS = exports.SOLANA_CHAIN_IDS = exports.EVM_CHAIN_IDS = exports.DEFAULT_CHAIN_ID_CAIP2 = exports.DEFAULT_CHAIN_ID_NUMERIC = exports.CAIP2_CHAIN_ID_REGEX = exports.FRIENDLY_CHAIN_NAME_TO_CAIP2 = exports.SUPPORTED_BITCOIN_P2WPKH_CHAINS = exports.CHAIN_NAMESPACES = exports.getChainNameForId = exports.getChainIdForName = exports.chainNameToId = exports.chainIdToName = void 0;
6
+ exports.sdkLogger = exports.UUID_V4_REGEX = exports.TRACE_ID_HEADER = exports.createExecutionContext = exports.generateTraceId = exports.EvaluateTransactionOperationType = exports.HttpRequester = exports.PortalRequests = exports.HttpRequest = exports.parseRequest = exports.numberToHexString = exports.getClientPlatformVersion = exports.Events = exports.RpcErrorCodes = exports.ProviderRpcError = exports.PortalMpcError = exports.PortalErrorCodeTypes = exports.PortalErrorCodes = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = exports.Storage = exports.PortalRequestMethod = exports.PasswordStorage = exports.MpcStatuses = exports.KeychainAdapter = exports.convert = exports.convertCryptoToLocal = exports.convertLocalToCrypto = exports.DEFAULT_HOSTS = exports.NAMESPACE_TO_CURVE = exports.ALL_CHAIN_IDS = exports.BITCOIN_CHAIN_IDS = exports.SOLANA_CHAIN_IDS = exports.EVM_CHAIN_IDS = exports.DEFAULT_CHAIN_ID_CAIP2 = exports.DEFAULT_CHAIN_ID_NUMERIC = exports.CAIP2_CHAIN_ID_REGEX = exports.FRIENDLY_CHAIN_NAME_TO_CAIP2 = exports.SUPPORTED_BITCOIN_P2WPKH_CHAINS = exports.CHAIN_NAMESPACES = exports.getChainNameForId = exports.getChainIdForName = exports.chainNameToId = exports.chainIdToName = void 0;
7
7
  var chains_1 = require("./chains");
8
8
  Object.defineProperty(exports, "chainIdToName", { enumerable: true, get: function () { return chains_1.chainIdToName; } });
9
9
  Object.defineProperty(exports, "chainNameToId", { enumerable: true, get: function () { return chains_1.chainNameToId; } });
@@ -61,5 +61,10 @@ var requesters_1 = require("./requesters");
61
61
  Object.defineProperty(exports, "HttpRequester", { enumerable: true, get: function () { return requesters_1.HttpRequester; } });
62
62
  var types_1 = require("./types");
63
63
  Object.defineProperty(exports, "EvaluateTransactionOperationType", { enumerable: true, get: function () { return types_1.EvaluateTransactionOperationType; } });
64
+ var tracing_1 = require("./tracing");
65
+ Object.defineProperty(exports, "generateTraceId", { enumerable: true, get: function () { return tracing_1.generateTraceId; } });
66
+ Object.defineProperty(exports, "createExecutionContext", { enumerable: true, get: function () { return tracing_1.createExecutionContext; } });
67
+ Object.defineProperty(exports, "TRACE_ID_HEADER", { enumerable: true, get: function () { return tracing_1.TRACE_ID_HEADER; } });
68
+ Object.defineProperty(exports, "UUID_V4_REGEX", { enumerable: true, get: function () { return tracing_1.UUID_V4_REGEX; } });
64
69
  var logger_1 = require("./logger");
65
70
  Object.defineProperty(exports, "sdkLogger", { enumerable: true, get: function () { return logger_1.sdkLogger; } });
@@ -10,45 +10,49 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  const index_1 = require("../index");
13
+ const tracing_1 = require("../tracing");
13
14
  class HttpRequester {
14
15
  constructor({ baseUrl }) {
15
16
  this.baseUrl = baseUrl;
16
17
  }
17
- buildHeaders(headers = {}) {
18
- return Object.assign({ 'Content-Type': 'application/json' }, headers);
18
+ buildHeaders(headers = {}, traceId) {
19
+ return Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), (traceId ? { [tracing_1.TRACE_ID_HEADER]: traceId } : {}));
19
20
  }
20
21
  delete(path, options) {
22
+ var _a;
21
23
  return __awaiter(this, void 0, void 0, function* () {
22
24
  const requestOptions = {
23
25
  method: 'DELETE',
24
26
  url: `${this.baseUrl}${path}`,
25
27
  };
26
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
28
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
27
29
  const request = new index_1.HttpRequest(requestOptions);
28
30
  const response = (yield request.send());
29
31
  return response;
30
32
  });
31
33
  }
32
34
  get(path, options) {
35
+ var _a;
33
36
  return __awaiter(this, void 0, void 0, function* () {
34
37
  const requestOptions = {
35
38
  method: 'GET',
36
39
  url: `${this.baseUrl}${path}`,
37
40
  };
38
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
41
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
39
42
  const request = new index_1.HttpRequest(requestOptions);
40
43
  const response = (yield request.send());
41
44
  return response;
42
45
  });
43
46
  }
44
47
  post(path, options) {
48
+ var _a;
45
49
  return __awaiter(this, void 0, void 0, function* () {
46
50
  const requestOptions = {
47
51
  method: 'POST',
48
52
  url: `${this.baseUrl}${path}`,
49
53
  };
50
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
51
- if (options && options.body) {
54
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
55
+ if (options === null || options === void 0 ? void 0 : options.body) {
52
56
  requestOptions.body = options.body;
53
57
  }
54
58
  const request = new index_1.HttpRequest(requestOptions);
@@ -57,13 +61,14 @@ class HttpRequester {
57
61
  });
58
62
  }
59
63
  put(path, options) {
64
+ var _a;
60
65
  return __awaiter(this, void 0, void 0, function* () {
61
66
  const requestOptions = {
62
67
  method: 'PUT',
63
68
  url: `${this.baseUrl}${path}`,
64
69
  };
65
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
66
- if (options && options.body) {
70
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
71
+ if (options === null || options === void 0 ? void 0 : options.body) {
67
72
  requestOptions.body = options.body;
68
73
  }
69
74
  const request = new index_1.HttpRequest(requestOptions);
@@ -72,13 +77,14 @@ class HttpRequester {
72
77
  });
73
78
  }
74
79
  patch(path, options) {
80
+ var _a;
75
81
  return __awaiter(this, void 0, void 0, function* () {
76
82
  const requestOptions = {
77
83
  method: 'PATCH',
78
84
  url: `${this.baseUrl}${path}`,
79
85
  };
80
- requestOptions.headers = this.buildHeaders((options === null || options === void 0 ? void 0 : options.headers) ? options.headers : {});
81
- if (options && options.body) {
86
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
87
+ if (options === null || options === void 0 ? void 0 : options.body) {
82
88
  requestOptions.body = options.body;
83
89
  }
84
90
  const request = new index_1.HttpRequest(requestOptions);
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ /**
3
+ * Request tracing for Portal API calls.
4
+ *
5
+ * Generates a UUID v4 trace ID
6
+ * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.TRACE_ID_HEADER = exports.createExecutionContext = exports.generateTraceId = exports.UUID_V4_REGEX = void 0;
10
+ /** Standard UUID v4 regex (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) */
11
+ exports.UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
12
+ /**
13
+ * Generates a UUID v4 trace ID for request correlation.
14
+ * - crypto.randomUUID() when available (browsers, Node, some RN runtimes)
15
+ * - Otherwise fallback to standard RFC 4122 UUID v4 with hyphens
16
+ *
17
+ * Ensures traceIds are consistent and searchable by the same UUID value.
18
+ */
19
+ function generateTraceId() {
20
+ if (typeof crypto !== 'undefined' &&
21
+ typeof crypto.randomUUID === 'function') {
22
+ return crypto.randomUUID();
23
+ }
24
+ return fallbackUuidV4();
25
+ }
26
+ exports.generateTraceId = generateTraceId;
27
+ /**
28
+ * Fallback UUID v4 generator when crypto.randomUUID is not available.
29
+ */
30
+ function fallbackUuidV4() {
31
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
32
+ const r = (Math.random() * 16) | 0;
33
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
34
+ return v.toString(16);
35
+ });
36
+ }
37
+ /**
38
+ * Creates an ExecutionContext with a new trace ID.
39
+ * This is typically called at the entry point of public SDK methods.
40
+ *
41
+ * @param traceId - Optional existing trace ID to use. If not provided, generates a new one.
42
+ * @param metadata - Optional custom metadata to attach to the context
43
+ * @returns A new ExecutionContext
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * // Generate a new context
48
+ * const context = createExecutionContext()
49
+ *
50
+ * // Reuse an existing trace ID
51
+ * const context = createExecutionContext(existingTraceId)
52
+ *
53
+ * // Add custom metadata
54
+ * const context = createExecutionContext(undefined, { userId: '123' })
55
+ * ```
56
+ */
57
+ function createExecutionContext(traceId, metadata) {
58
+ return Object.assign({ traceId: traceId !== null && traceId !== void 0 ? traceId : generateTraceId() }, (metadata && { metadata }));
59
+ }
60
+ exports.createExecutionContext = createExecutionContext;
61
+ /**
62
+ * The trace ID header used by connect-api (client + custodian APIs).
63
+ * Note: Other internal services may use different header names.
64
+ */
65
+ exports.TRACE_ID_HEADER = 'X-Portal-Trace-Id';
@@ -1 +1 @@
1
- { "version": "4.4.0" }
1
+ { "version": "4.5.1" }
@@ -142,6 +142,21 @@ export class KeychainAdapter {
142
142
  validateOperations() {
143
143
  throw new Error(`[Portal] KeychainAdapter method validateOperations() cannot be called directly. Please extend KeychainAdapter.`);
144
144
  }
145
+ getPresignatures(curve) {
146
+ throw new Error(`[Portal] KeychainAdapter method getPresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
147
+ }
148
+ insertPresignature(_curve, _presignature) {
149
+ throw new Error(`[Portal] KeychainAdapter method insertPresignature cannot be called directly. Please extend KeychainAdapter.`);
150
+ }
151
+ popOldestPresignature(curve) {
152
+ throw new Error(`[Portal] KeychainAdapter method popOldestPresignature(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
153
+ }
154
+ cleanupExpiredPresignatures(curve) {
155
+ throw new Error(`[Portal] KeychainAdapter method cleanupExpiredPresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
156
+ }
157
+ deletePresignatures(curve) {
158
+ throw new Error(`[Portal] KeychainAdapter method deletePresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`);
159
+ }
145
160
  }
146
161
  export var MpcStatuses;
147
162
  (function (MpcStatuses) {
package/lib/esm/index.js CHANGED
@@ -10,4 +10,5 @@ export { default as HttpRequest } from './http-request';
10
10
  export { default as PortalRequests } from './PortalRequests';
11
11
  export { HttpRequester } from './requesters';
12
12
  export { EvaluateTransactionOperationType } from './types';
13
+ export { generateTraceId, createExecutionContext, TRACE_ID_HEADER, UUID_V4_REGEX, } from './tracing';
13
14
  export { sdkLogger } from './logger';
@@ -8,45 +8,49 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { HttpRequest } from '../index';
11
+ import { TRACE_ID_HEADER } from '../tracing';
11
12
  class HttpRequester {
12
13
  constructor({ baseUrl }) {
13
14
  this.baseUrl = baseUrl;
14
15
  }
15
- buildHeaders(headers = {}) {
16
- return Object.assign({ 'Content-Type': 'application/json' }, headers);
16
+ buildHeaders(headers = {}, traceId) {
17
+ return Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), (traceId ? { [TRACE_ID_HEADER]: traceId } : {}));
17
18
  }
18
19
  delete(path, options) {
20
+ var _a;
19
21
  return __awaiter(this, void 0, void 0, function* () {
20
22
  const requestOptions = {
21
23
  method: 'DELETE',
22
24
  url: `${this.baseUrl}${path}`,
23
25
  };
24
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
26
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
25
27
  const request = new HttpRequest(requestOptions);
26
28
  const response = (yield request.send());
27
29
  return response;
28
30
  });
29
31
  }
30
32
  get(path, options) {
33
+ var _a;
31
34
  return __awaiter(this, void 0, void 0, function* () {
32
35
  const requestOptions = {
33
36
  method: 'GET',
34
37
  url: `${this.baseUrl}${path}`,
35
38
  };
36
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
39
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
37
40
  const request = new HttpRequest(requestOptions);
38
41
  const response = (yield request.send());
39
42
  return response;
40
43
  });
41
44
  }
42
45
  post(path, options) {
46
+ var _a;
43
47
  return __awaiter(this, void 0, void 0, function* () {
44
48
  const requestOptions = {
45
49
  method: 'POST',
46
50
  url: `${this.baseUrl}${path}`,
47
51
  };
48
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
49
- if (options && options.body) {
52
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
53
+ if (options === null || options === void 0 ? void 0 : options.body) {
50
54
  requestOptions.body = options.body;
51
55
  }
52
56
  const request = new HttpRequest(requestOptions);
@@ -55,13 +59,14 @@ class HttpRequester {
55
59
  });
56
60
  }
57
61
  put(path, options) {
62
+ var _a;
58
63
  return __awaiter(this, void 0, void 0, function* () {
59
64
  const requestOptions = {
60
65
  method: 'PUT',
61
66
  url: `${this.baseUrl}${path}`,
62
67
  };
63
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
64
- if (options && options.body) {
68
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
69
+ if (options === null || options === void 0 ? void 0 : options.body) {
65
70
  requestOptions.body = options.body;
66
71
  }
67
72
  const request = new HttpRequest(requestOptions);
@@ -70,13 +75,14 @@ class HttpRequester {
70
75
  });
71
76
  }
72
77
  patch(path, options) {
78
+ var _a;
73
79
  return __awaiter(this, void 0, void 0, function* () {
74
80
  const requestOptions = {
75
81
  method: 'PATCH',
76
82
  url: `${this.baseUrl}${path}`,
77
83
  };
78
- requestOptions.headers = this.buildHeaders((options === null || options === void 0 ? void 0 : options.headers) ? options.headers : {});
79
- if (options && options.body) {
84
+ requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
85
+ if (options === null || options === void 0 ? void 0 : options.body) {
80
86
  requestOptions.body = options.body;
81
87
  }
82
88
  const request = new HttpRequest(requestOptions);
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Request tracing for Portal API calls.
3
+ *
4
+ * Generates a UUID v4 trace ID
5
+ * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
6
+ */
7
+ /** Standard UUID v4 regex (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) */
8
+ export const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
9
+ /**
10
+ * Generates a UUID v4 trace ID for request correlation.
11
+ * - crypto.randomUUID() when available (browsers, Node, some RN runtimes)
12
+ * - Otherwise fallback to standard RFC 4122 UUID v4 with hyphens
13
+ *
14
+ * Ensures traceIds are consistent and searchable by the same UUID value.
15
+ */
16
+ export function generateTraceId() {
17
+ if (typeof crypto !== 'undefined' &&
18
+ typeof crypto.randomUUID === 'function') {
19
+ return crypto.randomUUID();
20
+ }
21
+ return fallbackUuidV4();
22
+ }
23
+ /**
24
+ * Fallback UUID v4 generator when crypto.randomUUID is not available.
25
+ */
26
+ function fallbackUuidV4() {
27
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
28
+ const r = (Math.random() * 16) | 0;
29
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
30
+ return v.toString(16);
31
+ });
32
+ }
33
+ /**
34
+ * Creates an ExecutionContext with a new trace ID.
35
+ * This is typically called at the entry point of public SDK methods.
36
+ *
37
+ * @param traceId - Optional existing trace ID to use. If not provided, generates a new one.
38
+ * @param metadata - Optional custom metadata to attach to the context
39
+ * @returns A new ExecutionContext
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * // Generate a new context
44
+ * const context = createExecutionContext()
45
+ *
46
+ * // Reuse an existing trace ID
47
+ * const context = createExecutionContext(existingTraceId)
48
+ *
49
+ * // Add custom metadata
50
+ * const context = createExecutionContext(undefined, { userId: '123' })
51
+ * ```
52
+ */
53
+ export function createExecutionContext(traceId, metadata) {
54
+ return Object.assign({ traceId: traceId !== null && traceId !== void 0 ? traceId : generateTraceId() }, (metadata && { metadata }));
55
+ }
56
+ /**
57
+ * The trace ID header used by connect-api (client + custodian APIs).
58
+ * Note: Other internal services may use different header names.
59
+ */
60
+ export const TRACE_ID_HEADER = 'X-Portal-Trace-Id';
@@ -1 +1 @@
1
- { "version": "4.4.0" }
1
+ { "version": "4.5.1" }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portal-hq/utils",
3
- "version": "4.4.0",
3
+ "version": "4.5.1",
4
4
  "main": "lib/commonjs/index",
5
5
  "module": "lib/esm/index",
6
6
  "source": "src/index",
@@ -26,5 +26,5 @@
26
26
  "ts-jest": "^29.0.3",
27
27
  "typescript": "^4.8.4"
28
28
  },
29
- "gitHead": "76ce311809d877d0f8aa5373b0f4e9d85ee963f0"
29
+ "gitHead": "7f010a0c86c95b2d28daa1b6640519bb9a22920a"
30
30
  }
@@ -39,6 +39,7 @@ import type {
39
39
  NFT,
40
40
  Network,
41
41
  PortalKeychainMetadata,
42
+ Presignature,
42
43
  ProgressCallback,
43
44
  QuoteArgs,
44
45
  QuoteResponse,
@@ -78,6 +79,7 @@ export interface RequestArguments {
78
79
  export interface RequestOptions {
79
80
  sponsorGas?: boolean
80
81
  signatureApprovalMemo?: string
82
+ traceId?: string
81
83
  }
82
84
 
83
85
  export enum PortalRequestMethod {
@@ -194,10 +196,18 @@ export interface SendAssetParams {
194
196
  * Only supported for EVM and Solana chains.
195
197
  */
196
198
  sponsorGas?: boolean
199
+ /**
200
+ * Optional trace ID for request tracing and debugging.
201
+ * If not provided, a trace ID will be automatically generated.
202
+ * For operations that support trace IDs, this value will be forwarded
203
+ * to underlying API requests to aid in observability.
204
+ */
205
+ traceId?: string
197
206
  }
198
207
 
199
208
  export interface RawSignOptions {
200
209
  signatureApprovalMemo?: string
210
+ traceId?: string
201
211
  }
202
212
 
203
213
  export type SigningRequestParams = Eip1559 | LegacyTx
@@ -211,14 +221,15 @@ export interface IPortalApi {
211
221
  token: string,
212
222
  amount: string,
213
223
  chain?: string,
224
+ traceId?: string,
214
225
  ): Promise<BuildEip155TransactionResponse | BuildSolanaTransactionResponse>
215
226
  fund(chainId: string, params: FundParams): Promise<FundResponse>
216
227
  getBackupSharesMetadata(chainId?: string): Promise<BackupSharePairMetadata[]>
217
- getBalances(chainId?: string): Promise<Balance[]>
218
- getClient(): Promise<ClientResponse>
228
+ getBalances(chainId?: string, traceId?: string): Promise<Balance[]>
229
+ getClient(traceId?: string): Promise<ClientResponse>
219
230
  getClientCipherText(backupSharePairId: string): Promise<string>
220
231
  getEnabledDapps(): Promise<Dapp[]>
221
- getNFTs(chainId?: string): Promise<NFT[]>
232
+ getNFTs(chainId?: string, traceId?: string): Promise<NFT[]>
222
233
  getNetworks(): Promise<Network[]>
223
234
  getQuote(
224
235
  apiKey: string,
@@ -234,6 +245,7 @@ export interface IPortalApi {
234
245
  limit?: number,
235
246
  offset?: number,
236
247
  order?: GetTransactionsOrder,
248
+ traceId?: string,
237
249
  ): Promise<Transaction[]>
238
250
  prepareClientEject(
239
251
  walletId: string,
@@ -433,6 +445,34 @@ export abstract class KeychainAdapter {
433
445
  `[Portal] KeychainAdapter method validateOperations() cannot be called directly. Please extend KeychainAdapter.`,
434
446
  )
435
447
  }
448
+ getPresignatures(curve: string): Promise<Presignature[]> {
449
+ throw new Error(
450
+ `[Portal] KeychainAdapter method getPresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`,
451
+ )
452
+ }
453
+ insertPresignature(
454
+ _curve: string,
455
+ _presignature: Presignature,
456
+ ): Promise<void> {
457
+ throw new Error(
458
+ `[Portal] KeychainAdapter method insertPresignature cannot be called directly. Please extend KeychainAdapter.`,
459
+ )
460
+ }
461
+ popOldestPresignature(curve: string): Promise<Presignature | null> {
462
+ throw new Error(
463
+ `[Portal] KeychainAdapter method popOldestPresignature(${curve}) cannot be called directly. Please extend KeychainAdapter.`,
464
+ )
465
+ }
466
+ cleanupExpiredPresignatures(curve: string): Promise<number> {
467
+ throw new Error(
468
+ `[Portal] KeychainAdapter method cleanupExpiredPresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`,
469
+ )
470
+ }
471
+ deletePresignatures(curve: string): Promise<boolean> {
472
+ throw new Error(
473
+ `[Portal] KeychainAdapter method deletePresignatures(${curve}) cannot be called directly. Please extend KeychainAdapter.`,
474
+ )
475
+ }
436
476
  }
437
477
 
438
478
  export enum MpcStatuses {
package/src/index.ts CHANGED
@@ -67,6 +67,14 @@ export { HttpRequester } from './requesters'
67
67
 
68
68
  export { EvaluateTransactionOperationType } from './types'
69
69
 
70
+ export {
71
+ generateTraceId,
72
+ createExecutionContext,
73
+ TRACE_ID_HEADER,
74
+ UUID_V4_REGEX,
75
+ type ExecutionContext,
76
+ } from './tracing'
77
+
70
78
  export { sdkLogger, type LogLevel, type ILogger } from './logger'
71
79
 
72
80
  export type {
@@ -4,6 +4,7 @@ import {
4
4
  type HttpRequesterOptions,
5
5
  } from '../../types'
6
6
  import { HttpRequest } from '../index'
7
+ import { TRACE_ID_HEADER } from '../tracing'
7
8
 
8
9
  class HttpRequester {
9
10
  public baseUrl: string
@@ -12,10 +13,14 @@ class HttpRequester {
12
13
  this.baseUrl = baseUrl
13
14
  }
14
15
 
15
- public buildHeaders(headers: Record<string, any> = {}): Record<string, any> {
16
+ public buildHeaders(
17
+ headers: Record<string, string> = {},
18
+ traceId?: string,
19
+ ): Record<string, string> {
16
20
  return {
17
21
  'Content-Type': 'application/json',
18
22
  ...headers,
23
+ ...(traceId ? { [TRACE_ID_HEADER]: traceId } : {}),
19
24
  }
20
25
  }
21
26
 
@@ -26,7 +31,8 @@ class HttpRequester {
26
31
  } as HttpRequestOptions
27
32
 
28
33
  requestOptions.headers = this.buildHeaders(
29
- options && options.headers ? options.headers : {},
34
+ (options?.headers ?? {}) as Record<string, string>,
35
+ options?.traceId,
30
36
  )
31
37
 
32
38
  const request = new HttpRequest(requestOptions)
@@ -42,7 +48,8 @@ class HttpRequester {
42
48
  } as HttpRequestOptions
43
49
 
44
50
  requestOptions.headers = this.buildHeaders(
45
- options && options.headers ? options.headers : {},
51
+ (options?.headers ?? {}) as Record<string, string>,
52
+ options?.traceId,
46
53
  )
47
54
 
48
55
  const request = new HttpRequest(requestOptions)
@@ -58,10 +65,11 @@ class HttpRequester {
58
65
  } as HttpRequestOptions
59
66
 
60
67
  requestOptions.headers = this.buildHeaders(
61
- options && options.headers ? options.headers : {},
68
+ (options?.headers ?? {}) as Record<string, string>,
69
+ options?.traceId,
62
70
  )
63
71
 
64
- if (options && options.body) {
72
+ if (options?.body) {
65
73
  requestOptions.body = options.body
66
74
  }
67
75
 
@@ -78,10 +86,11 @@ class HttpRequester {
78
86
  } as HttpRequestOptions
79
87
 
80
88
  requestOptions.headers = this.buildHeaders(
81
- options && options.headers ? options.headers : {},
89
+ (options?.headers ?? {}) as Record<string, string>,
90
+ options?.traceId,
82
91
  )
83
92
 
84
- if (options && options.body) {
93
+ if (options?.body) {
85
94
  requestOptions.body = options.body
86
95
  }
87
96
 
@@ -98,10 +107,11 @@ class HttpRequester {
98
107
  } as HttpRequestOptions
99
108
 
100
109
  requestOptions.headers = this.buildHeaders(
101
- options?.headers ? options.headers : {},
110
+ (options?.headers ?? {}) as Record<string, string>,
111
+ options?.traceId,
102
112
  )
103
113
 
104
- if (options && options.body) {
114
+ if (options?.body) {
105
115
  requestOptions.body = options.body
106
116
  }
107
117
 
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Request tracing for Portal API calls.
3
+ *
4
+ * Generates a UUID v4 trace ID
5
+ * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
6
+ */
7
+
8
+ /** Standard UUID v4 regex (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) */
9
+
10
+ export const UUID_V4_REGEX =
11
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
12
+
13
+ /**
14
+ * Generates a UUID v4 trace ID for request correlation.
15
+ * - crypto.randomUUID() when available (browsers, Node, some RN runtimes)
16
+ * - Otherwise fallback to standard RFC 4122 UUID v4 with hyphens
17
+ *
18
+ * Ensures traceIds are consistent and searchable by the same UUID value.
19
+ */
20
+ export function generateTraceId(): string {
21
+ if (
22
+ typeof crypto !== 'undefined' &&
23
+ typeof crypto.randomUUID === 'function'
24
+ ) {
25
+ return crypto.randomUUID()
26
+ }
27
+
28
+ return fallbackUuidV4()
29
+ }
30
+
31
+ /**
32
+ * Fallback UUID v4 generator when crypto.randomUUID is not available.
33
+ */
34
+ function fallbackUuidV4(): string {
35
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
36
+ const r = (Math.random() * 16) | 0
37
+ const v = c === 'x' ? r : (r & 0x3) | 0x8
38
+ return v.toString(16)
39
+ })
40
+ }
41
+
42
+ /**
43
+ * ExecutionContext provides a structured way to pass metadata through SDK operations.
44
+ * This context is propagated through all internal method calls and API requests.
45
+ *
46
+ * Currently supports request tracing, but designed to be extensible for future metadata:
47
+ * - Request correlation/debugging
48
+ * - User session tracking
49
+ * - Performance metrics
50
+ * - Custom business metadata
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const context: ExecutionContext = {
55
+ * traceId: generateTraceId(),
56
+ * // Future fields can be added here without breaking changes
57
+ * }
58
+ * ```
59
+ */
60
+ export interface ExecutionContext {
61
+ /**
62
+ * Unique identifier for tracing a request through the system.
63
+ * Used for correlating logs, debugging, and observability.
64
+ */
65
+ traceId: string
66
+
67
+ /**
68
+ * Optional custom metadata that can be attached to the execution context.
69
+ * Reserved for future extensibility.
70
+ */
71
+ metadata?: Record<string, any>
72
+ }
73
+
74
+ /**
75
+ * Creates an ExecutionContext with a new trace ID.
76
+ * This is typically called at the entry point of public SDK methods.
77
+ *
78
+ * @param traceId - Optional existing trace ID to use. If not provided, generates a new one.
79
+ * @param metadata - Optional custom metadata to attach to the context
80
+ * @returns A new ExecutionContext
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * // Generate a new context
85
+ * const context = createExecutionContext()
86
+ *
87
+ * // Reuse an existing trace ID
88
+ * const context = createExecutionContext(existingTraceId)
89
+ *
90
+ * // Add custom metadata
91
+ * const context = createExecutionContext(undefined, { userId: '123' })
92
+ * ```
93
+ */
94
+ export function createExecutionContext(
95
+ traceId?: string,
96
+ metadata?: Record<string, any>,
97
+ ): ExecutionContext {
98
+ return {
99
+ traceId: traceId ?? generateTraceId(),
100
+ ...(metadata && { metadata }),
101
+ }
102
+ }
103
+
104
+ /**
105
+ * The trace ID header used by connect-api (client + custodian APIs).
106
+ * Note: Other internal services may use different header names.
107
+ */
108
+ export const TRACE_ID_HEADER = 'X-Portal-Trace-Id'
@@ -1 +1 @@
1
- { "version": "4.4.0" }
1
+ { "version": "4.5.1" }
package/types.d.ts CHANGED
@@ -182,6 +182,12 @@ export interface DkgData {
182
182
  signingSharePairId?: string
183
183
  }
184
184
 
185
+ export interface Presignature {
186
+ id: string
187
+ expiresAt: string
188
+ data: string
189
+ }
190
+
185
191
  export interface HttpErrorOptions {
186
192
  message: string
187
193
  status: number
@@ -191,6 +197,7 @@ export interface HttpErrorOptions {
191
197
  export interface HttpOptions {
192
198
  body?: Record<string, any>
193
199
  headers?: Record<string, any>
200
+ traceId?: string
194
201
  }
195
202
 
196
203
  export interface HttpRequesterOptions extends RequesterOptions {
@@ -282,6 +289,7 @@ export interface SigningRequestArguments {
282
289
  readonly isRaw?: boolean
283
290
  readonly sponsorGas?: boolean
284
291
  readonly signatureApprovalMemo?: string
292
+ readonly traceId?: string
285
293
  }
286
294
 
287
295
  export interface SigningResponse {