> ## Documentation Index
> Fetch the complete documentation index at: https://shinydapps-bd9fa40b.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust SDK

> Complete reference for the l402-kit Rust SDK — axum middleware for Bitcoin Lightning pay-per-call APIs.

## Installation

```bash theme={null}
cargo add l402kit
```

Or in `Cargo.toml`:

```toml theme={null}
[dependencies]
l402kit = "1.9"
```

**Requirements**: Rust 1.75+, Tokio async runtime

***

## Quickstart

The fastest path uses `ManagedProvider` — no Lightning node needed, 0.3% fee:

```rust theme={null}
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](#custom-provider) below.

***

## Custom provider

```rust theme={null}
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`

| Field        | Type                                  | Description                                |
| ------------ | ------------------------------------- | ------------------------------------------ |
| `price_sats` | `u64`                                 | Price per call in satoshis (**required**)  |
| `lightning`  | `Arc<dyn LightningProvider>`          | Your Lightning backend (**required**)      |
| `on_payment` | `Option<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:

```rust theme={null}
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

| Request                            | Response                                                           |
| ---------------------------------- | ------------------------------------------------------------------ |
| No `Authorization` header          | `402` + `WWW-Authenticate: L402 macaroon="...", invoice="lnbc..."` |
| Valid `L402 <macaroon>:<preimage>` | Handler executes                                                   |
| Invalid or expired token           | `401 Unauthorized`                                                 |
| Replayed preimage                  | `401 Token already used`                                           |

### 402 response body

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

***

## `on_payment` callback

```rust theme={null}
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

```toml theme={null}
[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:

```toml theme={null}
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

| Status | Meaning                            |
| ------ | ---------------------------------- |
| `402`  | No payment token — pay the invoice |
| `401`  | Invalid token or expired macaroon  |
| `401`  | Replayed preimage (already used)   |

***

## Running

```bash theme={null}
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
```
