# Go SDK

> github.com/layerhop/layerhop-go — a dependency-free, context-aware Go client with typed models, an iterator-based Watch and webhook verification.

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

`layerhop-go` is the Go client for the LayerHop [REST API](/api-reference), mirroring the [TypeScript SDK](/sdk). It uses only the standard library, needs Go 1.23+ (`Watch` returns an `iter.Seq2`), and every method takes a `context.Context`.

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

## How do I install it?

```bash
go get github.com/layerhop/layerhop-go@latest
```

## Quickstart

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

```go
lh := layerhop.New(layerhop.Options{APIKey: os.Getenv("LAYERHOP_API_KEY")})

// 1. Quote
q, err := lh.Quote(ctx, layerhop.QuoteParams{
	SrcChain: "base", SrcToken: "USDC", Amount: "100000000",
	DstChain: "solana", DstToken: "SOL",
	Sender: "0xYourEvmAddress", Recipient: "YourSolanaAddress",
})
if err != nil { return err }

// 2. Build the unsigned transaction
tx, err := lh.BuildTx(ctx, q.Best.QuoteID)
if err != nil { return err }

// 3. Sign + send with YOUR wallet library. EVM: send tx.Approval first when set, then
//    {To: tx.To, Data: tx.Data, Value: tx.Value} on tx.ChainID. Solana: sign tx.SerializedTx;
//    when tx.SubmitViaAPI is true, call lh.Submit(ctx, quoteID, signedBase64) instead of an RPC.
txHash := signAndSend(tx)

// 4. Report the broadcast
if _, err := lh.ReportSubmitted(ctx, q.Best.QuoteID, txHash); err != nil { return err }

// 5. Watch until filled / refunded / failed
for st, err := range lh.Watch(ctx, q.Best.Provider, txHash, layerhop.WatchOptions{}) {
	if err != nil { return err }
	fmt.Println(st.State)
}
```

## Which methods are available?

| Method | Endpoint |
|---|---|
| `Health` · `Chains` · `Tokens(ctx, chain)` | `GET /v1/health` · `/v1/chains` · `/v1/tokens` |
| `SearchTokens(ctx, TokenSearchParams)` · `LookupToken(ctx, address, chain)` | `GET /v1/tokens?q=&cursor=` · `/v1/tokens/lookup` |
| `GetTokenRisk(ctx, chain, address)` | `GET /v1/tokens/{chain}/{address}/risk` |
| `Prices(ctx, ids)` · `Balances(ctx, BalancesParams)` | `GET /v1/prices` · `/v1/balances` |
| `Quote(ctx, QuoteParams)` | `GET /v1/quote` (`Amount`, or `DstAmount` for exact output) |
| `StreamQuotes(ctx, QuoteParams, QuoteStreamOptions)` | `GET /v1/quote/stream` (SSE): `iter.Seq2[*QuoteStreamUpdate, error]` |
| `Screen(ctx, addresses)` | `POST /v1/screen` (OFAC SDN list, public) |
| `QuoteCalls(ctx, CallsQuoteParams)` | `POST /v1/quote` (exact output with destination calls) |
| `BuildTx(ctx, quoteID)` | `POST /v1/orders` |
| `BuildGasless(ctx, quoteID)` · `SubmitGasless(ctx, quoteID, tradeSig, approvalSig)` · `GaslessStatus(ctx, quoteID)` | `POST /v1/orders` · `POST /v1/orders/gasless` · `GET /v1/orders/gasless/{quoteId}` |
| `Simulate(ctx, quoteID)` | `POST /v1/simulate` |
| `Submit(ctx, quoteID, signedTxBase64)` | `POST /v1/orders/submit` (Solana `SubmitViaAPI` only) |
| `ReportSubmitted(ctx, quoteID, txHash)` | `POST /v1/orders/{quoteId}/submitted` |
| `Status(ctx, provider, id)` | `GET /v1/orders/{provider}/{id}` |
| `Watch(ctx, provider, id, WatchOptions)` | `iter.Seq2[OrderStatus, error]`, one item per state change; stops when final, on error, or after `ErrWatchTimeout` (30 min by default) |
| `StreamOrder(ctx, quoteID)` | `GET /v1/orders/{quoteId}/events` (SSE): `iter.Seq2[*Order, error]` until final |
| `ListOrders(ctx, ListOrdersParams)` | `GET /v1/orders` |
| `CreateCheckoutSession(ctx, CreateCheckoutParams)` | `POST /v1/checkout/sessions` |
| `ListCheckoutSessions(ctx, ListCheckoutSessionsParams)` · `GetCheckoutSession(ctx, id)` | `GET /v1/checkout/sessions` · `/v1/checkout/sessions/{id}` |
| `ExpireCheckoutSession(ctx, id)` · `QuoteCheckoutSession(ctx, id, CheckoutQuoteParams)` | `POST /v1/checkout/sessions/{id}/expire` · `/quote` |
| `StartCheckoutTransfer(ctx, id)` · `StartCheckoutBitcoin(ctx, id, StartCheckoutBitcoinParams)` | `POST /v1/checkout/sessions/{id}/transfer` · `/bitcoin` (public) |
| `StreamCheckoutSession(ctx, id)` | `GET /v1/checkout/sessions/{id}/events` (SSE) until `paid`, `expired` or `needs_review` |
| `CreateCheckoutProduct(ctx, CreateCheckoutProductParams)` | `POST /v1/checkout/products` |
| `ListCheckoutProducts(ctx, ListCheckoutProductsParams)` · `GetCheckoutProduct(ctx, id)` | `GET /v1/checkout/products` · `/v1/checkout/products/{id}` |
| `UpdateCheckoutProduct(ctx, id, UpdateCheckoutProductParams)` · `StartProductCheckout(ctx, id, StartProductCheckoutParams)` | `PATCH /v1/checkout/products/{id}` · `POST /v1/checkout/products/{id}/sessions` |
| `CreateRefund(ctx, sessionID, CreateRefundParams)` · `ListRefunds(ctx, sessionID)` | `POST` · `GET /v1/checkout/sessions/{id}/refunds` |
| `CreateInvoice(ctx, CreateInvoiceParams)` · `ListInvoices(ctx, ListInvoicesParams)` · `GetInvoice(ctx, id)` | `POST /v1/invoices` · `GET /v1/invoices` · `/v1/invoices/{id}` |
| `UpdateInvoice(ctx, id, UpdateInvoiceParams)` · `SendInvoice(ctx, id)` · `VoidInvoice(ctx, id)` | `PATCH /v1/invoices/{id}` · `POST /v1/invoices/{id}/send` · `/void` |
| `GetPublicInvoice(ctx, id)` · `PayInvoice(ctx, id)` | `GET /v1/invoices/{id}/public` · `POST /v1/invoices/{id}/pay` (public) |
| `CreateRecurringOrder` · `SubmitRecurringOrder` · `ListRecurringOrders` · `CancelRecurringOrder` | `POST /v1/recurring-orders` · `/submit` · `GET /v1/recurring-orders` · `POST /v1/recurring-orders/{id}/cancel` |
| `CreateSplit` · `GetSplit` · `UpdateSplit(ctx, id, editToken, …)` | `POST /v1/splits` · `GET` · `PATCH /v1/splits/{id}` (public) |
| `GetTipJar(ctx, address)` | `GET /v1/tip-jars/{address}` (public) |
| `PlanPayouts` · `BuildPayoutTransfers` | `POST /v1/payouts/plan` · `/v1/payouts/transfers` (public) |
| `ServiceStatus(ctx)` | `GET /v1/status` (public) |
| `StreamWebhookEvents(ctx, WebhookStreamOptions{Since})` · `TriggerWebhookEvent(ctx, eventType)` | `GET /v1/webhooks/stream?since=` (SSE) · `POST /v1/webhooks/trigger` (test keys) |
| `ResendWebhookEvent(ctx, eventID, endpointID)` | `POST /v1/webhooks/events/{id}/resend` |
| `Usage(ctx, UsageParams)` · `UsageErrors(ctx, UsageErrorsParams)` | `GET /v1/usage` · `/v1/usage/errors` |
| `X402Supported` · `X402Requirements` · `X402Verify` · `X402Settle` | `GET /v1/x402/supported` · `POST /v1/x402/requirements` · `/verify` · `/settle` |
| `ListX402Payments(ctx, ListX402PaymentsParams)` · `GetX402Payment(ctx, id)` | `GET /v1/x402/payments` · `/v1/x402/payments/{id}` |

`Options`: `BaseURL` (default `https://api.layerhop.com`), `APIKey`, `Channel`, `Integrator`, `IntegratorFeeBps`, `HTTPClient`, `UserAgent`.

`QuoteParams` also takes optional attribution fields that never change the fee or the price: `Referrer`, `CopyOf`, `Purpose` (`layerhop.PurposeTip` … `PurposeFund`), `SplitID` with `SplitShare`, and `Note`.

## How do I sign a Tron transaction?

Where Tron is enabled, `BuildTx` can return a Tron transaction: `tx.IsTron()` is true and `tx.ChainID` is `layerhop.TronChainID`. The SDK never signs. Sign `tx.Unsigned` unchanged with a Tron wallet (TronWeb, TronLink). When `tx.Approval` is set, send `tx.Approval.Unsigned` first, as its own transaction. Broadcast each before its `raw_data.expiration`. Then report `tx.Unsigned.TxID`, a bare 64-hex hash without `0x`. `RawData` is a `json.RawMessage`, so it round-trips unchanged. `Simulate` reports `EnergyUsed`.

```go
if tx.IsTron() {
	if tx.Approval != nil { broadcastTron(tx.Approval.Unsigned) }
	broadcastTron(tx.Unsigned) // your TronWeb / TronLink signer
	_, err = lh.ReportSubmitted(ctx, q.Best.QuoteID, tx.Unsigned.TxID)
}
```

## How do I make a gasless swap?

Set `Gasless: true` on `QuoteParams`. The wallet then signs EIP-712 typed data, and the provider's relayer pays the gas out of the input token (`Quote.Gasless.GasFee`). This works for an ERC-20 input swapped on the same EVM chain, in live mode. `BuildTx` on a gasless quote returns `layerhop.ErrGaslessQuote`, and `BuildGasless` on a normal quote returns `layerhop.ErrNotGasless`. See [Gasless swaps](/guides/gasless-swaps).

```go
g, err := lh.BuildGasless(ctx, q.Best.QuoteID)
// sign g.Trade.EIP712 (and g.Approval.EIP712 when set) unchanged with eth_signTypedData_v4
st, err := lh.SubmitGasless(ctx, q.Best.QuoteID, tradeSig, approvalSig) // "" without an approval
st, err = lh.GaslessStatus(ctx, q.Best.QuoteID)                         // poll until filled or failed
```

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

`QuoteCalls` quotes by exact output. `DstAmount` of `DstToken` goes to contract calls on the destination chain, made by the provider's executor (`msg.sender` is the executor, not the user). Each quote has `SrcAmount`, which is what the sender pays, and `Calls` with the simulation result. A reverting call is `CALLS_REVERTED`. See [Destination calls](/guides/destination-calls).

```go
q, err := lh.QuoteCalls(ctx, layerhop.CallsQuoteParams{
	SrcChain: "base", SrcToken: "USDC", DstChain: "arbitrum", DstToken: "USDC",
	DstAmount: "10000000", Sender: "0xYou", Recipient: "0xYou",
	Action: &layerhop.DestinationAction{Type: layerhop.ActionAaveV3Supply},
})
```

## How do I look up and check tokens?

```go
page, _ := lh.SearchTokens(ctx, layerhop.TokenSearchParams{Chain: "berachain", Q: "HONEY"}) // page.NextCursor
tok, _ := lh.LookupToken(ctx, "0x4200000000000000000000000000000000000006", "")   // "" = the API finds the chain
risk, _ := lh.GetTokenRisk(ctx, "base", tok.Address)                              // ok | caution | danger | unknown
prices, _ := lh.Prices(ctx, []string{"8453:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"})
bal, _ := lh.Balances(ctx, layerhop.BalancesParams{Address: "0xYou", Chains: []string{"base"}, Fresh: true})
```

Tokens read on-chain have `Verified: false`, so warn before a user trades one. A risk level of `unknown` should never block a swap. `Chain` also carries `DestinationOnly`, `OnlyRoute` and `RouteHealth`. See [Chains, tokens, prices and balances](/guides/tokens-and-balances).

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

These endpoints are public and the SDK never signs. A split's payers quote with `SplitID` and `SplitShare`. Keep `EditToken` for `UpdateSplit`, which sends it as `x-edit-token`. Tips are quotes with `Purpose: layerhop.PurposeTip`. `PlanPayouts` checks the rows. You build the plain transfers with `BuildPayoutTransfers` and quote the routed rows with `Purpose: layerhop.PurposePayout`. See [Split the bill](/guides/split-the-bill), [Tip jar](/guides/tip-jar) and [Bulk payouts](/guides/bulk-payouts).

```go
s, err := lh.CreateSplit(ctx, layerhop.CreateSplitParams{Recipient: "alice.eth", Chain: "base", Token: "USDC", Total: "120000000", Participants: 3})
noNote := "" // a pointer to "" clears the note
lh.UpdateSplit(ctx, s.ID, s.EditToken, layerhop.UpdateSplitParams{Note: &noNote, Status: "closed"})
jar, _ := lh.GetTipJar(ctx, "0xabc...")
plan, _ := lh.PlanPayouts(ctx, layerhop.PlanPayoutsParams{SrcChain: "base", SrcToken: "USDC", Sender: "0xYou", CSV: "alice.eth,250,USDC,base"})
```

## How do I create recurring orders?

These are Solana recurring buys (beta, Jupiter Recurring, no LayerHop fee). The wallet signs `Tx` (sign only), and you submit it with its `RequestID`. A cancel works the same way. See [Limit and recurring orders](/guides/limit-and-recurring-orders).

```go
b, err := lh.CreateRecurringOrder(ctx, layerhop.CreateRecurringOrderParams{Wallet: w, DstToken: "SOL", Amount: "350000000", Orders: 7, IntervalSeconds: 86400})
r, err := lh.SubmitRecurringOrder(ctx, b.RequestID, signedBase64)
c, err := lh.CancelRecurringOrder(ctx, r.Order, w) // sign c.Tx, then SubmitRecurringOrder(ctx, c.RequestID, …)
```

## How do I take payments with checkout?

[Checkout](/guides/checkout) gets you paid in USDC or USDT while the customer pays with any token. Creating, listing and expiring sessions needs an API key; `GetCheckoutSession` and `QuoteCheckoutSession` are public. `StartCheckoutTransfer` (a "Send to address" QR, fills `Transfer`) and `StartCheckoutBitcoin` (a BTC deposit address, fills `Bitcoin`) are public too. `Payment.Method` is `wallet` or `transfer`, and `EmbedOrigins` limits which sites may embed the session.

```go
s, err := lh.CreateCheckoutSession(ctx, layerhop.CreateCheckoutParams{
	Amount: "49000000", SettleChain: "base", SettleToken: "USDC", // 49 USDC
	Recipient: "0xYourPayoutAddress", Reference: "order_1042",
	SuccessURL: "https://shop.example.com/thanks",
})
if err != nil { return err }
// redirect the customer to s.URL; fulfil on the checkout.session.completed webhook

// Your own payment page: quote, then pay with BuildTx + ReportSubmitted as usual
q, err := lh.QuoteCheckoutSession(ctx, s.ID, layerhop.CheckoutQuoteParams{SrcChain: "arbitrum", SrcToken: "ETH", Sender: payer})
if err != nil { return err }
tx, err := lh.BuildTx(ctx, 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](/guides/payment-buttons), `https://layerhop.com/buy/{id}` links and store plugins. `CreateCheckoutProduct`, `ListCheckoutProducts` and `UpdateCheckoutProduct` need an API key; `GetCheckoutProduct` and `StartProductCheckout` are public.

```go
p, err := lh.CreateCheckoutProduct(ctx, layerhop.CreateCheckoutProductParams{
	Name: "Pro plan", Amount: "49000000", // 49 USDC
	SettleChain: "base", SettleToken: "USDC", Recipient: "0xYourPayoutAddress",
	AllowedOrigins: []string{"https://shop.example.com"},
})
// share p.URL (https://layerhop.com/buy/prod_…) or put it behind a button

off := false // only set fields are sent; a pointer to "" clears a nullable field
_, err = lh.UpdateCheckoutProduct(ctx, p.ID, layerhop.UpdateCheckoutProductParams{Active: &off})

// Public (no key): a session on the product's terms, plus your order id
s, err := layerhop.New(layerhop.Options{}).StartProductCheckout(ctx, p.ID, layerhop.StartProductCheckoutParams{Reference: "order_1042"})
// s.ProductID == p.ID; send the payer to s.URL
```

## How do I send invoices?

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

```go
inv, err := lh.CreateInvoice(ctx, layerhop.CreateInvoiceParams{
	CustomerEmail: "jane@example.com",
	LineItems:     []layerhop.InvoiceLineItem{{Description: "Design work", Quantity: 2, UnitAmount: "100000000"}},
	SettleChain:   "base", SettleToken: "USDC", Recipient: "0xYourPayoutAddress",
	DueAt: "2026-11-01", Send: true,
})
if err != nil { return err }
// inv.Status == layerhop.InvoiceOpen; inv.URL is the hosted page
// drafts: UpdateInvoice (pointer to "" clears a field) · SendInvoice · VoidInvoice
// public, no key: GetPublicInvoice(ctx, id) · PayInvoice(ctx, id) → {SessionID, URL}
```

## How do I refund a payment?

[Refunds](/guides/refunds) are signed from your own wallet. `CreateRefund` 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 `RefundedAmount` grows.

```go
r, err := lh.CreateRefund(ctx, sessionID, layerhop.CreateRefundParams{Amount: "10000000", Reason: "Damaged item"}) // omit Amount for a full refund
if err != nil { return err }
tx, err := lh.BuildTx(ctx, r.Quote.QuoteID)
// sign and broadcast tx from r.Quote.From, then:
_, err = lh.ReportSubmitted(ctx, r.Quote.QuoteID, txHash)
```

`To: layerhop.RefundToSettlement` sends the settlement token instead of routing back to the payer's original token.

## How do I check LayerHop's status?

`ServiceStatus(ctx)` 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?

`StreamOrder` 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. `StreamCheckoutSession` does the same for a checkout session.

```go
for o, err := range lh.StreamOrder(ctx, quoteID) {
	if err != nil { return err } // *APIError (ORDER_NOT_FOUND), network error or ctx.Err()
	fmt.Println(o.Status, o.DstTxHash)
}
```

Breaking out of the loop or cancelling `ctx` closes the connection. Streams ignore `HTTPClient.Timeout`; use `ctx` to bound them.

## How do I stream live quotes?

`StreamQuotes` takes the same `QuoteParams` as `Quote` and yields a fresh ranked quote set whenever the best route or any amount changes. It ends after 5 minutes. A failed refresh yields one `*APIError` (`NO_ROUTE`, `RATE_LIMITED`, `ADDRESS_SANCTIONED`, …), and then the stream stops. Each refresh counts against your rate limit. See [Live quotes](/guides/live-quotes).

```go
for u, err := range lh.StreamQuotes(ctx, params, layerhop.QuoteStreamOptions{}) {
	if err != nil { return err }
	fmt.Println(u.Seq, u.Best.QuoteID, u.Best.DstAmount)
}
```

`Screen(ctx, addresses)` checks addresses against the OFAC SDN list. `QuoteResponse.Screening` and `CheckoutQuoteResponse.Screening` list the flagged addresses of a request.

## How do I charge per request with x402?

Call `X402Requirements` to get what to answer `402` with. Check the payment header with `X402Verify`, run the handler, then call `X402Settle`. `ListX402Payments` lists the settled payments. See [x402](/guides/x402).

## How do I test webhooks locally?

With an API key, `StreamWebhookEvents` yields your account's webhook events (in the key's mode) as they are created. Each `*WebhookEvent` has typed `Data.Order` / `Data.Session` and the exact payload in `Raw`. `TriggerWebhookEvent` creates a sample event; it needs an `lh_test_` key. Pass `WebhookStreamOptions{Since: …}` on reconnect to replay missed events, and `ResendWebhookEvent` sends an event again. `Usage` and `UsageErrors` show your key's traffic and recent errors. See [Test webhooks locally](/guides/live-status#test-webhooks-locally).

```go
lh := layerhop.New(layerhop.Options{APIKey: "lh_test_..."})
if _, err := lh.TriggerWebhookEvent(ctx, layerhop.EventOrderFilled); err != nil { return err }
for e, err := range lh.StreamWebhookEvents(ctx) {
	if err != nil { return err }
	fmt.Println(e.Type, string(e.Raw))
}
```

## 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](/guides/test-mode).

## How are errors reported?

Non-2xx responses return `*layerhop.APIError` with `Code`, `Message`, `Status`, `RequestID` and `Details` (`error.details` as raw JSON, nil when absent). The `Code` is one of the stable [error codes](/errors), and unknown codes are kept as they come.

Typed helpers read `Details`. `ProviderErrors()` lists why each provider failed. `AmountMinimum()` gives `MinAmount`, `MinAmountUsd` and `MinAmountApprox` on `AMOUNT_TOO_SMALL`. `Suggestions()` returns up to 4 route suggestions from a live `NO_ROUTE`. Each one is of kind `dst_token`, `src_token` or `via_hub`, and a `via_hub` suggestion has a `Hub` and two `Steps`. Malformed entries are dropped.

```go
var apiErr *layerhop.APIError
if errors.As(err, &apiErr) {
	switch apiErr.Code {
	case "QUOTE_EXPIRED":
		// re-quote
	case "NO_ROUTE":
		for _, s := range apiErr.Suggestions() {
			fmt.Println(s.Kind, s.Message) // quote each leg again before building it
		}
	}
}
```

## How do I verify webhooks?

```go
body, _ := io.ReadAll(r.Body) // raw bytes
if err := layerhop.VerifyWebhookSignature(secret, body, r.Header.Get("LayerHop-Signature"), 0, time.Time{}); err != nil {
	http.Error(w, "bad signature", http.StatusUnauthorized)
	return
}
```

The header is `t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>`. A zero tolerance means the default of 300 s. The errors are `ErrWebhookMalformedHeader`, `ErrWebhookTimestamp` and `ErrWebhookSignature`.

## What else should I know?

`Watch`, `StreamOrder` and `IsFinal` treat `dropped` as final, alongside `filled`, `refunded` and `failed`. A dropped order means the source transaction never reached the network and no funds moved, so quote again. Webhook event constants include `EventOrderDropped` and the `limit_order.*` events.
