npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

a402-sdk

v0.1.0

Published

Express middleware SDK for 402 Payment Required protocol

Readme

A402 SDK

Express middleware SDK for implementing the 402 Payment Required protocol with Aptos blockchain.

Installation

npm install @a402/sdk

Quick Start

import express from "express";
import A402 from "@a402/sdk";

const app = express();

// Initialize the SDK
const a402 = new A402({
  contractAddress: "0x...", // Your deployed smart contract
  backendUrl: "http://localhost:3001", // Your backend API
  secret: process.env.A402_SECRET, // JWT secret
});

// Apply CORS middleware
app.use(a402.cors());

// Protect routes with payment requirements
app.use("/api/protected/*", a402.protect({
  resource: "api-access",
  tier: "premium",
  priceUSD: 0.01,
}));

app.listen(3000);

Configuration

Required Options

  • contractAddress: Aptos smart contract address
  • backendUrl: Backend API URL for payment session management
  • secret: JWT secret for token generation

Optional Options

  • nodeUrl: Aptos node URL (default: testnet)
  • tokenTTL: Token time-to-live in seconds (default: 3600)
  • allowedOrigins: CORS allowed origins (default: ["*"])
  • paymentBaseUrl: Base URL for payment UI (default: "http://localhost:3000/pay")

Usage Examples

Basic Protection

// Protect a single route
app.get("/api/data", 
  a402.protect({
    resource: "data-access",
    priceUSD: 0.001,
  }),
  (req, res) => {
    res.json({ data: "Protected content" });
  }
);

Tiered Access

// Different pricing tiers
app.use("/api/basic/*", a402.protect({
  resource: "api",
  tier: "basic",
  priceUSD: 0.001,
}));

app.use("/api/premium/*", a402.protect({
  resource: "api",
  tier: "premium",
  priceUSD: 0.01,
}));

app.use("/api/enterprise/*", a402.protect({
  resource: "api",
  tier: "enterprise",
  priceUSD: 0.1,
}));

Access User Payment Info

app.get("/api/user-data",
  a402.protect({
    resource: "user-data",
    priceUSD: 0.005,
  }),
  (req: any, res) => {
    // Access payment information
    const { userId, resource, tier, token } = req.payment;
    
    res.json({
      data: "User specific content",
      userId,
      tier,
    });
  }
);

Payment Flow

  1. Initial Request: Client requests protected resource
  2. 402 Response: Server returns payment required with payment info
  3. Payment: User completes payment via provided URL
  4. Token Exchange: Client exchanges payment ID for access token
  5. Authenticated Request: Client includes token in Authorization header

Example Client Flow

// 1. Initial request
const response = await fetch("/api/protected");

if (response.status === 402) {
  const { payment } = await response.json();
  
  // 2. Redirect to payment
  window.location.href = payment.paymentUrl;
  
  // 3. After payment, exchange for token
  const tokenResponse = await fetch("/api/protected?paymentId=xxx");
  const token = tokenResponse.headers.get("X-Access-Token");
  
  // 4. Use token for future requests
  const data = await fetch("/api/protected", {
    headers: {
      "Authorization": `Bearer ${token}`,
    },
  });
}

Testing

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Advanced Configuration

Custom Payment URL

a402.protect({
  resource: "api-access",
  priceUSD: 0.01,
  customPaymentUrl: "https://pay.myapp.com",
});

Custom Contract Address

a402.protect({
  resource: "special-feature",
  priceUSD: 0.05,
  contractAddress: "0x456...", // Different contract
});

Error Handling

The SDK throws specific errors:

  • PaymentRequiredError: No valid payment or token
  • InvalidTokenError: Token validation failed
  • PaymentVerificationError: On-chain payment verification failed
app.use((err, req, res, next) => {
  if (err.name === "PaymentRequiredError") {
    res.status(402).json({
      error: err.message,
      payment: err.paymentInfo,
    });
  } else {
    res.status(500).json({ error: "Internal server error" });
  }
});

Security Considerations

  1. Always use HTTPS in production
  2. Keep your JWT secret secure
  3. Implement rate limiting on payment endpoints
  4. Validate contract addresses
  5. Use environment variables for sensitive config

License

MIT