# Rust SDK

> The layerhop crate — an async reqwest (rustls) client with serde models, a typed error enum, a watch Stream and webhook verification.

Source: https://docs.layerhop.com/sdks/rust

The `layerhop` crate is the async Rust client for the LayerHop [REST API](/api-reference), mirroring the [TypeScript SDK](/sdk). It is built on `reqwest` (rustls, no OpenSSL), `tokio` and `serde`.

> The SDK never holds keys. It returns **unsigned** transactions; your wallet library (alloy, solana-sdk, a KMS…) signs and broadcasts them.

## How do I install it?

```toml
[dependencies]
layerhop = "0.9"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
futures-util = "0.3"                            # StreamExt for watch() and the streams
```

## Quickstart

Amounts are **integer strings in base units** (`"100000000"` = 100 USDC).

```rust
use futures_util::StreamExt;
use layerhop::{BuiltTx, LayerHop, QuoteParams, WatchOptions};

let lh = LayerHop::builder().build(); // .api_key(..).base_url("http://localhost:8787")

// 1. Quote
let q = lh.quote(&QuoteParams {
    src_chain: "base".into(), src_token: "USDC".into(), amount: "100000000".into(),
    dst_chain: "solana".into(), dst_token: "SOL".into(),
    sender: "0xYourEvmAddress".into(), recipient: "YourSolanaAddress".into(),
    ..Default::default() // slippage, gas on arrival, gasless, referrer, purpose, ...
}).await?;

// 2. Build the unsigned transaction
let tx = lh.build_tx(&q.best.quote_id).await?;

// 3. Sign + send with YOUR wallet library
let tx_hash = match tx {
    BuiltTx::Evm(evm) => sign_evm(evm).await?,   // send evm.approval first when Some
    BuiltTx::Svm(svm) => sign_svm(svm).await?,   // submit_via_api == Some(true) → lh.submit(..)
    BuiltTx::Tvm(tron) => sign_tron(tron).await?, // send tron.approval first; report the bare txID
};

// 4. Report the broadcast
lh.report_submitted(&q.best.quote_id, &tx_hash).await?;

// 5. Watch until filled / refunded / failed / dropped
let mut updates = Box::pin(lh.watch(&q.best.provider, &tx_hash, WatchOptions::default()));
while let Some(status) = updates.next().await {
    println!("{}", status?.state);
}
```

## Which methods are available?

| Method | Endpoint |
|---|---|
| `health()` · `chains()` · `tokens(chain)` | `GET /v1/health` · `/v1/chains` · `/v1/tokens` |
| `search_tokens(&TokenSearchParams)` · `lookup_token(address, Option<chain>)` | `GET /v1/tokens` (search, pages) · `/v1/tokens/lookup` |
| `get_token_risk(chain, address)` | `GET /v1/tokens/{chain}/{address}/risk` |
| `prices(&[ids])` · `balances(&BalancesParams)` | `GET /v1/prices` · `/v1/balances` |
| `quote(&QuoteParams)` | `GET /v1/quote` |
| `quote_exact_output(&ExactOutputQuoteParams)` | `GET /v1/quote?dstAmount=` ([receive an exact amount](/guides/exact-output)) |
| `quote_stream(&QuoteParams, &QuoteStreamOptions)` · `quote_stream_exact_output(..)` | `GET /v1/quote/stream` (SSE): a `Stream` of `QuoteStreamUpdate` |
| `quote_calls(&CallsQuoteParams)` | `POST /v1/quote` (exact output + destination calls) |
| `screen(&[addresses])` | `POST /v1/screen` (OFAC SDN list, public) |
| `build_tx(quote_id)` | `POST /v1/orders` → `BuiltTx::Evm` / `Svm` / `Tvm` |
| `build_gasless(quote_id)` · `submit_gasless(quote_id, trade, approval)` · `gasless_status(quote_id)` | `POST /v1/orders` · `POST /v1/orders/gasless` · `GET /v1/orders/gasless/{quoteId}` |
| `simulate(quote_id)` | `POST /v1/simulate` |
| `submit(quote_id, signed_base64)` | `POST /v1/orders/submit` (Solana `submit_via_api` only) |
| `report_submitted(quote_id, tx_hash)` | `POST /v1/orders/{quoteId}/submitted` |
| `status(provider, id)` | `GET /v1/orders/{provider}/{id}` |
| `watch(provider, id, WatchOptions)` | A `Stream` of state changes; ends when final, yields `Error::Timeout` after 30 min by default |
| `stream_order(quote_id)` | `GET /v1/orders/{quoteId}/events` (SSE): a `Stream` of `Order` until final |
| `list_orders(&ListOrdersParams)` | `GET /v1/orders` |
| `checkout().create(&CreateCheckoutParams)` | `POST /v1/checkout/sessions` |
| `checkout().list(&ListCheckoutSessionsParams)` · `checkout().get(id)` | `GET /v1/checkout/sessions` · `/v1/checkout/sessions/{id}` |
| `checkout().expire(id)` · `checkout().quote(id, &CheckoutQuoteParams)` | `POST /v1/checkout/sessions/{id}/expire` · `/quote` |
| `checkout().stream(id)` | `GET /v1/checkout/sessions/{id}/events` (SSE) until `paid`, `expired` or `needs_review` |
| `checkout().start_transfer(id)` · `checkout().start_bitcoin(id, Option<refund_address>)` | `POST /v1/checkout/sessions/{id}/transfer` · `/bitcoin` (public) |
| `checkout().products().create(&CreateCheckoutProductParams)` | `POST /v1/checkout/products` |
| `checkout().products().list(&ListCheckoutProductsParams)` · `checkout().products().get(id)` | `GET /v1/checkout/products` · `/v1/checkout/products/{id}` |
| `checkout().products().update(id, &UpdateCheckoutProductParams)` · `checkout().products().start_session(id, &StartProductCheckoutParams)` | `PATCH /v1/checkout/products/{id}` · `POST /v1/checkout/products/{id}/sessions` |
| `checkout().refunds().create(session_id, &CreateRefundParams)` · `checkout().refunds().list(session_id)` | `POST` · `GET /v1/checkout/sessions/{id}/refunds` |
| `invoices().create(&CreateInvoiceParams)` · `invoices().list(&ListInvoicesParams)` · `invoices().get(id)` | `POST /v1/invoices` · `GET /v1/invoices` · `/v1/invoices/{id}` |
| `invoices().update(id, &UpdateInvoiceParams)` · `invoices().send(id)` · `invoices().void(id)` | `PATCH /v1/invoices/{id}` · `POST /v1/invoices/{id}/send` · `/void` |
| `invoices().public_view(id)` · `invoices().pay(id)` | `GET /v1/invoices/{id}/public` · `POST /v1/invoices/{id}/pay` (public) |
| `recurring_orders().create(..)` · `.submit(request_id, signed)` · `.list(..)` · `.cancel(id, wallet)` | `/v1/recurring-orders` · `/submit` · `/{id}/cancel` |
| `splits().create(..)` · `.get(id)` · `.update(id, edit_token, ..)` | `POST /v1/splits` · `GET` · `PATCH /v1/splits/{id}` (public) |
| `get_tip_jar(address)` | `GET /v1/tip-jars/{address}` (public) |
| `payouts().plan(..)` · `payouts().transfers(..)` | `POST /v1/payouts/plan` · `/v1/payouts/transfers` (public) |
| `service_status()` | `GET /v1/status` (public) |
| `webhooks().stream()` · `webhooks().stream_since(since)` · `webhooks().trigger(event_type)` | `GET /v1/webhooks/stream` (SSE, `?since=` replays missed events) · `POST /v1/webhooks/trigger` (test keys) |
| `webhooks().resend(event_id, Option<endpoint_id>)` | `POST /v1/webhooks/events/{id}/resend` |
| `usage().get(&UsageParams)` · `usage().errors(&UsageErrorsParams)` | `GET /v1/usage` · `/v1/usage/errors` |
| `x402().supported()` · `x402().requirements(..)` · `x402().verify(..)` · `x402().settle(..)` | `GET /v1/x402/supported` · `POST /v1/x402/requirements` · `/verify` · `/settle` |
| `x402().payments().list(..)` · `x402().payments().get(id)` | `GET /v1/x402/payments` · `/v1/x402/payments/{id}` |

Builder options: `base_url`, `api_key`, `channel`, `integrator`, `integrator_fee_bps`, `http_client`.

## How do I take payments with checkout?

[Checkout](/guides/checkout) gets you paid in USDC or USDT while the customer pays with any token. `lh.checkout()` wraps the session endpoints; `create`, `list` and `expire` need an API key, `get` and `quote` are public.

```rust
use layerhop::{CheckoutQuoteParams, CreateCheckoutParams};

let session = lh.checkout().create(&CreateCheckoutParams {
    amount: "49000000".into(), // 49 USDC
    settle_chain: "base".into(), settle_token: "USDC".into(),
    recipient: "0xYourPayoutAddress".into(),
    reference: Some("order_1042".into()),
    ..Default::default()
}).await?;
// redirect the customer to session.url; fulfil on the checkout.session.completed webhook

// Your own payment page: quote, then pay with build_tx + report_submitted as usual
let q = lh.checkout().quote(&session.id, &CheckoutQuoteParams {
    src_chain: "arbitrum".into(), src_token: "ETH".into(), sender: payer.into(), slippage_bps: None,
}).await?;
let tx = lh.build_tx(&q.best.quote_id).await?; // q.best.src_amount is what the payer sends
```

## How do I sell with products and payment buttons?

A product is a fixed price (amount, settlement token, payout address and redirect URLs) that anyone may start a session from without being able to change it. It backs [payment buttons](/guides/payment-buttons), `https://layerhop.com/buy/{id}` links and store plugins. `lh.checkout().products()` wraps the product endpoints; `create`, `list` and `update` need an API key, `get` and `start_session` are public.

```rust
use layerhop::{CreateCheckoutProductParams, StartProductCheckoutParams, UpdateCheckoutProductParams};

let product = lh.checkout().products().create(&CreateCheckoutProductParams {
    name: "Pro plan".into(),
    amount: "49000000".into(), // 49 USDC
    settle_chain: "base".into(), settle_token: "USDC".into(),
    recipient: "0xYourPayoutAddress".into(),
    allowed_origins: Some(vec!["https://shop.example.com".into()]),
    ..Default::default()
}).await?;
// share product.url (https://layerhop.com/buy/prod_…) or put it behind a button

// Only `Some` fields are sent; `Some(None)` clears a nullable field
lh.checkout().products().update(&product.id, &UpdateCheckoutProductParams {
    active: Some(false), ..Default::default()
}).await?;

// Public (no key): a session on the product's terms, plus your order id
let session = LayerHop::new().checkout().products().start_session(&product.id, &StartProductCheckoutParams {
    reference: Some("order_1042".into()), ..Default::default()
}).await?;
// session.product_id == Some(product.id); send the payer to session.url
```

## How do I send invoices?

[Invoices](/guides/invoices) bill a customer by email and are paid through checkout. `send: Some(true)` (or `invoices().send(id)` later) emails the hosted page `https://layerhop.com/invoice/{id}`; payment marks it `paid`, emails a receipt with a PDF and sends `invoice.paid`.

```rust
use layerhop::{CreateInvoiceParams, InvoiceLineItem};

let inv = lh.invoices().create(&CreateInvoiceParams {
    customer_email: Some("jane@example.com".into()),
    line_items: vec![InvoiceLineItem { description: "Design work".into(), quantity: 2, unit_amount: "100000000".into() }],
    settle_chain: "base".into(), settle_token: "USDC".into(),
    recipient: "0xYourPayoutAddress".into(),
    due_at: Some("2026-11-01".into()), send: Some(true),
    ..Default::default()
}).await?;
// inv.status == "open"; inv.url is the hosted page
// drafts: update (Some(None) clears a field) · send · void
// public, no key: invoices().public_view(id) · invoices().pay(id) → { session_id, url }
```

## How do I refund a payment?

[Refunds](/guides/refunds) are signed from your own wallet. `checkout().refunds().create` returns the refund and a quote; build it, sign it from `quote.from`, and report the hash. It completes with a `checkout.session.refunded` webhook and the session's `refunded_amount` grows.

```rust
use layerhop::CreateRefundParams;

let r = lh.checkout().refunds().create(&session_id, &CreateRefundParams {
    amount: Some("10000000".into()), // omit for a full refund
    reason: Some("Damaged item".into()),
    ..Default::default()
}).await?;
let tx = lh.build_tx(&r.quote.quote_id).await?;
// sign and broadcast tx from r.quote.from, then:
lh.report_submitted(&r.quote.quote_id, &tx_hash).await?;
```

`to: Some("settlement".into())` sends the settlement token instead of routing back to the payer's original token.

## How do I sign Tron transactions?

Where the API runs with Tron enabled, `build_tx` returns `BuiltTx::Tvm(TronTx)` on chain `layerhop::TRON_CHAIN_ID` (728126428). The SDK never signs. Sign `tx.unsigned` unchanged with a Tron wallet (TronWeb, TronLink; `raw_data` is kept as raw JSON for that), send `tx.approval` first when it is `Some`, broadcast before `raw_data.expiration`, then `report_submitted` with the main transaction's `tx_id` (bare 64-hex). `simulate` reports `energy_used`. See [Wallets](/guides/wallets).

## How do I do a gasless swap?

[Gasless swaps](/guides/gasless-swaps) let a wallet with no native gas swap an ERC-20 on the same EVM chain: the user signs EIP-712 typed data and the provider's relayer pays the network fee out of the input token.

```rust
let q = lh.quote(&QuoteParams { gasless: Some(true), ..params }).await?; // q.best.gasless.gas_fee
let req = lh.build_gasless(&q.best.quote_id).await?;
// sign req.trade.eip712 (and req.approval's, when Some) with eth_signTypedData_v4, unchanged
lh.submit_gasless(&q.best.quote_id, &trade_sig, approval_sig.as_deref()).await?;
let st = lh.gasless_status(&q.best.quote_id).await?; // poll until "filled" or "failed"
```

`build_tx` on a gasless quote returns `Error::Usage` instead of a decode error.

## How do I run calls on the destination chain?

[Destination calls](/guides/destination-calls) quote by exact output: `quote_calls` sends `POST /v1/quote` with `dst_amount` and `calls` (or `action: Some(DestinationAction::aave_v3_supply())`). Each quote carries `src_amount` (what the sender pays) and `calls` (the committed calls, the executor and the simulation). A call that would revert is `CALLS_REVERTED`.

## How do I search, look up and check tokens?

```rust
let page = lh.search_tokens(&TokenSearchParams { chain: "base".into(), q: Some("BRETT".into()), ..Default::default() }).await?;
let t = lh.lookup_token("0x4200000000000000000000000000000000000006", None).await?; // the API finds the chain
let risk = lh.get_token_risk("base", &t.address).await?; // level: ok | caution | danger | unknown
let prices = lh.prices(&["8453:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]).await?;
let b = lh.balances(&BalancesParams { address: "0x…".into(), ..Default::default() }).await?;
```

Tokens read on-chain have `verified: false`; warn before a user trades them. `unknown` risk never blocks a swap. `Chain` has `destination_only`, `only_route` and `route_health`. See [Chains, tokens, prices and balances](/guides/tokens-and-balances).

## How do I use splits, tip jars and payouts?

All public, and nothing is signed by the SDK. `splits().create` returns the split with `edit_token` (shown once); pay a share with a quote carrying `purpose: Some("split".into())`, `split_id` and `split_share`; `splits().update(id, edit_token, ..)` sends the secret as `x-edit-token` (`note: Some(None)` clears the note). `get_tip_jar(address)` counts tips (quotes with `purpose: "tip"`). `payouts().plan` checks up to 100 rows (`rows` or `csv`, human amounts) and groups them; build each transfer batch with `payouts().transfers` and quote routed rows with `purpose: "payout"`. See [Split the bill](/guides/split-the-bill), [Tip jar](/guides/tip-jar) and [Bulk payouts](/guides/bulk-payouts).

## How do I set up recurring buys?

`recurring_orders().create` builds a Solana recurring order (Jupiter Recurring, no LayerHop fee): `amount` spent in `orders` buys every `interval_seconds`. Sign `tx` with the wallet (sign only), then `submit(request_id, signed)`. `list` reads a wallet's orders (`active` or `history`); `cancel(id, wallet)` returns a tx to sign and submit the same way. See [Limit and recurring orders](/guides/limit-and-recurring-orders).

## How do I check LayerHop's status?

`service_status()` returns the data behind [status.layerhop.com](/guides/status-and-monitoring): `status` (`operational`, `degraded` or `outage`), `components` with 90-day uptime, and recent `incidents`.

## How do I get live order status?

`stream_order` reads the order's [Server-Sent Events stream](/guides/live-status) instead of polling. It yields the order now and on every change, and ends when the order is final. `checkout().stream(id)` does the same for a checkout session.

```rust
let mut orders = Box::pin(lh.stream_order(&quote_id));
while let Some(order) = orders.next().await {
    let order = order?; // Error::Api (ORDER_NOT_FOUND), Error::Http or Error::Decode
    println!("{:?} {:?}", order.status, order.dst_tx_hash);
}
```

The request is sent on the first poll; dropping the stream closes the connection. A client-wide `reqwest` timeout also applies to streams, so leave it unset for long-lived ones.

## How do I stream live quotes?

`quote_stream` reads [`GET /v1/quote/stream`](/guides/live-quotes): a ranked quote set at once, then whenever the best route or any amount changes (and before the shown quote expires), for up to 5 minutes. Each refresh counts against your rate limit. A failed refresh (`NO_ROUTE`, `RATE_LIMITED`, `ADDRESS_SANCTIONED`, …) yields one `Error::Api`, then the stream ends.

```rust
let mut quotes = Box::pin(lh.quote_stream(&params, &QuoteStreamOptions { interval_ms: Some(10_000) }));
while let Some(update) = quotes.next().await {
    let update = update?;
    println!("#{} {}", update.seq, update.response.best.dst_amount);
}
```

`quote_stream_exact_output` takes `ExactOutputQuoteParams` (`dst_amount`); those quotes carry `src_amount` and `src_amount_max`.

## How do I screen addresses?

`lh.screen(&[..])` checks up to 100 addresses against the OFAC SDN list ([Address screening](/guides/address-screening)). Quotes and checkout quotes carry `screening` with any listed address of the request; where screening is enforced, listed addresses fail with `ADDRESS_SANCTIONED` (HTTP 451).

## How do I charge per request with x402?

`lh.x402()` wraps the [x402 facilitator](/guides/x402): `requirements` returns what to answer `402 Payment Required` with (`accepts`, `accepts_v1`, `payment_required`), `verify` and `settle` take the payer's decoded header as an `X402FacilitatorRequest`, and `payments().list(..)` / `get(id)` read settled payments (`x402.payment.settled` fires for each).

## How do I test webhooks locally?

With an API key, `webhooks().stream()` yields your account's webhook events (in the key's mode) as `WebhookEvent`s as they are created. `webhooks().trigger(event_type)` creates a sample event; it needs an `lh_test_` key. See [Test webhooks locally](/guides/live-status#test-webhooks-locally).

```rust
let lh = LayerHop::builder().api_key("lh_test_...").build();
lh.webhooks().trigger("order.filled").await?;
let mut events = Box::pin(lh.webhooks().stream());
while let Some(event) = events.next().await {
    let event = event?;
    println!("{} {:?}", event.event_type, event.data.order);
}
```

After a disconnect, `webhooks().stream_since(&last.created_at)` replays the missed events first (at most an hour back). `webhooks().resend(event_id, None)` sends an event again to your endpoints and open streams. `usage().get(..)` and `usage().errors(..)` return the key's request counts, latency and recent failed requests.

## How do I use test mode?

Pass an `lh_test_` key instead of a live one; nothing else changes. Requests are served by the `sandbox` provider, responses carry `livemode: false`, and built transactions have `sandbox: Some(true)` (never broadcast them; report any hash). The last digits of the amount choose the outcome: `…4001` refunds, `…4002` fails, `…4004` returns `NO_ROUTE`. See [Test mode](/guides/test-mode).

## How are errors reported?

`layerhop::Error::Api { code, message, status, request_id, details }` for non-2xx responses, where `code` is one of the stable [error codes](/errors) and `details` the raw `error.details` JSON; `err.code()` returns the code. The other variants are `Error::Http` (transport), `Error::Decode` (unexpected body), `Error::Timeout` (`watch`) and `Error::Usage` (e.g. `build_tx` on a gasless quote). Streams yield one error, then end.

Typed helpers read `details`: `err.suggestions()` returns the alternatives a live `NO_ROUTE` carries (`dst_token`, `src_token` or `via_hub` with its `hub` and two `steps`; malformed entries dropped, at most 4), `err.amount_too_small()` the route's `min_amount` on `AMOUNT_TOO_SMALL`, and `err.provider_errors()` why each provider had no quote. See [Error handling](/guides/error-handling).

```rust
match lh.quote(&params).await {
    Err(e) if e.code() == Some("NO_ROUTE") => for s in e.suggestions() { println!("{}", s.message) },
    other => { other?; }
}
```

## How do I verify webhooks?

```rust
layerhop::webhook::verify(&secret, &raw_body, signature_header)?; // 300 s tolerance
```

The header is `t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`. `webhook::verify_signature` takes an explicit tolerance and clock.

## What else should I know?

Unknown response fields are ignored and new values of string enums (`vm`, risk `level`, reason `code`, error `code`) decode as plain strings, so newer API versions never break older clients.
