Skip to content

Overview

Bridge402 Examples

This folder contains example implementations for integrating with the Bridge402 API using x402 payments.

Solana WebSocket Example

The Solana Example demonstrates how to connect to the Bridge402 news WebSocket stream using Solana (x402) payments.

Features

  • Solana Payment Integration: Pays invoice using Solana x402 exact scheme
  • WebSocket Connection: Connects to Bridge402 news stream
  • Automatic Session Extension: Extends sessions when expiry warnings are received
  • Real-time News Processing: Receives and processes news messages as they arrive
  • Error Handling: Robust error handling for payment and connection issues

Prerequisites

  1. Node.js >= 18
  2. Install dependencies:
    npm install undici ws dotenv @solana/web3.js @solana/spl-token
    

Configuration

Set the following environment variables:

# Required
BASE_URL=https://bridge402.tech
SOLANA_RPC=https://api.mainnet-beta.solana.com
KEYPAIR_PATH=path/to/your/keypair.json
# OR
KEYPAIR_JSON='[1,2,3,...]'  # JSON array of secret key

# Optional
SOL_USDC_MINT=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
SOL_FEE_PAYER=<fee_payer_address>
FACILITATOR_URL=https://facilitator.payai.network

Usage

# Set environment variables
export BASE_URL="https://bridge402.tech"
export SOLANA_RPC="https://api.mainnet-beta.solana.com"
export KEYPAIR_PATH="test-keypair.json"

# Run the example
node prod-test-sol.js

How It Works

  1. Get Invoice: Requests a payment invoice from /connect?duration_min=5&network=sol
  2. Pay Invoice: Builds and signs a Solana transaction using x402 exact scheme
  3. Connect WebSocket: Connects to the news stream using the access token
  4. Process Messages: Receives news messages and handles expiry warnings
  5. Auto-Extend: Automatically extends the session when expiry_soon messages are received

Key Functions

  • buildExactPaymentTx() - Builds the Solana transaction for x402 exact payment
  • getInvoice() - Requests payment invoice from Bridge402
  • payInvoice() - Signs and submits payment transaction
  • extendSession() - Extends an existing session when needed

Message Types

The WebSocket receives different message types:

  • status: 'connected' - Connection confirmation
  • type: 'expiry_soon' - Session expiry warning (triggers auto-extension)
  • type: 'session_extended' - Server acknowledgment of session extension
  • News messages - Real-time news updates from Tree of Alpha

Error Handling

The example handles: - Payment failures (insufficient funds, invalid signatures) - Connection issues (WebSocket disconnections) - Network errors (RPC failures, API errors) - Missing keypair (helpful error messages)

Generating a Test Keypair

To generate a test keypair for development:

node -e "const { Keypair } = require('@solana/web3.js'); const kp = Keypair.generate(); console.log(JSON.stringify(Array.from(kp.secretKey)))"

Save the output to a file:

# Create test-keypair.json
echo '[1,2,3,...]' > test-keypair.json

⚠️ Warning: Never use production keypairs or commit keypair files to version control.

Diffbot Extraction Example

The Diffbot Example demonstrates how to extract structured content from web pages using Bridge402's Diffbot endpoints.

Features

  • Interactive URL Input: Prompts user for URL to extract
  • Solana Payment Integration: Pays invoice using Solana x402 exact scheme
  • Multiple Extraction Types: Supports article, product, and discussion extraction
  • Result Saving: Saves extraction results to output.json
  • Error Handling: Robust error handling for payment and API issues

Prerequisites

  1. Node.js >= 18
  2. Install dependencies:
    npm install undici ws dotenv @solana/web3.js @solana/spl-token readline
    

Configuration

Set the following environment variables:

# Required
BASE_URL=http://localhost:8081  # or your Bridge402 server URL
SOLANA_RPC=https://api.mainnet-beta.solana.com
KEYPAIR_PATH=path/to/your/keypair.json
# OR
KEYPAIR_JSON='[1,2,3,...]'  # JSON array of secret key

# Optional
SOL_USDC_MINT=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
SOL_FEE_PAYER=<fee_payer_address>
FACILITATOR_URL=https://facilitator.payai.network

Usage

# Set environment variables
export BASE_URL="http://localhost:8081"
export SOLANA_RPC="https://api.mainnet-beta.solana.com"
export KEYPAIR_PATH="test-keypair.json"

# Run the example
node diff.js

The script will: 1. Prompt you to enter a URL 2. Request a payment invoice from the Diffbot endpoint 3. Display the invoice amount ($0.01 USDC) 4. Sign and submit the payment transaction 5. Receive the extraction data 6. Save the result to output.json 7. Display a summary in the console

How It Works

  1. Get Invoice: Requests payment invoice from /diffbot/article?url=...&network=sol
  2. Pay Invoice: Builds and signs a Solana transaction using x402 exact scheme
  3. Get Extraction: Receives structured content from Diffbot API
  4. Save Result: Writes the complete extraction to output.json

Example Output

Enter URL to extract: https://techcrunch.com/2024/01/01/article

📄 Extracting article from: https://techcrunch.com/2024/01/01/article

🧾 Requesting invoice...
💰 Invoice received: 0.01 USDC
   Pay to: BjxbJg48jQmoBLJnRunB1CMY5SZwvcUmnXCaWNeSXBei
   Asset: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v

💸 Paying invoice...
✅ Payment successful!

📝 Writing extraction result to output.json...
✅ Result saved to output.json

📊 Extraction Summary:
   URL: https://techcrunch.com/2024/01/01/article
   Type: article
   Payment Verified: true
   Transaction Hash: 5xK...
   Title: Article Title Here

✅ Complete! Check output.json for full extraction data.

Support

For questions about these examples or the Bridge402 API:

  1. Check the main API documentation
  2. Review the example code comments
  3. Join our Discord community