Skip to main content

layerhop (Python SDK)

PyPI Python license docs

Best-price cross-chain and same-chain swaps through one non-custodial API. Sync and async clients on top of httpx, mirroring the TypeScript @layerhop/sdk.

The SDK never holds keys. It returns unsigned transactions. Your own wallet library (web3.py, eth-account, solders, a KMS, a hardware wallet…) signs and broadcasts them.

Install

pip install layerhop

Python 3.9+. The only runtime dependency is httpx.

Quickstart

Amounts are integer strings in base units (100 USDC = "100000000"), never floats.

from layerhop import LayerHop

lh = LayerHop(api_key="lh_live_...")  # api_key is optional

# 1. Quote: every provider is asked; `best` pays the user the most.
q = lh.quote("base", "USDC", "100000000", "solana", "SOL",
             sender="0xYourEvmAddress", recipient="YourSolanaAddress")
best = q["best"]
print(best["provider"], best["dstAmount"], best["estimatedSeconds"])

# 2. Build the unsigned transaction.
tx = lh.build_tx(best["quoteId"])

# 3. Sign and send with YOUR wallet library (example: web3.py on Base).
if tx["vm"] == "evm":
    # if tx.get("approval"): send ERC-20 approve(spender, amount) on approval["token"] first
    tx_hash = w3.eth.send_transaction({
        "to": tx["to"], "data": tx["data"], "value": int(tx["value"]), "chainId": tx["chainId"],
    }).hex()
else:
    # Solana: tx["serializedTx"] is a base64 VersionedTransaction; sign it with solders.
    # When tx.get("submitViaApi") is true, only sign, then: tx_hash = lh.submit(best["quoteId"], signed_b64)
    ...

# 4. Tell LayerHop you broadcast it (enables tracking, history and webhooks).
lh.report_submitted(best["quoteId"], tx_hash)

# 5. Track until filled / refunded / failed.
for s in lh.watch(best["provider"], tx_hash):
    print(s["state"], s.get("dstTxHash"))

Async

from layerhop import AsyncLayerHop

async with AsyncLayerHop() as lh:
    q = await lh.quote("base", "USDC", "100000000", "solana", "SOL", sender=s, recipient=r)
    async for st in lh.watch("relay", tx_hash):
        print(st["state"])

API

Method Endpoint
health() GET /v1/health
chains() GET /v1/chains
tokens(chain, *, q, limit, cursor) · tokens_page(chain, *, q, limit, cursor) GET /v1/tokens → the tokens · {tokens, nextCursor}
lookup_token(address, chain=None) GET /v1/tokens/lookup → the token (chain found by the API when omitted)
token_risk(chain, address) GET /v1/tokens/{chain}/{address}/risk → the risk
prices(ids) GET /v1/prices → {"chainId:address": usd}
balances(address, chains=None, *, tokens, fresh) GET /v1/balances
quote(src_chain, src_token, amount, dst_chain, dst_token, *, sender, recipient, slippage_bps=50, gas_on_arrival=None, gasless=False, referrer, copy_of, purpose, split_id, split_share, note, exclude_providers, exclude_bridges, exclude_exchanges) GET /v1/quote
quote_calls(src_chain, src_token, dst_chain, dst_token, dst_amount, *, sender, recipient, slippage_bps=50, calls, action, referrer, copy_of) POST /v1/quote (destination calls; without calls / action: receive an exact amount)
quotes.stream(src_chain, src_token, amount, dst_chain, dst_token, *, sender, recipient, dst_amount=None, interval_ms=None, …) GET /v1/quote/stream (SSE): yields live quote sets, raises LayerHopApiError on an error event
screen(addresses) POST /v1/screen (OFAC SDN list lookup, public)
build_tx(quote_id) POST /v1/orders → the tx (EVM, Solana or Tron)
build_gasless(quote_id) POST /v1/orders → the gasless typed data to sign
submit_gasless(quote_id, trade_signature, approval_signature=None) · gasless_status(quote_id) POST /v1/orders/gasless · GET /v1/orders/gasless/{quoteId}
simulate(quote_id) POST /v1/simulate (dry-run, records nothing)
submit(quote_id, signed_transaction) POST /v1/orders/submit (Solana submitViaApi only)
report_submitted(quote_id, tx_hash) POST /v1/orders/{quoteId}/submitted
status(provider, id) GET /v1/orders/{provider}/{id}
watch(provider, id, *, interval=3.0, timeout=1800) polls status, yields on change, stops when final
stream_order(quote_id) GET /v1/orders/{quoteId}/events (SSE), yields the order until final
list_orders(*, address, status, cursor, limit) GET /v1/orders
checkout.create(amount, settle_chain, settle_token, recipient, *, merchant_name, description, reference, metadata, success_url, cancel_url, expires_in_minutes, embed_origins) POST /v1/checkout/sessions
checkout.list(*, status, cursor, limit) GET /v1/checkout/sessions
checkout.get(id) GET /v1/checkout/sessions/{id} (public)
checkout.expire(id) POST /v1/checkout/sessions/{id}/expire
checkout.quote(id, src_chain, src_token, *, sender, slippage_bps=None) POST /v1/checkout/sessions/{id}/quote (public)
checkout.stream(id) GET /v1/checkout/sessions/{id}/events (SSE, public)
checkout.start_transfer(id) · checkout.start_bitcoin(id, *, refund_address) POST /v1/checkout/sessions/{id}/transfer · /bitcoin (public)
checkout.products.create(name, amount, settle_chain, settle_token, recipient, *, description, merchant_name, success_url, cancel_url, expires_in_minutes, allowed_origins, active) POST /v1/checkout/products
checkout.products.list(*, active, cursor, limit) GET /v1/checkout/products
checkout.products.get(id) GET /v1/checkout/products/{id} (public)
checkout.products.update(id, **fields) PATCH /v1/checkout/products/{id} (only the fields you pass)
checkout.products.start_session(id, *, reference, metadata) POST /v1/checkout/products/{id}/sessions (public)
checkout.refunds.create(session_id, *, amount, reason, from_, to) POST /v1/checkout/sessions/{id}/refunds
checkout.refunds.list(session_id) GET /v1/checkout/sessions/{id}/refunds
invoices.create(line_items, settle_chain, settle_token, recipient, *, customer_email, customer_name, merchant_name, memo, due_at, send) POST /v1/invoices
invoices.list(*, status, cursor, limit) · invoices.get(id) · invoices.update(id, **fields) GET /v1/invoices · GET/PATCH /v1/invoices/{id}
invoices.send(id) · invoices.void(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)
subscriptions.create(customer_email, interval, *, interval_count, product_id, amount, settle_chain, settle_token, recipient, description, customer_name, merchant_name, memo, days_until_due, start_at, metadata) POST /v1/subscriptions
subscriptions.list(*, status, customer_email, cursor, limit) · subscriptions.get(id) · subscriptions.update(id, **fields) GET /v1/subscriptions · GET/PATCH /v1/subscriptions/{id}
subscriptions.cancel(id, *, at_period_end) · subscriptions.pause(id) · subscriptions.resume(id) POST /v1/subscriptions/{id}/cancel · /pause · /resume
subscriptions.invoices(id) GET /v1/subscriptions/{id}/invoices → the invoices
deposit_addresses.create(src_chain, src_token, dst_chain, dst_token, recipient, refund_to, *, reusable, amount, label, metadata, integrator, integrator_fee_bps) POST /v1/deposit-addresses
deposit_addresses.list(*, status, label, cursor, limit) · deposit_addresses.get(id) GET /v1/deposit-addresses · GET /v1/deposit-addresses/{id}
deposit_addresses.refresh(id) · deposit_addresses.disable(id) POST /v1/deposit-addresses/{id}/refresh · /disable
deposit_addresses.simulate(id, amount) POST /v1/deposit-addresses/{id}/simulate (test keys only)
limit_orders.create(wallet, src_token, dst_token, amount, dst_amount, *, expires_at, chain, metadata, integrator, integrator_fee_bps) POST /v1/limit-orders
limit_orders.submit(id, signed_transaction) POST /v1/limit-orders/{id}/submit
limit_orders.list(*, wallet, status, cursor, limit) · limit_orders.get(id) GET /v1/limit-orders · GET /v1/limit-orders/{id}
limit_orders.cancel(id) POST /v1/limit-orders/{id}/cancel
limit_orders.simulate(id, outcome) POST /v1/limit-orders/{id}/simulate (test keys only)
recurring_orders.create(wallet, dst_token, amount, orders, interval_seconds, *, src_token, chain) POST /v1/recurring-orders
recurring_orders.submit(request_id, signed_transaction) · recurring_orders.list(wallet, *, status, page) POST /v1/recurring-orders/submit · GET /v1/recurring-orders
recurring_orders.cancel(id, wallet) POST /v1/recurring-orders/{id}/cancel
splits.create(recipient, chain, token, total, *, participants, shares, note) · splits.get(id) POST /v1/splits · GET /v1/splits/{id}
splits.update(id, edit_token, *, note, labels, status) PATCH /v1/splits/{id} (x-edit-token)
tip_jars.get(address) GET /v1/tip-jars/{address}
payouts.plan(src_chain, src_token, sender, *, rows, csv) · payouts.transfers(chain, token, sender, transfers) POST /v1/payouts/plan · /v1/payouts/transfers
service_status() GET /v1/status (platform status, public)
webhooks.stream(*, since) GET /v1/webhooks/stream (SSE, API key; since replays up to an hour)
webhooks.trigger(type) POST /v1/webhooks/trigger (test keys only)
webhooks.resend(event_id, *, endpoint_id) POST /v1/webhooks/events/{id}/resend
usage.get(*, bucket, from_, to, key_id) · usage.errors(*, code, key_id, limit) GET /v1/usage · GET /v1/usage/errors → the errors
x402.supported() · x402.requirements(amount, pay_to, resource, *, network, description, mime_type, max_timeout_seconds) GET /v1/x402/supported · POST /v1/x402/requirements
x402.verify(payment_payload, payment_requirements, *, x402_version) · x402.settle(…) POST /v1/x402/verify · /settle
x402.payments.list(*, status, cursor, limit) · x402.payments.get(id) GET /v1/x402/payments · /v1/x402/payments/{id}

Client options: base_url (default https://api.layerhop.com), api_key (sent as x-api-key), channel (default "api"), integrator, integrator_fee_bps, timeout, stream_timeout (read timeout of streams; None, the default, waits forever), and http_client / transport for custom httpx setups or tests.

Responses are plain dicts typed with TypedDict (keys keep the API's camelCase), so new fields never break you.

Gas on arrival

Pass gas_on_arrival=True to also deliver $2 of native gas to the recipient on the destination chain, or a USD amount from 0.5 to 20 (gas_on_arrival=5). Quotes that include it carry gasOnArrival (amount, token, symbol, decimals, usd); its cost is already taken out of dstAmount. It is ignored for same-chain swaps, non-EVM destinations and native outputs, and providers that can't do it ignore it, so check the quote.

q = lh.quote("solana", "USDC", "100000000", "base", "USDC",
             sender="YourSolanaAddress", recipient="0xYourEvmAddress", gas_on_arrival=True)
goa = q["best"].get("gasOnArrival")
if goa:
    print(goa["amount"], goa["symbol"], goa.get("usd"))  # e.g. 800000000000000 ETH 2.0

Tron transactions

On a Tron route, build_tx returns a TronTx (tx["vm"] == "tvm", chainId 728126428, TRON_CHAIN_ID). The SDK never signs: sign tx["unsigned"] unchanged with a Tron wallet (TronWeb, TronLink), send tx["approval"] first when present (its own transaction), broadcast before raw_data["expiration"], then report the main transaction's txID (bare 64-hex, no 0x). simulate reports energyUsed for Tron.

tx = lh.build_tx(quote_id)
if tx["vm"] == "tvm":
    if tx.get("approval"):
        ...  # sign and broadcast tx["approval"]["unsigned"] first
    # sign and broadcast tx["unsigned"] with your Tron wallet, then:
    lh.report_submitted(quote_id, tx["unsigned"]["txID"])

Gasless swaps

gasless=True asks for a swap where the wallet signs EIP-712 typed data instead of sending a transaction, and the provider's relayer takes the network fee from the input token (ERC-20 input, same EVM chain, when the deployment enables it). build_tx raises ValueError on a gasless quote.

q = lh.quote("base", "USDC", "100000000", "base", "WETH", sender=addr, recipient=addr, gasless=True)
g = lh.build_gasless(q["best"]["quoteId"])            # {"chainId", "approval"?, "trade", "gasFee"?}
approval_sig = sign_typed_data(g["approval"]["eip712"]) if g.get("approval") else None  # your wallet
trade_sig = sign_typed_data(g["trade"]["eip712"])     # sign the typed data unchanged
lh.submit_gasless(q["best"]["quoteId"], trade_sig, approval_sig)
lh.gasless_status(q["best"]["quoteId"])               # poll until "filled" or "failed"

Destination calls

quote_calls asks for an exact output that contract calls on the destination chain then use, run by the provider's executor (it is the calls' msg.sender). Send calls or an action preset. Quotes carry srcAmount (what the sender pays) and calls (the plan and its simulation).

q = lh.quote_calls("arbitrum", "USDC", "base", "USDC", "100000000",  # exactly 100 USDC on Base
                   sender="0xYou", recipient="0xYou", action={"type": "aave-v3-supply"})
print(q["best"]["srcAmount"], q["best"]["calls"]["executor"])

Referrals, tips and splits on a quote

quote also takes referrer and copy_of (referral attribution only), and purpose (tip, split, payout, gather, rebalance, fund), split_id + split_share and note (140 characters), recorded on the order. None of them change the fee or the route.

Tokens, prices and balances

lh.tokens("base", q="usd")                           # one page of tokens
page = lh.tokens_page("base", limit=50)              # {"tokens", "nextCursor"}
lh.lookup_token("0x4200000000000000000000000000000000000006")          # chain found by the API
lh.lookup_token("0x4200000000000000000000000000000000000006", "base")
risk = lh.token_risk("base", "0x532f27101965dd16442E59d40670FaF5eBB142E4")
if risk["level"] == "danger":
    ...  # show risk["reasons"] and ask for an explicit confirmation
lh.prices(["8453:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"])   # {"8453:0x8335...": 1.0}
lh.balances("0xYou", ["base", "arbitrum"], fresh=True)        # balances, totalUsd, errors

Chains from chains() may carry destinationOnly (hide them from source pickers), onlyRoute (the one route into the chain) and routeHealth (health["in"], health["out"], status).

Splits, tip jars and payouts

Public, no API key. A split divides a bill into shares that anyone pays with a normal quote (purpose="split", split_id, split_share). Keep the editToken from create: it is shown once.

s = lh.splits.create("alice.eth", "base", "USDC", "120000000", participants=4, note="Dinner")
lh.splits.update(s["id"], s["editToken"], status="closed")   # note=None clears the note
lh.splits.get(s["id"])["shares"]                              # unpaid / partial / paid
lh.tip_jars.get("0xCreator")                                  # tippers, tips, messages

Payouts: plan checks rows (amounts in human units, e.g. "25") and groups them; transfers builds unsigned batch transfers (EVM calls or a Solana serializedTx). The SDK never signs.

plan = lh.payouts.plan("base", "USDC", "0xPayer",
                       rows=[{"recipient": "bob.eth", "amount": "25", "token": "USDC", "chain": "base"}])
t = lh.payouts.transfers("base", "USDC", "0xPayer", [{"recipient": "0x3333...", "amount": "25000000"}])

Recurring orders (Solana)

Recurring buys through Jupiter Recurring (beta, no LayerHop fee). create returns an unsigned tx and a requestId: have the wallet sign it (sign only), then submit.

b = lh.recurring_orders.create("UserSolanaWallet", "SOL", "700000000", 7, 86400)  # 7 daily buys, 700 USDC
lh.recurring_orders.submit(b["requestId"], signed_b64)        # {"txHash", "order"}
lh.recurring_orders.list("UserSolanaWallet", status="active")
c = lh.recurring_orders.cancel(order_id, "UserSolanaWallet")  # sign c["tx"], submit with c["requestId"]

Live order status

stream_order follows an order over Server-Sent Events instead of polling: it yields the order now and on every change, and ends once it is final (filled, refunded, failed, expired or dropped). checkout.stream(id) does the same for a checkout session (until paid, expired or needs_review).

for order in lh.stream_order(best["quoteId"]):
    print(order["status"], order.get("dstTxHash"))

# async
async for session in alh.checkout.stream(session_id):
    print(session["status"])

The request is sent when iteration starts; break out of the loop to close the connection. A missing order raises LayerHopApiError (ORDER_NOT_FOUND). Guide: https://docs.layerhop.com/guides/live-status

Live quotes

quotes.stream (GET /v1/quote/stream) yields a fresh ranked quote set (the quote response plus seq) whenever the best route or an amount changes, and before the shown quote expires. It ends after 5 minutes; a failed refresh raises LayerHopApiError (NO_ROUTE, RATE_LIMITED, ADDRESS_SANCTIONED, …). Each refresh counts as one request against your rate limit (default every 10 s, interval_ms at least 5000); at most 3 open streams per key. Pass amount=None, dst_amount="…" for exact output.

for update in lh.quotes.stream("base", "USDC", "100000000", "solana", "SOL", sender=a, recipient=b):
    show(update["best"])  # any quoteId is buildable with build_tx

# async
async for update in alh.quotes.stream("base", "USDC", None, "arbitrum", "USDC", sender=a, recipient=a,
                                      dst_amount="5000000", interval_ms=15000):
    ...

Guide: https://docs.layerhop.com/guides/live-quotes

Address screening

lh.screen([...]) checks up to 100 addresses against the OFAC SDN list (public, a list lookup only). Quotes and checkout quotes carry screening (the listed addresses of the request) once the API has the list loaded; where the API enforces screening, listed addresses get ADDRESS_SANCTIONED (HTTP 451).

r = lh.screen(["0x098B716B8Aaf21512996dC57EB0615e2383E2f96"])
r["results"][0]["sanctioned"], r["list"], r["enforced"]

Checkout (pay with any token)

Get paid in USDC or USDT on the chain you choose while the customer pays with any token on any chain. Create a session with your API key and send the customer to its hosted url; the session becomes paid (and a checkout.session.completed webhook fires) once the delivery is verified on chain.

lh = LayerHop(api_key="lh_live_...")

session = lh.checkout.create("49000000", "base", "USDC", "0xYourPayoutAddress",  # 49 USDC
                             description="Pro plan, 1 month", reference="order_1042",
                             success_url="https://shop.example.com/thanks")
print(session["url"])  # redirect the customer here

lh.checkout.get(session["id"])["status"]  # open | processing | paid | expired | needs_review
lh.checkout.list(status="paid", limit=20)
lh.checkout.expire(session["id"])         # cancel an open session

Building your own payment page instead? get and quote are public (no key needed):

q = lh.checkout.quote(session_id, "arbitrum", "ETH", sender=payer_address)
best = q["best"]  # best["srcAmount"] is what the payer sends; dstAmountMin >= amount due
tx = lh.build_tx(best["quoteId"])
# ... the payer's wallet signs and broadcasts tx ...
lh.report_submitted(best["quoteId"], tx_hash)

Sessions also carry the hosted page's other payment methods: transferAvailable / transfer ("Send to address" QR, checkout.start_transfer(id)), bitcoinAvailable / bitcoin ("Pay with Bitcoin", checkout.start_bitcoin(id, refund_address=…)) and payment["method"] (wallet or transfer; a transfer has no quoteId). embed_origins on create limits which sites may embed the session.

The async client has the same methods under await lh.checkout.…. Guide: https://docs.layerhop.com/guides/checkout

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: the backing for payment buttons, https://layerhop.com/buy/{id} links and store plugins. create, list and update need your API key; get and start_session are public.

product = lh.checkout.products.create("Pro plan", "49000000", "base", "USDC", "0xYourPayoutAddress",
                                      description="1 month", success_url="https://shop.example.com/thanks",
                                      allowed_origins=["https://shop.example.com"])
print(product["url"])  # https://layerhop.com/buy/prod_...: share it or put it behind a button

lh.checkout.products.list(active=True)
lh.checkout.products.update(product["id"], active=False)  # stops new sessions; only passed fields change

# Public (no key): start a session on the product's terms, adding only your order id.
session = LayerHop().checkout.products.start_session(product["id"], reference="order_1042")
print(session["url"], session["productId"])

update sends only the fields you pass; pass None to clear a nullable field such as description. Guide: https://docs.layerhop.com/guides/payment-buttons

Invoices

Bill a customer by email for one or more line items; they pay with any token on the hosted page https://layerhop.com/invoice/{id} and get a receipt (with a PDF) once it is paid. create, get, list, update, send and void need an API key; public_view and pay are public.

inv = lh.invoices.create(
    [{"description": "Design work (hours)", "quantity": 10, "unitAmount": "80000000"}],  # 10 x 80 USDC
    "base", "USDC", "0xYourPayoutAddress",
    customer_email="ap@client.example", customer_name="Client Co", due_at="2026-11-01",
    send=True,  # finalize and email now (otherwise it stays a draft you can update)
)
print(inv["number"], inv["url"])  # INV-0001 https://layerhop.com/invoice/inv_...

lh.invoices.list(status="open")
lh.invoices.send(inv["id"])   # re-sends the email of an open invoice
lh.invoices.void(inv["id"])   # draft or open only
# Fulfil on the invoice.paid webhook. Statuses: draft, open, paid, void.

Subscriptions

Recurring billing. Crypto can't be pulled from a wallet, so LayerHop issues and emails an invoice every period and the customer pays it with any token. Unpaid past the due date, the subscription turns past_due (reminders on day 1 and 3) and is canceled after 7 days. Everything needs an API key.

sub = lh.subscriptions.create(
    "ada@example.com", "month",  # interval: day, week, month or year
    amount="49000000", settle_chain="base", settle_token="USDC", recipient="0xYourPayoutAddress",
    description="Pro plan",      # or product_id="prod_..." instead of these five
    interval_count=1, days_until_due=3,
)
print(sub["status"], sub["nextInvoiceAt"])

lh.subscriptions.update(sub["id"], amount="59000000")         # applies from the next invoice
lh.subscriptions.cancel(sub["id"], at_period_end=True)         # or cancel(id) to cancel now
lh.subscriptions.update(sub["id"], cancel_at_period_end=False)  # undo the scheduled cancel
lh.subscriptions.pause(sub["id"]); lh.subscriptions.resume(sub["id"])
lh.subscriptions.invoices(sub["id"])  # its invoices (with subscriptionId), newest first
lh.subscriptions.list(status="past_due")

Statuses: active, past_due, paused, canceled. Webhooks: subscription.created, subscription.renewed (a period's invoice was issued, with data.invoice), subscription.past_due and subscription.canceled; the period invoices send the usual invoice.paid.

Deposit addresses

Let a user swap or bridge by just sending tokens to an address: no wallet connection, no signing in your app. The provider (Relay) owns the address and delivers dst_token to recipient; LayerHop never holds the funds. Each detected deposit becomes an order with depositAddressId set and the usual order.* webhooks. Everything needs an API key.

da = lh.deposit_addresses.create(
    "base", "USDC", "arbitrum", "USDC",
    "0xRecipientOnArbitrum", "0xUserRefundAddressOnBase",  # refund_to: never a CEX deposit address
    label="user_42",  # reusable=True by default; reusable=False + amount = one-time address
)
print(da["address"], da["estimate"]["dstAmount"])  # show the address to your user

lh.deposit_addresses.refresh(da["id"])            # "I sent it": check for deposits now
lh.deposit_addresses.get(da["id"])["deposits"]    # its 20 most recent deposits (orders)
lh.deposit_addresses.list(label="user_42")
lh.deposit_addresses.disable(da["id"])

Live mode may be disabled by the operator: create with a live key then raises a LayerHopApiError with code FORBIDDEN. Test keys always work, and lh.deposit_addresses.simulate(da["id"], "25000000") records a test deposit that settles like any test order. Deposits under $1 may not be processed.

Limit orders (Solana)

Sell a token at your price or better (Jupiter Trigger, beta). The order lives on chain; the user's wallet signs it and keeps custody. Each fill becomes an order with limitOrderId set. An API key is optional (without one, list needs wallet).

lo = lh.limit_orders.create(
    "UserSolanaWallet", "SOL", "USDC",
    "1000000000", "200000000",  # sell 1 SOL for at least 200 USDC (worth at least $5)
    expires_at=None,            # unix seconds, or None for good-till-cancelled
)
# lo["tx"]["serializedTx"]: base64 VersionedTransaction. Only SIGN it (submitViaApi), then:
r = lh.limit_orders.submit(lo["id"], signed_b64)  # {"limitOrder": {... "status": "open"}, "txHash"}

lh.limit_orders.get(lo["id"])["fills"]            # its fills (orders), newest first
lh.limit_orders.list(wallet="UserSolanaWallet", status="open")
c = lh.limit_orders.cancel(lo["id"])               # c["tx"]: sign and submit it the same way
                                                   # (None when the order was never submitted)

Statuses: built, open, filled, cancelled, expired, failed. Webhooks: limit_order.opened, limit_order.filled (with the fill in data.fill), limit_order.cancelled, limit_order.expired, limit_order.failed. Our fee applies when dst_token is SOL, USDC or USDT.

Live mode may be disabled by the operator: create with a live key (or no key) then raises a LayerHopApiError with code FORBIDDEN. Test keys always work, and lh.limit_orders.simulate(lo["id"], "fill") (or "partial_fill", "expire") settles an open test order.

Refunds

Refunds are non-custodial: you sign them from your own wallet. create returns a quote that you build, sign from quote["from"] (by default the session's payout address) and report; the refund goes back to the payer's original chain and token (to="original", the default) or as the settlement token (to="settlement"). Leave out amount to refund everything not yet refunded.

r = lh.checkout.refunds.create("cs_...", amount="10000000", reason="Partial refund")
tx = lh.build_tx(r["quote"]["quoteId"])   # sign and broadcast from r["quote"]["from"]
lh.report_submitted(r["quote"]["quoteId"], tx_hash)
lh.checkout.refunds.list("cs_...")        # pending -> submitted -> completed (or failed)
# The session's refundedAmount grows and checkout.session.refunded is sent.

Platform status

lh.service_status() returns GET /v1/status, the data behind status.layerhop.com: the overall status (operational, degraded or outage), each component with its 90-day uptime, and the last 14 days of incidents. lh.status(provider, id) is still the provider order status.

Test mode

Use an lh_test_ key exactly like a live key: everything is served by the sandbox provider, responses carry livemode: False, and built transactions have sandbox: True (never broadcast them; report any hash with report_submitted). The last digits of amount pick the outcome: …4001 refunds, …4002 fails, …4004 returns NO_ROUTE. Checkout sessions created with a test key (cs_test_…) are paid through the sandbox too. See https://docs.layerhop.com/guides/test-mode

Errors

Every non-2xx response raises LayerHopApiError with a stable code (QUOTE_EXPIRED, NO_ROUTE, …), status, message and request_id. See https://docs.layerhop.com/errors/<code>.

from layerhop import LayerHopApiError
try:
    lh.build_tx(quote_id)
except LayerHopApiError as e:
    if e.code == "QUOTE_EXPIRED":
        ...  # re-quote

e.details is the raw error.details object (or None). On NO_ROUTE, e.suggestions() lists alternative routes that quoted (dst_token, src_token or via_hub with hub and two steps), validated and at most 4. On AMOUNT_TOO_SMALL, e.min_amount (base units), e.min_amount_usd and e.min_amount_approx give the route's minimum when known. e.provider_errors() lists why each provider returned no quote.

try:
    lh.quote("base", "USDC", "1000000", "blast", "ETH", sender=a, recipient=b)
except LayerHopApiError as e:
    for s in e.suggestions():
        print(s["kind"], s["message"])  # e.g. "Receive USDC on Ethereum instead"

Webhooks

from layerhop import verify_webhook_signature, construct_webhook_event

# Flask example — use the RAW body
ok = verify_webhook_signature(secret, request.get_data(), request.headers.get("LayerHop-Signature"))
event = construct_webhook_event(secret, request.get_data(), request.headers.get("LayerHop-Signature"))

The header is t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>. Signatures older or newer than 300 s (tolerance) are rejected; comparison is constant-time.

Webhook tools

With an API key, webhooks.stream() yields your account's webhook events (in the key's live or test mode) as they are created, with the exact payloads your endpoints receive. webhooks.trigger creates a sample event in test mode (test keys only; a live key raises FORBIDDEN).

lh = LayerHop(api_key="lh_test_...")
r = lh.webhooks.trigger("order.filled")  # {"eventId", "deliveries", "payload"}
for event in lh.webhooks.stream(since="2026-11-04T09:30:00Z"):  # replays missed events first
    print(event["type"], event["data"])
lh.webhooks.resend("evt_...")            # to subscribed endpoints (or endpoint_id=...) and open streams

Usage

usage.get() returns the key's requests per hour or day (status classes, p50 / p95 latency, endpoint groups, error codes); usage.errors(code="NO_ROUTE") the newest failed requests with their requestId.

x402 pay-per-request

LayerHop is an x402 facilitator: charge USDC per HTTP request, paid to your own fee-splitting deposit address (the payer pays the fee on top). Answer an unpaid request with 402 and the requirements, then verify and settle the X-PAYMENT / PAYMENT-SIGNATURE header (base64 JSON):

req = lh.x402.requirements("10000", "0xYourWallet", "https://api.example.com/weather")  # 0.01 USDC net
# 402 body: {"x402Version": 1, "error": "...", "accepts": req["acceptsV1"]}
payload = json.loads(base64.b64decode(request.headers["X-PAYMENT"]))
if lh.x402.verify(payload, req["acceptsV1"][0])["isValid"]:
    ...  # serve the request
    lh.x402.settle(payload, req["acceptsV1"][0])
lh.x402.payments.list(status="settled")

Guide: https://docs.layerhop.com/guides/x402

Development

python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest

MIT licensed.

Metadata

Release files for layerhop 0.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for layerhop 0.9.0
File Size Uploaded Provenance Actions
layerhop-0.9.0.tar.gz 84.2 kB Without provenance Details for layerhop-0.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for layerhop 0.9.0
File Interpreter ABI Platform Actions
layerhop-0.9.0-py3-none-any.whl Python 3 none any Details for layerhop-0.9.0-py3-none-any.whl

Total release size: 135.7 kB

Release files / layerhop-0.9.0.tar.gz

Download URL layerhop-0.9.0.tar.gz
Size 84.2 kB
Tags Source
SHA-256 checksum
How to use checksums
bba026b0c9eb04e01330b7361073380ec5379d0aac136a0b26183f72421065c6
BLAKE2b-256 checksum
How to use checksums
399b396d87393afd4d2898d8e74c1bdd8527073acbad6fad254e374efc122bbb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / layerhop-0.9.0-py3-none-any.whl

Download URL layerhop-0.9.0-py3-none-any.whl
Size 51.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
73db7180855efa63f39d30876a5ffc3646e6bab2cdc8571e02bf0e57224ac10b
BLAKE2b-256 checksum
How to use checksums
f045692fbd718c8b30d47d1971290553fb2527b6a2ba6610b64368a56cd4d2aa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for layerhop 0.9.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page