Python: cross-chain swap with requests or the SDK
Complete Python recipe for a LayerHop cross-chain swap with requests and web3.py, or the layerhop SDK, covering quote, approval, signing, order report and status polling.
This recipe performs a cross-chain swap from Python. It calls the LayerHop REST API with requests to get a quote and an unsigned transaction, signs and sends the ERC-20 approval and the swap with web3.py, reports the hash and polls the order until it is final. A shorter version with the official layerhop package follows.
Warning
The script signs and broadcasts real transactions with
PRIVATE_KEY. Develop with anlh_test_key (test mode): its transactions are placeholders and the script refuses to send them. Never commit keys.
What do I need first?#
- Python 3.9+ and
pip install requests "web3>=7"(orpip install layerhop web3for the SDK variant). PRIVATE_KEYof a funded EVM wallet, and optionallyLAYERHOP_API_KEY.- The source chain's RPC URL in
RPC_URL. The script uses Base as the source chain.
1. Write the script with requests#
# swap.py
import os, time, requests
from web3 import Web3
API = os.environ.get("LAYERHOP_API_URL", "https://api.layerhop.com/v1")
HEADERS = {"x-api-key": os.environ["LAYERHOP_API_KEY"]} if os.environ.get("LAYERHOP_API_KEY") else {}
w3 = Web3(Web3.HTTPProvider(os.environ["RPC_URL"])) # RPC of the source chain (Base here)
acct = w3.eth.account.from_key(os.environ["PRIVATE_KEY"])
ERC20 = [
{"name": "allowance", "type": "function", "stateMutability": "view",
"inputs": [{"name": "owner", "type": "address"}, {"name": "spender", "type": "address"}],
"outputs": [{"name": "", "type": "uint256"}]},
{"name": "approve", "type": "function", "stateMutability": "nonpayable",
"inputs": [{"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}],
"outputs": [{"name": "", "type": "bool"}]},
]
def call(method, path, **kw):
r = requests.request(method, f"{API}/{path}", headers=HEADERS, timeout=30, **kw)
body = r.json()
if not r.ok:
e = body.get("error", {})
raise RuntimeError(f'{e.get("code")}: {e.get("message")} (request {r.headers.get("x-request-id")})')
return body
def send(tx: dict) -> str:
base = w3.eth.get_block("latest")["baseFeePerGas"]
prio = w3.eth.max_priority_fee
params = {"to": Web3.to_checksum_address(tx["to"]), "data": tx["data"], "value": int(tx["value"]),
"chainId": tx["chainId"], "from": acct.address}
params["gas"] = w3.eth.estimate_gas(params) # raises if the call would revert
params.update({"nonce": w3.eth.get_transaction_count(acct.address),
"maxFeePerGas": 2 * base + prio, "maxPriorityFeePerGas": prio})
del params["from"]
signed = acct.sign_transaction(params)
return w3.to_hex(w3.eth.send_raw_transaction(signed.raw_transaction))
# 1. Quote: 100 USDC on Base to SOL on Solana (amounts are integer strings in base units)
quote = call("GET", "quote", params={
"srcChain": "base", "srcToken": "USDC", "amount": "100000000",
"dstChain": "solana", "dstToken": "SOL",
"sender": acct.address, "recipient": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
"slippageBps": 50,
})
best = quote["best"]
print(best["provider"], best["dstAmountMin"], best["estimatedSeconds"], best["fees"]["ourFeeBps"])
# 2. Build the unsigned transaction right before sending
built = call("POST", "orders", json={"quoteId": best["quoteId"]})
if built.get("livemode") is False:
raise SystemExit("Test-mode transaction: do not broadcast")
tx = built["tx"]
assert tx["vm"] == "evm", "this script handles EVM source transactions"
# 3. ERC-20 approval first, only when the allowance is short
if tx.get("approval"):
a = tx["approval"]
token = w3.eth.contract(address=Web3.to_checksum_address(a["token"]), abi=ERC20)
spender = Web3.to_checksum_address(a["spender"])
if token.functions.allowance(acct.address, spender).call() < int(a["amount"]):
data = token.encode_abi("approve", args=[spender, int(a["amount"])])
h = send({"to": a["token"], "data": data, "value": "0", "chainId": tx["chainId"]})
w3.eth.wait_for_transaction_receipt(h)
# 4. Swap, then report so LayerHop tracks the order
tx_hash = send(tx)
call("POST", f'orders/{best["quoteId"]}/submitted', json={"txHash": tx_hash})
# 5. Poll until the order is final
while True:
s = call("GET", f'orders/{best["provider"]}/{tx_hash}')
print(s["state"], s.get("dstTxHash", ""))
if s["state"] in ("filled", "refunded", "failed", "dropped"):
break
time.sleep(3)2. Or use the layerhop package#
The SDK ships sync and async clients with the same endpoints and keeps the camelCase keys of the API. It never signs; your wallet library does. send below is the helper above.
from layerhop import LayerHop
lh = LayerHop() # LayerHop(api_key="lh_live_...", integrator="myapp")
best = lh.quote("base", "USDC", "100000000", "solana", "SOL",
sender=acct.address, recipient="9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM")["best"]
tx = lh.build_tx(best["quoteId"])
tx_hash = send(tx) # after sending tx["approval"] when present
lh.report_submitted(best["quoteId"], tx_hash)
for s in lh.watch(best["provider"], tx_hash):
print(s["state"])See the Python SDK reference for every method, including AsyncLayerHop.
How does it work?#
The script makes the calls described in the Quickstart: GET /v1/quote returns best and the other quotes; POST /v1/orders returns the unsigned tx (vm, chainId, to, data, value, optional approval); POST /v1/orders/{quoteId}/submitted starts tracking; GET /v1/orders/{provider}/{id} reports pending, filled, refunded, failed or dropped. The approval is described in Approvals.
Which Python errors should I retry?#
The API returns { "error": { "code", "message", "docsUrl" } }. Re-quote on QUOTE_EXPIRED; retry PROVIDER_ERROR, PROVIDER_TIMEOUT, RATE_LIMITED and INTERNAL with exponential backoff; fix the request for INVALID_PARAMS. See Error handling and the error catalog.
Can I verify webhooks in Python too?#
Yes. verify_webhook_signature and construct_webhook_event ship in the SDK; see the webhook receiver recipe.
Next: Node.js + viem, API reference.
Last updated