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

x402-megaeth-sdk

v0.3.0

Published

x402 micropayment SDK for native ETH on MegaETH

Downloads

568

Readme

x402-megaeth-sdk

Modular SDK for x402 HTTP micropayments on MegaETH. Supports both native ETH and USDM (ERC-20) with gasless permits for users.

Implements the x402 protocol with a Three-Entity Architecture: Payer, Target Server, and Facilitator.

Features

  • MegaETH Optimized: 10ms block times and low fees.
  • 💰 Dual Asset Support: Pay with Native ETH or USDM.
  • Gasless for Users (USDM): Uses EIP-2612 Permits so the Facilitator pays the gas for USDM payments.
  • 🔌 Plug & Play Middleware: Protect any Express.js endpoint with one line of code.
  • 🌐 Browser & Node Friendly: Works with any EIP-1193 wallet or private keys.

Live Demo & Resources


How It Works (Three-Entity Architecture)

The x402 flow involves a Facilitator that acts as a verified settlement layer between the User and the API Server.

User (Payer)             API Server                Facilitator
     |                      |                           |
     |  1. GET /resource    |                           |
     | -------------------> |                           |
     |                      |                           |
     |  2. 402 Payment Req  |                           |
     | <------------------- |                           |
     |                      |                           |
     |  3. [ETH Tx] or      |                           |
     |     [Permit Sig]     |                           |
     | -------------------> |                           |
     |                      |                           |
     |                      | 4. Forward to Facilitator |
     |                      | ------------------------> |
     |                      |                           |
     |                      |    5. Verify (ETH) &      |
     |                      |       Settle (USDM)       |
     |                      | <------------------------ |
     |                      |                           |
     |  6. 200 OK + Content |                           |
     | <------------------- |                           |

Installation

npm install x402-megaeth-sdk

Note: express is required as a peer dependency if you are using the server middleware. viem is required for client-side wallet interactions.


Integration Guide

1. Server — Protect Endpoints

Add the paymentMiddleware to your Express app. You can configure different prices and assets (ETH/USDM) per route.

import express from "express";
import { Server } from "x402-megaeth-sdk";

const app = express();

app.use(Server.paymentMiddleware({
  routes: {
    "/api/standard": {
      price: "$0.001",         // 0.1 cents in ETH
      payTo: "0xProvider...",
      asset: "ETH",
      scheme: "exact-native",
    },
    "/api/premium": {
      price: "$0.05",          // 5 cents in USDM
      asset: "USDM",
      scheme: "permit-erc20",
      payTo: "0xProvider...",
    },
  },
  // facilitatorUrl: "https://abdoopx6d7.execute-api.ap-southeast-1.amazonaws.com",  leave option blank to use facilitator set up by skate
}));

app.get("/api/premium", (req, res) => {
  res.json({ 
    data: "Premium Content", 
    paidBy: res.locals.payerAddress 
  });
});

2. Client — Browser (Frontend UI)

For frontend applications, use BrowserProviderPayer. You can also hook into the payment selection process if your server offers multiple payment methods (e.g., ETH and USDM).

import { Client } from "x402-megaeth-sdk";
import type { PaymentRequired, PaymentRequirements } from "x402-megaeth-sdk";

// 1. Initialize with window.ethereum
const payer = new Client.BrowserProviderPayer(window.ethereum, userAddress);

// 2. Wrap fetch with an optional selection callback
const x402Fetch = Client.createX402Fetch(payer, {
  onPaymentRequired: (paymentRequired: PaymentRequired) => {
    return new Promise((resolve) => {
      // Show a UI modal to let the user choose which asset to pay with
      // resolve(chosenRequirement) or resolve(undefined) to cancel
      showMyCustomModal(paymentRequired.accepts, (choice) => resolve(choice));
    });
  }
});

// 3. Call your API — the wrapper handles retries and payments automatically
const res = await x402Fetch("http://localhost:3402/api/premium");
const data = await res.json();

3. Client — Node.js (Private Key)

Use X402Payer for automated agents or backend-to-backend micropayments.

import { Client } from "x402-megaeth-sdk";

const payer = new Client.X402Payer("0xYourPrivateKey");
const x402Fetch = Client.createX402Fetch(payer);

const res = await x402Fetch("http://localhost:3402/api/premium");

API Reference

paymentMiddleware(config)

Express middleware. Gated routes will return 402 Payment Required with a PAYMENT-REQUIRED header if payment proof is missing.

| Config Field | Description | |---|---| | facilitatorUrl | The URL of the x402 Facilitator server. | | routes | Map of paths to RouteConfig. | | ethUsdRate | Optional fixed rate for $ to wei conversion. |

BaseX402Payer

Abstract base class for all payers.

  • getBalance(): Returns wallet balance.
  • createPayment(pr): Handles the logic for sending ETH or signing a USDM permit.

createX402Fetch(payer)

Returns a fetch wrapper that:

  1. Catches 402 responses.
  2. Calls payer.createPayment().
  3. Retries the request with the PAYMENT-SIGNATURE header.

Network Details (MegaETH Mainnet)

| Property | Value | |---|---| | Chain ID | 4326 | | RPC | https://mainnet.megaeth.com/rpc | | Block Time | ~10ms | | Gas Model | 60,000 min gas per tx (intrinsic) | | USDM Address | 0xFAfDdbb3FC7688494971a79cc65DCa3EF82079E7 |


The Facilitator Settlement Layer

The Facilitator acts as a trusted third party that ensures the API Server receives payment before the content is released. It handles different verification logic depending on the asset:

Native ETH (Direct Settlement)

  1. The User sends ETH directly to the Server's wallet.
  2. The Facilitator verifies the transaction hash on MegaETH using an RPC provider.
  3. It checks that the recipient address, amount, and sender match the signed request.
  4. Once verified, it signals the Server to release the content.

USDM (Permit Settlement)

  1. The User signs an EIP-2612 Permit (off-chain signature), giving the Facilitator permission to move a specific amount of USDM.
  2. The Facilitator receives this signature and submits it to the MegaETH network.
  3. The Facilitator executes the permit() and transferFrom() transactions (paying the gas).
  4. Since the settlement is atomic via the Facilitator, the User experiences a seamless, gasless checkout.

License

MIT