@miradorlabs/parallax-web 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1053,7 +1053,8 @@ function requireParallax_gateway_pb () {
1053
1053
  var f, obj = {
1054
1054
  name: jspb.Message.getFieldWithDefault(msg, 1, ""),
1055
1055
  attributesMap: (f = msg.getAttributesMap()) ? f.toObject(includeInstance, undefined) : [],
1056
- tagsList: (f = jspb.Message.getRepeatedField(msg, 3)) == null ? undefined : f
1056
+ tagsList: (f = jspb.Message.getRepeatedField(msg, 3)) == null ? undefined : f,
1057
+ startTime: (f = msg.getStartTime()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f)
1057
1058
  };
1058
1059
 
1059
1060
  if (includeInstance) {
@@ -1104,6 +1105,11 @@ function requireParallax_gateway_pb () {
1104
1105
  var value = /** @type {string} */ (reader.readString());
1105
1106
  msg.addTags(value);
1106
1107
  break;
1108
+ case 4:
1109
+ var value = new google_protobuf_timestamp_pb.Timestamp;
1110
+ reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader);
1111
+ msg.setStartTime(value);
1112
+ break;
1107
1113
  default:
1108
1114
  reader.skipField();
1109
1115
  break;
@@ -1151,6 +1157,14 @@ function requireParallax_gateway_pb () {
1151
1157
  f
1152
1158
  );
1153
1159
  }
1160
+ f = message.getStartTime();
1161
+ if (f != null) {
1162
+ writer.writeMessage(
1163
+ 4,
1164
+ f,
1165
+ google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter
1166
+ );
1167
+ }
1154
1168
  };
1155
1169
 
1156
1170
 
@@ -1232,6 +1246,43 @@ function requireParallax_gateway_pb () {
1232
1246
  };
1233
1247
 
1234
1248
 
1249
+ /**
1250
+ * optional google.protobuf.Timestamp start_time = 4;
1251
+ * @return {?proto.google.protobuf.Timestamp}
1252
+ */
1253
+ proto.gateway.parallax.v1.CreateTraceRequest.prototype.getStartTime = function() {
1254
+ return /** @type{?proto.google.protobuf.Timestamp} */ (
1255
+ jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 4));
1256
+ };
1257
+
1258
+
1259
+ /**
1260
+ * @param {?proto.google.protobuf.Timestamp|undefined} value
1261
+ * @return {!proto.gateway.parallax.v1.CreateTraceRequest} returns this
1262
+ */
1263
+ proto.gateway.parallax.v1.CreateTraceRequest.prototype.setStartTime = function(value) {
1264
+ return jspb.Message.setWrapperField(this, 4, value);
1265
+ };
1266
+
1267
+
1268
+ /**
1269
+ * Clears the message field making it undefined.
1270
+ * @return {!proto.gateway.parallax.v1.CreateTraceRequest} returns this
1271
+ */
1272
+ proto.gateway.parallax.v1.CreateTraceRequest.prototype.clearStartTime = function() {
1273
+ return this.setStartTime(undefined);
1274
+ };
1275
+
1276
+
1277
+ /**
1278
+ * Returns whether this field is set.
1279
+ * @return {boolean}
1280
+ */
1281
+ proto.gateway.parallax.v1.CreateTraceRequest.prototype.hasStartTime = function() {
1282
+ return jspb.Message.getField(this, 4) != null;
1283
+ };
1284
+
1285
+
1235
1286
 
1236
1287
 
1237
1288
 
@@ -1265,7 +1316,8 @@ function requireParallax_gateway_pb () {
1265
1316
  proto.gateway.parallax.v1.CreateTraceResponse.toObject = function(includeInstance, msg) {
1266
1317
  var f, obj = {
1267
1318
  status: (f = msg.getStatus()) && proto_common_v1_status_pb.ResponseStatus.toObject(includeInstance, f),
1268
- traceId: jspb.Message.getFieldWithDefault(msg, 2, "")
1319
+ traceId: jspb.Message.getFieldWithDefault(msg, 2, ""),
1320
+ rootSpanId: jspb.Message.getFieldWithDefault(msg, 3, "")
1269
1321
  };
1270
1322
 
1271
1323
  if (includeInstance) {
@@ -1311,6 +1363,10 @@ function requireParallax_gateway_pb () {
1311
1363
  var value = /** @type {string} */ (reader.readString());
1312
1364
  msg.setTraceId(value);
1313
1365
  break;
1366
+ case 3:
1367
+ var value = /** @type {string} */ (reader.readString());
1368
+ msg.setRootSpanId(value);
1369
+ break;
1314
1370
  default:
1315
1371
  reader.skipField();
1316
1372
  break;
@@ -1355,6 +1411,13 @@ function requireParallax_gateway_pb () {
1355
1411
  f
1356
1412
  );
1357
1413
  }
1414
+ f = message.getRootSpanId();
1415
+ if (f.length > 0) {
1416
+ writer.writeString(
1417
+ 3,
1418
+ f
1419
+ );
1420
+ }
1358
1421
  };
1359
1422
 
1360
1423
 
@@ -1413,6 +1476,24 @@ function requireParallax_gateway_pb () {
1413
1476
  };
1414
1477
 
1415
1478
 
1479
+ /**
1480
+ * optional string root_span_id = 3;
1481
+ * @return {string}
1482
+ */
1483
+ proto.gateway.parallax.v1.CreateTraceResponse.prototype.getRootSpanId = function() {
1484
+ return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, ""));
1485
+ };
1486
+
1487
+
1488
+ /**
1489
+ * @param {string} value
1490
+ * @return {!proto.gateway.parallax.v1.CreateTraceResponse} returns this
1491
+ */
1492
+ proto.gateway.parallax.v1.CreateTraceResponse.prototype.setRootSpanId = function(value) {
1493
+ return jspb.Message.setProto3StringField(this, 3, value);
1494
+ };
1495
+
1496
+
1416
1497
 
1417
1498
 
1418
1499
 
@@ -1447,7 +1528,7 @@ function requireParallax_gateway_pb () {
1447
1528
  var f, obj = {
1448
1529
  name: jspb.Message.getFieldWithDefault(msg, 1, ""),
1449
1530
  traceId: jspb.Message.getFieldWithDefault(msg, 2, ""),
1450
- parentSpanId: (f = jspb.Message.getField(msg, 3)) == null ? undefined : f,
1531
+ parentSpanId: jspb.Message.getFieldWithDefault(msg, 3, ""),
1451
1532
  attributesMap: (f = msg.getAttributesMap()) ? f.toObject(includeInstance, undefined) : [],
1452
1533
  startTime: (f = msg.getStartTime()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f)
1453
1534
  };
@@ -1552,8 +1633,8 @@ function requireParallax_gateway_pb () {
1552
1633
  f
1553
1634
  );
1554
1635
  }
1555
- f = /** @type {string} */ (jspb.Message.getField(message, 3));
1556
- if (f != null) {
1636
+ f = message.getParentSpanId();
1637
+ if (f.length > 0) {
1557
1638
  writer.writeString(
1558
1639
  3,
1559
1640
  f
@@ -1624,25 +1705,7 @@ function requireParallax_gateway_pb () {
1624
1705
  * @return {!proto.gateway.parallax.v1.StartSpanRequest} returns this
1625
1706
  */
1626
1707
  proto.gateway.parallax.v1.StartSpanRequest.prototype.setParentSpanId = function(value) {
1627
- return jspb.Message.setField(this, 3, value);
1628
- };
1629
-
1630
-
1631
- /**
1632
- * Clears the field making it undefined.
1633
- * @return {!proto.gateway.parallax.v1.StartSpanRequest} returns this
1634
- */
1635
- proto.gateway.parallax.v1.StartSpanRequest.prototype.clearParentSpanId = function() {
1636
- return jspb.Message.setField(this, 3, undefined);
1637
- };
1638
-
1639
-
1640
- /**
1641
- * Returns whether this field is set.
1642
- * @return {boolean}
1643
- */
1644
- proto.gateway.parallax.v1.StartSpanRequest.prototype.hasParentSpanId = function() {
1645
- return jspb.Message.getField(this, 3) != null;
1708
+ return jspb.Message.setProto3StringField(this, 3, value);
1646
1709
  };
1647
1710
 
1648
1711
 
@@ -4689,6 +4752,339 @@ class GrpcWebRpc {
4689
4752
  }
4690
4753
  }
4691
4754
 
4755
+ /**
4756
+ * Parallax Service - Transaction Tracing for Web Applications
4757
+ * Creates individual traces for each transaction and tracks them through their lifecycle
4758
+ *
4759
+ * This service provides a simplified interface for tracking transactions with automatic
4760
+ * client metadata collection and lifecycle management.
4761
+ */
4762
+ class ParallaxService {
4763
+ constructor() {
4764
+ Object.defineProperty(this, "client", {
4765
+ enumerable: true,
4766
+ configurable: true,
4767
+ writable: true,
4768
+ value: null
4769
+ });
4770
+ Object.defineProperty(this, "activeTransactions", {
4771
+ enumerable: true,
4772
+ configurable: true,
4773
+ writable: true,
4774
+ value: new Map()
4775
+ });
4776
+ // Client will be initialized lazily
4777
+ }
4778
+ /**
4779
+ * Initialize the Parallax client (lazy initialization)
4780
+ * @param apiKey - Optional API key for authentication
4781
+ * @param gatewayUrl - Optional custom gateway URL
4782
+ */
4783
+ _ensureClient(apiKey, gatewayUrl) {
4784
+ if (this.client)
4785
+ return;
4786
+ // Determine gateway URL based on environment if not provided
4787
+ let url = gatewayUrl;
4788
+ if (!url && typeof window !== 'undefined') {
4789
+ const isDevelopment = window.location.hostname === 'localhost' ||
4790
+ window.location.hostname === '127.0.0.1';
4791
+ url = isDevelopment
4792
+ ? `${window.location.protocol}//${window.location.host}/parallax-gateway`
4793
+ : 'https://gateway-parallax-dev.mirador.org';
4794
+ }
4795
+ this.client = new ParallaxClient(apiKey || '', url);
4796
+ console.log('[ParallaxService] Client initialized with URL:', url);
4797
+ }
4798
+ /**
4799
+ * Start a new transaction trace
4800
+ * Called when user initiates a transaction
4801
+ *
4802
+ * Note: Since createTrace now automatically creates a root span, we don't need
4803
+ * to call startSpan separately. The rootSpanId from the response is the parent span.
4804
+ *
4805
+ * @param txData - Transaction data
4806
+ * @param name - Name for the trace (e.g., 'SendingTrace', 'SwappingTrace')
4807
+ * @param options - Optional configuration (apiKey, gatewayUrl, includeClientMeta)
4808
+ * @returns Promise with traceId, rootSpanId, and txId
4809
+ */
4810
+ async startTransactionTrace(txData, name = 'WalletTransaction', options) {
4811
+ this._ensureClient(options?.apiKey, options?.gatewayUrl);
4812
+ if (!this.client) {
4813
+ throw new Error('Failed to initialize Parallax client');
4814
+ }
4815
+ try {
4816
+ const txId = `tx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
4817
+ const timestamp = new Date().toISOString();
4818
+ // Create trace attributes
4819
+ const traceAttributes = {
4820
+ transactionId: txId,
4821
+ walletAddress: txData.walletAddress || txData.from,
4822
+ network: txData.network || 'Unknown',
4823
+ transactionStart: timestamp,
4824
+ from: txData.from,
4825
+ to: txData.to,
4826
+ value: txData.value,
4827
+ };
4828
+ // Add any additional transaction data
4829
+ if (txData.additionalData) {
4830
+ Object.entries(txData.additionalData).forEach(([key, value]) => {
4831
+ traceAttributes[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);
4832
+ });
4833
+ }
4834
+ // Create a trace for this transaction
4835
+ const createTraceReq = await this.client.createTraceRequest({
4836
+ name: name,
4837
+ attr: traceAttributes,
4838
+ tags: ['transaction', 'wallet', txData.network || 'unknown'],
4839
+ includeClientMeta: options?.includeClientMeta ?? true,
4840
+ });
4841
+ const traceResponse = await this.client.createTrace(createTraceReq);
4842
+ const traceId = traceResponse.getTraceId();
4843
+ const rootSpanId = traceResponse.getRootSpanId();
4844
+ // Store transaction info
4845
+ this.activeTransactions.set(txId, {
4846
+ traceId,
4847
+ rootSpanId,
4848
+ spanId: rootSpanId, // Use rootSpanId as the main span for this transaction
4849
+ timestamp,
4850
+ txHash: null,
4851
+ from: txData.from,
4852
+ to: txData.to,
4853
+ network: txData.network,
4854
+ });
4855
+ console.log('[ParallaxService] Transaction trace started:', {
4856
+ txId,
4857
+ traceId,
4858
+ rootSpanId,
4859
+ from: txData.from,
4860
+ to: txData.to,
4861
+ });
4862
+ // Add initial event to the root span
4863
+ await this.addTransactionEvent(txId, 'transaction_initiated', {
4864
+ from: txData.from,
4865
+ to: txData.to,
4866
+ value: txData.value,
4867
+ timestamp,
4868
+ });
4869
+ return { traceId, rootSpanId, txId };
4870
+ }
4871
+ catch (error) {
4872
+ console.error('[ParallaxService] Failed to start transaction trace:', error);
4873
+ throw error;
4874
+ }
4875
+ }
4876
+ /**
4877
+ * Associate a transaction hash with an existing trace
4878
+ * Called when the transaction hash is available after signing/sending
4879
+ *
4880
+ * @param txId - Transaction identifier returned from startTransactionTrace
4881
+ * @param txHash - Blockchain transaction hash
4882
+ * @param chainId - Chain ID
4883
+ */
4884
+ async associateTransactionHash(txId, txHash, chainId) {
4885
+ const txInfo = this.activeTransactions.get(txId);
4886
+ if (!txInfo) {
4887
+ console.warn(`[ParallaxService] Transaction ${txId} not found in active transactions`);
4888
+ return;
4889
+ }
4890
+ if (!this.client) {
4891
+ console.warn('[ParallaxService] Client not initialized');
4892
+ return;
4893
+ }
4894
+ try {
4895
+ // Update stored tx info
4896
+ txInfo.txHash = txHash;
4897
+ this.activeTransactions.set(txId, txInfo);
4898
+ // Add chain hint to correlate with blockchain events
4899
+ const hintReq = this.client.createAddSpanHintRequest({
4900
+ traceId: txInfo.traceId,
4901
+ parentSpanId: txInfo.rootSpanId,
4902
+ txHash: txHash,
4903
+ chainId: chainId,
4904
+ });
4905
+ await this.client.addSpanHint(hintReq);
4906
+ // Add event for transaction sent
4907
+ await this.addTransactionEvent(txId, 'transaction_hash_available', {
4908
+ txHash,
4909
+ chainId: chainId.toString(),
4910
+ timestamp: new Date().toISOString(),
4911
+ });
4912
+ console.log('[ParallaxService] Transaction hash associated with trace:', {
4913
+ txId,
4914
+ txHash,
4915
+ traceId: txInfo.traceId,
4916
+ });
4917
+ }
4918
+ catch (error) {
4919
+ console.error('[ParallaxService] Failed to associate transaction hash:', error);
4920
+ }
4921
+ }
4922
+ /**
4923
+ * Add an event to a transaction trace
4924
+ *
4925
+ * @param txId - Transaction identifier
4926
+ * @param eventName - Event name
4927
+ * @param attributes - Event attributes
4928
+ */
4929
+ async addTransactionEvent(txId, eventName, attributes = {}) {
4930
+ const txInfo = this.activeTransactions.get(txId);
4931
+ if (!txInfo) {
4932
+ console.warn(`[ParallaxService] Transaction ${txId} not found. Cannot add event '${eventName}'`);
4933
+ return;
4934
+ }
4935
+ if (!this.client || !txInfo.spanId) {
4936
+ console.warn('[ParallaxService] Client not initialized or span not available');
4937
+ return;
4938
+ }
4939
+ try {
4940
+ // Convert attributes to plain object with string values
4941
+ const eventAttributes = {};
4942
+ Object.entries(attributes).forEach(([key, value]) => {
4943
+ eventAttributes[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);
4944
+ });
4945
+ const request = this.client.createAddSpanEventRequest({
4946
+ traceId: txInfo.traceId,
4947
+ spanId: txInfo.spanId,
4948
+ eventName: eventName,
4949
+ attr: eventAttributes,
4950
+ });
4951
+ await this.client.addSpanEvent(request);
4952
+ }
4953
+ catch (error) {
4954
+ console.error(`[ParallaxService] Failed to add transaction event '${eventName}':`, error);
4955
+ }
4956
+ }
4957
+ /**
4958
+ * Add an error to a transaction trace
4959
+ * Creates a proper span error event in Parallax
4960
+ *
4961
+ * @param txId - Transaction identifier
4962
+ * @param error - Error object or message
4963
+ * @param errorType - Type/category of error (e.g., 'TransactionError', 'NetworkError', 'UserRejection')
4964
+ */
4965
+ async addTransactionError(txId, error, errorType = 'TransactionError') {
4966
+ const txInfo = this.activeTransactions.get(txId);
4967
+ if (!txInfo) {
4968
+ console.warn(`[ParallaxService] Transaction ${txId} not found. Cannot add error.`);
4969
+ return;
4970
+ }
4971
+ if (!this.client || !txInfo.spanId) {
4972
+ console.warn('[ParallaxService] Client not initialized or span not available');
4973
+ return;
4974
+ }
4975
+ try {
4976
+ // Extract error message and stack trace
4977
+ let errorMessage = '';
4978
+ let stackTrace;
4979
+ if (error instanceof Error) {
4980
+ errorMessage = error.message;
4981
+ stackTrace = error.stack;
4982
+ }
4983
+ else {
4984
+ errorMessage = String(error);
4985
+ }
4986
+ const request = this.client.createAddSpanErrorRequest({
4987
+ traceId: txInfo.traceId,
4988
+ spanId: txInfo.spanId,
4989
+ errorMessage: errorMessage,
4990
+ errorType: errorType,
4991
+ stackTrace: stackTrace,
4992
+ });
4993
+ await this.client.addSpanError(request);
4994
+ console.log('[ParallaxService] Transaction error added to trace:', {
4995
+ txId,
4996
+ errorType,
4997
+ message: error instanceof Error ? error.message : String(error),
4998
+ });
4999
+ }
5000
+ catch (err) {
5001
+ console.error('[ParallaxService] Failed to add transaction error:', err);
5002
+ }
5003
+ }
5004
+ /**
5005
+ * Finish a transaction trace
5006
+ * Called when transaction is confirmed or permanently failed
5007
+ *
5008
+ * @param txId - Transaction identifier
5009
+ * @param options - Finish options (success, error message)
5010
+ */
5011
+ async finishTransactionTrace(txId, options = { success: true }) {
5012
+ const txInfo = this.activeTransactions.get(txId);
5013
+ if (!txInfo) {
5014
+ console.warn(`[ParallaxService] Transaction ${txId} not found. Cannot finish.`);
5015
+ return;
5016
+ }
5017
+ if (!this.client || !txInfo.spanId) {
5018
+ console.warn('[ParallaxService] Client not initialized or span not available');
5019
+ return;
5020
+ }
5021
+ try {
5022
+ // Add final event
5023
+ await this.addTransactionEvent(txId, options.success ? 'transaction_completed' : 'transaction_failed', {
5024
+ success: options.success.toString(),
5025
+ error: options.error || '',
5026
+ duration: (Date.now() - new Date(txInfo.timestamp).getTime()).toString(),
5027
+ timestamp: new Date().toISOString(),
5028
+ });
5029
+ // Finish the span
5030
+ const request = this.client.createFinishSpanRequest({
5031
+ traceId: txInfo.traceId,
5032
+ spanId: txInfo.spanId,
5033
+ status: {
5034
+ success: options.success,
5035
+ errorMessage: options.error || '',
5036
+ },
5037
+ });
5038
+ await this.client.finishSpan(request);
5039
+ console.log('[ParallaxService] Transaction trace finished:', {
5040
+ txId,
5041
+ traceId: txInfo.traceId,
5042
+ success: options.success,
5043
+ txHash: txInfo.txHash,
5044
+ });
5045
+ // Remove from active transactions
5046
+ this.activeTransactions.delete(txId);
5047
+ }
5048
+ catch (error) {
5049
+ console.error('[ParallaxService] Failed to finish transaction trace:', error);
5050
+ }
5051
+ }
5052
+ /**
5053
+ * Get info about an active transaction
5054
+ *
5055
+ * @param txId - Transaction identifier
5056
+ * @returns Transaction info or null if not found
5057
+ */
5058
+ getTransactionInfo(txId) {
5059
+ return this.activeTransactions.get(txId) || null;
5060
+ }
5061
+ /**
5062
+ * Get all active transactions
5063
+ *
5064
+ * @returns Array of active transaction info
5065
+ */
5066
+ getAllActiveTransactions() {
5067
+ return Array.from(this.activeTransactions.entries()).map(([txId, info]) => ({
5068
+ txId,
5069
+ ...info,
5070
+ }));
5071
+ }
5072
+ /**
5073
+ * Get the ParallaxClient instance for advanced usage
5074
+ * @param apiKey - Optional API key
5075
+ * @param gatewayUrl - Optional gateway URL
5076
+ */
5077
+ getClient(apiKey, gatewayUrl) {
5078
+ this._ensureClient(apiKey, gatewayUrl);
5079
+ if (!this.client) {
5080
+ throw new Error('Failed to initialize Parallax client');
5081
+ }
5082
+ return this.client;
5083
+ }
5084
+ }
5085
+ // Export singleton instance
5086
+ const parallaxService = new ParallaxService();
5087
+
4692
5088
  var AddSpanErrorRequest = parallax_gateway_pbExports.AddSpanErrorRequest;
4693
5089
  var AddSpanErrorResponse = parallax_gateway_pbExports.AddSpanErrorResponse;
4694
5090
  var AddSpanEventRequest = parallax_gateway_pbExports.AddSpanEventRequest;
@@ -4701,5 +5097,5 @@ var FinishSpanRequest = parallax_gateway_pbExports.FinishSpanRequest;
4701
5097
  var FinishSpanResponse = parallax_gateway_pbExports.FinishSpanResponse;
4702
5098
  var StartSpanRequest = parallax_gateway_pbExports.StartSpanRequest;
4703
5099
  var StartSpanResponse = parallax_gateway_pbExports.StartSpanResponse;
4704
- export { AddSpanErrorRequest, AddSpanErrorResponse, AddSpanEventRequest, AddSpanEventResponse, AddSpanHintRequest, AddSpanHintResponse, CreateTraceRequest, CreateTraceResponse, FinishSpanRequest, FinishSpanResponse, GrpcWebRpc, ParallaxClient, StartSpanRequest, StartSpanResponse };
5100
+ export { AddSpanErrorRequest, AddSpanErrorResponse, AddSpanEventRequest, AddSpanEventResponse, AddSpanHintRequest, AddSpanHintResponse, CreateTraceRequest, CreateTraceResponse, FinishSpanRequest, FinishSpanResponse, GrpcWebRpc, ParallaxClient, ParallaxService, StartSpanRequest, StartSpanResponse, parallaxService };
4705
5101
  //# sourceMappingURL=index.esm.js.map