Examples

Complete examples demonstrating various Shade402 use cases.

Express Server Example

Complete Express.js server with payment-protected endpoints:

import express from 'express';
import cors from 'cors';
import { initX402, paymentRequired, x402ErrorMiddleware } from '@shade402/express';
import { generateKeyPair } from '@shade402/core';

const app = express();
app.use(cors());
app.use(express.json());

// Generate encryption keys
const { publicKey, privateKey } = generateKeyPair();

// Initialize X402
initX402({
  paymentAddress: process.env.PAYMENT_WALLET_ADDRESS!,
  tokenMint: process.env.TOKEN_MINT!,
  network: process.env.SOLANA_NETWORK || 'solana-devnet',
  rpcUrl: process.env.SOLANA_RPC_URL,
  defaultAmount: '0.01',
  paymentTimeout: 300,
  autoVerify: true,
  encryptionPublicKey: publicKey,
  encryptionPrivateKey: privateKey,
});

// Public endpoint
app.get('/', (req, res) => {
  res.json({
    message: 'Welcome to X402 Payment API',
    endpoints: {
      free: '/api/free',
      premium: '/api/premium-data',
      analysis: '/api/premium-analysis',
    },
  });
});

// Free endpoint
app.get('/api/free', (req, res) => {
  res.json({
    message: 'This is a free endpoint',
    data: {
      timestamp: new Date().toISOString(),
      value: Math.random() * 100,
    },
  });
});

// Premium endpoint
app.get(
  '/api/premium-data',
  paymentRequired({
    amount: '0.01',
    description: 'Access to premium data endpoint',
  }),
  (req, res) => {
    res.json({
      message: 'Premium data accessed successfully',
      data: {
        timestamp: new Date().toISOString(),
        premiumValue: Math.random() * 1000,
        secretData: 'This is premium content',
        paymentId: req.payment?.paymentId,
      },
    });
  }
);

// Premium analysis endpoint
app.post(
  '/api/premium-analysis',
  paymentRequired({
    amount: '0.05',
    description: 'Premium AI analysis service',
    expiresIn: 600,
  }),
  async (req, res) => {
    const { text } = req.body;
    
    if (!text) {
      return res.status(400).json({
        error: 'Missing text field in request body',
      });
    }

    // Simulate analysis
    res.json({
      message: 'Analysis completed',
      input: text,
      analysis: {
        sentiment: 'positive',
        wordCount: text.split(' ').length,
        estimatedCost: '0.05 USDC',
        paymentId: req.payment?.paymentId,
      },
    });
  }
);

// Error handling
app.use(x402ErrorMiddleware());

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Client Example

Complete client that makes payment-protected requests:

Explicit Client Example

Manual payment control with explicit client:

LangChain Agent Example

LangChain agent with payment tool:

LangGraph Workflow Example

LangGraph workflow with payment nodes:

Next.js API Route Example

Next.js API route with payment protection:

Multiple Payment Tiers Example

Different payment tiers for different endpoints:

Custom Verification Example

Custom payment verification logic:

Error Handling Example

Comprehensive error handling:

Next Steps

Last updated