PayStream

Micropayments for Web3 APIs & AI. State channels enable $0.000001 charges with zero gas fees.

PayStream

Created At

HackMoney 2026

Project Description

PayStream is a real-time payment streaming protocol that enables true micropayments on Web3. Built on Yellow Network's Nitrolite state channels, PayStream allows developers to monetize APIs, WebSocket streams, and LLM responses with micro-cent precision—charging as little as $0.000001 per message, per second, or per byte—with zero gas fees and instant settlement.

The core innovation is our "pay-only-while-connected" model: users are charged exclusively when their WebSocket connection is active and consuming resources. The moment they disconnect, payments stop immediately. No wasted money on idle subscriptions—you pay exactly for what you use, nothing more, nothing less.

We're implementing HTTP 402 "Payment Required" as a complete protocol standard, bringing native micropayments to the web for the first time. Our system uses cryptographically signed state channel updates that settle off-chain with instant finality, bypassing the scalability limits and transaction costs of traditional blockchains.

PayStream integrates ENS for human-readable identities (vitalik.eth instead of hex addresses) and provides three developer-ready SDKs: @paystream/client/react for frontend integration, @paystream/server for Node.js backends, and @paystream/core for protocol utilities. Integration takes under an hour.

Use cases include: pay-per-token AI services (GPT-4, Claude), pay-per-request API gateways, pay-per-second content streaming with real-time creator payments, and autonomous machine-to-machine resource trading for IoT devices. PayStream is chain-agnostic and works on any EVM-compatible network including Base, Polygon, and Arbitrum.

By eliminating gas fees and enabling granular usage-based pricing, PayStream unlocks business models that were previously impossible, making micropayments practical for the decentralized web.

How it's Made

PayStream is built on a WebSocket-based architecture that bridges Yellow Network's Nitrolite state channels with a custom payment metering protocol. Here's how we pieced it together:

CORE ARCHITECTURE: We built three main packages as a monorepo. The @paystream/core library handles the fundamental protocol logic - pricing models, ENS resolution via ethers.js connecting to Ethereum mainnet, and the standardized HTTP 402 negotiation schema. This layer is framework-agnostic and provides the foundation for both client and server implementations.

YELLOW NETWORK INTEGRATION: The critical breakthrough came from integrating the @erc7824/nitrolite SDK for state channel management. We embed NitroliteChannel instances directly into WebSocket connections, allowing us to process micro-payments off-chain with zero gas fees. Each payment is a cryptographically signed state update that both parties verify instantly - no blockchain confirmation needed. When a user's prepaid balance runs low, our server sends a PAYMENT_REQUIRED message (implementing HTTP 402), the client signs a Nitrolite state update authorizing the transfer, and the server verifies the signature using Yellow's SDK before unlocking continued service. Settlement to the clearing layer (ClearNode) happens asynchronously and only when necessary, batching hundreds of micro-transactions into efficient on-chain reconciliations.

CLIENT SDK (@paystream/client/react): We built custom React hooks (usePayStream, usePaymentChannel, useBalance) that manage WebSocket lifecycle, automatic reconnection with exponential backoff, and real-time balance tracking. The hooks integrate with wagmi for wallet connections and viem for transaction signing. We created UI components (PaymentStatus, BalanceDisplay, ConnectionIndicator) that developers can drop into their apps. The particularly hacky part: we implemented a heartbeat mechanism that pings the server every 5 seconds while connected - this proves the connection is active and triggers metering. If heartbeats stop, the server knows the client disconnected and immediately halts payment accumulation.

SERVER SDK (@paystream/server): Built on Node.js with ws (WebSocket library) and express for HTTP endpoints. We implemented a custom MeteringEngine class that tracks usage per connection in real-time using high-resolution timestamps (process.hrtime.bigint()) for nanosecond precision. The engine supports multiple pricing models: per-message, per-second (time-based), per-byte (data volume), and hybrid combinations. For payment verification, we validate Nitrolite signatures using elliptic curve cryptography (secp256k1) to ensure the state channel update is legitimate before crediting the user's session balance.

ENS INTEGRATION: One challenge: PayStream runs on fast L2s like Base Sepolia for low latency, but ENS lives on Ethereum mainnet. We solved this by maintaining a lightweight ethers.js provider connection to mainnet specifically for ENS resolution. We cache resolved addresses in-memory (LRU cache with 1-hour TTL) to avoid repeated mainnet calls. When a user connects, we resolve their ENS name once, display it in the UI, and use the underlying address for all payment operations. This gives users human-readable identity without compromising L2 performance.

HTTP 402 STANDARDIZATION: We created a complete schema for the 402 Payment Required response, including fields for: pricing_model (structure defining cost per unit), supported_tokens (USDC, ETH, etc.), channel_params (network, contract address, minimum deposit), and payment_uri (WebSocket endpoint). Both client and server SDKs implement automatic 402 detection and negotiation - when a client hits a paid resource, our SDK intercepts the 402, opens the appropriate Nitrolite channel, and signs the required payment without interrupting user flow.

NOTABLE HACKS:

  1. Optimistic Metering - We meter usage optimistically on the server and only request payment when balance drops below a threshold (not after every single message). This reduces signature operations by 10-100x while maintaining security since we never deliver more value than the user has paid for.

  2. Graceful Degradation - If the Nitrolite channel fails to open (network issues, insufficient funds), we automatically fall back to "Free Mode" with rate limiting instead of completely blocking access. This improves UX during onboarding.

  3. State Reconciliation - WebSockets can disconnect unexpectedly. We implemented a session recovery mechanism using JWT tokens - if a client reconnects within 5 minutes, they resume their previous session with the same balance and channel state intact.

  4. Cross-Chain Routing - Since Yellow Network supports multiple chains, we built a smart router that automatically detects which network the user's wallet is connected to and opens the state channel on that network. Users never have to manually switch networks.

CHALLENGES AND SOLUTIONS: Challenge: State channels require both parties to be online. How do we handle server restarts? Solution: We persist channel state to Redis with automatic restoration on server startup. Channels survive restarts seamlessly.

Challenge: How do we prevent double-spending if a malicious client signs multiple state updates? Solution: Yellow's SDK includes nonce-based replay protection. Each state update increments a nonce, and the server rejects any update with an out-of-order nonce.

Challenge: Real-time balance updates caused UI flickering. Solution: We debounce balance updates with a 200ms delay and use React's useTransition hook for non-blocking state updates.

DEVELOPER EXPERIENCE: We used TypeScript throughout for type safety. Turborepo manages our monorepo with shared tsconfig and build pipelines. We publish all three packages to npm with automated releases via semantic-release. Documentation is built with Docusaurus and includes interactive code examples using CodeSandbox embeds.

TESTING: We wrote comprehensive tests using Vitest for unit tests and Playwright for end-to-end WebSocket flow testing. We simulate network failures, race conditions, and malicious payment attempts to ensure robustness. Our CI/CD pipeline runs tests on every commit via GitHub Actions.

The result is a production-ready payment streaming protocol that makes micropayments finally viable on Web3, with a developer experience as simple as adding a few hooks to your React app.

background image mobile

Join the mailing list

Get the latest news and updates