Skip to main content

Installation

cargo add l402kit
Or in Cargo.toml:
[dependencies]
l402kit = "1.9"
Requirements: Rust 1.75+, Tokio async runtime

Quickstart

The fastest path uses ManagedProvider — no Lightning node needed, 0.3% fee:
use axum::{middleware, routing::get, Router, Json};
use l402kit::{l402_middleware, Options, ManagedProvider};
use serde_json::{json, Value};
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let provider = ManagedProvider::new("you@yourdomain.com".into());
    let opts = Arc::new(Options::new(10, provider));

    let app = Router::new()
        .route("/api/data", get(handler))
        .route_layer(middleware::from_fn_with_state(opts, l402_middleware));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handler() -> Json<Value> {
    Json(json!({ "data": "premium content" }))
}
For sovereign mode (0% fee), implement the LightningProvider trait — see Custom provider below.

Custom provider

use std::sync::Arc;
use l402kit::{Options, LightningProvider, Invoice, BoxFuture, L402Error};

struct MyProvider;

impl LightningProvider for MyProvider {
    fn create_invoice<'a>(&'a self, amount_sats: u64) -> BoxFuture<'a, Result<Invoice, L402Error>> {
        Box::pin(async move {
            Ok(Invoice {
                payment_request: "lnbc...".into(),
                payment_hash: "abc123...".into(),
                macaroon: "eyJ...".into(),
                amount_sats,
            })
        })
    }
}

let opts = Arc::new(Options::new(10, Arc::new(MyProvider)));

Options

FieldTypeDescription
price_satsu64Price per call in satoshis (required)
lightningArc<dyn LightningProvider>Your Lightning backend (required)
on_paymentOption<Box<dyn Fn(L402Token, u64)>>Callback fired after each verified payment

Deprecated: with_address()

Options::with_address(address) was removed in v1.4.0. Use Options::new(sats, ManagedProvider::new(address)) instead:
use l402kit::{Options, ManagedProvider};
use std::sync::Arc;

let provider = ManagedProvider::new("you@yourdomain.com".into());
let opts = Arc::new(Options::new(10, provider));

l402_middleware(opts: Options)

Returns an axum::middleware::Layer compatible with axum 0.8+.

Behavior

RequestResponse
No Authorization header402 + WWW-Authenticate: L402 macaroon="...", invoice="lnbc..."
Valid L402 <macaroon>:<preimage>Handler executes
Invalid or expired token401 Unauthorized
Replayed preimage401 Token already used

402 response body

{
  "error": "Payment Required",
  "invoice": "lnbc100n1...",
  "macaroon": "eyJoYXNoIjoiYWJjMTIzIiwiZXhwIjoxNzAwMDAwMDAwfQ==",
  "price_sats": 10
}

on_payment callback

use l402kit::{Options, L402Token};

let opts = Arc::new(
    Options::new(10, provider).on_payment(|token: L402Token, amount_sats: u64| {
        println!("payment received: {} sats", amount_sats);
    }),
);

Feature flags

[features]
default = ["axum-middleware"]
axum-middleware = ["dep:axum", "dep:reqwest", "dep:http"]
Disable axum-middleware to use only the core verification functions without axum or reqwest:
l402kit = { version = "1.9", default-features = false }

Verification

SHA256(preimage) == paymentHash is verified locally using the sha2 crate — no network call on the hot path. Token expiry is checked in the same operation.

Error codes

StatusMeaning
402No payment token — pay the invoice
401Invalid token or expired macaroon
401Replayed preimage (already used)

Running

cargo run

# Test — triggers 402
curl http://localhost:3000/api/data

# Pay invoice, then:
curl -H "Authorization: L402 <macaroon>:<preimage>" http://localhost:3000/api/data