Guides
Webhooks
Webhooks tell your backend how each sweep, revocation and hot wallet deployment ended, when a token you sweep is
refused, and when your gas wallet runs low. You can always read the same state with GET requests; webhooks spare
you the polling.
Set up the webhook
Section titled “Set up the webhook”curl -X PUT "https://api-testnet.portuna.io/v1/webhook" \ -H "Authorization: Bearer $PORTUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"url": "https://processing.example/hooks/sweeps", "low_balance": [{"chain_id": 11155111, "threshold": "20000000000000000"}]}'- The URL must use
httpsand resolve to a public address. Redirects are not followed. - The response contains
secret,whsec_…, which signs every delivery. Keep it on your backend. - Changing the URL with another
PUTkeeps the secret. To get a new secret,DELETE /v1/webhookand set it again: deleting drops the events not delivered yet. GET /v1/webhookshows the current settings,DELETE /v1/webhookremoves them.
Events
Section titled “Events”Sweeps go on chain in batches, and the events of their outcomes come per transaction: one event for the whole batch, with every sweep in it.
| Type | When | data |
|---|---|---|
transaction.sent | A transaction of sweeps or revocations was sent: its first version, and again each replacement at a higher gas price, with a new hash. Its items are processing. | TransactionEventData |
transaction.mined | The transaction is mined and has its confirmations. Each item is swept or failed, for good. | TransactionEventData |
transaction.reverted | The transaction is mined but reverted as a whole: its gas is spent. Each item is queued, to ride a new transaction, or failed if its attempts ran out. | TransactionEventData |
transaction.dropped | Another transaction took its nonce: nothing was spent. Its items are as in transaction.reverted. | TransactionEventData |
sweep.rejected | A sweep was never sent: a check before sending kept failing. | Sweep |
sweep.failed | A sweep’s attempts ran out before any transaction carried it, for example while the gas wallet could not pay. | Sweep |
revocation.rejected, revocation.failed | The same for a revocation. | Revocation |
hot_wallet.active, hot_wallet.failed | A hot wallet’s own delegate was deployed, or was not. | HotWallet |
delegate.active, delegate.failed | A delegate of a set of hot wallets was deployed, or was not. | Delegate |
token.refused | A token you could sweep is refused: its sweeps kept failing, it failed the checks again, or it was blocked. See Tokens. | Token |
tariff.changed | What you pay for a token changed, or will: an agreed rate was set, taken back, runs out within 7 days (expiring) or ran out, or a token’s conventional cost changed. See Tokens. | TariffChange |
balance.low | Your gas wallet fell below a threshold. | BalanceLow |
balance.payout | A payout of the available balance to your hot wallet was sent, paid or failed; status says which. See Fees. | Payout |
The body is the event: {"id", "type", "created_at", "data"}. New event types may appear: accept and ignore the
ones you do not handle.
Every sweep’s outcome comes in exactly one event:
| Outcome | Event |
|---|---|
swept | transaction.mined |
failed: the transfer reverted inside a batch that went through | transaction.mined |
failed: the attempts ran out when the transaction reverted or was dropped | transaction.reverted, transaction.dropped |
failed: the attempts ran out before it was sent | sweep.failed |
rejected | sweep.rejected |
A sweep that goes back to the queue (queued in transaction.reverted or transaction.dropped) is not final: it
rides a new transaction, and the events of that one tell how it ended.
Transaction events
Section titled “Transaction events”data of a transaction.* event holds the transaction, transaction, and what it carried, items, as they were
when the event happened. Three sweeps that went in one batch on Sepolia, two of them swept and one that found
nothing on its address:
{ "id": "7e2c9a41-3b5d-4f60-8c17-d9a0e4b2f816", "type": "transaction.mined", "created_at": "2026-10-27T10:01:12Z", "data": { "transaction": { "id": 48420, "chain_id": 11155111, "kind": "sweep", "status": "mined", "hash": "0x315137ae951da414629cf9481c89422639bd7e238873820559e0b0a2f8071457", "block_number": 11987254, "hot_wallets": ["0x2Cd50979a8A33e8CA37DA85F8517fb148a67b769"], "sweeps": { "total": 3, "processing": 0, "swept": 2, "failed": 1, "requeued": 0 }, "revocations": null, "gas_used": 104220, "gas_cost": "125064000000000", "fees": "25278000000000", "created_at": "2026-10-27T10:00:03Z", "mined_at": "2026-10-27T10:01:12Z", "list_id": null }, "part": 1, "parts": 1, "items": [ { "id": "c7d41a92-5b3e-4f08-9d21-6e8a0b3f5c71", "external_id": "dep-81f0a2", "batch_index": 0, "account": "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23", "hot_wallet": "0x2Cd50979a8A33e8CA37DA85F8517fb148a67b769", "token": "USDT", "token_address": "0x3809a97a7a25C8bA577027c0AE2D81a09cdA1a2f", "amount": null, "status": "swept", "swept_amount": "120000000", "fee": "23358000000000", "log_index": 211, "transfer_log_index": 210 }, { "id": "1e8b6f04-9a27-4c3d-b5e1-0f4a7d2c9e63", "external_id": "dep-81f0a3", "batch_index": 1, "account": "0x4B506125a16ab3A70A2970e11B1cd9039b0b0D99", "hot_wallet": "0x2Cd50979a8A33e8CA37DA85F8517fb148a67b769", "token": "ETH", "token_address": null, "amount": null, "status": "swept", "swept_amount": "4180000000000000", "fee": "1920000000000", "log_index": 212 }, { "id": "5f2a9c7e-0d14-4b86-a3f9-7c1e2b8d4a50", "external_id": "dep-81f0a4", "batch_index": 2, "account": "0xa4c0D7FcDDd1e47925E354eB506Cc3C209C1787b", "hot_wallet": "0x2Cd50979a8A33e8CA37DA85F8517fb148a67b769", "token": "USDT", "token_address": "0x3809a97a7a25C8bA577027c0AE2D81a09cdA1a2f", "amount": "50000000", "status": "failed", "reason": "NothingToSweep", "log_index": 213 } ] }}transaction is the transaction as GET /v1/transactions/{id} showed it at the event. items are its sweeps in
batch order, each with these fields:
| Field | What it is | Comes |
|---|---|---|
id, external_id | The sweep’s id, as in GET /v1/sweeps/{id}, and yours, null if the request had none. | always |
batch_index | The sweep’s place in the batch, from 0. | always |
account, hot_wallet, token, token_address, amount | What was asked for: token_address is null for the native coin, amount null for the whole balance. | always |
status | processing in transaction.sent; swept or failed in transaction.mined; queued or failed in transaction.reverted and transaction.dropped. | always |
reason | Why it failed, or why it went back to the queue: a code of Statuses, confirmations and reorgs. | with failed and queued |
swept_amount, fee | What reached the hot wallet, and the fee in wei. | with swept |
log_index | Where the batch contract’s Swept or SweepFailed event of the sweep is in the block. | in transaction.mined |
transfer_log_index | Where the token’s Transfer to the hot wallet is in the block; the native coin has none. | with swept, for a token |
attempts | How many attempts the sweep has had. | in transaction.reverted and transaction.dropped |
The whole sweep, with its gas, rate and conventional cost, is in GET /v1/sweeps?transaction_id=<id>&limit=200: one
page for a batch.
What to do on each event
Section titled “What to do on each event”| Event | What to do |
|---|---|
transaction.sent | Nothing is final yet. Show the sweeps as on their way, if you like. |
transaction.mined | Credit each swept item’s swept_amount. Each failed item is final: see its reason, for example NothingToSweep when the balance was gone. |
transaction.reverted, transaction.dropped | Wait for the queued items: they ride a new transaction, with events of its own. A failed item is final: its attempts ran out. |
sweep.rejected, sweep.failed | Final. Fix what reason says, for example sign an authorization for not_upgraded, and send a new sweep. |
Versions and the mined hash
Section titled “Versions and the mined hash”A transaction that waits too long is replaced with the same transaction at a higher gas price. Each replacement
comes as another transaction.sent, with a new hash, its version, from 1, and the hash it replaces, null for
the first. Its items and their batch_index stay the same.
The highest version is the latest attempt, not necessarily the one mined: an earlier version can still make it
into a block. The mined hash is the one in transaction.mined or transaction.reverted; transaction.dropped has
the latest version’s. GET /v1/transactions?tx_hash=… finds the transaction by any of its hashes.
Where a sweep is on chain
Section titled “Where a sweep is on chain”- The transaction’s
idandbatch_indexname a sweep’s place for good, from the firsttransaction.senton. On chain, the sweep ofbatch_indexk is the k-thSweptorSweepFailedevent of the batch contract in the transaction’s logs. Aqueuedsweep rides a new transaction and gets a new place there. log_indexandtransfer_log_indexcome once the transaction is mined. With its hash,transfer_log_indexfinds a token’s transfer to the hot wallet as your blockchain node or indexer shows it; for the native coin, which emits noTransfer, uselog_index. See Reconcile with your books.GET /v1/sweeps/{id}shows the samebatch_index,log_indexandtransfer_log_index.
A transaction of up to 200 items comes in one event: part 1 of parts 1. A larger one comes in parts of 200,
each with the same transaction. Each part stands on its own: apply its items as they come. To reconcile the
transaction as a whole, wait for all its parts.
Sweep lists
Section titled “Sweep lists”The transaction of a sweep list comes in the same events, with the list’s id in
transaction.list_id; a batch of single sweeps has null there. Its items are the list’s in the order of the
request, without those rejected before sending: each of those comes in a sweep.rejected of its own. When the list’s
transaction reverts or is dropped, its items come queued, to ride a new transaction with the same list_id, or
failed once their attempts ran out. GET /v1/transactions?list_id= gives every transaction of a list.
Revocations
Section titled “Revocations”Revocations come in the same events, with transaction.kind revocation. Their items have id, external_id,
batch_index, their place in the authorization list, account, status (revoked for swept), reason and
attempts; revocation.rejected and revocation.failed are for revocations no transaction carried.
A snapshot of the moment
Section titled “A snapshot of the moment”data of a transaction event shows the transaction as it was when the event happened: a transaction.sent that
arrives late still says pending and processing. The events of a single sweep or revocation, sweep.* and
revocation.*, show it as it is at delivery, with its final status.
The keys of data may come in another order than in the examples here: parse the JSON, never compare it as text.
The delivery log (GET /v1/webhook/deliveries) keeps an event for 90 days after it was delivered or failed for good.
Delivery
Section titled “Delivery”Each event is a POST with a JSON body and these headers:
| Header | Value |
|---|---|
Portuna-Signature | t=<unix seconds>,v1=<hex HMAC-SHA256> |
Portuna-Event | the event type, such as transaction.mined |
Portuna-Delivery | the event id |
Content-Type | application/json |
- At least once. An event can arrive more than once, with the same
id. - Any order. Events can arrive out of order: a
transaction.sentcan come after thetransaction.minedof the same transaction. - Retries. Any response other than 2xx, a redirect included, and no response within 10 seconds count as a failure.
The event is tried again after 10 s, 20 s, 40 s and so on, up to an hour between attempts, 12 attempts in all.
Then it is
failed.
GET /v1/webhook/deliveries lists your recent events with their delivery state: pending, delivered or
failed, the attempts, your endpoint’s last HTTP status and the next attempt. The console shows the same log.
What your receiver must do
Section titled “What your receiver must do”- Store the event, then respond. Verify the signature, save the event and answer 2xx within 10 seconds; apply it after, outside the request. Do not call the API from the handler. Your endpoint gets several requests at a time. If one takes 5 seconds or more, answered or not, it gets one at a time until it answers faster: a slow endpoint delays only its own events.
- Apply each item once. Skip an event
idyou have handled, and apply each item of a transaction event once, for example by recording the eventidin the same database transaction as the items. - Never roll back a final status.
swept,failed,rejectedandrevokednever change. Aprocessingorqueuedthat arrives for an item that is already final is older news: ignore it.isFinalStatusin TypeScript andFinalStatusin Go tell a final status. - Accept bodies of up to 256 KiB. A transaction event carries up to 200 items. Some servers refuse larger
bodies by default: Express’s body parsers stop at 100 KB unless you raise their
limit.
Verify the signature
Section titled “Verify the signature”v1 is the HMAC-SHA256, in hex, of the string <t>.<body> with your webhook secret as the key, where <t> is the
t of the header and <body> the raw request body. To verify a delivery:
- read the raw body, before any JSON parsing: re-serialized JSON would not match;
- take
tandv1from the header; with severalv1, the last one counts; - compute the HMAC and compare it with
v1in constant time; - check that
tis within 5 minutes of your clock, either way, so that an old delivery cannot be replayed.
Each attempt is signed again with its own t.
With the Go SDK, ParseWebhook verifies and decodes, Event.Transaction() decodes a transaction event and its
Sweeps() the items:
http.HandleFunc("POST /hooks/sweeps", func(w http.ResponseWriter, r *http.Request) { // Verify the body exactly as it arrived, before parsing it. Bodies go up to 256 KiB; this allows 1 MiB. body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { http.Error(w, "cannot read the body", http.StatusBadRequest) return } event, err := portuna.ParseWebhook(secret, r.Header.Get(portuna.SignatureHeader), body) if err != nil { http.Error(w, "bad signature", http.StatusUnauthorized) return } // Delivery is at least once: an event may come again, with the same id. if handled(event.ID) { w.WriteHeader(http.StatusNoContent) return } switch event.Type { case portuna.EventTransactionSent, portuna.EventTransactionMined, portuna.EventTransactionReverted, portuna.EventTransactionDropped: // One event per transaction, with every sweep it carries. tx, err := event.Transaction() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } if tx.Transaction.Kind != portuna.TransactionSweep { break // revocations: tx.Revocations() } sweeps, err := tx.Sweeps() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } for _, s := range sweeps { // processing in transaction.sent; swept or failed in transaction.mined; queued or failed in // transaction.reverted and transaction.dropped. apply(s.ID, s.Status) log.Printf("sweep %s (%s), transaction %d #%d: %s %s %s", s.ID, s.ExternalID, tx.Transaction.ID, s.BatchIndex, s.Status, s.SweptAmount, s.Reason) } case portuna.EventSweepRejected, portuna.EventSweepFailed: // A sweep that ended before any transaction carried it. sweep, err := event.Sweep() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } apply(sweep.ID, sweep.Status) log.Printf("sweep %s (%s): %s %s", sweep.ID, sweep.ExternalID, sweep.Status, sweep.Reason) case portuna.EventBalanceLow: alert, err := event.BalanceLow() if err != nil { http.Error(w, "bad event", http.StatusBadRequest) return } log.Printf("top up the gas wallet on chain %d: %s wei left", alert.ChainID, alert.Balance) default: // Other and future event types: accept them. } markHandled(event.ID) w.WriteHeader(http.StatusNoContent)})With the TypeScript SDK on Node.js, parseWebhookSync from @portuna/sdk/node; elsewhere (edge runtimes,
Deno, Bun) the async parseWebhook from @portuna/sdk, on Web Crypto. sweepItems gives the items of a
transaction event:
// Records a sweep's status, unless it already has a final one: events may come out of order, and a processing or// queued that comes after swept or failed is older news.function apply(id: string, status: string): void { const old = statuses.get(id) if (old === undefined || !isFinalStatus(old)) statuses.set(id, status)}
function handle(event: Event): void { switch (event.type) { case 'transaction.sent': case 'transaction.mined': case 'transaction.reverted': case 'transaction.dropped': { // One event per transaction, with every sweep it carries; revocations: revocationItems. const { transaction } = event.data if (transaction.kind !== 'sweep') break for (const s of sweepItems(event.data)) { // processing in transaction.sent; swept or failed in transaction.mined; queued or failed in // transaction.reverted and transaction.dropped. apply(s.id, s.status) console.log(`sweep ${s.id} (${s.external_id}), transaction ${transaction.id} #${s.batch_index}: ${s.status}`) } break } case 'sweep.rejected': case 'sweep.failed': // A sweep that ended before any transaction carried it. apply(event.data.id, event.data.status) console.log(`sweep ${event.data.id} (${event.data.external_id}): ${event.data.status} ${event.data.reason}`) break case 'balance.low': console.log(`top up the gas wallet on chain ${event.data.chain_id}: ${event.data.balance} wei left`) break case 'balance.payout': console.log(`payout ${event.data.id} of ${event.data.amount} wei to ${event.data.to}: ${event.data.status}`) break default: // Other and future event types: accept them. }}
createServer((req, res) => { const chunks: Buffer[] = [] req.on('data', (chunk: Buffer) => chunks.push(chunk)) req.on('end', () => { // Verify the body exactly as it arrived, before parsing it. Bodies go up to 256 KiB: node:http has no limit, // while Express's body parsers stop at 100 KB unless told otherwise: // express.raw({ type: 'application/json', limit: '1mb' }). const body = Buffer.concat(chunks) let event: Event try { event = parseWebhookSync(secret, String(req.headers[signatureHeader.toLowerCase()] ?? ''), body) } catch { res.writeHead(401).end() return } // Delivery is at least once: an event may come again, with the same id. if (!handled.has(event.id)) { handle(event) handled.add(event.id) } res.writeHead(204).end() })}).listen(8080)No SDK needed, only the standard library:
# Verifies the Portuna-Signature header of a webhook delivery, with the standard library only.# The docs tests run it against the signature vectors the SDKs and the service share.import hashlibimport hmacimport reimport time
TOLERANCE = 300 # seconds between the signature time and now, either way
class SignatureError(Exception): pass
def verify_webhook(secret: str, header: str, body: bytes, now: float | None = None, tolerance: int = TOLERANCE) -> None: """Raises SignatureError unless the header signs body with secret within tolerance of now.
body must be the request body exactly as received, before any JSON parsing. """ ts, sig = None, None for part in header.split(","): key, _, value = part.partition("=") if key == "t": ts = value elif key == "v1": sig = value if ts is None or not re.fullmatch(r"[+-]?[0-9]+", ts) or not sig: raise SignatureError("malformed signature header") if abs((time.time() if now is None else now) - int(ts)) > tolerance: raise SignatureError("signature timestamp out of tolerance") expected = hmac.new(secret.encode(), ts.encode() + b"." + body, hashlib.sha256).hexdigest() if not hmac.compare_digest(sig.encode(), expected.encode()): raise SignatureError("signature mismatch")In a Flask app:
@app.post("/hooks/sweeps")def sweeps_hook(): try: verify_webhook(SECRET, request.headers.get("Portuna-Signature", ""), request.get_data()) except SignatureError: abort(401) event = request.get_json() ... # store the event; apply event["data"]["items"] once each, by event["id"] return "", 204Check your implementation with this delivery: with now = 1800000000, it must verify; with another secret or a
changed body, it must not.
| secret | whsec_test |
| body | {"id":"e1","type":"transaction.mined"} |
| header | t=1800000000,v1=b4a7e6ed6f00ceb2a7b48630ec90f0c0bab685e6d44d62e71aac58f37bbf2800 |
Test your endpoint
Section titled “Test your endpoint”curl -X POST "https://api-testnet.portuna.io/v1/webhook/test" -H "Authorization: Bearer $PORTUNA_API_KEY"It queues a sample transaction.mined event, signed and delivered like any other, and responds with 202 and the
event id. Nothing in it is real: transaction 0, sweeps with zero ids, a hash of zeros, and test: true in its
data. Make your receiver store it and skip it: credit nothing for an event whose data.test is true. Without a
webhook set, the response is 404 not_found.
Low balance alerts
Section titled “Low balance alerts”low_balance in PUT /v1/webhook sets a threshold in wei for each chain you want an alert on. The gas wallet is
checked every minute. When it falls below the threshold, you get one balance.low event; the alert re-arms once the
balance is back above it. low in GET /v1/webhook shows whether a chain is below its threshold now. Chains
without a threshold get no alert.
Set the threshold to a day or two of your usual gas: if the gas wallet runs dry, sweeps wait and retry, and after their attempts run out they fail.