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

@parad0x_labs/x402

v0.1.0

Published

DNA Payment Rail — x402 SDK and CLI for AI agent buyers and sellers on Solana.

Downloads

231

Readme

DNA x402 — Payment Rail for Agents and APIs

DNA x402 is Parad0x Labs' x402 payment protocol for Solana. Any API can require payment, and any agent can pay programmatically with quote, proof, receipt, and optional on-chain anchoring.

Program: 9bPBmDNnKGxF8GTt4SqodNJZ1b9nSjoKia2ML4V5gGCF

Why DNA

AI agents need to pay for things: inference, storage, data, compute. Current options are API keys (no metering), credit cards (no agents), or crypto wallets (too manual). DNA solves this with a single SDK that handles quoting, payment, verification, and receipts — from $0.00001 to $100+ per call.

What This Package Is Not

  • Not a mixer
  • Not a privacy pool
  • Not a zk-SNARK payment hot path

Privacy-oriented Dark Null work is a separate product line. The live DNA x402 request path is optimized for fast payments and does not require zk proof generation per call. Builders can opt into the Dark Null private receipt path after a normal DNA receipt exists.

Features

Payments

  • Three settlement modes: Netting (off-chain batched, cheapest), Transfer (real on-chain USDC), Stream (Streamflow time-locked)
  • x402 HTTP standard: Any REST API becomes payment-gated with one middleware call
  • Receipt anchoring: Cryptographic receipts anchored on Solana via receipt_anchor program with Merkle-style accumulator hashing
  • Optional Dark Null privacy path: Hash-only private receipt request after a DNA receipt is issued
  • Replay protection: TTL-based replay attack prevention on every payment proof
  • Surge pricing: Dynamic price multipliers (0.8x–2.5x) based on real-time load (queue depth, inflight, latency, error rate)

Marketplace

  • Shop discovery: Agents find providers by capability, price, latency, and reputation
  • Reputation engine: Scores sellers 0–100 based on fulfillment rate, latency, disputes, uptime, and anchored receipts — bronze/silver/gold tiers
  • Badge system: Auto-awarded badges — FAST_P95, FULFILLMENT_99, TOP_SELLER_24H, PROOF_ANCHORED, STREAM_READY
  • Ranking engine: Weighted scoring (50% price, 30% latency, 20% reputation) for quote comparison
  • Limit orders: Agents set "buy at max $X" — auto-executes when a quote matches
  • Market analytics: Trending, top-selling, top-revenue, on-sale detection, price history, demand velocity, volatility scores
  • Bundle system: Multi-step capability chains with cost breakdowns, margin policies, and execution hashing
  • Abuse reporting: Scam/malware/impersonation reports against shops
  • OpenAPI/MCP import: Auto-generate shop endpoints from OpenAPI specs or MCP tool definitions
  • Shop templates: Pre-built configs for research, ops, action, and always-on agent types

Developer Tools

  • Seller SDK: Self-contained dnaSeller() scaffold for trusted/demo integrations
  • DNA Guard: Fail-open/fail-closed middleware for spend ceilings, replay alerts, quality validation, receipt verification logs, and provider scoring
  • x402 Doctor: Diagnostic tool that detects x402 dialects (Coinbase, Memeputer, generic), identifies missing headers, suggests fixes
  • Tool catalog: Cost estimation, balance coverage, projected spend based on usage patterns
  • 25+ structured error codes: Every error returns hints, trace IDs, docs URLs, and redacted payloads
  • Trace IDs: UUID per request via X-TRACE-ID header

Polymarket Multi-User Precheck

  • Shared builder credentials, per-user signer model: Server can keep shared builder headers/attribution credentials while each user order still requires a user-owned deposit wallet signer context (POLY_1271 / signature type 3)
  • Live readiness endpoint: GET /api/polymarket/live/readiness or GET /v1/polymarket/live/readiness
  • Per-user order precheck endpoint: POST /api/polymarket/live/order-precheck or POST /v1/polymarket/live/order-precheck
  • Live signed-order relay endpoint (gate-protected): POST /api/polymarket/live/submit or POST /v1/polymarket/live/submit
  • Alias env support:
    • POLY_BUILDER_CODE -> POLYMARKET_BUILDER_CODE
    • POLYMARKET_API_KEY -> POLYMARKET_BUILDER_API_KEY
    • POLYMARKET_API_SECRET -> POLYMARKET_BUILDER_SECRET
    • POLYMARKET_API_PASSPHRASE -> POLYMARKET_BUILDER_PASSPHRASE
  • Runtime non-regression rules:
    • Keep shared builder credentials for attribution/API auth.
    • Keep per-user signer/deposit wallet context for every order.
    • Do not allow backend custody or backend signing.
    • Do not skip /v1/polymarket/live/order-precheck before live submit.
    • Production gate lock: keep X402_ENABLE_POLYMARKET_LIVE=1 with checklist ref X402_POLYMARKET_LIVE_CHECKLIST_REF=docs/DNA_X402_POLYMARKET_LIVE_CONSTITUTION.md#live-gate-lock.
    • Do not switch back to paper/signal-only gate state unless explicitly requested by sls_0x.

Multi-User Ledger Runtime (Website Agents)

  • Users can scale to large concurrent agent counts under one platform builder integration, while balances remain per-user in ledger state.
  • Funding path:
    1. User funds agent wallet.
    2. User does one cash-in transfer to platform ledger.
    3. Tips and bets run gasless against internal ledger balance.
    4. User cashes out back to wallet when needed.
  • Required properties:
    • Per-user ledger segregation and audit trail
    • Explicit user-owned wallet flow
    • No backend private-key custody/signing

Infrastructure

  • Audit logging: NDJSON corporate-grade audit trail for every payment event
  • Webhooks: HMAC-signed async payment notifications with retry logic and exponential backoff
  • Cached RPC client: Solana RPC with TTL cache, circuit breaker, retry logic, and in-flight deduplication
  • Heartbeat system: Real-time shop load monitoring (queue depth, p95 latency, error rate)
  • Admin API: Full observability — audit export, receipt inspection, pause controls, replay store stats
  • Liquefy bridge: Archive payment data into verified .null vaults with live sidecar streaming
  • Benchmarking suite: Compute profiling, transaction size analysis, soak test thresholds

NULL Tip Account Eligibility

  • Recipient enrollment required: a wallet must open Tips and complete wallet-session enrollment before it can receive in-app NULL tips.
  • Gift-icon / chat gating endpoint:
    • GET /api/tips/account-status?wallet=<ownerWallet>
    • GET /v1/tips/account-status?wallet=<ownerWallet>
    • GET /api/tips/account/:ownerWallet/status
    • GET /v1/tips/account/:ownerWallet/status
  • Response shape: { ok, ownerWallet, hasTipAccount, canReceiveTips }
  • Cash-out automation runtime:
    • NULL_TIP_WITHDRAW_MODE=manual|webhook|mock
    • NULL_TIP_WITHDRAW_AUTO_PROCESS=1|0
    • automation processor endpoint: POST /api|/v1/admin/tips/withdrawals/process
    • user status feed endpoint: GET /api|/v1/tips/withdrawals

Install

npm install dna-x402

That installs the SDK and the dna-x402 CLI. Use the SDK for production buyer/seller integrations, and use the CLI for zero-config demos or starter scaffolds.

Zero-Config Demo

Bring up a local seller in one terminal:

npx dna-x402 demo seller --mode netting --port 3000

Then hit it from a buyer in another terminal:

npx dna-x402 demo buyer --mode netting --base-url http://127.0.0.1:3000

Supported demo modes:

  • transfer
  • netting
  • stream

The demo path is for proving the full 402 handshake, receipt flow, and settlement-mode wiring without forcing you to wire a real wallet first. It is not a substitute for production wallet and custody policy.

Starter Scaffolds

Generate a runnable seller project:

npx dna-x402 init seller my-seller
cd my-seller
npm start

Generate a runnable buyer project:

npx dna-x402 init buyer my-buyer
cd my-buyer
npm start

The generated seller starter enables trusted local netting by default via DNA_TRUSTED_LOCAL_NETTING=1, and the generated buyer starter uses that mode so you can validate the full loop immediately. Disable it before exposing the seller beyond local development, then replace the buyer wallet stub before using real transfer or stream money flows.

Quick Start

For Buyers (AI Agents)

import { fetchWith402 } from "dna-x402";

const result = await fetchWith402("https://provider.example/api/inference", {
  wallet: {
    payTransfer: async (quote) => ({
      settlement: "transfer",
      txSignature: "replace-with-real-wallet-tx-signature",
    }),
  },
  maxSpendAtomic: "50000",
});

const data = await result.response.json();

For a no-code smoke test instead of writing a buyer immediately:

npx dna-x402 demo buyer --mode transfer --base-url http://127.0.0.1:3000

If your buyer wants a deterministic receipt binding instead of a random per-call commitment, pass payerCommitment32B explicitly:

const result = await fetchWith402("https://provider.example/api/inference", {
  wallet: myWallet,
  maxSpendAtomic: "50000",
  payerCommitment32B: "9f".repeat(32), // 32-byte hex, with or without 0x prefix
});

For Sellers (Sell Compute, AI, Data — Anything)

import express from "express";
import { dnaSeller, dnaPrice } from "dna-x402/seller";

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

// 1. One line — enable payments to your wallet
const pay = dnaSeller(app, { recipient: "YOUR_SOLANA_WALLET" });

// 2. Gate any endpoint with a price
app.get("/api/inference", dnaPrice("5000", pay), (req, res) => {
  res.json({ result: "inference output" });
});

app.listen(3000);

That is the fastest scaffold, not the strongest control surface. dnaSeller() now verifies transfer proofs through the local Solana payment verifier, and it can verify stream proofs too if you pass a real streamflowClient into the scaffold options. Signed receipts for the payment finalize handshake preserve the transfer signature or verified streamId, and unlocked JSON routes emit a second delivery-bound receipt tied to the actual protected response body. Finalized commits are bound to the quoted HTTP method and full request target; a commit for GET /api/a?x=1 will not unlock POST /api/a?x=1, GET /api/a?x=2, or /api/b. The scaffold also rejects reusing the same transfer signature across different commits, so one on-chain payment proof cannot unlock multiple paid requests. Unlocked text and binary responses also carry a signed delivery receipt in the x-dna-receipt header. Manual streaming/chunked handlers and redirect/file helper responses are rejected with 501 unsupported_delivery_mode so the scaffold does not pretend it can prove a delivery it never signed. Failed protected deliveries now restore the paid unlock on any 4xx or 5xx, instead of charging for an application error by default. Guard policies, replay controls, market routing, and anchoring still live in the full x402 server path.

For the zero-config runnable seller instead of hand-writing the app first:

npx dna-x402 demo seller --mode transfer --port 3000

Transfer is now the default buyer path. Unsigned netting is disabled by default in the main server, and the buyer SDK no longer auto-picks it just because payNetted() exists. If you deliberately run a trusted bilateral off-chain settlement loop, opt in with UNSAFE_UNVERIFIED_NETTING_ENABLED=1 and pass preferNetting: true in the buyer call. The main server only accrues balances into the netting ledger for actual netting settlements now; verified transfer and stream payments are not silently mirrored into off-chain netting state.

If you expose stream in a scaffolded seller or paywall, wire a real streamflowClient; otherwise stream verification now fails closed instead of accepting a bare top-up signature. In the current per-request quote/finalize flow, verified streamId proofs are also treated as single-use, just like transfer proofs. If you want long-lived subscription semantics, build that session policy explicitly instead of reusing one finalize proof forever. The x402 header-compat flow also fails closed if a verifier claims a transfer succeeded but does not return the canonical txSignature.

Add DNA Guard (Spend Caps + Quality + Reputation API)

import express from "express";
import { AuditLogger, createDnaGuard, dnaPrice, dnaSeller } from "dna-x402";

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

const pay = dnaSeller(app, { recipient: "YOUR_SOLANA_WALLET" });
const audit = new AuditLogger({ filePath: "./audit-guard.ndjson" });
const guard = createDnaGuard({ auditLog: audit });

app.use("/guard", guard.router());

app.get("/api/inference", dnaPrice("5000", pay), guard.protect({
  providerId: "gpu-cluster-a",
  endpointId: "inference",
  amountAtomic: "5000",
  spendCeilings: { buyerAtomic: "15000", walletAtomic: "25000" },
  qualityValidator: (body) => ({
    ok: typeof (body as { result?: unknown }).result === "string",
    reason: "missing_result_string",
  }),
  failMode: "fail-open",
}), (_req, res) => {
  res.json({ result: "inference output" });
});

That gives you:

  • spend ceilings per buyer / wallet / agent / api key
  • replay anomaly logging
  • quality validation and dispute tagging
  • /guard/leaderboard, /guard/reputation/:providerId, /guard/compare, /guard/quote/best
  • receipt verification endpoints at /guard/receipt/:receiptId/verify

Use examples/dna-guard-seller.ts for the full runnable example.

Settlement Modes

| Mode | Per-TX Solana Fee | Best For | How It Works | |------|-------------------|----------|-------------| | Netting | None | Nano/micro payments | Off-chain ledger, batched settlement | | Transfer | ~$0.0001 | Larger payments | Real on-chain USDC SPL transfer | | Stream | ~$0.0001 | Continuous access | Streamflow time-locked payments |

Optional Dark Null Privacy Path

The normal DNA path stays default:

quote -> commit -> payment proof -> signed receipt -> paid unlock

The optional Dark Null path adds a private receipt request after the signed DNA receipt:

signed DNA receipt -> createDarkNullPrivacyRequest() -> Dark Null private receipt summary
import {
  createDarkNullPrivacyRequest,
  verifyDarkNullPrivacyRequest,
} from "dna-x402";

const request = createDarkNullPrivacyRequest({
  signedReceipt,
  target: {
    cluster: "devnet",
    programId: "2stas3cZYnBiWpndcTXQDGLXwfQ7kjEYYrW52DsUAcxF",
    manifestLabel: "canonical-devnet-root-2",
  },
  settlementSlot: 434395918,
  confirmationStatus: "finalized",
});

if (!verifyDarkNullPrivacyRequest(request).ok) {
  throw new Error("Dark Null privacy request failed verification");
}

Use it for privacy-sensitive paid unlocks. Do not put Dark Null proving in the live per-request hot path.

Devnet is the current Dark Null evidence lane. Mainnet-beta use requires promoted Dark Null deployment evidence and hosted enablement.

Architecture

Agent (buyer)                         API Provider (seller)
     |                                      |
     |  1. GET /api/inference               |
     |------------------------------------->|
     |  2. 402 Payment Required             |
     |<-------------------------------------|
     |  3. POST /commit (lock quote)        |
     |------------------------------------->|
     |  4. Pay (netting/transfer/stream)    |
     |------------------------------------->|
     |  5. POST /finalize (submit proof)    |
     |------------------------------------->|
     |  6. Receipt + access                 |
     |<-------------------------------------|
     |                                      |
     |  All receipts anchored on Solana     |
     |  via receipt_anchor program          |

Project Structure

x402/
├── src/
│   ├── cli.ts                 # `dna-x402` CLI (`demo` + `init`)
│   ├── server.ts              # Main x402 payment server
│   ├── client.ts              # Agent SDK (fetchWith402, marketCall)
│   ├── catalog.ts             # Tool catalog — cost estimation + balance coverage
│   ├── streaming.ts           # Streamflow integration for streaming payments
│   ├── demo/                  # Zero-config buyer/seller demos for transfer/netting/stream
│   ├── sdk/
│   │   ├── seller.ts          # Self-contained seller SDK (start here)
│   │   ├── guard.ts           # DNA Guard middleware + provider reputation API
│   │   ├── paywall.ts         # Express payment middleware
│   │   └── webhook.ts         # HMAC webhook delivery with retries
│   ├── market/
│   │   ├── analytics.ts       # Trending, top-selling, revenue, on-sale, price history
│   │   ├── reputation.ts      # Seller reputation scoring (0-100, bronze/silver/gold)
│   │   ├── badges.ts          # Auto-awarded performance badges
│   │   ├── ranking.ts         # Weighted quote ranking (price/latency/reputation)
│   │   ├── orders.ts          # Limit order book with auto-execution
│   │   ├── bundles.ts         # Multi-step capability chains
│   │   ├── heartbeat.ts       # Real-time shop load monitoring
│   │   ├── policy.ts          # Smart routing with preferences and denylists
│   │   ├── import/            # OpenAPI + MCP auto-importers
│   │   └── templates/         # Pre-built shop configs (research, ops, action)
│   ├── pricing/
│   │   └── surge.ts           # Dynamic surge pricing (0.8x–2.5x)
│   ├── x402/
│   │   ├── doctor.ts          # x402 dialect diagnostics + fix suggestions
│   │   ├── errors.ts          # 25+ structured error codes with hints
│   │   └── compat/            # Multi-dialect parser (Coinbase, Memeputer, etc.)
│   ├── verifier/
│   │   ├── splTransfer.ts     # On-chain USDC transfer verification
│   │   ├── streamflow.ts      # Stream payment verification
│   │   ├── replayStore.ts     # Replay attack prevention
│   │   └── rpcClient.ts       # Cached RPC with circuit breaker
│   ├── packing/
│   │   └── anchorV1.ts        # Binary packing + Merkle accumulator hashing
│   ├── logging/
│   │   └── audit.ts           # NDJSON corporate audit logger
│   ├── bridge/liquefy/        # Vault exporter, sidecar, CLI, adapter
│   ├── admin/                 # Admin API (audit, receipts, pause controls)
│   ├── bench/                 # Compute profiling, tx metrics, thresholds
│   └── middleware/             # HTTPS enforcement, trace ID injection
├── examples/
│   ├── sell-compute.ts        # Runnable seller demo (CLI-compatible)
│   ├── dna-guard-seller.ts    # Add spend caps, quality checks, and reputation APIs
│   ├── buyer-agent.ts         # Runnable buyer demo (pairs with sell-compute)
│   ├── seller-api.ts          # API accepting payments (advanced)
│   └── liquefy-gated-vault.ts # Liquefy + DNA integration
├── test-mainnet/
│   ├── mayhem-50.mjs          # 50-agent stress test
│   └── MAYHEM_50_REPORT.md    # Test results
└── AGENTS.md                  # AI agent quick reference

Running the Server

git clone https://github.com/Parad0x-Labs/dna-x402
cd dna-x402
npm install
cp .env.example .env       # Configure your wallet + RPC
npm run build
npm start

If you only want a local buyer/seller proof without running the full server, prefer:

npx dna-x402 demo seller --mode netting --port 3000
npx dna-x402 demo buyer --mode netting --base-url http://127.0.0.1:3000

DNA Guard Commands

npm run test:guard
npx tsx examples/dna-guard-seller.ts

Main x402 server integration is now built in behind config flags. When DNA_GUARD_ENABLED=1, createX402App() mounts /guard, enforces spend ceilings during quote/finalize flows, records receipt verification, and persists ledger state if DNA_GUARD_SNAPSHOT_PATH is set.

On the built-in protected routes (/resource, /inference, /stream-access, and audit fixtures), a finalized x-dnp-commit-id is now treated as a single-use delivery token. Successful delivery consumes it; failed delivery can be retried after a 5xx.

DNA_GUARD_ENABLED=1
DNA_GUARD_FAIL_MODE=fail-closed
DNA_GUARD_SNAPSHOT_PATH=./state/dna-guard.json
DNA_GUARD_BUYER_CEILING_ATOMIC=500000
DNA_GUARD_WALLET_CEILING_ATOMIC=1000000

For custom servers, you can also use the file-backed ledger helper directly:

import { createDnaGuard, createFileBackedDnaGuardLedger } from "dna-x402";

const ledger = createFileBackedDnaGuardLedger({
  snapshotPath: "./state/dna-guard.json",
  windowMs: 86_400_000,
});
const guard = createDnaGuard({ ledger });

Key routes after mounting app.use("/guard", guard.router()):

  • GET /guard/summary
  • GET /guard/leaderboard
  • GET /guard/score/:providerId
  • GET /guard/reputation/:providerId
  • GET /guard/compare?providers=provider-a,provider-b
  • GET /guard/quote/best?providers=provider-a,provider-b
  • GET /guard/receipt/:receiptId/verify
  • POST /guard/receipt/:receiptId/verify

Liquefy Integration

DNA integrates with Liquefy for archiving payment data into verified .null vaults.

Export Payment Data to Liquefy Vault

# One-shot export
curl -s http://localhost:8080/admin/audit/export | \
  npx tsx src/bridge/liquefy/cli.ts --stdin --out ./vault-staging/run-001

# Pack with Liquefy
python tools/tracevault_pack.py ./vault-staging/run-001 --org dna --out ./vault/run-001

DNA Guard audit events archive through the same bridge, including:

  • spend blocks
  • replay alerts
  • validation failures and disputes
  • receipt verified / invalid states
  • fail-open and runtime-error signals

Live Sidecar (Auto-Archive)

import { LiquefySidecar } from "dna-x402";

const sidecar = new LiquefySidecar({
  outDir: "./vault-live",
  cluster: "mainnet-beta",
});
sidecar.attachAuditLogger(auditLogger);
sidecar.startPeriodicFlush();

Payment-Gated Vault Access

Use DNA to monetize Liquefy vault operations. See examples/liquefy-gated-vault.ts for a complete example.

Market Intelligence API

Real-time analytics on every trade flowing through DNA:

| Endpoint | What It Returns | |----------|----------------| | GET /market/trending?window=1h | What's hot — demand velocity vs previous period | | GET /market/top-selling?window=24h | Most transactions by shop/endpoint | | GET /market/top-revenue?window=24h | Highest earning shops | | GET /market/on-sale?window=24h | Price drops detected | | GET /market/price-history?endpointId=X | Price chart for any endpoint | | GET /market/snapshot | Full dashboard — demand velocity, median prices, seller density, volatility, recommended providers |

Agents use this to shop smart — compare providers, find deals, track trends, and make data-driven purchasing decisions. All programmatic, no human needed.

Historical Mainnet Reports

This repo includes checked-in mainnet test artifacts for the receipt-anchor and payment rail flows. Summary from the tracked 50-agent stress report:

| Metric | Result | |--------|--------| | Agents | 50 (30 netting + 20 transfer) | | Total Trades | 80 | | Tests Passed | 84/84 (100%) | | On-Chain USDC Transfers | 20 | | Receipts Anchored | 80/80 | | Amount Range | $0.00001 — $2.00 |

Full report: test-mainnet/MAYHEM_50_REPORT.md

API Reference

See AGENTS.md for the complete API reference and copy-paste integration guide.

License

MIT — Parad0x Labs