@miradorlabs/parallax-web 1.0.6 → 1.0.8

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,33 @@
1
+ {
2
+ "name": "parallax-web-demo",
3
+ "version": "1.0.0",
4
+ "description": "Interactive demo for Parallax Web SDK",
5
+ "type": "module",
6
+ "scripts": {
7
+ "build-sdk": "cd .. && npm run build",
8
+ "build": "npm run build-sdk && rollup -c",
9
+ "proxy": "node proxy-server.js",
10
+ "start": "npm run build && python3 -m http.server 8000",
11
+ "serve": "npm run build && npx http-server -p 8000 -o",
12
+ "dev": "npm run build && npx concurrently \"npm run proxy\" \"npx http-server -p 8000 -o\"",
13
+ "dev:no-proxy": "npm run build && npx http-server -p 8000 -o"
14
+ },
15
+ "keywords": [
16
+ "parallax",
17
+ "demo",
18
+ "web",
19
+ "tracing"
20
+ ],
21
+ "author": "@mirador",
22
+ "license": "ISC",
23
+ "devDependencies": {
24
+ "@rollup/plugin-node-resolve": "^16.0.3",
25
+ "rollup": "^4.53.3"
26
+ },
27
+ "dependencies": {
28
+ "concurrently": "^9.1.0",
29
+ "cors": "^2.8.5",
30
+ "express": "^4.22.1",
31
+ "http-proxy-middleware": "^3.0.3"
32
+ }
33
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Simple Express proxy server to handle CORS issues
3
+ * Proxies gRPC-Web requests to the Parallax Gateway
4
+ */
5
+
6
+ import express from 'express';
7
+ import cors from 'cors';
8
+ import { createProxyMiddleware } from 'http-proxy-middleware';
9
+
10
+ const app = express();
11
+ const PORT = 3001;
12
+
13
+ // Target Parallax Gateway
14
+ const GATEWAY_URL = 'https://parallax-gateway.dev.mirador.org:443';
15
+
16
+ // Enable CORS for all origins (development only)
17
+ app.use(cors({
18
+ origin: '*',
19
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
20
+ allowedHeaders: ['Content-Type', 'x-grpc-web', 'x-user-agent', 'x-parallax-api-key'],
21
+ exposedHeaders: ['grpc-status', 'grpc-message'],
22
+ credentials: true
23
+ }));
24
+
25
+ // Health check endpoint (before proxy)
26
+ app.get('/health', (req, res) => {
27
+ res.json({
28
+ status: 'ok',
29
+ proxy: GATEWAY_URL,
30
+ timestamp: new Date().toISOString()
31
+ });
32
+ });
33
+
34
+ // Log all requests
35
+ app.use((req, res, next) => {
36
+ console.log(`[${new Date().toLocaleTimeString()}] ${req.method} ${req.path}`);
37
+ next();
38
+ });
39
+
40
+ // Proxy all other requests to the gateway (gRPC-Web)
41
+ app.use('/', createProxyMiddleware({
42
+ target: GATEWAY_URL,
43
+ changeOrigin: true,
44
+ secure: true,
45
+ ws: false,
46
+ onProxyReq: (proxyReq, req, res) => {
47
+ console.log(` → Proxying to: ${GATEWAY_URL}${req.url}`);
48
+
49
+ // Forward gRPC-Web headers
50
+ if (req.headers['content-type']) {
51
+ proxyReq.setHeader('content-type', req.headers['content-type']);
52
+ }
53
+ if (req.headers['x-grpc-web']) {
54
+ proxyReq.setHeader('x-grpc-web', req.headers['x-grpc-web']);
55
+ }
56
+ if (req.headers['x-user-agent']) {
57
+ proxyReq.setHeader('x-user-agent', req.headers['x-user-agent']);
58
+ }
59
+ },
60
+ onProxyRes: (proxyRes, req, res) => {
61
+ console.log(` ← Response: ${proxyRes.statusCode}`);
62
+ },
63
+ onError: (err, req, res) => {
64
+ console.error('Proxy error:', err.message);
65
+ res.status(500).json({
66
+ error: 'Proxy error',
67
+ message: err.message
68
+ });
69
+ }
70
+ }));
71
+
72
+ app.listen(PORT, () => {
73
+ console.log(`
74
+ ╔════════════════════════════════════════════════════════════╗
75
+ ║ Parallax gRPC-Web Proxy Server ║
76
+ ╟────────────────────────────────────────────────────────────╢
77
+ ║ Proxy running at: http://localhost:${PORT} ║
78
+ ║ Gateway target: ${GATEWAY_URL} ║
79
+ ╟────────────────────────────────────────────────────────────╢
80
+ ║ Usage: ║
81
+ ║ - All gRPC-Web requests are proxied to the gateway ║
82
+ ║ - CORS headers are automatically added ║
83
+ ║ - Health check: http://localhost:${PORT}/health ║
84
+ ╚════════════════════════════════════════════════════════════╝
85
+ `);
86
+ });
@@ -0,0 +1,16 @@
1
+ import resolve from '@rollup/plugin-node-resolve';
2
+
3
+ export default {
4
+ input: 'app.js',
5
+ output: {
6
+ file: 'bundle.js',
7
+ format: 'es',
8
+ sourcemap: true
9
+ },
10
+ plugins: [
11
+ resolve({
12
+ browser: true,
13
+ preferBuiltins: false
14
+ })
15
+ ]
16
+ };
package/index.ts CHANGED
@@ -8,14 +8,4 @@ export { ParallaxService, parallaxService } from './src/parallax/ParallaxService
8
8
  export {
9
9
  CreateTraceRequest,
10
10
  CreateTraceResponse,
11
- StartSpanRequest,
12
- StartSpanResponse,
13
- FinishSpanRequest,
14
- FinishSpanResponse,
15
- AddSpanEventRequest,
16
- AddSpanEventResponse,
17
- AddSpanErrorRequest,
18
- AddSpanErrorResponse,
19
- AddSpanHintRequest,
20
- AddSpanHintResponse,
21
11
  } from 'mirador-gateway-parallax-web/proto/gateway/parallax/v1/parallax_gateway_pb';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miradorlabs/parallax-web",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "Parallax Web Client Side SDK ",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.esm.js",
@@ -25,6 +25,7 @@
25
25
  "@rollup/plugin-commonjs": "^29.0.0",
26
26
  "@rollup/plugin-node-resolve": "^16.0.3",
27
27
  "@rollup/plugin-typescript": "^12.3.0",
28
+ "@types/google-protobuf": "^3.15.12",
28
29
  "@types/jest": "^30.0.0",
29
30
  "@types/node": "^24.10.1",
30
31
  "eslint": "^9.39.1",
@@ -46,7 +47,7 @@
46
47
  "dependencies": {
47
48
  "google-protobuf": "^3.21.4",
48
49
  "grpc-web": "^2.0.2",
49
- "mirador-gateway-parallax-web": "https://storage.googleapis.com/mirador-shd-packages/gateway/parallax/grpc-web/mirador-gateway-parallax-grpc-web-1.0.10.tgz",
50
+ "mirador-gateway-parallax-web": "https://storage.googleapis.com/mirador-shd-packages/gateway/parallax/grpc-web/mirador-gateway-parallax-grpc-web-1.0.11.tgz",
50
51
  "rxjs": "^7.8.2"
51
52
  },
52
53
  "author": "@mirador",
package/src/grpc/index.ts CHANGED
@@ -52,7 +52,7 @@ export class GrpcWebRpc implements Rpc {
52
52
 
53
53
  // Add API key to headers if provided
54
54
  if (this.apiKey) {
55
- headers['x-api-key'] = this.apiKey;
55
+ headers['x-parallax-api-key'] = this.apiKey;
56
56
  }
57
57
 
58
58
  // Add custom metadata
@@ -103,7 +103,7 @@ export class GrpcWebRpc implements Rpc {
103
103
 
104
104
  // Add API key to headers if provided
105
105
  if (this.apiKey) {
106
- headers['x-api-key'] = this.apiKey;
106
+ headers['x-parallax-api-key'] = this.apiKey;
107
107
  }
108
108
 
109
109
  fetch(`${this.url}/${service}/${method}`, {
@@ -9,17 +9,10 @@
9
9
  import { ParallaxClient } from './index';
10
10
  import type {
11
11
  CreateTraceResponse,
12
- StartSpanResponse,
13
- FinishSpanResponse,
14
- AddSpanEventResponse,
15
- AddSpanErrorResponse,
16
- AddSpanHintResponse,
17
12
  } from 'mirador-gateway-parallax-web/proto/gateway/parallax/v1/parallax_gateway_pb';
18
13
 
19
14
  interface TransactionInfo {
20
15
  traceId: string;
21
- rootSpanId: string;
22
- spanId: string | null;
23
16
  timestamp: string;
24
17
  txHash: string | null;
25
18
  from?: string;
@@ -77,8 +70,7 @@ export class ParallaxService {
77
70
  * Start a new transaction trace
78
71
  * Called when user initiates a transaction
79
72
  *
80
- * Note: Since createTrace now automatically creates a root span, we don't need
81
- * to call startSpan separately. The rootSpanId from the response is the parent span.
73
+ * Uses the builder pattern to create a trace with events
82
74
  *
83
75
  * @param txData - Transaction data
84
76
  * @param name - Name for the trace (e.g., 'SendingTrace', 'SwappingTrace')
@@ -98,44 +90,41 @@ export class ParallaxService {
98
90
 
99
91
  try {
100
92
  const txId = `tx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
101
- const timestamp = new Date().toISOString();
102
-
103
- // Create trace attributes
104
- const traceAttributes: Record<string, string> = {
105
- transactionId: txId,
106
- walletAddress: txData.walletAddress || txData.from,
107
- network: txData.network || 'Unknown',
108
- transactionStart: timestamp,
109
- from: txData.from,
110
- to: txData.to,
111
- value: txData.value,
112
- };
93
+ const timestamp = new Date();
94
+
95
+ // Build the trace using the builder pattern
96
+ const builder = this.client
97
+ .trace(name, options?.includeClientMeta ?? true)
98
+ .addAttribute('transactionId', txId)
99
+ .addAttribute('walletAddress', txData.walletAddress || txData.from)
100
+ .addAttribute('network', txData.network || 'Unknown')
101
+ .addAttribute('transactionStart', timestamp.toISOString())
102
+ .addAttribute('from', txData.from)
103
+ .addAttribute('to', txData.to)
104
+ .addAttribute('value', txData.value)
105
+ .addTags(['transaction', 'wallet', txData.network || 'unknown'])
106
+ .addEvent('transaction_initiated', {
107
+ from: txData.from,
108
+ to: txData.to,
109
+ value: txData.value,
110
+ timestamp: timestamp.toISOString(),
111
+ });
113
112
 
114
- // Add any additional transaction data
113
+ // Add any additional transaction data as attributes
115
114
  if (txData.additionalData) {
116
115
  Object.entries(txData.additionalData).forEach(([key, value]) => {
117
- traceAttributes[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);
116
+ builder.addAttribute(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
118
117
  });
119
118
  }
120
119
 
121
- // Create a trace for this transaction
122
- const createTraceReq = await this.client.createTraceRequest({
123
- name: name,
124
- attr: traceAttributes,
125
- tags: ['transaction', 'wallet', txData.network || 'unknown'],
126
- includeClientMeta: options?.includeClientMeta ?? true,
127
- });
128
-
129
- const traceResponse: CreateTraceResponse = await this.client.createTrace(createTraceReq);
120
+ // Submit the trace
121
+ const traceResponse: CreateTraceResponse = await builder.submit();
130
122
  const traceId = traceResponse.getTraceId();
131
- const rootSpanId = traceResponse.getRootSpanId();
132
123
 
133
124
  // Store transaction info
134
125
  this.activeTransactions.set(txId, {
135
126
  traceId,
136
- rootSpanId,
137
- spanId: rootSpanId, // Use rootSpanId as the main span for this transaction
138
- timestamp,
127
+ timestamp: timestamp.toISOString(),
139
128
  txHash: null,
140
129
  from: txData.from,
141
130
  to: txData.to,
@@ -145,20 +134,11 @@ export class ParallaxService {
145
134
  console.log('[ParallaxService] Transaction trace started:', {
146
135
  txId,
147
136
  traceId,
148
- rootSpanId,
149
- from: txData.from,
150
- to: txData.to,
151
- });
152
-
153
- // Add initial event to the root span
154
- await this.addTransactionEvent(txId, 'transaction_initiated', {
155
137
  from: txData.from,
156
138
  to: txData.to,
157
- value: txData.value,
158
- timestamp,
159
139
  });
160
140
 
161
- return { traceId, rootSpanId, txId };
141
+ return { traceId, rootSpanId: traceId, txId };
162
142
  } catch (error) {
163
143
  console.error('[ParallaxService] Failed to start transaction trace:', error);
164
144
  throw error;
@@ -169,9 +149,13 @@ export class ParallaxService {
169
149
  * Associate a transaction hash with an existing trace
170
150
  * Called when the transaction hash is available after signing/sending
171
151
  *
152
+ * NOTE: This method is deprecated as the new API does not support adding hints to existing traces.
153
+ * Transaction hashes should be provided at trace creation time via the builder's submit(txHash, chainId) method.
154
+ *
172
155
  * @param txId - Transaction identifier returned from startTransactionTrace
173
156
  * @param txHash - Blockchain transaction hash
174
157
  * @param chainId - Chain ID
158
+ * @deprecated Use submit(txHash, chainId) when creating the trace instead
175
159
  */
176
160
  async associateTransactionHash(txId: string, txHash: string, chainId: number): Promise<void> {
177
161
  const txInfo = this.activeTransactions.get(txId);
@@ -180,49 +164,28 @@ export class ParallaxService {
180
164
  return;
181
165
  }
182
166
 
183
- if (!this.client) {
184
- console.warn('[ParallaxService] Client not initialized');
185
- return;
186
- }
187
-
188
- try {
189
- // Update stored tx info
190
- txInfo.txHash = txHash;
191
- this.activeTransactions.set(txId, txInfo);
192
-
193
- // Add chain hint to correlate with blockchain events
194
- const hintReq = this.client.createAddSpanHintRequest({
195
- traceId: txInfo.traceId,
196
- parentSpanId: txInfo.rootSpanId,
197
- txHash: txHash,
198
- chainId: chainId,
199
- });
167
+ // Update stored tx info
168
+ txInfo.txHash = txHash;
169
+ this.activeTransactions.set(txId, txInfo);
200
170
 
201
- await this.client.addSpanHint(hintReq);
202
-
203
- // Add event for transaction sent
204
- await this.addTransactionEvent(txId, 'transaction_hash_available', {
205
- txHash,
206
- chainId: chainId.toString(),
207
- timestamp: new Date().toISOString(),
208
- });
209
-
210
- console.log('[ParallaxService] Transaction hash associated with trace:', {
211
- txId,
212
- txHash,
213
- traceId: txInfo.traceId,
214
- });
215
- } catch (error) {
216
- console.error('[ParallaxService] Failed to associate transaction hash:', error);
217
- }
171
+ console.warn('[ParallaxService] associateTransactionHash is deprecated. The new API does not support adding transaction hashes after trace creation. Please provide the txHash when creating the trace using submit(txHash, chainId).');
172
+ console.log('[ParallaxService] Transaction hash updated in local cache:', {
173
+ txId,
174
+ txHash,
175
+ traceId: txInfo.traceId,
176
+ });
218
177
  }
219
178
 
220
179
  /**
221
180
  * Add an event to a transaction trace
222
181
  *
182
+ * NOTE: This method is deprecated as the new API does not support adding events to existing traces.
183
+ * Events should be added to the trace builder before calling submit().
184
+ *
223
185
  * @param txId - Transaction identifier
224
186
  * @param eventName - Event name
225
187
  * @param attributes - Event attributes
188
+ * @deprecated Use the trace builder's addEvent() method before calling submit() instead
226
189
  */
227
190
  async addTransactionEvent(
228
191
  txId: string,
@@ -235,38 +198,19 @@ export class ParallaxService {
235
198
  return;
236
199
  }
237
200
 
238
- if (!this.client || !txInfo.spanId) {
239
- console.warn('[ParallaxService] Client not initialized or span not available');
240
- return;
241
- }
242
-
243
- try {
244
- // Convert attributes to plain object with string values
245
- const eventAttributes: Record<string, string> = {};
246
- Object.entries(attributes).forEach(([key, value]) => {
247
- eventAttributes[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);
248
- });
249
-
250
- const request = this.client.createAddSpanEventRequest({
251
- traceId: txInfo.traceId,
252
- spanId: txInfo.spanId,
253
- eventName: eventName,
254
- attr: eventAttributes,
255
- });
256
-
257
- await this.client.addSpanEvent(request);
258
- } catch (error) {
259
- console.error(`[ParallaxService] Failed to add transaction event '${eventName}':`, error);
260
- }
201
+ console.warn('[ParallaxService] addTransactionEvent is deprecated. The new API does not support adding events after trace creation. Events should be added using the builder pattern before calling submit().');
261
202
  }
262
203
 
263
204
  /**
264
205
  * Add an error to a transaction trace
265
- * Creates a proper span error event in Parallax
206
+ *
207
+ * NOTE: This method is deprecated as the new API does not support adding errors to existing traces.
208
+ * Errors should be added as events to the trace builder before calling submit().
266
209
  *
267
210
  * @param txId - Transaction identifier
268
211
  * @param error - Error object or message
269
212
  * @param errorType - Type/category of error (e.g., 'TransactionError', 'NetworkError', 'UserRejection')
213
+ * @deprecated Use the trace builder's addEvent() method to add error events before calling submit() instead
270
214
  */
271
215
  async addTransactionError(
272
216
  txId: string,
@@ -279,49 +223,18 @@ export class ParallaxService {
279
223
  return;
280
224
  }
281
225
 
282
- if (!this.client || !txInfo.spanId) {
283
- console.warn('[ParallaxService] Client not initialized or span not available');
284
- return;
285
- }
286
-
287
- try {
288
- // Extract error message and stack trace
289
- let errorMessage = '';
290
- let stackTrace: string | undefined;
291
-
292
- if (error instanceof Error) {
293
- errorMessage = error.message;
294
- stackTrace = error.stack;
295
- } else {
296
- errorMessage = String(error);
297
- }
298
-
299
- const request = this.client.createAddSpanErrorRequest({
300
- traceId: txInfo.traceId,
301
- spanId: txInfo.spanId,
302
- errorMessage: errorMessage,
303
- errorType: errorType,
304
- stackTrace: stackTrace,
305
- });
306
-
307
- await this.client.addSpanError(request);
308
-
309
- console.log('[ParallaxService] Transaction error added to trace:', {
310
- txId,
311
- errorType,
312
- message: error instanceof Error ? error.message : String(error),
313
- });
314
- } catch (err) {
315
- console.error('[ParallaxService] Failed to add transaction error:', err);
316
- }
226
+ console.warn('[ParallaxService] addTransactionError is deprecated. The new API does not support adding errors after trace creation. Add error events using the builder pattern before calling submit().');
317
227
  }
318
228
 
319
229
  /**
320
230
  * Finish a transaction trace
321
- * Called when transaction is confirmed or permanently failed
231
+ *
232
+ * NOTE: This method is deprecated as the new API does not support span lifecycle management.
233
+ * Traces are completed when submit() is called on the builder.
322
234
  *
323
235
  * @param txId - Transaction identifier
324
236
  * @param options - Finish options (success, error message)
237
+ * @deprecated Traces are automatically completed when submit() is called
325
238
  */
326
239
  async finishTransactionTrace(txId: string, options: FinishOptions = { success: true }): Promise<void> {
327
240
  const txInfo = this.activeTransactions.get(txId);
@@ -330,48 +243,17 @@ export class ParallaxService {
330
243
  return;
331
244
  }
332
245
 
333
- if (!this.client || !txInfo.spanId) {
334
- console.warn('[ParallaxService] Client not initialized or span not available');
335
- return;
336
- }
246
+ console.warn('[ParallaxService] finishTransactionTrace is deprecated. The new API does not support span lifecycle. Traces are completed when submit() is called.');
337
247
 
338
- try {
339
- // Add final event
340
- await this.addTransactionEvent(
341
- txId,
342
- options.success ? 'transaction_completed' : 'transaction_failed',
343
- {
344
- success: options.success.toString(),
345
- error: options.error || '',
346
- duration: (Date.now() - new Date(txInfo.timestamp).getTime()).toString(),
347
- timestamp: new Date().toISOString(),
348
- }
349
- );
350
-
351
- // Finish the span
352
- const request = this.client.createFinishSpanRequest({
353
- traceId: txInfo.traceId,
354
- spanId: txInfo.spanId,
355
- status: {
356
- success: options.success,
357
- errorMessage: options.error || '',
358
- },
359
- });
360
-
361
- await this.client.finishSpan(request);
362
-
363
- console.log('[ParallaxService] Transaction trace finished:', {
364
- txId,
365
- traceId: txInfo.traceId,
366
- success: options.success,
367
- txHash: txInfo.txHash,
368
- });
248
+ console.log('[ParallaxService] Transaction trace marked as finished (local only):', {
249
+ txId,
250
+ traceId: txInfo.traceId,
251
+ success: options.success,
252
+ txHash: txInfo.txHash,
253
+ });
369
254
 
370
- // Remove from active transactions
371
- this.activeTransactions.delete(txId);
372
- } catch (error) {
373
- console.error('[ParallaxService] Failed to finish transaction trace:', error);
374
- }
255
+ // Remove from active transactions
256
+ this.activeTransactions.delete(txId);
375
257
  }
376
258
 
377
259
  /**