@miradorlabs/parallax-web 1.0.8 → 2.0.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.
@@ -0,0 +1,15 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(npm test:*)",
5
+ "Bash(npx jest:*)",
6
+ "Bash(npm install:*)",
7
+ "Bash(npm run build:*)",
8
+ "Bash(mkdir:*)",
9
+ "Bash(chmod:*)",
10
+ "Bash(gh pr view:*)",
11
+ "Bash(gh api:*)",
12
+ "Bash(npm run lint:*)"
13
+ ]
14
+ }
15
+ }
@@ -0,0 +1,33 @@
1
+ version: 2
2
+ updates:
3
+ # npm dependencies
4
+ - package-ecosystem: "npm"
5
+ directory: "/"
6
+ schedule:
7
+ interval: "weekly"
8
+ day: "monday"
9
+ open-pull-requests-limit: 10
10
+ commit-message:
11
+ prefix: "chore(deps)"
12
+ groups:
13
+ # Group minor and patch updates together
14
+ minor-and-patch:
15
+ patterns:
16
+ - "*"
17
+ update-types:
18
+ - "minor"
19
+ - "patch"
20
+ # Keep major updates separate for review
21
+ ignore:
22
+ # Ignore major version updates for stability (review manually)
23
+ - dependency-name: "*"
24
+ update-types: ["version-update:semver-major"]
25
+
26
+ # GitHub Actions
27
+ - package-ecosystem: "github-actions"
28
+ directory: "/"
29
+ schedule:
30
+ interval: "weekly"
31
+ day: "monday"
32
+ commit-message:
33
+ prefix: "chore(ci)"
@@ -0,0 +1,33 @@
1
+ name: PR Build & Lint
2
+
3
+ on:
4
+ pull_request:
5
+ branches: [main]
6
+ push:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - name: Checkout
15
+ uses: actions/checkout@v6
16
+
17
+ - name: Setup Node.js
18
+ uses: actions/setup-node@v6
19
+ with:
20
+ node-version: '20'
21
+ cache: 'npm'
22
+
23
+ - name: Install dependencies
24
+ run: npm ci
25
+
26
+ - name: Lint
27
+ run: npm run lint
28
+
29
+ - name: Run tests
30
+ run: npm test
31
+
32
+ - name: Build
33
+ run: npm run build
package/README.md CHANGED
@@ -10,267 +10,168 @@ npm install @miradorlabs/parallax-web
10
10
 
11
11
  ## Features
12
12
 
13
- - 🚀 **ParallaxService** - High-level API for transaction tracing with automatic lifecycle management
14
- - 🔧 **ParallaxClient** - Low-level client for advanced use cases
15
- - 🌐 **Browser-optimized** - Automatic client metadata collection (browser, OS, IP, etc.)
16
- - ⛓️ **Blockchain integration** - Built-in support for correlating transactions with blockchain events
17
- - 📦 **TypeScript support** - Full type definitions included
18
- - 🎯 **Automatic root spans** - Creating a trace now automatically creates a root span
13
+ - **Fluent Builder Pattern** - Method chaining for creating traces
14
+ - **Browser-optimized** - Automatic client metadata collection (browser, OS, etc.)
15
+ - **Blockchain Integration** - Built-in support for correlating traces with blockchain transactions
16
+ - **TypeScript Support** - Full type definitions included
17
+ - **Single Request** - All trace data submitted in one efficient gRPC call
19
18
 
20
- ## Quick Start with ParallaxService (Recommended)
21
-
22
- The `ParallaxService` provides a simplified API for tracking transactions:
19
+ ## Quick Start
23
20
 
24
21
  ```typescript
25
- import { parallaxService } from '@miradorlabs/parallax-web';
26
-
27
- // Start tracking a transaction (creates trace + root span automatically)
28
- const { traceId, rootSpanId, txId } = await parallaxService.startTransactionTrace(
29
- {
30
- from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
31
- to: '0x8626f6940E2eb28930eFb4CeF49B2d1F2C9C1199',
32
- value: '0.1',
33
- network: 'ethereum',
34
- walletAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
35
- },
36
- 'SendTransaction',
37
- { includeClientMeta: true } // Automatically collects browser, OS, IP, etc.
38
- );
39
-
40
- // Associate the blockchain transaction hash
41
- await parallaxService.associateTransactionHash(txId, '0xabc123...', 1);
42
-
43
- // Add events as the transaction progresses
44
- await parallaxService.addTransactionEvent(txId, 'wallet_signed', {
45
- timestamp: new Date().toISOString(),
46
- });
47
-
48
- // Track errors if they occur
49
- try {
50
- // transaction logic
51
- } catch (error) {
52
- await parallaxService.addTransactionError(txId, error, 'TransactionError');
53
- }
54
-
55
- // Finish the trace when done
56
- await parallaxService.finishTransactionTrace(txId, { success: true });
57
- ```
58
-
59
- ### ParallaxService API
22
+ import { ParallaxClient } from '@miradorlabs/parallax-web';
60
23
 
61
- #### `startTransactionTrace(txData, name, options)`
24
+ // API key is required, gateway URL is optional
25
+ const client = new ParallaxClient('your-api-key');
62
26
 
63
- Starts a new transaction trace with automatic root span creation.
27
+ // Create and submit a trace
28
+ const traceId = await client.trace('SwapExecution')
29
+ .addAttribute('from', '0xabc...')
30
+ .addAttribute('slippage', { bps: 50, tolerance: 'auto' }) // objects are stringified
31
+ .addTags(['dex', 'swap'])
32
+ .addEvent('quote_received', { provider: 'Uniswap' })
33
+ .addEvent('transaction_signed')
34
+ .setTxHint('0xtxhash...', 'ethereum') // optional
35
+ .create();
36
+
37
+ console.log('Trace ID:', traceId);
38
+ ```
64
39
 
65
- **Important:** When you create a trace, a root span is **automatically created** on the backend. You receive a `rootSpanId` in the response - no need to call `startSpan` separately!
40
+ ## API Reference
66
41
 
67
- **Parameters:**
68
- - `txData`: Transaction details (from, to, value, network, etc.)
69
- - `name`: Trace name (default: 'WalletTransaction')
70
- - `options`: Optional configuration
71
- - `apiKey`: API key for authentication
72
- - `gatewayUrl`: Custom gateway URL
73
- - `includeClientMeta`: Include browser/OS metadata (default: true)
42
+ ### ParallaxClient
74
43
 
75
- **Returns:** `{ traceId, rootSpanId, txId }`
44
+ The main client for interacting with the Parallax Gateway.
76
45
 
77
- #### Other Methods
46
+ #### Constructor
78
47
 
79
- - `associateTransactionHash(txId, txHash, chainId)` - Link blockchain transaction
80
- - `addTransactionEvent(txId, eventName, attributes)` - Add event to trace
81
- - `addTransactionError(txId, error, errorType)` - Track errors with stack traces
82
- - `finishTransactionTrace(txId, options)` - Complete the trace
83
- - `getTransactionInfo(txId)` - Get active transaction info
84
- - `getAllActiveTransactions()` - List all active transactions
85
- - `getClient()` - Access underlying ParallaxClient for advanced usage
48
+ ```typescript
49
+ new ParallaxClient(apiKey: string, apiUrl?: string)
50
+ ```
86
51
 
87
- See [PARALLAX_SERVICE_USAGE.md](./PARALLAX_SERVICE_USAGE.md) for comprehensive documentation.
52
+ | Parameter | Type | Required | Description |
53
+ |-----------|------|----------|-------------|
54
+ | `apiKey` | `string` | Yes | API key for authentication (sent as `x-parallax-api-key` header) |
55
+ | `apiUrl` | `string` | No | Gateway URL (defaults to `https://parallax-gateway.dev.mirador.org:443`) |
88
56
 
89
- ## Advanced Usage with ParallaxClient
57
+ #### Methods
90
58
 
91
- For more control, use the low-level `ParallaxClient`:
59
+ ##### `trace(name?, includeClientMeta?)`
92
60
 
93
- ### Basic Setup
61
+ Creates a new trace builder.
94
62
 
95
63
  ```typescript
96
- import { ParallaxClient } from '@miradorlabs/parallax-web';
97
-
98
- // Initialize the client
99
- const client = new ParallaxClient('your-api-key');
100
-
101
- // Or with a custom gateway URL
102
- const client = new ParallaxClient('your-api-key', 'https://your-gateway.example.com:50053');
64
+ const trace = client.trace('MyTrace'); // client metadata included by default
65
+ const trace = client.trace(); // name is optional (defaults to empty string)
66
+ // Or explicitly disable client metadata: client.trace('MyTrace', false)
103
67
  ```
104
68
 
105
- ### Helper Methods
69
+ | Parameter | Type | Default | Description |
70
+ |-----------|------|---------|-------------|
71
+ | `name` | `string` | `''` | Optional name of the trace |
72
+ | `includeClientMeta` | `boolean` | `true` | Include browser/OS metadata |
106
73
 
107
- The client provides helper methods to create requests easily:
74
+ Returns: `ParallaxTrace` builder instance
108
75
 
109
- #### Creating a Trace
76
+ ### ParallaxTrace (Builder)
110
77
 
111
- ```typescript
112
- // Use the helper method
113
- const createTraceReq = await client.createTraceRequest({
114
- name: 'My Application Trace',
115
- attr: {
116
- 'project.id': 'my-project',
117
- 'environment': 'production',
118
- },
119
- tags: ['web', 'user-action'],
120
- includeClientMeta: true, // Includes browser, OS, IP, etc.
121
- });
122
-
123
- const traceResponse = await client.createTrace(createTraceReq);
124
- const traceId = traceResponse.getTraceId();
125
- const rootSpanId = traceResponse.getRootSpanId(); // Root span automatically created!
126
- ```
78
+ Fluent builder for constructing traces. All methods return `this` for chaining.
127
79
 
128
- #### Starting a Span (Child Span)
80
+ #### `addAttribute(key, value)`
129
81
 
130
- Note: You only need to call `startSpan` if you want to create **child spans**. The root span is automatically created when you create a trace.
82
+ Add a single attribute. Objects are automatically stringified.
131
83
 
132
84
  ```typescript
133
- // Create a child span under the root span
134
- const startSpanReq = await client.createStartSpanRequest({
135
- traceId: traceId,
136
- name: 'User Login',
137
- parentSpanId: rootSpanId, // Use root span as parent
138
- attr: {
139
- 'user.id': 'user-123',
140
- 'action': 'login',
141
- },
142
- includeClientMeta: false, // Optional
143
- });
144
-
145
- const spanResponse = await client.startSpan(startSpanReq);
146
- const spanId = spanResponse.getSpanId();
85
+ trace.addAttribute('user', '0xabc...')
86
+ .addAttribute('amount', 1.5)
87
+ .addAttribute('config', { slippage: 50, deadline: 300 }) // stringified to JSON
147
88
  ```
148
89
 
149
- #### Adding Span Events
90
+ #### `addAttributes(attrs)`
150
91
 
151
- ```typescript
152
- const eventReq = client.createAddSpanEventRequest({
153
- traceId: traceId,
154
- spanId: spanId,
155
- eventName: 'User Authenticated',
156
- attr: {
157
- 'auth.method': 'oauth',
158
- 'auth.provider': 'google',
159
- },
160
- });
161
-
162
- await client.addSpanEvent(eventReq);
163
- ```
164
-
165
- #### Adding Span Errors
92
+ Add multiple attributes at once. Objects are automatically stringified.
166
93
 
167
94
  ```typescript
168
- try {
169
- // some operation
170
- } catch (error) {
171
- const errorReq = client.createAddSpanErrorRequest({
172
- traceId: traceId,
173
- spanId: spanId,
174
- errorMessage: error.message,
175
- errorType: 'ValidationError',
176
- stackTrace: error.stack,
177
- });
178
-
179
- await client.addSpanError(errorReq);
180
- }
95
+ trace.addAttributes({
96
+ from: '0xabc...',
97
+ to: '0xdef...',
98
+ value: 1.0,
99
+ metadata: { source: 'web', version: '1.0' } // stringified to JSON
100
+ })
181
101
  ```
182
102
 
183
- #### Adding Span Hints (Blockchain Transactions)
103
+ #### `addTag(tag)` / `addTags(tags)`
184
104
 
185
- ```typescript
186
- const hintReq = client.createAddSpanHintRequest({
187
- traceId: traceId,
188
- parentSpanId: rootSpanId,
189
- txHash: '0x1234567890abcdef',
190
- chainId: 1, // Ethereum mainnet
191
- });
192
-
193
- await client.addSpanHint(hintReq);
194
- ```
195
-
196
- #### Finishing a Span
105
+ Add tags to categorize the trace.
197
106
 
198
107
  ```typescript
199
- const finishReq = client.createFinishSpanRequest({
200
- traceId: traceId,
201
- spanId: spanId,
202
- status: {
203
- success: true,
204
- errorMessage: '', // or error message if failed
205
- },
206
- });
207
-
208
- await client.finishSpan(finishReq);
108
+ trace.addTag('transaction')
109
+ .addTags(['ethereum', 'send'])
209
110
  ```
210
111
 
211
- ## Complete Example: Transaction Tracking
212
-
213
- ```typescript
214
- import { parallaxService } from '@miradorlabs/parallax-web';
215
-
216
- async function handleWalletTransaction(userAddress, recipientAddress, amount) {
217
- let txId;
112
+ #### `addEvent(name, details?)`
218
113
 
219
- try {
220
- // 1. Start the trace (automatically creates root span)
221
- const result = await parallaxService.startTransactionTrace(
222
- {
223
- from: userAddress,
224
- to: recipientAddress,
225
- value: amount,
226
- network: 'ethereum',
227
- walletAddress: userAddress,
228
- },
229
- 'SendETH',
230
- { includeClientMeta: true }
231
- );
114
+ Add an event with optional details (string or object).
232
115
 
233
- txId = result.txId;
234
- console.log('Trace started:', result.traceId);
116
+ ```typescript
117
+ trace.addEvent('wallet_connected', { wallet: 'MetaMask' })
118
+ .addEvent('transaction_initiated')
119
+ .addEvent('transaction_confirmed', { blockNumber: 12345 })
120
+ ```
235
121
 
236
- // 2. User signs the transaction
237
- await parallaxService.addTransactionEvent(txId, 'user_signing', {});
122
+ #### `setTxHint(txHash, chain, details?)`
238
123
 
239
- const signedTx = await wallet.signTransaction(txData);
124
+ Set the transaction hash hint for blockchain correlation.
240
125
 
241
- await parallaxService.addTransactionEvent(txId, 'transaction_signed', {});
126
+ ```typescript
127
+ trace.setTxHint('0x123...', 'ethereum', 'Main transaction')
128
+ ```
242
129
 
243
- // 3. Send to network
244
- await parallaxService.addTransactionEvent(txId, 'sending_to_network', {});
130
+ | Parameter | Type | Description |
131
+ |-----------|------|-------------|
132
+ | `txHash` | `string` | Transaction hash |
133
+ | `chain` | `ChainName` | Chain name: 'ethereum' \| 'polygon' \| 'arbitrum' \| 'base' \| 'optimism' \| 'bsc' |
134
+ | `details` | `string` | Optional details about the transaction |
245
135
 
246
- const txReceipt = await provider.sendTransaction(signedTx);
136
+ #### `create()`
247
137
 
248
- // 4. Associate the blockchain transaction hash
249
- await parallaxService.associateTransactionHash(txId, txReceipt.hash, 1);
138
+ Submit the trace to the gateway.
250
139
 
251
- // 5. Wait for confirmation
252
- await parallaxService.addTransactionEvent(txId, 'waiting_confirmation', {
253
- txHash: txReceipt.hash,
254
- });
140
+ ```typescript
141
+ const traceId = await trace.create();
142
+ ```
255
143
 
256
- await txReceipt.wait();
144
+ Returns: `Promise<string | undefined>` - The trace ID if successful, undefined if failed
257
145
 
258
- // 6. Success!
259
- await parallaxService.finishTransactionTrace(txId, { success: true });
260
- console.log('Transaction completed successfully');
146
+ ## Complete Example: Transaction Tracking
261
147
 
262
- } catch (error) {
263
- console.error('Transaction failed:', error);
148
+ ```typescript
149
+ import { ParallaxClient } from '@miradorlabs/parallax-web';
264
150
 
265
- if (txId) {
266
- await parallaxService.addTransactionError(txId, error, 'TransactionError');
267
- await parallaxService.finishTransactionTrace(txId, {
268
- success: false,
269
- error: error.message,
270
- });
271
- }
151
+ const client = new ParallaxClient('your-api-key');
272
152
 
273
- throw error;
153
+ async function handleWalletTransaction(userAddress: string, recipientAddress: string, amount: string) {
154
+ // Build trace with all transaction details (client metadata included by default)
155
+ const traceId = await client.trace('SendETH')
156
+ .addAttribute('from', userAddress)
157
+ .addAttribute('to', recipientAddress)
158
+ .addAttribute('value', amount)
159
+ .addAttribute('network', 'ethereum')
160
+ .addTags(['transaction', 'send', 'ethereum'])
161
+ .addEvent('wallet_connected', { wallet: 'MetaMask' })
162
+ .addEvent('transaction_initiated')
163
+ .addEvent('user_signed')
164
+ .addEvent('transaction_sent', {
165
+ txHash: receipt.hash,
166
+ blockNumber: receipt.blockNumber,
167
+ gasUsed: receipt.gasUsed,
168
+ success: true
169
+ })
170
+ .setTxHint(receipt.hash, 'ethereum')
171
+ .create();
172
+
173
+ if (traceId) {
174
+ console.log('Trace ID:', traceId);
274
175
  }
275
176
  }
276
177
  ```
@@ -279,47 +180,46 @@ async function handleWalletTransaction(userAddress, recipientAddress, amount) {
279
180
 
280
181
  When `includeClientMeta: true` is set, the SDK automatically collects:
281
182
 
282
- - **Browser**: Chrome, Firefox, Safari, Edge, etc.
283
- - **Operating System**: Windows, macOS, Linux, Android, iOS
284
- - **User Agent**: Full user agent string
285
- - **Platform**: Browser platform
286
- - **Language**: Browser language
287
- - **Screen**: Width and height
288
- - **Viewport**: Width and height
289
- - **Timezone**: User's timezone and offset
290
- - **URL**: Current page URL
291
- - **Referrer**: Page referrer
292
- - **IP Address**: Client IP (if not blocked by CSP)
293
-
294
- All metadata is prefixed with `client.` in trace attributes.
295
-
296
- ## Environment Detection
297
-
298
- The SDK automatically detects the environment:
299
-
300
- - **Localhost/127.0.0.1**: Uses proxy at `${window.location.protocol}//${window.location.host}/parallax-gateway`
301
- - **Production**: Uses `https://gateway-parallax-dev.mirador.org`
302
-
303
- Override with the `gatewayUrl` option.
183
+ | Metadata | Description |
184
+ |----------|-------------|
185
+ | `client.browser` | Chrome, Firefox, Safari, Edge |
186
+ | `client.browserVersion` | Browser version number |
187
+ | `client.os` | Windows, macOS, Linux, Android, iOS |
188
+ | `client.osVersion` | Operating system version |
189
+ | `client.deviceType` | desktop, mobile, or tablet |
190
+ | `client.userAgent` | Full user agent string |
191
+ | `client.language` | Primary browser language |
192
+ | `client.languages` | All preferred languages (comma-separated) |
193
+ | `client.screenWidth` / `client.screenHeight` | Screen dimensions |
194
+ | `client.viewportWidth` / `client.viewportHeight` | Viewport dimensions |
195
+ | `client.colorDepth` | Screen color depth |
196
+ | `client.pixelRatio` | Device pixel ratio (for retina displays) |
197
+ | `client.cpuCores` | Number of CPU cores |
198
+ | `client.deviceMemory` | Device memory in GB (if available) |
199
+ | `client.touchSupport` | Whether touch is supported |
200
+ | `client.connectionType` | Network connection type (4g, 3g, wifi, etc.) |
201
+ | `client.cookiesEnabled` | Whether cookies are enabled |
202
+ | `client.online` | Whether browser is online |
203
+ | `client.doNotTrack` | Do Not Track preference |
204
+ | `client.timezone` | User's timezone |
205
+ | `client.timezoneOffset` | Timezone offset from UTC |
206
+ | `client.url` | Current page URL |
207
+ | `client.origin` | Page origin |
208
+ | `client.pathname` | Page pathname |
209
+ | `client.referrer` | Page referrer |
210
+ | `client.documentVisibility` | Document visibility state |
211
+
212
+ Note: IP address is captured by the backend from request headers.
304
213
 
305
214
  ## TypeScript Support
306
215
 
307
216
  Full TypeScript support with exported types:
308
217
 
309
218
  ```typescript
310
- import type {
311
- CreateTraceRequest,
312
- CreateTraceResponse,
313
- StartSpanRequest,
314
- StartSpanResponse,
315
- FinishSpanRequest,
316
- FinishSpanResponse,
317
- AddSpanEventRequest,
318
- AddSpanEventResponse,
319
- AddSpanErrorRequest,
320
- AddSpanErrorResponse,
321
- AddSpanHintRequest,
322
- AddSpanHintResponse,
219
+ import {
220
+ ParallaxClient,
221
+ ParallaxTrace,
222
+ ChainName, // 'ethereum' | 'polygon' | 'arbitrum' | 'base' | 'optimism' | 'bsc'
323
223
  } from '@miradorlabs/parallax-web';
324
224
  ```
325
225
 
@@ -330,7 +230,6 @@ This SDK uses modern browser APIs and is compatible with:
330
230
  - ES2020+
331
231
  - Fetch API
332
232
  - Promises
333
- - Uint8Array
334
233
  - Modern browsers (Chrome, Firefox, Safari, Edge)
335
234
 
336
235
  For older browsers, you may need polyfills.
@@ -343,35 +242,6 @@ The package provides multiple module formats:
343
242
  - **UMD** (`dist/index.umd.js`): For browser globals and older module systems
344
243
  - **TypeScript** (`dist/index.d.ts`): Type definitions
345
244
 
346
- ## Key Differences from Node.js Client
347
-
348
- The web client (`@miradorlabs/parallax-web`) differs from the Node.js client (`@miradorlabs/parallax`):
349
-
350
- | Feature | Web Client | Node.js Client |
351
- |---------|------------|----------------|
352
- | Transport | gRPC-Web (HTTP/1.1) | gRPC (@grpc/grpc-js) |
353
- | Protocol | `https://` | `http://` or `https://` |
354
- | Environment | Browser | Node.js |
355
- | Protobuf | google-protobuf (classes) | ts-proto (plain objects) |
356
- | API Style | `.getTraceId()` setters/getters | `.traceId` properties |
357
- | Client Metadata | Browser-specific | Server-specific |
358
-
359
- ## Important Update: Automatic Root Span Creation
360
-
361
- **Breaking Change (v1.0.5+):**
362
-
363
- When you call `createTrace()`, a root span is now **automatically created** on the backend. The response includes:
364
- - `traceId`: The trace identifier
365
- - `rootSpanId`: The automatically created root span ID
366
-
367
- **You no longer need to:**
368
- - Call `startSpan()` immediately after `createTrace()`
369
- - Manually create the first span
370
-
371
- **When to use `startSpan()`:**
372
- - Only when you need **child spans** for more detailed tracking
373
- - Use `rootSpanId` as the `parentSpanId` for child spans
374
-
375
245
  ## Development
376
246
 
377
247
  ### Building
@@ -396,11 +266,6 @@ npm run release:minor # 1.x.0
396
266
  npm run release:major # x.0.0
397
267
  ```
398
268
 
399
- ## Documentation
400
-
401
- - [ParallaxService Usage Guide](./PARALLAX_SERVICE_USAGE.md) - Comprehensive guide for the high-level API
402
- - [Examples](./examples) - More usage examples
403
-
404
269
  ## License
405
270
 
406
271
  ISC