LayerHopDocsLaunch app (opens in a new tab)

Python SDK

The layerhop Python package — sync and async httpx clients for quotes, transactions, order tracking and webhook verification.

layerhop is the Python client for the LayerHop REST API, with a sync LayerHop and an async AsyncLayerHop class that mirror the TypeScript SDK. It needs Python 3.9+ and depends only on httpx.

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

How do I install it?#

Terminal
pip install layerhop

Quickstart#

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

Python
from layerhop import LayerHop

lh = LayerHop()  # LayerHop(api_key="...", integrator="myapp", base_url="http://localhost:8787")

# 1. Quote
q = lh.quote("base", "USDC", "100000000", "solana", "SOL",
             sender="0xYourEvmAddress", recipient="YourSolanaAddress")
best = q["best"]

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

# 3. Sign + send with YOUR wallet library (web3.py shown)
if tx["vm"] == "evm":
    # send tx["approval"] first when present
    tx_hash = w3.eth.send_transaction({"to": tx["to"], "data": tx["data"],
                                       "value": int(tx["value"]), "chainId": tx["chainId"]}).hex()

# 4. Report the broadcast (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"])

For Solana, tx["serializedTx"] is a base64 VersionedTransaction; sign it with solders. When tx.get("submitViaApi") is true, only sign it and call lh.submit(quote_id, signed_b64) (why).

Async:

Python
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(q["best"]["provider"], tx_hash):
        print(st["state"])

Which methods are available?#

Method Endpoint
health() · chains() GET /v1/health · /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) · token_risk(chain, address) GET /v1/tokens/lookup · GET /v1/tokens/{chain}/{address}/risk
prices(ids) · balances(address, chains=None, *, tokens, fresh) GET /v1/prices · GET /v1/balances
quote(src_chain, src_token, amount, dst_chain, dst_token, *, sender, recipient, slippage_bps=50, gas_on_arrival, gasless, referrer, copy_of, purpose, split_id, split_share, note) GET /v1/quote
quote_calls(src_chain, src_token, dst_chain, dst_token, dst_amount, *, sender, recipient, calls, action, …) POST /v1/quote (destination calls; without them: 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 until the stream ends
screen(addresses) POST /v1/screen (OFAC SDN list lookup)
build_tx(quote_id) POST /v1/orders → the tx (EVM, Solana or Tron)
build_gasless(quote_id) · submit_gasless(quote_id, trade_signature, approval_signature=None) · gasless_status(quote_id) POST /v1/orders → the gasless · POST /v1/orders/gasless · GET /v1/orders/gasless/{quoteId}
simulate(quote_id) POST /v1/simulate
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 and yields on each change until final
stream_order(quote_id) GET /v1/orders/{quoteId}/events (SSE): yields the Order now and on each change until final
list_orders(*, address, status, cursor, limit) GET /v1/orders
checkout.create(amount, settle_chain, settle_token, recipient, *, …) POST /v1/checkout/sessions
checkout.list(*, status, cursor, limit) · checkout.get(id) GET /v1/checkout/sessions · /v1/checkout/sessions/{id}
checkout.expire(id) · checkout.quote(id, src_chain, src_token, *, sender, slippage_bps=None) 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, *, refund_address) POST /v1/checkout/sessions/{id}/transfer · /bitcoin (public)
checkout.products.create(name, amount, settle_chain, settle_token, recipient, *, …) POST /v1/checkout/products
checkout.products.list(*, active, cursor, limit) · checkout.products.get(id) GET /v1/checkout/products · /v1/checkout/products/{id}
checkout.products.update(id, **fields) · checkout.products.start_session(id, *, reference, metadata) PATCH /v1/checkout/products/{id} · POST /v1/checkout/products/{id}/sessions
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)
recurring_orders.create(wallet, dst_token, amount, orders, interval_seconds, *, src_token, chain) POST /v1/recurring-orders
recurring_orders.submit(request_id, signed_transaction) · .list(wallet, *, status, page) · .cancel(id, wallet) POST /v1/recurring-orders/submit · GET /v1/recurring-orders · POST /v1/recurring-orders/{id}/cancel
splits.create(recipient, chain, token, total, *, participants, shares, note) · splits.get(id) · splits.update(id, edit_token, *, note, labels, status) POST /v1/splits · GET/PATCH /v1/splits/{id}
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) · webhooks.trigger(type) GET /v1/webhooks/stream (SSE) · POST /v1/webhooks/trigger (test keys)
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
x402.supported() · x402.requirements(amount, pay_to, resource, *, network, …) GET /v1/x402/supported · POST /v1/x402/requirements
x402.verify(payment_payload, payment_requirements) · 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}

Options: base_url, api_key (sent as x-api-key), channel, integrator, integrator_fee_bps, timeout, stream_timeout (read timeout of streams, none by default), http_client / transport. Responses are dicts typed with TypedDict, with the API's camelCase keys.

How do I sign a Tron transaction?#

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

Python
tx = lh.build_tx(quote_id)
if tx["vm"] == "tvm":
    # sign + broadcast tx["approval"]["unsigned"] first when present, then tx["unsigned"]
    lh.report_submitted(quote_id, tx["unsigned"]["txID"])

How do I make a gasless swap?#

Pass gasless=True to quote (ERC-20 input, same EVM chain). 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. build_tx raises ValueError on a gasless quote.

Python
q = lh.quote("base", "USDC", "100000000", "base", "WETH", sender=addr, recipient=addr, gasless=True)
g = lh.build_gasless(q["best"]["quoteId"])     # sign g["approval"]["eip712"] (if any) and g["trade"]["eip712"] unchanged
lh.submit_gasless(q["best"]["quoteId"], trade_sig, approval_sig)
lh.gasless_status(q["best"]["quoteId"])        # poll until "filled" or "failed"

How do I run calls on the destination chain?#

quote_calls asks for an exact output (dst_amount) that contract calls (or an action preset such as {"type": "aave-v3-supply"}) then use on the destination chain, run by the provider's executor. Quotes carry srcAmount (what the sender pays) and the calls plan with its simulation.

Python
q = lh.quote_calls("arbitrum", "USDC", "base", "USDC", "100000000",
                   sender="0xYou", recipient="0xYou", action={"type": "aave-v3-supply"})

quote also takes referrer and copy_of (referral attribution only), and purpose, split_id + split_share and note, recorded on the order. None of them change the fee.

How do I look up tokens, prices and balances?#

Python
lh.tokens_page("base", q="usd", limit=50)         # {"tokens", "nextCursor"}; tokens(...) returns the list
lh.lookup_token("0x4200000000000000000000000000000000000006")   # the API finds the chain
risk = lh.token_risk("base", "0x532f27101965dd16442E59d40670FaF5eBB142E4")  # level: ok / caution / danger / unknown
lh.prices(["8453:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"])
lh.balances("0xYou", ["base", "arbitrum"], fresh=True)

Show a danger risk prominently and ask for an explicit confirmation before a buy. Chains may carry destinationOnly, onlyRoute and routeHealth (read health["in"]). See Chains, tokens, prices and balances.

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

All public. A split's shares are paid with normal quotes (purpose="split", split_id, split_share); keep the editToken from create, it is shown once. Payout transfers are unsigned: the SDK never signs.

Python
s = lh.splits.create("alice.eth", "base", "USDC", "120000000", participants=4)
lh.splits.update(s["id"], s["editToken"], status="closed")   # sent as x-edit-token; note=None clears the note
lh.tip_jars.get("0xCreator")
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"}])

How do I set up recurring buys?#

Solana recurring buys (Jupiter Recurring, beta, no LayerHop fee). create returns an unsigned tx and a requestId: sign only, then submit.

Python
b = lh.recurring_orders.create("UserSolanaWallet", "SOL", "700000000", 7, 86400)  # 7 daily buys
lh.recurring_orders.submit(b["requestId"], signed_b64)
lh.recurring_orders.list("UserSolanaWallet", status="history")

How do I take payments with checkout?#

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

Python
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")
# 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
q = lh.checkout.quote(session["id"], "arbitrum", "ETH", sender=payer_address)
tx = lh.build_tx(q["best"]["quoteId"])  # q["best"]["srcAmount"] 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, https://layerhop.com/buy/{id} links and store plugins. lh.checkout.products (and await lh.checkout.products… on AsyncLayerHop) wraps the product endpoints: create, list and update need an API key; get and start_session are public.

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

lh.checkout.products.update(product["id"], active=False)  # only the fields you pass; None clears a nullable one

# Public (no key): a session on the product's terms, plus your order id
session = LayerHop().checkout.products.start_session(product["id"], reference="order_1042")
# session["productId"] == product["id"]; send the payer to session["url"]

How do I send invoices?#

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.

Python
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.

How do I refund a payment?#

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.

Python
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.

How do I read the 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.

How do I get live order status?#

stream_order reads the order's Server-Sent Events stream 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. On AsyncLayerHop, use async for.

Python
for order in lh.stream_order(quote_id):
    print(order["status"], order.get("dstTxHash"))  # ends after filled / refunded / failed / expired / dropped

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

Break out of the loop to close the connection. An unknown order raises LayerHopApiError (ORDER_NOT_FOUND).

How do I stream live quotes?#

quotes.stream reads GET /v1/quote/stream: it yields a fresh quote set (the quote response plus seq) whenever the best route or an amount changes, and ends after 5 minutes. A failed refresh raises LayerHopApiError with its stable code (NO_ROUTE, RATE_LIMITED, ADDRESS_SANCTIONED, …). Each refresh counts against your rate limit.

Python
for update in lh.quotes.stream("base", "USDC", "100000000", "solana", "SOL", sender=s, recipient=r, interval_ms=10000):
    show(update["best"])

How do I screen addresses?#

lh.screen(addresses) checks up to 100 addresses against the OFAC SDN list (Address screening). Quotes and checkout quotes carry screening once the API has the list loaded; where screening is enforced, listed addresses get ADDRESS_SANCTIONED (HTTP 451).

How do I charge per request with x402?#

lh.x402.requirements(price, pay_to, resource) returns the requirements to answer 402 with; verify and settle the payer's decoded X-PAYMENT header with lh.x402.verify(payload, requirements) and lh.x402.settle(payload, requirements). lh.x402.payments.list() lists settled payments. See x402.

How do I test webhooks locally?#

With an API key, webhooks.stream() yields your account's webhook events (in the key's mode) as they are created, with the exact payloads your endpoints receive. webhooks.trigger(type) creates a sample event; it needs an lh_test_ key. See Test webhooks locally.

Python
lh = LayerHop(api_key="lh_test_...")
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_...")  # again to subscribed endpoints and open streams

lh.usage.get() and lh.usage.errors() return the key's request counts, latency and recent errors.

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: 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.

How are errors reported?#

Non-2xx responses raise LayerHopApiError with code, status, message and request_id. The code is one of the stable error codes.

Python
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 (or None). On NO_ROUTE, e.suggestions() returns alternative routes that quoted (dst_token, src_token, or via_hub with a hub and two steps), validated and at most 4. On AMOUNT_TOO_SMALL, e.min_amount, e.min_amount_usd and e.min_amount_approx give the route's minimum when known; e.provider_errors() lists each provider's reason.

Python
except LayerHopApiError as e:
    for s in e.suggestions():
        print(s["kind"], s["message"])

How do I verify webhooks?#

Python
from layerhop import verify_webhook_signature

ok = verify_webhook_signature(secret, request.get_data(), request.headers["LayerHop-Signature"])

The header is t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>. Verify it against the raw body. The check rejects timestamps more than 300 s off (tolerance) and compares in constant time.

Last updated