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

mongo402-sdk

v1.0.1

Published

Official SDK for mongo402 - Pay-per-query MongoDB access using x402 protocol with USDC on Solana

Readme

mongo402-sdk

Official SDK for mongo402 - Pay-per-query MongoDB access using x402 protocol with USDC on Solana.

npm version License: MIT

Overview

mongo402 enables data providers to monetize their MongoDB databases through a simple pay-per-query model. Buyers pay with USDC on Solana, and sellers receive instant payments for each query.

Installation

npm install mongo402-sdk
# or
yarn add mongo402-sdk
# or
pnpm add mongo402-sdk

Peer Dependencies

npm install @solana/web3.js

Quick Start

For Buyers (Data Consumers)

import { BuyerClient } from 'mongo402-sdk';

const client = new BuyerClient({
  network: 'devnet', // or 'mainnet-beta'
});

// Browse available endpoints
const endpoints = await client.browseEndpoints();

// Query a free endpoint
const result = await client.queryFree('endpoint-slug', {
  operation: 'find',
  filter: { status: 'active' },
  limit: 10,
});

console.log(result.data);

For Sellers (Data Providers)

import { SellerClient } from 'mongo402-sdk';

const client = new SellerClient({
  accessToken: 'your-jwt-token',
  network: 'devnet',
});

// Create a monetized endpoint
const endpoint = await client.createEndpoint({
  name: 'Premium Data API',
  description: 'Access to premium market data',
  mongodb_uri: 'mongodb+srv://...',
  database: 'mydb',
  collection: 'data',
  price_usdc: 0.01, // $0.01 per query
  sample_query: { type: 'market' },
  solana_wallet: 'YourSolanaWalletAddress',
  tags: ['market', 'data'],
  category: 'finance',
});

// Check revenue
const stats = await client.getRevenueStats();
console.log(`Total earned: ${stats.total_received_usdc}`);

Paid Queries with x402 Protocol

For paid endpoints, you need to complete a USDC payment on Solana before querying:

import { BuyerClient } from 'mongo402-sdk';
import { Connection, PublicKey, Transaction } from '@solana/web3.js';

const client = new BuyerClient({ network: 'devnet' });

// 1. Get payment info for the endpoint
const paymentInfo = await client.getPaymentInfo('paid-endpoint-slug');

if (paymentInfo) {
  // 2. Create and send USDC transfer transaction
  // (Use your preferred Solana wallet adapter)
  const transaction = await createUsdcTransfer({
    recipient: paymentInfo.recipient,
    amount: paymentInfo.amountLamports,
    mint: paymentInfo.usdcMint,
  });
  
  const signature = await sendTransaction(transaction);
  
  // 3. Query with payment proof
  const result = await client.queryPaid('paid-endpoint-slug', 
    { operation: 'find', filter: {} },
    { signature, payer: 'your-wallet-address', network: 'devnet' }
  );
}

API Reference

BuyerClient

| Method | Description | |--------|-------------| | browseEndpoints(filters?) | List available endpoints | | getEndpoint(slug) | Get endpoint details | | queryFree(slug, query) | Query a free endpoint | | queryPaid(slug, query, tx) | Query with payment | | getPaymentInfo(slug) | Get payment requirements |

SellerClient

| Method | Description | |--------|-------------| | createEndpoint(data) | Create new endpoint | | getMyEndpoints() | List your endpoints | | updateEndpoint(id, data) | Update endpoint | | deleteEndpoint(id) | Delete endpoint | | invalidateCache(id) | Clear cached results for endpoint | | getPaymentHistory(limit?) | View payments received | | getRevenueStats() | Get revenue statistics | | getRevenueAnalytics(params?) | Get revenue analytics by period | | getQueryAnalytics(params?) | Get popular queries analytics | | getGeoAnalytics(params?) | Get geographic buyer statistics |

Query Operations

Supported MongoDB operations:

  • find - Find multiple documents
  • findOne - Find a single document
  • count - Count documents
  • aggregate - Run aggregation pipeline
  • distinct - Get distinct values
// Find with options
await client.query.find('slug', { status: 'active' }, {
  projection: { name: 1, price: 1 },
  sort: { price: -1 },
  limit: 20,
  skip: 0,
});

// Aggregation
await client.query.aggregate('slug', [
  { $match: { category: 'tech' } },
  { $group: { _id: '$type', count: { $sum: 1 } } },
]);

Caching

Some endpoints support caching, which can reduce costs for frequently requested data.

Using Cached Data (Buyers)

// Query with caching enabled (default)
const result = await client.queryFree('endpoint-slug', {
  operation: 'find',
  filter: { status: 'active' },
});

// Check if result came from cache
if (result.is_cached) {
  console.log(`Cached result, expires in ${result.cache_ttl_remaining}s`);
  console.log(`Paid: ${result.actual_cost_usdc} USDC (discounted)`);
}

// Force fresh data (bypass cache)
const freshResult = await client.queryFree('endpoint-slug', 
  { operation: 'find', filter: {} },
  { useCache: false }
);

Cache Configuration (Sellers)

// Create endpoint with caching enabled
const endpoint = await client.createEndpoint({
  name: 'Cached Data API',
  // ... other fields
  cache_enabled: true,
  cache_ttl_seconds: 300,      // Cache for 5 minutes
  cache_discount_percent: 50,   // 50% off for cached results
});

// Invalidate cache when data changes
await client.invalidateCache(endpoint.id);

Authentication

mongo402 uses Phantom wallet for authentication:

import { BuyerClient } from 'mongo402-sdk';

const client = new BuyerClient();

// 1. Get nonce message
const { message, nonce } = await client.auth.getNonce();

// 2. Sign with Phantom wallet
const encodedMessage = new TextEncoder().encode(message);
const { signature } = await window.solana.signMessage(encodedMessage, 'utf8');

// 3. Authenticate
const auth = await client.auth.authenticateWallet(
  window.solana.publicKey.toString(),
  Buffer.from(signature).toString('base64'),
  message
);

console.log('Logged in as:', auth.user.wallet_address);

Error Handling

import { 
  PaymentRequiredError, 
  AuthenticationError,
  NotFoundError 
} from 'mongo402-sdk';

try {
  const result = await client.queryFree('paid-endpoint', query);
} catch (error) {
  if (error instanceof PaymentRequiredError) {
    console.log('Payment needed:', error.paymentInfo);
  } else if (error instanceof AuthenticationError) {
    console.log('Please login first');
  } else if (error instanceof NotFoundError) {
    console.log('Endpoint not found');
  }
}

Configuration

const client = new BuyerClient({
  baseUrl: 'https://mongo402.xyz/api', // API base URL
  timeout: 30000, // Request timeout in ms
  network: 'devnet', // Solana network
  accessToken: 'jwt-token', // Optional auth token
});

Networks

| Network | Description | |---------|-------------| | devnet | Solana Devnet (testing) | | mainnet-beta | Solana Mainnet (production) |

Links

License

MIT © mongo402