> For the complete documentation index, see [llms.txt](https://docs-sdk.crypto-chief.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-sdk.crypto-chief.com/processing/js/guides/webhooks.md). Agents can also search and read this documentation through its [MCP server](https://docs-sdk.crypto-chief.com/~gitbook/mcp).

# Webhooks

Verify and handle Crypto Chief webhooks in Node.js with typed event payloads.

Webhooks are signed with your API key using HMAC-SHA256.

| Header               | Value                                                                               |
| -------------------- | ----------------------------------------------------------------------------------- |
| `X-Webhook-Delivery` | Delivery id, 1–128 characters `[A-Za-z0-9_-]`; the same on every attempt and resend |
| `X-CC-Timestamp`     | Unix time of the attempt, seconds                                                   |
| `X-CC-Signature`     | `v1=` + 64 hex characters                                                           |

The string to sign is four lines joined with `\n`, with no line break after the last one:

```
CC-HMAC-SHA256-WEBHOOK-V1
<X-CC-Timestamp>
<X-Webhook-Delivery>
<lowercase hex SHA-256 of the body>
```

`X-CC-Signature` is `v1=` followed by the lowercase hex HMAC-SHA256 of that string under your API key.

`body` is the raw request body. The SDK checks, in order: the three headers, the timestamp window (300 seconds), the signature (constant-time, hex in any case).

A retry or resend carries the same `X-Webhook-Delivery` and a new `X-CC-Timestamp`. Deduplicate by the delivery id — see [Webhook deliveries](https://docs-sdk.crypto-chief.com/processing/js/guides/webhook-deliveries.md#keep-the-delivery-id).

## Express

Mount `express.raw` so the body reaches you untouched, then verify and parse in one step:

```ts
import express from 'express';
import { parseWebhookEvent, WebhookVerificationError, type PayoutWebhookEvent } from '@cryptochiefs/cryptochief-crypto-processing-node';

app.post('/webhook/payout', express.raw({ type: '*/*' }), (req, res) => {
  try {
    const evt = parseWebhookEvent<PayoutWebhookEvent>(apiKey, req.body, req.headersDistinct);
    console.log(`payout ${evt.uuid} → ${evt.status}`);
    res.sendStatus(200);
  } catch (err) {
    if (err instanceof WebhookVerificationError) return res.sendStatus(401);
    throw err;
  }
});
```

## Plain Node `http`

`createWebhookHandler` reads the raw body, verifies it, parses the typed event, and replies `200` for you:

```ts
import { createServer } from 'node:http';
import { createWebhookHandler, type WebhookEvent } from '@cryptochiefs/cryptochief-crypto-processing-node';

const handler = createWebhookHandler<WebhookEvent>(apiKey, (evt, { res }) => {
  console.log(evt.event); // e.g. "payout.paid"
  res.writeHead(200).end('ok');
});

createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/webhook') return handler(req, res);
  res.writeHead(404).end();
}).listen(3000);
```

## Manual verification

For any other stack, pass the raw body and the request headers:

```ts
import { verifyWebhook, WebhookVerificationError } from '@cryptochiefs/cryptochief-crypto-processing-node';

try {
  verifyWebhook(apiKey, rawBody, headers);
} catch (err) {
  if (err instanceof WebhookVerificationError) {
    // reject with 401
  }
  throw err;
}
```

`headers` is `req.headers`, `req.headersDistinct`, a WHATWG `Headers`, a `Map`, a plain object or `[name, value]` pairs. Names are matched case-insensitively, and values under two spellings of one name count as a repeat.

`err.reason` says which check failed:

| `reason`      | Cause                                                                     |
| ------------- | ------------------------------------------------------------------------- |
| `'headers'`   | A signature header is missing, repeated or malformed                      |
| `'timestamp'` | `X-CC-Timestamp` differs from the current time by more than the tolerance |
| `'signature'` | The signature does not match the body                                     |

An empty API key throws a plain `CryptoChiefError`. `toleranceSec` and `now` set the tolerance and the time source, in `verifyWebhook`, `parseWebhookEvent` and `createWebhookHandler` alike:

```ts
verifyWebhook(apiKey, rawBody, headers, { toleranceSec: 60, now: () => new Date() });
```

`signWebhookV1(apiKey, timestamp, deliveryId, body)` returns the `X-CC-Signature` value, for testing a receiver.

## Event types

Typed payloads: `PayoutWebhookEvent`, `TransactionWebhookEvent`, `PayInWebhookEvent`, `StaticDepositWebhookEvent`, `SweepWebhookEvent`. Event-name prefixes are `payout.*`, `transaction.*`, `invoice.*` (pay-ins), `static_deposit.*`, and `sweep.*`. Payout and transaction webhooks fire **only on terminal status**.

`sweep.confirmed` is the moment swept funds reach the network's finality depth in your master wallet — the other half of a deposit's life, and what treasury reporting should key off. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/js/guides/sweep-callbacks.md).

Confirmation fields on events:

| Event type                | Field                                    | Meaning                                                                                                                                                                                                                                                                                 |
| ------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PayoutWebhookEvent`      | `confirmations`                          | The lowest count among the sources; absent while no source has a transaction. Each entry of `sources` and `serviceOperations` has its own `confirmations`, absent until on chain. See [Send a payout](https://docs-sdk.crypto-chief.com/processing/js/guides/payouts.md#confirmations). |
| `PayoutWebhookEvent`      | `requiredConfirmations`                  | The network's finality depth, at least `1`. Optional.                                                                                                                                                                                                                                   |
| `TransactionWebhookEvent` | `confirmations`, `requiredConfirmations` | Always sent. See [Sign & execute](https://docs-sdk.crypto-chief.com/processing/js/guides/sign-execute.md#confirm).                                                                                                                                                                      |
| `SweepWebhookEvent`       | `sweepConfirmations`                     | At least `requiredConfirmations`. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/js/guides/sweep-callbacks.md#payload).                                                                                                                                             |
| `SweepWebhookEvent`       | `requiredConfirmations`                  | The network's finality depth. Optional.                                                                                                                                                                                                                                                 |

{% hint style="info" %}
`WEBHOOK_SENDER_IPS` lists the addresses webhooks are delivered from — whitelist them at your edge for defence in depth.
{% endhint %}

## Empty string or absent

"This field has no value" is not spelled the same way on every payload, and in TypeScript the two spellings land on different sides of a `??` — so test for the one the payload actually uses.

On a **static-deposit** event, `contract` is an **empty string** for a native coin transfer, not an absent key:

```ts
import { parseWebhookEvent, type StaticDepositWebhookEvent } from '@cryptochiefs/cryptochief-crypto-processing-node';

const evt = parseWebhookEvent<StaticDepositWebhookEvent>(apiKey, rawBody, headers);

const isNative = !evt.contract; // '' on a native coin, a contract address on a token
if (evt.status === 'paid' && evt.paidAt) {
  // credited - confirmedAt and paidAt are absent until the deposit reaches those points
}
```

`amountFiat` may be empty when no conversion rate was available, and `blockNumber` appears only once the transaction is in a block.

On a **sweep** event the convention is reversed: optional fields are omitted rather than emptied, so `assetContract` is `undefined` on a native sweep. Sweep *history*, a plain API response rather than a webhook, goes back to the empty string. [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/js/guides/sweep-callbacks.md) and [Auto-sweep settings](https://docs-sdk.crypto-chief.com/processing/js/guides/auto-sweep-settings.md) each spell out their own side.

Wallet responses are the strict case: `masterWalletAddress`, `callbackUrl` and `label` are always present and `null` when unset, never `''` — see [Wallets](https://docs-sdk.crypto-chief.com/processing/js/guides/wallets.md#what-the-three-return).
