PipeGate Server Middleware Documentation
Overview
The pipegate middleware provides server-side verification and multi-scheme payment enforcement (one-time transfers, Superfluid streams, and payment channels) for the PipeGate protocol.
As of version 0.6.0 a unified middleware PaymentsLayer (alias of PipegateMiddlewareLayer) replaces the need to stack separate middleware layers. It automatically:
- Parses the
X-Payment(x402) header - Detects the payment scheme (
one-time,stream,channel) - Verifies and (if needed) initializes internal state lazily
- Updates response headers (for channels) with refreshed channel data
- Emits a proper
402 Payment Requiredx402-formatted error if verification fails
Legacy per-scheme layers (PaymentChannelMiddlewareLayer, OnetimePaymentMiddlewareLayer, StreamMiddlewareLayer) are still documented below but deprecated and will be removed in a future major release. Prefer the unified approach for all new integrations.
NOTE: Payment channel on-chain deployment is currently live on Base Sepolia ( rpc: https://base-sepolia-rpc.publicnode.com ). Other schemes support multiple networks as long as supported by their respective infrastructure.
Installation
Add the following dependencies to your Cargo.toml:
[]
= { = "0.6.0" } # PipeGate server middleware
= "0.7" # Web framework
= { = "1.0", = ["full"] }
= { = "0.1", = ["full"] }
Note: Axum v0.8.0 has breaking changes. The pipegate tower-based middleware layers are not yet supported in the latest version.
Unified Payments Middleware (Preferred in >= 0.6.0)
Quick Start
use FromStr;
use ;
use Address;
use ;
async
async
Request Flow
- Client sends
X-Payment: { x402Version, scheme, network, payload }header. - Middleware selects matching
SchemeConfig(or returns402if unsupported). - Verification path per scheme:
- one-time: checks on-chain tx + local redemption rules
- stream: verifies Superfluid flow (with caching & optional listener)
- channel: verifies signed request & updates channel state, returning updated channel headers
- Request continues to handler; for channels, response headers are augmented.
Migrating from v0.5.x Per-Scheme Layers
| Old API (Deprecated) | New Unified API |
|---|---|
PaymentChannelMiddlewareLayer::new(state, cfg) |
PaymentsLayer::new(state, config) |
OnetimePaymentMiddlewareLayer::new(cfg, state) |
(Include one-time SchemeConfig in MiddlewareConfig) |
StreamMiddlewareLayer::new(cfg, state) |
(Include stream SchemeConfig in MiddlewareConfig) |
Multiple .layer(...) calls |
Single .layer(PaymentsLayer::new(...)) |
Steps:
- Build one
MiddlewareConfigby converting each old per-scheme config into aSchemeConfigviaSchemeConfig::new(...)(async). - Replace stacked layers with one
PaymentsLayerinstance. - Remove direct uses of individual state types unless you need custom inspection (the unified
PaymentsStateholds them lazily). - Update docs/imports to prefer
PaymentsLayer,PaymentsStateandSchemeenums. - Resolve deprecation warnings; the old layers will be removed in a future major release.
Header Format (x402)
Clients must send a single JSON header:
X-Payment: { "x402Version":1, "network":"base-sepolia", "scheme":"one-time", "payload": { ... } }
Exact payload shape depends on scheme (see original per-scheme sections below for structure reference). The unified middleware internally validates payload vs. scheme and returns InvalidHeaders if mismatched.
Legacy (Deprecated) Middleware Guides
The following sections remain for reference and will be removed after the unified API fully replaces them.
Basic Setup
Simple Server Implementation for Payment Channel middleware (Deprecated)
use ;
use ;
use ;
async
async
Simple Server Implementation for One Time payment middleware (Deprecated)
use ;
use ;
use ;
async
async
Simple Server Implementation for Stream middleware (Deprecated)
use ;
use ;
use ;
async
async
Closing channel & withdraw
use ;
pub async
Verify one time payment tx
Use the verify_tx function to verify a one-time payment transaction. The function takes a SignedPaymentTx and OneTimePaymentConfig as input and returns a Result with the verification status or an error.
async
Verification functions
-
Verify and Update Channel State:
verify_and_update_channel- Verifies the signed request and updates the channel state.ChannelStateis required to be persisted, better suited for serverful applications. -
Verify Channel:
verify_channel- Verifies the signed request and returns the updated channel.ChannelStateis not required to be persisted, better suited for serverless applications, but would add latency due to extra RPC calls to verify the channel info on each call. -
Verify Stream:
verify_stream- Verifies the stream payment request from onchain contracts -
Verify Stream via indexer:
verify_stream_indexer- Verifies the stream payment request using indexer. -
Verify one time tx:
verify_tx- Verifies the one time payment tx from onchain records and logs
Helper functions
-
Parse headers for payment channel:
parse_headers- Parsing and extracting signed request with payment channel from request headers -
Modify headers for updated channel with axum:
modify_headers_axum- Modifying response headers with updated channel state in axum. -
Modify headers for updated channel with HTTP:
modify_headers- Modifying response headers with updated channel state in HTTP. -
Parse headers for onetime payment tx:
parse_tx_headers- Parsing and extracting signed request with onetime payment tx from request headers -
Parse headers for stream based request:
parse_stream_headers- Parsing and extracting signed request with onetime payment tx from request headers
Error Handling
use AuthError;
async
WASM Compatibility
The PipeGate middleware can be compiled to WebAssembly (WASM) for use in browser-based applications. The middleware can be compiled using the wasm-pack tool and integrated into web applications using JavaScript. Only a subset of functions are exported currently with wasm-bindgen and can be found in wasm.rs. But other functions which are available can be easily exported as needed.
For ESM, web build
For CJS, nodejs build
Example usage can be found at tests/index.ts
Middleware Configuration Options
Environment Variables
# .env
RPC_URL=https://base-sepolia-rpc.publicnode.com
MIN_PAYMENT_AMOUNT=1000
CHANNEL_FACTORY_ADDRESS=0x...
Loading Configuration
use dotenv;
use env;
async
Best Practices
-
Security
- Always verify signatures and nonces
- Implement rate limiting
- Monitor for suspicious activity
- Keep RPC endpoint secure
-
Performance
- Use connection pooling for RPC calls
- Implement caching for channel states
- Monitor middleware performance
-
Maintenance
- Regularly update dependencies
- Monitor channel states
- Implement proper logging
- Set up monitoring and alerts
-
Error Handling
- Implement comprehensive error handling
- Provide meaningful error messages
- Log errors appropriately
- Handle edge cases
Note: This middleware is part of the PipeGate protocol. Ensure you're using compatible versions of both client SDK and server middleware.