# Guide to Layerswap Webhooks: Features and Best Practices

[Layerswap](https://layerswap.io) moves crypto between networks: from an exchange to a chain, or from one chain to another, through a swap API that wallets and apps embed. A swap passes through several states, waiting for the user's deposit, Layerswap sending funds out, and finally completing, failing, expiring or being refunded. Layerswap's webhooks push those status changes to your backend, so you can credit a balance or update an order without polling `GET /swaps/{id}`.

Layerswap's webhook documentation is short and openly lists several guarantees as gaps. This guide sets out what is documented about the payload and signature, and how to build a receiver that is safe despite what isn't.

## What are Layerswap webhooks?

Webhooks are set up per app in Layerswap's Partner Dashboard, and each app can have one or more endpoint URLs. Delivery runs on Svix. Layerswap tells you to verify the raw body and the Svix signature headers with the app's secret, and links Svix's guide rather than describing the scheme itself.

Each delivery describes a swap as it stands when the webhook is sent. There's no event name: the meaning of a delivery comes from `swap.status` and the transactions inside the swap. Layerswap's own Track swaps page lists event, retry, ordering and payload guarantees as gaps, and recommends fetching the swap from the API before any irreversible action.

## Layerswap webhook features

| Feature | Details |
| --- | --- |
| Configuration | Partner Dashboard > organisation > app > **Webhooks** |
| Endpoints | One or more per app. No event selection |
| Delivery platform | Svix |
| Headers | `svix-id`, `svix-timestamp`, `svix-signature` (Svix defaults, not printed by Layerswap) |
| Signature | Standard Webhooks HMAC-SHA256, `v1,<base64>` |
| Secret | Per app, in the **Webhooks** section (Svix secrets start with `whsec_`) |
| Body | `{swap, quote, deposit_actions}` |
| Event field | None. Branch on `swap.status` |
| Timeout, retries, ordering | Not documented; listed by Layerswap as gaps |
| Source IPs | Not published |

## Events and payloads

Layerswap publishes a representative shape rather than per-event examples:

```json
{
  "swap": {
    "id": "SWAP_ID",
    "status": "ls_transfer_pending",
    "destination_address": "0x...",
    "requested_amount": 100,
    "fail_reason": null,
    "metadata": {
      "reference_id": "your-external-id"
    },
    "transactions": []
  },
  "quote": {
    "receive_amount": 99.5,
    "min_receive_amount": 99.0
  },
  "deposit_actions": []
}

```

| Field | Meaning |
| --- | --- |
| `swap.id` | The durable key for the swap |
| `swap.status` | The swap's lifecycle state. The handlers branch on this |
| `swap.metadata` | Your own data, such as `reference_id` |
| `swap.transactions` | Input, output, refuel and refund transactions, each with its own `type` and `status` |
| `quote` | `receive_amount` and `min_receive_amount`; more quote data arrives as processing progresses |
| `deposit_actions` | What the user must do to fund the swap |

`swap.status` takes the values Layerswap's API returns on swap objects:

| `swap.status` | Meaning |
| --- | --- |
| `user_transfer_pending` | Waiting for the user's deposit |
| `ls_transfer_pending` | Layerswap is sending the output |
| `pending_refund` | A refund is under way |
| `completed` | The swap finished |
| `failed` | The swap failed (see `fail_reason`) |
| `expired` | No deposit arrived within 6 hours |
| `refunded` | The refund finished |

These snake_case values are not the same as the PascalCase filters `GET /swaps` takes (`PendingDeposit`, `Completed` and so on), so don't reuse one where the other is expected. Use the swap-level `status` for the swap as a whole and a transaction's `status` for a single on-chain operation.

## Setting up Layerswap webhooks

1. Open the [Partner Dashboard](https://layerswap.io/dashboard).
2. Select your organisation and app.
3. Open **Webhooks**, add the endpoint URL and create the webhook.
4. Copy the webhook secret into your secret manager as `LAYERSWAP_WEBHOOK_SECRET`.

Layerswap doesn't show the secret's format. Svix-issued secrets start with `whsec_`, which both the code below and Hookdeck's Layerswap source expect, so check it. Each app has its own secret. For local development, forward deliveries with the [Hookdeck CLI](/docs/cli):

```bash
npx hookdeck-cli listen 3000 layerswap --path /webhooks/layerswap

```

**With Hookdeck.** Make a **Layerswap** source in Hookdeck, paste the app's webhook secret, and add the source URL as an endpoint in the Partner Dashboard. Only `POST` requests are accepted. Layerswap gets a `200` back every time; requests that don't verify are logged in Hookdeck as failed verification and stop there.

## Securing Layerswap webhooks

Under Svix's scheme, the signed content is `{svix-id}.{svix-timestamp}.{raw body}`, the key is the base64-decoded secret after `whsec_`, and `svix-signature` lists `v1,<base64>` signatures separated by spaces. Layerswap asks you to verify before parsing and to keep verification ahead of "any balance credit, order fulfillment, or database state transition". Because Layerswap never names the headers itself, this verifier reads `svix-*` and falls back to `webhook-*`:

```javascript
const crypto = require('node:crypto');

function decodeBase64(value) {
  if (typeof value !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return null;
  const bytes = Buffer.from(value, 'base64');
  return bytes.length > 0 && bytes.toString('base64').replace(/=+$/, '') === value.replace(/=+$/, '')
    ? bytes : null;
}

function verifySignature(rawBody, headers, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof secret !== 'string' || !secret) return false;
  const prefix = headers['svix-id'] ? 'svix' : 'webhook';
  const id = headers[`${prefix}-id`];
  const timestamp = headers[`${prefix}-timestamp`];
  const signature = headers[`${prefix}-signature`];
  if (typeof id !== 'string' || !id || typeof timestamp !== 'string' ||
      !/^[0-9]+$/.test(timestamp) || typeof signature !== 'string') return false;
  const key = decodeBase64(secret.replace(/^whsec_/, ''));
  if (!key) return false;
  const message = Buffer.concat([Buffer.from(`${id}.${timestamp}.`, 'utf8'), rawBody]);
  const candidates = signature.split(/\s+/).filter((item) => item.startsWith('v1,')).map((item) => item.slice(3));
  const expected = crypto.createHmac('sha256', key).update(message).digest();
  return candidates.some((candidate) => {
    const received = decodeBase64(candidate);
    if (!received) return false;
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

```

Layerswap suggests deduplicating by swap ID and resulting status (or transaction hash), and returning success only once the event is durably stored:

```javascript
const express = require('express');

// Returns the parsed body when it is a JSON object, otherwise null.
function parseJsonObject(rawBody) {
  try {
    const value = JSON.parse(rawBody.toString('utf8'));
    return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
  } catch {
    return null;
  }
}

const app = express();

const FINAL = new Set(['completed', 'failed', 'expired', 'refunded']);

app.post('/webhooks/layerswap', express.raw({ type: '*/*' }), async (req, res) => {
  const secret = process.env.LAYERSWAP_WEBHOOK_SECRET;
  if (!secret) return res.sendStatus(500);
  if (!verifySignature(req.body, req.headers, secret)) return res.sendStatus(401);

  const payload = parseJsonObject(req.body);
  if (!payload) return res.sendStatus(400); // signed, but not a JSON object
  const { swap } = payload;
  if (!swap || typeof swap !== 'object' || !swap.id || typeof swap.status !== 'string') return res.sendStatus(400);
  const dedupeKey = `${swap.id}:${swap.status}`;
  try {
    await swapEvents.insertOnce(dedupeKey, { swapId: swap.id, status: swap.status, final: FINAL.has(swap.status) });
  } catch {
    return res.sendStatus(503); // not stored, so don't acknowledge
  }
  return res.sendStatus(200);
});

// A worker calls GET /swaps/{id} before crediting anything for a final status.

```

`swapEvents.insertOnce` stands in for your own durable store.

Layerswap's checklist says to reject stale requests "according to the verification library", and Svix's library treats anything over 5 minutes old as stale. Hookdeck doesn't enforce any window and resends the original `svix-timestamp` when it retries or replays, so a receiver behind Hookdeck should verify the signature without the age check, as above, and rely on the swap-and-status key for duplicates.

> **Make Layerswap webhooks production-ready.** [Hookdeck Event Gateway](/event-gateway) verifies Layerswap's Svix signatures, keeps every swap update, and gives you the retry and replay guarantees Layerswap doesn't document.

## Layerswap webhook limitations and pain points

### Delivery guarantees are explicit gaps

**The Problem:** You can't tell whether a missed update will be resent, or in what order updates arrive.

**Why It Happens:** Layerswap documents no timeout, retry schedule or ordering, and its own docs mark these as gaps.

**Workarounds:**

* Reconcile periodically using `GET /swaps` with status filters, as Layerswap recommends.
* Treat every webhook as a hint and confirm with `GET /swaps/{id}` before irreversible steps.

**How Hookdeck Can Help:** Hookdeck accepts and stores each update on arrival, then [retries](/docs/retries) delivery to your backend on a policy you define.

### No event names

**The Problem:** Routing and monitoring tools that expect an event type have nothing to key on.

**Why It Happens:** The body is the swap object; the only signal is `swap.status`.

**Workarounds:**

* Route on `swap.status` and on transaction types and statuses inside `swap.transactions`.

**How Hookdeck Can Help:** Hookdeck [filters](/docs/filters) can match on `swap.status`, so completed and failed swaps can go to different destinations.

### Payload contents grow over time

**The Problem:** A field you need, such as an output transaction hash, isn't there yet.

**Why It Happens:** Layerswap says quote and transaction data become available as processing progresses, so early updates are sparse.

**Workarounds:**

* Read optional fields defensively and fetch the swap when you need complete data.

**How Hookdeck Can Help:** Hookdeck keeps each update for a swap, so you can compare what Layerswap sent at each stage.

### Undocumented headers and secret format

**The Problem:** Verification fails because the headers or secret aren't what your library expects.

**Why It Happens:** Layerswap relies on Svix's defaults without stating them.

**Workarounds:**

* Confirm the header names and `whsec_` prefix against a real delivery before going live.

**How Hookdeck Can Help:** Hookdeck's Layerswap source reads either header set and shows failed verifications immediately.

## Best practices

### Verify before crediting

Read the raw body with `express.raw({ type: '*/*' })`, a Next.js handler's `await request.text()`, or FastAPI's `await request.body()`, and verify before any balance or order changes.

### Key on swap ID plus status

`svix-id` covers Svix resends, but Layerswap's own advice is to deduplicate business effects on the swap ID and status, or a transaction hash. Our [idempotency guide](/webhooks/guides/implement-webhook-idempotency) covers the storage side.

### Put your own ID in `metadata`

`swap.metadata.reference_id` comes back on every update, so set it when you create the swap and use it to find the order without a lookup table.

## Conclusion

Layerswap's webhooks are status pushes for crypto swaps, signed by Svix and shaped like the swap object itself. Because Layerswap leaves event names, retries and ordering undocumented, a safe receiver verifies first, keys on swap ID and status, stores before acknowledging, and checks `GET /swaps/{id}` before moving money.

[Hookdeck Event Gateway](https://hookdeck.com) supplies the durable storage and retries that make those updates dependable. [Sign up](https://dashboard.hookdeck.com/signup) to create a Layerswap source.