> ## Documentation Index
> Fetch the complete documentation index at: https://second.tech/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Design payment flows

> Design send and receive flows for a wallet app built on Bark to show users what is instant, what is pending, and why.

One Bark integration gives your wallet app three rails (Ark, Lightning, on-chain). Nothing in a pasted address or invoice tells the user how each one settles.

## Accept anything the user pastes

Build one destination field with auto-detection, not a rail picker. Match whatever the user pastes or scans against the supported formats in this priority order:

1. `lightning:` URIs, which carry a BOLT11 invoice, a BOLT12 offer, a Lightning address, or an LNURL-pay link
2. BIP 321 `bitcoin:` URIs, which can carry several payment options at once
3. BOLT11 invoices and BOLT12 offers
4. Lightning addresses (`user@domain`), LNURL-pay links, and `lnurlp://` URIs
5. Ark addresses
6. Bare on-chain addresses
7. Hex-encoded output scripts

> [tab] Bark SDK
>
> Trim whitespace from whatever the user pastes, then call `parsePaymentRequest()`. Each parsed option carries its own validation errors, so a URI with one invalid rail still offers the others. A rail that does not parse at all makes the whole URI fail. `defaultOption` selects Ark, then Lightning, then on-chain among the clean ones. `estimatePaymentFee()` prices an option's `method` and `sendPayment()` pays it. A hex output script and an on-chain address for another network each parse with an error on their option. Show that error instead of offering the option.

> [tab] Bark CLI
>
> `bark send <destination>` accepts every format above except hex output scripts. It pays an on-chain address from the Ark balance through the same path as `bark send-onchain`. When a BIP 321 URI carries several valid options, `bark` prompts for a choice (`--method-index <n>` skips the prompt).

> [tab] Barkd
>
> `POST /api/v1/wallet/send` parses the destination itself. It accepts every format above except hex output scripts. It pays an on-chain address from the Ark balance. When the destination offers several valid options, set `method` to `ark`, `lightning`, or `onchain` to pick one. Without `method`, Barkd picks Ark, then Lightning, then on-chain.

Show the detected rail on the confirmation screen. It sets the user's expectations for speed and fees.

## Give payers one thing to scan

For receiving, build a single BIP 321 `bitcoin:` URI with up to three options. Those are an on-chain address, a fresh Ark address in the `ark=` parameter, and a BOLT11 invoice when an amount is set. Render it as one QR code with a copy field. Each payer's wallet app selects the option it understands.

* **Every surface builds the URI:** The SDK's `bip321Uri()`, the Rust crate's `bip321_uri()`, `bark bip321 --all`, and `POST /api/v1/wallet/bip321` (`onchain: true` for the address) assemble one. In the SDK, `bip321Uri()` includes an on-chain address only when you pass one in `onchainAddress`.
* **No amount, no invoice:** Include the BOLT11 invoice only when the user sets an amount, so a QR without an amount serves Ark and on-chain payers only.
* **Request a fresh address per receive:** Each call to `newAddress` (`new_address()` in Rust) derives and stores a new key. Generate a new Ark address for each receive instead of caching one.

## Show the right state while receiving

Pending means something different on each rail:

| Rail | While pending | Spendable when |
| - | - | - |
| Ark | Nothing to show. Delivery is near-instant. | The wallet app picks the payment up from the server mailbox on its next sync. |
| Lightning | Show "Incoming payment" from the receive's `pending` movement. `claimable_lightning_receive_sat` counts the payment only after the preimage goes out and before the claim completes. | The wallet app claims the payment during sync and sweeps it into a spendable VTXO. |
| On-chain, then [board](https://second.tech/docs/learn/board.md) | Show "Confirming deposit" from `pending_board_sat`. | The board transaction reaches the server's required confirmations. |

A Lightning receive (`bark lightning invoice <amount>` on the CLI) moves through a lifecycle your app can surface directly:

* `awaiting-payment`: The invoice exists but the sender has not paid.
* `htlcs-ready`: The payment arrived and the server granted HTLC VTXOs.
* `preimage-revealed`: A claim failed after the preimage went out. The wallet app retries it.
* `delivering`: The claimed bitcoin is on its way to another Ark address, for an invoice the wallet app created for someone else.
* `settled`: The receive is complete.

A successful receive into the user's own wallet goes straight from `htlcs-ready` to `settled`. The wallet app moves through these states automatically during sync, so render them as a status line ("Waiting for payment", "Claiming payment") with no buttons. The receive's movement appears as `pending` when the HTLCs arrive, before the wallet app claims them. Show the payment as received only once that movement is `successful`. [Maintenance](https://second.tech/docs/patterns/maintenance.md#expose-the-next-refresh-deadline) covers the notification streams that push these updates instead of polling.

> [!NOTE]
>
> **A canceled invoice stays payable until it expires**
>
> `cancelLightningReceive` in the SDK (`DELETE /api/v1/lightning/receives/{identifier}` on Barkd) works only while the receive is `awaiting-payment`. The wallet app drops the invoice locally. If someone pays the invoice anyway, the server holds the payment and then fails it back to the sender. Once the HTLCs are granted, your wallet app can no longer cancel.
>
> To shorten how long a canceled invoice stays payable, create it with a short expiry. Pass `expirySecs` to `bolt11Invoice()` in the SDK, `--expiry <seconds>` to `bark lightning invoice` on the CLI, or `expiry_secs` to Barkd. The expiry cannot exceed the Ark server's invoice expiry.

## Set expectations when sending

* **Ark, near-instant:** A payment to another user of the same server completes out-of-round, without waiting for a [round](https://second.tech/docs/learn/rounds.md). Show success when the movement completes. The recipient's wallet app picks it up on its next sync, even if it is offline right now.
* **Lightning, stepped:** Show a stepped progress indicator rather than an indefinite spinner, and keep a failed payment visible as being reclaimed until its movement settles. The sats sit in `pending_lightning_send_sat` until then.
* **On-chain, confirming:** A send from the Ark balance (`bark send-onchain`, or an offboard back to the user's own on-chain wallet) forfeits VTXOs to deliver an on-chain output. The wallet app broadcasts the server-signed transaction immediately. The recipient waits for block confirmations like any [on-chain payment](https://second.tech/docs/learn/payments-on-chain.md). [Choose the on-chain payment source](https://second.tech/docs/patterns/payment-source.md) covers which balance pays.

A Lightning send progresses through observable states:

* **On the way to `paid`:** `start`, `inputs-locked`, `htlc-received`, and `payment-initiated`.
* **Only after a failure or timeout:** `revocable-htlcs` and `revocation-stuck`, while the wallet app revokes the [HTLC](https://second.tech/docs/learn/payments-lightning.md) to reclaim the bitcoin. A send in `revocation-stuck` keeps retrying the revocation. Bark exits it only after your wallet app calls `allowLightningSendToExit(paymentHash)`. It then hands the HTLC VTXOs to the exit process as they near expiry. `stuckFailedLightningSends()` lists the stuck sends. Both calls are SDK and Rust only.
* **At `paid`:** The state carries the preimage, which your app can store as proof of payment.

Set `retryForSecs` (SDK), `--retry-for <seconds>` (CLI), or `retry_for_secs` (Barkd) to the number of seconds the Ark server keeps trying to pay. The server caps it at its own maximum and picks a default when you omit it.

Read the state by payment hash:

> [tab] Bark SDK
>
> `lightningSendState` (`lightning_send_state` in Rust) reports three states:
>
> * `unknown`: No record of that payment hash.
> * `inProgress`: Carries a `send` object with `amountSats`, `feeSats`, and a `hasFailedRevocation` flag.
> * `paid`: Carries the preimage.

> [tab] Bark CLI
>
> `bark lightning pay status` returns the full list of phases above. It syncs the wallet and drives the send forward as far as it can go before it prints the state.

> [tab] Barkd
>
> `GET /api/v1/lightning/sends/{identifier}` returns the full list of phases, as a plain read. Barkd's send responses include the `payment_hash` for this lookup.

Every surface returns `unknown` for a payment hash the wallet never recorded. It also returns `unknown` once Bark reclaims or exits a failed send. Read the movements to tell the two apart. A payment the wallet never recorded has none. Each attempt to pay an invoice records its own movement, so read the latest one for the outcome.

## Reflect outcomes from movements

Every Ark payment, Lightning payment, and send from the Ark balance lands in the payment history with status `pending`, `successful`, `failed`, or `canceled`. A Lightning receive appears only once the payment arrives. Sends and deposits of Bark's on-chain wallet never appear there. Boards and emergency exits do. Drive the payment detail screen from the movement record rather than an in-memory state machine, so the screen still shows the truth after a process kill or restart. In the Bark SDK, the first three fields below are `effectiveBalanceSats`, `intendedBalanceSats`, and `offchainFeeSats`. The fields that matter, under their Barkd and CLI names:

* **Amounts:** Display `effective_balance_sat`, how much the balance changed, fees included. `intended_balance_sat` is an estimate that often excludes fees.
* **Fees:** `offchain_fee_sat` carries the off-chain fee. On-chain fees can appear in `metadata`, depending on the subsystem.
* **Destinations:** `sent_to` and `received_on` list each destination with an amount and a type tag (`ark`, `bitcoin`, `invoice`, `offer`, `lightning-address`, `lnurl`, `output-script`, or `custom`). Select the rail icon from the tag instead of parsing the destination string. On the SDK, `sentToAddresses` and `receivedOnAddresses` hold each destination's type tag and value as a JSON string.
* **Metadata:** The `metadata` map is writable for your own references, like an order ID, from the Rust crate (`update_history_metadata`) and Barkd. On Barkd, `POST /api/v1/history/{id}/metadata` merges a patch and removes keys set to `null`.

To open the detail screen right after a send, read the movement by the ID the send returns. In the SDK, `sendArkoorPayment`, the Ark case of `sendPayment`, `sendOnchain`, and the offboard calls return it. On Barkd, the offboard and `send-onchain` responses carry `movement_id`. After `POST /api/v1/wallet/send`, find the movement in the history. For Lightning, the send response carries the payment hash.

Sort movements in your app when the order matters. `GET /api/v1/history` returns them newest first. `bark history` and that endpoint filtered with `type` and `value` return them oldest first.

> [!NOTE]
>
> **A failed movement can still have moved VTXOs**
>
> A movement with status `failed` can still have consumed and produced VTXOs. Its `exited_vtxos` field lists VTXOs handed to the exit subsystem, for example after a Lightning send that could not be revoked. Read the VTXO lists instead of assuming nothing changed.

## Handle these edge cases

* **Two Ark address shapes behave differently:** An address whose delivery mechanisms Bark does not support fails before any VTXO is locked, so show that error on the send screen. Bark pays an address that lists no delivery mechanism without any mailbox delivery, by the recipient's own choice.
* **Received Ark payments start on an adjusted trust model:** An out-of-round payment keeps the [spend VTXO trust model](https://second.tech/docs/learn/payments.md#the-payment-security-trade-off) until it is refreshed. Your payment flow does not need to act on this, because [maintenance](https://second.tech/docs/patterns/maintenance.md) refreshes on schedule.
* **Lightning receives can require authentication:** As anti-DoS protection, the server may require a receive token (passed when creating the invoice) or a proof of VTXO ownership. It enforces them when the wallet app claims the payment. A brand-new wallet app with an empty balance is the case to test end to end. Bark drops a receive the server refuses right away and records no movement. The server holds the payment, then fails it back to the sender. Hand a receive stuck after the preimage went out to the exit process with `attemptLightningReceiveExit` (SDK and Rust only).
* **An on-chain deposit is not an Ark receive:** Sats sent to the on-chain address land in the separate on-chain balance. Moving them into a VTXO is a [board](https://second.tech/docs/learn/board.md) with its own confirmation wait. Make the two receive paths visually distinct.

> [accordion] How Bark Wallet does it
>
> * **Destination field:** [Bark Wallet](https://second.tech/docs/bark-wallet.md) uses one destination field (placeholder "Ark, Lightning, or on-chain"). When a pasted or scanned URI offers several rails, it shows a picker with each option's fee and preselects Ark, then Lightning, then on-chain. [Send bitcoin](https://second.tech/docs/bark-wallet/send-receive.md#send-bitcoin) lists the formats it accepts.
> * **Receive screen:** The [receive screen](https://second.tech/docs/bark-wallet/send-receive.md#receive-bitcoin) requests a fresh Ark address each time the dialog opens and encodes the BIP 321 URI client-side.
> * **Live updates:** The installed version keeps one WebSocket open and refetches balance, history, and VTXOs on every movement notification, with a balance poll as backstop. A positive incoming movement flips the receive dialog to "Payment received", while an unconfirmed deposit shows "On-chain payment incoming".
> * **History:** The history list shows one status badge per row (Pending, Successful, Failed, Canceled) and a payment-type label taken from the movement's subsystem or its destination type tag. "Ark: Refresh" movements are hidden by default behind a "Hide refreshes" option.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.