JSPM

x402-analytics

0.2.2
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 52
  • Score
    100M100P100Q54332F
  • License MIT

Analytics wrapper for x402 payment protocol - track payment events, performance metrics, and transaction data for both buyers and sellers with zero configuration

Package Exports

  • x402-analytics
  • x402-analytics/buyer
  • x402-analytics/seller

Readme

x402-analytics

npm version

Analytics wrapper for x402 payment protocol - Track payment events, performance metrics, and transaction data for both buyers and sellers with zero configuration.

๐Ÿš€ Quick Start

For Buyers (Client-side)

import { withBuyerAnalytics } from 'x402-analytics';

// Wrap your x402 fetch function with analytics
const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment);

// Use it like normal - analytics happen automatically!
const response = await fetchWithAnalytics('https://api.example.com/data', {
  payment: { maxAmountRequired: '10000' }
});

For Sellers (Server-side)

import { withSellerAnalytics } from 'x402-analytics';
import express from 'express';

const app = express();

// Wrap your x402 middleware with analytics
const analytics = await withSellerAnalytics(x402Middleware);
app.use('/api', analytics);

// All requests are now tracked automatically!

โœจ Features

  • ๐ŸŽฏ Zero Configuration: Works immediately without API keys or setup
  • ๐Ÿ“Š Real-time Dashboard: Get instant analytics at https://x402station.com/dashboard/anonymous/{your-id}
  • ๐Ÿ”‘ Claim Token System: Secure anonymous project claiming with claim tokens
  • ๐Ÿ”„ Automatic Tracking: Captures all payment events, errors, and performance metrics
  • โšก Non-blocking: Analytics don't slow down your application
  • ๐Ÿ›ก๏ธ Resilient: Built-in retry logic, circuit breakers, and offline persistence
  • ๐ŸŒ Universal: Works in browsers, Node.js, and serverless environments
  • ๐Ÿ“ฑ TypeScript: Full TypeScript support with comprehensive type definitions

๐Ÿ“ฆ Installation

npm install x402-analytics

Peer Dependencies: This package requires x402 v0.6.6 or higher.

๐ŸŽฏ Zero-Config Mode

The easiest way to get started - no API key required:

import { withBuyerAnalytics } from 'x402-analytics';

// Zero-config: Analytics work immediately
const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment);

// You'll see this in your console:
// ๐Ÿ“Š x402 Analytics Dashboard: https://x402station.com/dashboard/anonymous/abc123
// ๐Ÿ’ก Save your claim token to upgrade later (stored locally)
// ๐Ÿ”‘ Claim Token: your-secure-claim-token

๐Ÿ”‘ API Key Mode

For production use and data retention beyond 24 hours:

import { withBuyerAnalytics } from 'x402-analytics';

const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment, {
  apiKey: process.env.X402_ANALYTICS_API_KEY
});

๐Ÿ“Š What Gets Tracked

Buyer Events

  • Request Details: URL, payment amount, success/failure
  • Performance: Response time, duration
  • Payment Data: Transaction hash, payer address, network
  • Error Information: Error messages and failure reasons

Seller Events

  • Request Details: Path, payment amount, success/failure
  • Performance: Response time, duration
  • Payment Data: Transaction hash, payer address, network
  • Error Information: HTTP status codes and error messages

๐Ÿ› ๏ธ Configuration Options

Buyer Configuration

interface BuyerConfig {
  apiKey?: string;           // API key for data retention
  anonymousId?: string;      // Custom anonymous ID
  userId?: string;           // User identifier
  batchSize?: number;        // Events per batch (default: 100)
  flushInterval?: number;    // Flush interval in ms (default: 10000)
  enableRetry?: boolean;     // Enable retry logic (default: true)
  maxRetries?: number;       // Max retry attempts (default: 3)
  claimToken?: string;       // Custom claim token for anonymous projects
}

Seller Configuration

interface SellerConfig {
  apiKey?: string;           // API key for data retention
  anonymousId?: string;      // Custom anonymous ID
  userId?: string;           // User identifier
  batchSize?: number;        // Events per batch (default: 100)
  flushInterval?: number;    // Flush interval in ms (default: 10000)
  enableRetry?: boolean;     // Enable retry logic (default: true)
  maxRetries?: number;       // Max retry attempts (default: 3)
  claimToken?: string;       // Custom claim token for anonymous projects
}

๐Ÿ”ง Advanced Usage

Custom Configuration

const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment, {
  apiKey: process.env.X402_ANALYTICS_API_KEY,
  batchSize: 50,
  flushInterval: 5000,
  enableRetry: true,
  maxRetries: 5
});

Express Middleware Integration

import express from 'express';
import { withSellerAnalytics } from 'x402-analytics';

const app = express();

// Apply analytics to specific routes
app.use('/api', await withSellerAnalytics(x402Middleware, {
  apiKey: process.env.X402_ANALYTICS_API_KEY
}));

// Or apply globally
app.use(await withSellerAnalytics(x402Middleware));

Multiple Analytics Instances

// Different configurations for different services
const userAnalytics = await withBuyerAnalytics(userFetch, {
  userId: 'user-123',
  batchSize: 25
});

const adminAnalytics = await withBuyerAnalytics(adminFetch, {
  userId: 'admin-456',
  batchSize: 100
});

๐Ÿ”‘ Claim Token System

The SDK includes a secure claim token system for anonymous projects:

How It Works

  1. Anonymous Mode: When no API key is provided, the SDK generates a unique anonymous ID and claim token
  2. Secure Storage: Claim tokens are stored locally and securely hashed before transmission
  3. Project Claiming: Use your claim token to upgrade anonymous projects to full accounts
  4. Data Retention: Claimed projects retain data beyond the 24-hour anonymous limit

Using Claim Tokens

// The SDK automatically generates and displays your claim token
const analytics = await withSellerAnalytics(x402Middleware);

// Console output:
// ๐Ÿ“Š x402 Analytics Dashboard: https://x402station.com/dashboard/anonymous/abc123
// ๐Ÿ’ก Save your claim token to upgrade later (stored locally)
// ๐Ÿ”‘ Claim Token: your-secure-claim-token-here

// Use the claim token to upgrade your project at x402station.com

Custom Claim Tokens

// Provide your own claim token
const analytics = await withSellerAnalytics(x402Middleware, {
  claimToken: 'your-custom-claim-token'
});

๐ŸŒ Environment Variables

Variable Description Default
X402_ANALYTICS_API_KEY API key for data retention None (uses anonymous mode)
X402_ANALYTICS_SILENT Disable console logging false
X402_ANALYTICS_DEV_MODE Log events instead of sending false

๐Ÿ” Development Mode

For development and testing:

# Log events to console instead of sending to analytics service
X402_ANALYTICS_DEV_MODE=true npm run dev

๐Ÿ“ˆ Analytics Dashboard

Visit your dashboard at https://x402station.com/dashboard/anonymous/{your-id} to see:

  • Real-time Metrics: Live request tracking and performance data
  • Payment Analytics: Transaction volumes, success rates, and revenue
  • Error Monitoring: Failed requests and error patterns
  • Performance Insights: Response times and optimization opportunities
  • Claim Token Management: Secure anonymous project claiming

๐Ÿ›ก๏ธ Reliability Features

Automatic Retry Logic

  • Exponential backoff for failed requests
  • Configurable retry attempts
  • Circuit breaker pattern to prevent cascading failures

Offline Persistence

  • Failed events stored in localStorage (browser) or memory (Node.js)
  • Automatic retry on next session
  • Graceful degradation when analytics service is unavailable

Error Handling

  • Non-blocking analytics - failures don't affect your application
  • Comprehensive error logging and monitoring
  • Graceful fallbacks for all failure scenarios

๐Ÿงช Testing

import { withBuyerAnalytics } from 'x402-analytics';

// Mock fetch for testing
const mockFetch = jest.fn().mockResolvedValue({
  json: () => Promise.resolve({ data: 'test' }),
  headers: { get: () => null }
});

const analyticsFetch = await withBuyerAnalytics(mockFetch);

// Test your analytics integration
const result = await analyticsFetch('https://api.test.com/data');
expect(result).toBeDefined();

๐Ÿ“š Examples

Check out the complete examples in the repository:

๐Ÿ†˜ Support


Made with โค๏ธ by RemsLabs