Skip to content

swapwallet: Settle Lightning receives over Ark channels - #1139

Open
sputn1ck wants to merge 5 commits into
kon/ark-channel-daemonfrom
kon/modular-ark-channels
Open

sputn1ck wants to merge 5 commits into
kon/ark-channel-daemonfrom
kon/modular-ark-channels

Conversation

@sputn1ck

@sputn1ck sputn1ck commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Integration only: do not merge on the personal lnd replacements. Land the required recovery and idle-worker behavior upstream. Select official versions of both github.com/lightningnetwork/lnd and github.com/lightningnetwork/lnd/kvdb, remove both personal replacements, and verify both resolved versions from an external main module with GOWORK=off and no replacements. Build native, mobile and WASM and run both default mixed-version directions and the enabled daemon suite on those official versions. A passing fork-pinned matrix is not release clearance.

Add an explicit wallet invoice on an already-active channel with sufficient inbound capacity. An ordinary invoice or payment does not select this path or create a channel. Persist the selected identity so settlement survives restart. The daemon's raw action gate, lazy startup and local recovery are already present in #1192. This PR adds the SDK payment bridge and passes the same default-off choice through embedded Go (wavewalletdk.Config.ArkChannelsEnabled) and mobile/WASM host startup JSON (ark_channels_enabled). The host, not an ordinary invoice call, opts in.

Base: #1192. The generic pending-swap worker is independently reviewed in #1643 and does not change in this diff. The backend observation changes are #1642, policy parser #1637, mailbox #1638, ordinary deadlines #1639, ordinary refund protocol #1640, and both integration module pins #1641.

Verification: Go resolves the immutable #03 head on kon/ark-channel-verified-20261124-03: root v0.0.2-alpha.0.20261124193101-631755fef433, baselib v0.0.0-20261124193101-631755fef433. Both identify the same Git commit. Relative to #2, only the explicit promotion completion check and its daemon test changed, in #1192. Wallet code did not change in the recut. Full tagged daemon and native-runtime unit packages passed on this head, as did focused SDK and mobile tests. The #2 hosted mobile checks are not #3 platform builds or a two-daemon E2E result. See the lifecycle guide.

@sputn1ck

Copy link
Copy Markdown
Member Author

/gateway review

@lightninglabs-gateway

Copy link
Copy Markdown

Cannot run /gateway review on a draft PR. Mark it ready for review first.

@sputn1ck
sputn1ck marked this pull request as ready for review August 17, 2026 19:36
Copilot AI lite review requested due to automatic review settings August 17, 2026 19:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

@sputn1ck

Copy link
Copy Markdown
Member Author

/gateway review

@lightninglabs-gateway

lightninglabs-gateway Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

❌ gateway review failed: could not fetch PR context: {"level":"info","script":"fetch-pr-context.sh","event":"fetch","outcome":"attempt","step":"pr","path":"repos/lightninglabs/wavelength/pulls/1139"} {"level":"info","script":"fetch-pr-context.sh","event":"fetch","outcome":"attempt","step":"diff","path":"repos/lightninglabs/wavelength/pulls/1139"} {"level":"error","script":"fetch-pr-context.sh","event":"fetch_diff","outcome":"failure","message":"fetch diff failed: gh: Sorry, the diff exceeded the maximum number of lines (20000) (HTTP 406) "}

See workflow logs for details.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3c0bffeffb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread waved/native_ark_channel_controller.go Outdated
Comment on lines +1164 to +1167
if record.Snapshot.Phase != arkchannel.PhaseActive ||
record.Snapshot.Terms.Kind !=
arkchannel.KindReceiveIntent {
return arkchannel.ID{}, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Wait for channel activation before reporting settlement

When the private invoice settles while the receive channel is still PhaseActivating—after lnd activates the link but before the coordinator records ChannelActive—this branch returns a zero channel ID with no error. waitForChannelOrVHTLC consequently persists the swap as successfully completed with SettlementTypeArkChannel and an empty channel ID, losing the correlation needed to inspect or recover the manifested channel. Continue waiting for syncReceiveIntent to establish PhaseActive, or return an error instead of treating this intermediate state as success.

Useful? React with 👍 / 👎.

Comment thread waved/native_ark_channel_controller.go Outdated
Comment on lines +1172 to +1181
case err := <-syncResult:
if err != nil && c.cfg.Log != nil {
c.cfg.Log.WarnS(
ctx,
"Receive channel intent stopped",
err,
btclog.Hex("payment_hash", hash[:]),
)
}
syncResult = nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep synchronizing after transient receive-intent errors

If syncReceiveIntent encounters any transient mailbox or store error before activation, this case only logs it and permanently disables the synchronization branch by setting syncResult to nil. The receive then waits for an invoice that cannot settle because the client no longer binds or advances the prepared channel, typically consuming the entire invoice deadline before the swap worker can retry. Retry the durable synchronization operation or propagate the error promptly so the outer worker can resume it.

Useful? React with 👍 / 👎.

@sputn1ck
sputn1ck requested a review from bhandras August 24, 2026 13:34
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch from 2b9973c to bbded8e Compare August 24, 2026 14:37
@sputn1ck
sputn1ck changed the base branch from main to kon/ark-channel-daemon August 24, 2026 14:37
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch from bbded8e to bec163d Compare August 24, 2026 15:28
@sputn1ck sputn1ck changed the title waved: add OOR-backed native Ark channels swapwallet: Settle Lightning receives over Ark channels Aug 24, 2026
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch from bec163d to 95edaaf Compare August 24, 2026 15:35
@litbot-9000

Copy link
Copy Markdown
Collaborator

Doc advisory

This PR's Go changes left the per-package docs for sdk/swaps,
swapclientserver, rpc/swapclientrpc, rpc/wavewalletrpc, and swaprpc
behind the code: the Ark-channel receive rail and its new exported surface are
undocumented, and swapclientserver/AGENTS.md was never re-mirrored after
swapclientserver/CLAUDE.md was edited in this PR.

Proposed doc changes (advisory only — nothing is committed)
diff --git a/rpc/swapclientrpc/AGENTS.md b/rpc/swapclientrpc/AGENTS.md
index 33aa666c..fe82cfcc 100644
--- a/rpc/swapclientrpc/AGENTS.md
+++ b/rpc/swapclientrpc/AGENTS.md
@@ -14,6 +14,13 @@ credit funding/redemption/listing). Registered only in swapruntime builds.
 - Request/response messages (`QuotePayRequest`, `StartPayRequest`,
   `CreateCreditRequest`, `ListCreditsRequest`, etc.) and enums
   (`SwapState`, `SwapDirection`, `CreditOperationState`, ...).
+- `SwapSettlementType` — how a swap is backed: `LIGHTNING`, `IN_ARK`,
+  `CREDIT`, `MIXED`, and `ARK_CHANNEL` (the receive settled directly into an
+  Ark-backed native Lightning channel).
+- `SwapSummary` — flat durable view of one swap. Beyond the amount/state
+  fields it carries `channel_id` (the Ark channel manifested for a receive,
+  empty when an existing channel was reused) and `reserved_scid` (the future
+  virtual SCID advertised in the invoice).
 
 ## Relationships
 
@@ -25,6 +32,9 @@ credit funding/redemption/listing). Registered only in swapruntime builds.
 
 - Generated from `swap_client.proto` via `make rpc`; do not hand-edit any
   `.pb.go` / `.pb.gw.go` file.
+- `SwapSummary` field 29 is `reserved` under the retired name
+  `channel_backing_fee_sat`. Reserved numbers and names are a wire contract:
+  never reuse them, and reserve rather than delete when a field is dropped.
 
 ## Deep Docs
 
diff --git a/rpc/swapclientrpc/CLAUDE.md b/rpc/swapclientrpc/CLAUDE.md
index 33aa666c..fe82cfcc 100644
--- a/rpc/swapclientrpc/CLAUDE.md
+++ b/rpc/swapclientrpc/CLAUDE.md
@@ -14,6 +14,13 @@ credit funding/redemption/listing). Registered only in swapruntime builds.
 - Request/response messages (`QuotePayRequest`, `StartPayRequest`,
   `CreateCreditRequest`, `ListCreditsRequest`, etc.) and enums
   (`SwapState`, `SwapDirection`, `CreditOperationState`, ...).
+- `SwapSettlementType` — how a swap is backed: `LIGHTNING`, `IN_ARK`,
+  `CREDIT`, `MIXED`, and `ARK_CHANNEL` (the receive settled directly into an
+  Ark-backed native Lightning channel).
+- `SwapSummary` — flat durable view of one swap. Beyond the amount/state
+  fields it carries `channel_id` (the Ark channel manifested for a receive,
+  empty when an existing channel was reused) and `reserved_scid` (the future
+  virtual SCID advertised in the invoice).
 
 ## Relationships
 
@@ -25,6 +32,9 @@ credit funding/redemption/listing). Registered only in swapruntime builds.
 
 - Generated from `swap_client.proto` via `make rpc`; do not hand-edit any
   `.pb.go` / `.pb.gw.go` file.
+- `SwapSummary` field 29 is `reserved` under the retired name
+  `channel_backing_fee_sat`. Reserved numbers and names are a wire contract:
+  never reuse them, and reserve rather than delete when a field is dropped.
 
 ## Deep Docs
 
diff --git a/rpc/wavewalletrpc/AGENTS.md b/rpc/wavewalletrpc/AGENTS.md
index 00d5fbdf..c1425954 100644
--- a/rpc/wavewalletrpc/AGENTS.md
+++ b/rpc/wavewalletrpc/AGENTS.md
@@ -67,6 +67,12 @@ id; unlike `List` it may leak internal correlators, so it is kept out of
 - `ExitMode` — which of the two exits an `Exit` call actually ran
   (`COOPERATIVE` / `UNILATERAL`). `EXIT_MODE_UNSPECIFIED` is what an older
   daemon sends; clients must treat it as "unknown", not as a default.
+- `ActivitySwapTrace` — `InspectActivity`'s per-swap drill-down. Carries the
+  internal correlators `List` deliberately drops, including `channel_id` (the
+  Ark channel manifested by a receive fallback, empty when existing inbound
+  was used) and `reserved_scid` (the virtual SCID advertised in the receive
+  invoice and later installed as the channel's local alias). Field 23 is
+  `reserved` under the retired name `channel_backing_fee_sat`.
 - `FailureDomain` / `Reason*` constants (`failure_reasons.go`) — the
   `google.rpc.ErrorInfo` domain/reason wire contract for failed wallet
   RPCs; existing reason values MUST NOT be renamed.
diff --git a/rpc/wavewalletrpc/CLAUDE.md b/rpc/wavewalletrpc/CLAUDE.md
index 00d5fbdf..c1425954 100644
--- a/rpc/wavewalletrpc/CLAUDE.md
+++ b/rpc/wavewalletrpc/CLAUDE.md
@@ -67,6 +67,12 @@ id; unlike `List` it may leak internal correlators, so it is kept out of
 - `ExitMode` — which of the two exits an `Exit` call actually ran
   (`COOPERATIVE` / `UNILATERAL`). `EXIT_MODE_UNSPECIFIED` is what an older
   daemon sends; clients must treat it as "unknown", not as a default.
+- `ActivitySwapTrace` — `InspectActivity`'s per-swap drill-down. Carries the
+  internal correlators `List` deliberately drops, including `channel_id` (the
+  Ark channel manifested by a receive fallback, empty when existing inbound
+  was used) and `reserved_scid` (the virtual SCID advertised in the receive
+  invoice and later installed as the channel's local alias). Field 23 is
+  `reserved` under the retired name `channel_backing_fee_sat`.
 - `FailureDomain` / `Reason*` constants (`failure_reasons.go`) — the
   `google.rpc.ErrorInfo` domain/reason wire contract for failed wallet
   RPCs; existing reason values MUST NOT be renamed.
diff --git a/sdk/swaps/AGENTS.md b/sdk/swaps/AGENTS.md
index a981539e..ec779ada 100644
--- a/sdk/swaps/AGENTS.md
+++ b/sdk/swaps/AGENTS.md
@@ -18,7 +18,9 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 - `SwapClient` — top-level entry point. Constructed via `NewSwapClient`
   (no persistence) or `NewSwapClientWithStore` (SQLite-backed). Holds
   an `OutSwapEventReceiver` overridable via
-  `SetOutSwapEventReceiver`.
+  `SetOutSwapEventReceiver`, and an optional
+  `ArkChannelPaymentBridge` installed via
+  `SetArkChannelPaymentBridge`.
 - `PaySession` — Ark-to-Lightning pay FSM:
   `Created → SwapCreated → FundingInitiated → VHTLCFunded →
   WaitingForClaim → Completed` (or `Expired` / `RefundInitiated →
@@ -28,7 +30,10 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
   ClaimInitiated → Completed` (or `Expired` / `NeedsIntervention` /
   `Failed`). `HTLCEventAccepted` is a durable checkpoint persisted
   after the server mailbox event is validated so funding detection
-  resumes without re-driving mailbox delivery.
+  resumes without re-driving mailbox delivery. When an
+  `ArkChannelPaymentBridge` is installed, `InvoiceCreated` can also
+  advance straight to `Completed`: the payment settled inside an
+  Ark-backed native Lightning channel, so there is no vHTLC to claim.
 - `MailboxOutSwapEventReceiver` — mailbox-backed receiver. Pulls
   out-swap HTLC events from a `mailbox/pb` edge keyed by a per-session
   mailbox ID derived from the client identity key and payment hash.
@@ -55,9 +60,18 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 - `IncomingVHTLCEventReceiver` — interface for receivers that
   handle both Lightning-backed and same-Ark vHTLC events; implemented
   by `MailboxOutSwapEventReceiver`.
-- `SettlementType` — `SettlementTypeLightning`, `SettlementTypeInArk`
-  (returned in `InSwapConfig` identifying how the server bridges
-  payment).
+- `SettlementType` — how a swap is backed: `SettlementTypeLightning`,
+  `SettlementTypeInArk`, `SettlementTypeCredit`, `SettlementTypeMixed`
+  (vHTLC + reserved credit), and `SettlementTypeArkChannel` (the
+  receive settled directly into an active Ark-backed native Lightning
+  channel). Returned in `InSwapConfig` for pay quotes and recorded on
+  `SwapSummary` / `ReceiveResult` for receives.
+- `ArkChannelPaymentBridge` — narrow daemon-owned channel boundary
+  (`PrepareIncomingPayment`, `RegisterIncomingPayment`,
+  `WaitIncomingPayment`) that lets a receive settle over a native
+  Ark channel without the SDK owning invoices or channel state. lnd
+  stays authoritative; the production implementation is
+  `swapclientserver.arkChannelPaymentBridge` over `waved.RPCServer`.
 - `Store` — isolated SQLite persistence. Runs its own migration table
   (`swap_client_schema_migrations`) separate from the main daemon DB.
 - `SwapServerConn` / `GRPCSwapServerConn` — remote swap-server gRPC
@@ -83,7 +97,13 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 - `PayState` / `ReceiveState` — typed FSM enums with `IsTerminal()` /
   `String()`. `ReceiveState` includes `ReceiveStateHTLCEventAccepted`.
 - `VHTLCConfig`, `InSwapConfig`, `RouteHint` — server-negotiation
-  DTOs. `SwapSummary` — flat list view for persisted sessions.
+  DTOs. `SwapSummary` — flat list view for persisted sessions; it
+  also carries `ChannelID` (the Ark channel manifested for a receive,
+  zero when an existing channel was reused) and `ReservedSCID` (the
+  virtual SCID advertised in the invoice route hint).
+- `ReceiveResult` — returned by `ReceiveSession.Wait` / `Claim`;
+  reports `ChannelID` and `SettlementType` alongside the claimed VTXO
+  outpoint so callers can tell a channel settlement from a vHTLC claim.
 - `RecoveryPolicy` / `DefaultRecoveryPolicy` — governs auto-escalation
   from cooperative vHTLC retry to daemon-owned on-chain recovery
   (arm/escalate/cancel via `DaemonConn`'s VHTLC recovery RPCs).
@@ -110,7 +130,8 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 ## Relationships
 
 - **Depends on**: `lib/arkscript` (vHTLC policy + claim/refund
-  tapscript paths), `sdk/ark` (type aliases), `swaprpc` (gRPC stubs),
+  tapscript paths), `arkchannel` (`arkchannel.ID` returned by the
+  channel bridge), `sdk/ark` (type aliases), `swaprpc` (gRPC stubs),
   `vtxo` (forfeit sign-request conversion), `mailbox/pb` (edge
   pull/ack), `serverconn` + `serverconn/mailboxpull` (`CompoundMailboxID`,
   `PubKeyMailboxID`, mailbox pull backoff), `db` + `db/migrate` +
@@ -134,6 +155,13 @@ same-Ark vHTLC event: if `outEvents` implements
 otherwise the flow falls back to `WaitOutSwapHtlc` and converts the
 result into an `IncomingVHTLCNotification`.
 
+When an `ArkChannelPaymentBridge` is installed, `prepareInvoice`
+additionally calls `PrepareIncomingPayment` (before the route quote,
+to install the known-preimage native invoice) and
+`RegisterIncomingPayment` (after it, to bind the quoted final-hop
+SCID at the hub). `waitForChannelOrVHTLC` then races
+`WaitIncomingPayment` against the mailbox vHTLC rail.
+
 ## Invariants
 
 - `mutateAndPersist` is the only way to change session state — it
@@ -168,6 +196,20 @@ result into an `IncomingVHTLCNotification`.
   and durably persisted the event. `AckCursor` is `eventSeq + 1`.
 - `ReceiveAuthKey` signing/ECDH is always delegated to the daemon;
   the SDK never holds the raw private key for receive-auth.
+- **Exactly one receive rail may reveal the shared preimage.**
+  `waitForChannelOrVHTLC` cancels only its own child context, so a
+  losing local subscription is torn down without failing the swap. A
+  channel-bridge error while the wait context is still live drops that
+  rail and keeps waiting on the vHTLC rail; a vHTLC error is returned.
+- `SettlementTypeArkChannel` is **receive-only**. Both
+  `validateInSwapPreview` and `validateInSwapQuote` reject it for pay
+  quotes rather than trying to price a channel settlement.
+- Receive rows persist `reserved_scid` (8 bytes big-endian, empty when
+  unset) and `channel_id` (32 bytes, empty when unset).
+  `receiveSummaryFromRow` / `receiveSessionFromRow` reject any other
+  width and a negative `channel_backing_fee_sat` rather than silently
+  truncating. `LatestMigrationVersion` is `2`; bump it with every new
+  file in `migrations/`.
 - Error sentinels (`ErrSwapExpired`, `ErrSwapRefunded`,
   `ErrSwapSummaryNotFound`) are exported; callers use `errors.Is`.
 - The credit ledger is server-authoritative; local state only records
diff --git a/sdk/swaps/CLAUDE.md b/sdk/swaps/CLAUDE.md
index a981539e..ec779ada 100644
--- a/sdk/swaps/CLAUDE.md
+++ b/sdk/swaps/CLAUDE.md
@@ -18,7 +18,9 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 - `SwapClient` — top-level entry point. Constructed via `NewSwapClient`
   (no persistence) or `NewSwapClientWithStore` (SQLite-backed). Holds
   an `OutSwapEventReceiver` overridable via
-  `SetOutSwapEventReceiver`.
+  `SetOutSwapEventReceiver`, and an optional
+  `ArkChannelPaymentBridge` installed via
+  `SetArkChannelPaymentBridge`.
 - `PaySession` — Ark-to-Lightning pay FSM:
   `Created → SwapCreated → FundingInitiated → VHTLCFunded →
   WaitingForClaim → Completed` (or `Expired` / `RefundInitiated →
@@ -28,7 +30,10 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
   ClaimInitiated → Completed` (or `Expired` / `NeedsIntervention` /
   `Failed`). `HTLCEventAccepted` is a durable checkpoint persisted
   after the server mailbox event is validated so funding detection
-  resumes without re-driving mailbox delivery.
+  resumes without re-driving mailbox delivery. When an
+  `ArkChannelPaymentBridge` is installed, `InvoiceCreated` can also
+  advance straight to `Completed`: the payment settled inside an
+  Ark-backed native Lightning channel, so there is no vHTLC to claim.
 - `MailboxOutSwapEventReceiver` — mailbox-backed receiver. Pulls
   out-swap HTLC events from a `mailbox/pb` edge keyed by a per-session
   mailbox ID derived from the client identity key and payment hash.
@@ -55,9 +60,18 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 - `IncomingVHTLCEventReceiver` — interface for receivers that
   handle both Lightning-backed and same-Ark vHTLC events; implemented
   by `MailboxOutSwapEventReceiver`.
-- `SettlementType` — `SettlementTypeLightning`, `SettlementTypeInArk`
-  (returned in `InSwapConfig` identifying how the server bridges
-  payment).
+- `SettlementType` — how a swap is backed: `SettlementTypeLightning`,
+  `SettlementTypeInArk`, `SettlementTypeCredit`, `SettlementTypeMixed`
+  (vHTLC + reserved credit), and `SettlementTypeArkChannel` (the
+  receive settled directly into an active Ark-backed native Lightning
+  channel). Returned in `InSwapConfig` for pay quotes and recorded on
+  `SwapSummary` / `ReceiveResult` for receives.
+- `ArkChannelPaymentBridge` — narrow daemon-owned channel boundary
+  (`PrepareIncomingPayment`, `RegisterIncomingPayment`,
+  `WaitIncomingPayment`) that lets a receive settle over a native
+  Ark channel without the SDK owning invoices or channel state. lnd
+  stays authoritative; the production implementation is
+  `swapclientserver.arkChannelPaymentBridge` over `waved.RPCServer`.
 - `Store` — isolated SQLite persistence. Runs its own migration table
   (`swap_client_schema_migrations`) separate from the main daemon DB.
 - `SwapServerConn` / `GRPCSwapServerConn` — remote swap-server gRPC
@@ -83,7 +97,13 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 - `PayState` / `ReceiveState` — typed FSM enums with `IsTerminal()` /
   `String()`. `ReceiveState` includes `ReceiveStateHTLCEventAccepted`.
 - `VHTLCConfig`, `InSwapConfig`, `RouteHint` — server-negotiation
-  DTOs. `SwapSummary` — flat list view for persisted sessions.
+  DTOs. `SwapSummary` — flat list view for persisted sessions; it
+  also carries `ChannelID` (the Ark channel manifested for a receive,
+  zero when an existing channel was reused) and `ReservedSCID` (the
+  virtual SCID advertised in the invoice route hint).
+- `ReceiveResult` — returned by `ReceiveSession.Wait` / `Claim`;
+  reports `ChannelID` and `SettlementType` alongside the claimed VTXO
+  outpoint so callers can tell a channel settlement from a vHTLC claim.
 - `RecoveryPolicy` / `DefaultRecoveryPolicy` — governs auto-escalation
   from cooperative vHTLC retry to daemon-owned on-chain recovery
   (arm/escalate/cancel via `DaemonConn`'s VHTLC recovery RPCs).
@@ -110,7 +130,8 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
 ## Relationships
 
 - **Depends on**: `lib/arkscript` (vHTLC policy + claim/refund
-  tapscript paths), `sdk/ark` (type aliases), `swaprpc` (gRPC stubs),
+  tapscript paths), `arkchannel` (`arkchannel.ID` returned by the
+  channel bridge), `sdk/ark` (type aliases), `swaprpc` (gRPC stubs),
   `vtxo` (forfeit sign-request conversion), `mailbox/pb` (edge
   pull/ack), `serverconn` + `serverconn/mailboxpull` (`CompoundMailboxID`,
   `PubKeyMailboxID`, mailbox pull backoff), `db` + `db/migrate` +
@@ -134,6 +155,13 @@ same-Ark vHTLC event: if `outEvents` implements
 otherwise the flow falls back to `WaitOutSwapHtlc` and converts the
 result into an `IncomingVHTLCNotification`.
 
+When an `ArkChannelPaymentBridge` is installed, `prepareInvoice`
+additionally calls `PrepareIncomingPayment` (before the route quote,
+to install the known-preimage native invoice) and
+`RegisterIncomingPayment` (after it, to bind the quoted final-hop
+SCID at the hub). `waitForChannelOrVHTLC` then races
+`WaitIncomingPayment` against the mailbox vHTLC rail.
+
 ## Invariants
 
 - `mutateAndPersist` is the only way to change session state — it
@@ -168,6 +196,20 @@ result into an `IncomingVHTLCNotification`.
   and durably persisted the event. `AckCursor` is `eventSeq + 1`.
 - `ReceiveAuthKey` signing/ECDH is always delegated to the daemon;
   the SDK never holds the raw private key for receive-auth.
+- **Exactly one receive rail may reveal the shared preimage.**
+  `waitForChannelOrVHTLC` cancels only its own child context, so a
+  losing local subscription is torn down without failing the swap. A
+  channel-bridge error while the wait context is still live drops that
+  rail and keeps waiting on the vHTLC rail; a vHTLC error is returned.
+- `SettlementTypeArkChannel` is **receive-only**. Both
+  `validateInSwapPreview` and `validateInSwapQuote` reject it for pay
+  quotes rather than trying to price a channel settlement.
+- Receive rows persist `reserved_scid` (8 bytes big-endian, empty when
+  unset) and `channel_id` (32 bytes, empty when unset).
+  `receiveSummaryFromRow` / `receiveSessionFromRow` reject any other
+  width and a negative `channel_backing_fee_sat` rather than silently
+  truncating. `LatestMigrationVersion` is `2`; bump it with every new
+  file in `migrations/`.
 - Error sentinels (`ErrSwapExpired`, `ErrSwapRefunded`,
   `ErrSwapSummaryNotFound`) are exported; callers use `errors.Is`.
 - The credit ledger is server-authoritative; local state only records
diff --git a/swapclientserver/AGENTS.md b/swapclientserver/AGENTS.md
index 69571f77..19e3f69d 100644
--- a/swapclientserver/AGENTS.md
+++ b/swapclientserver/AGENTS.md
@@ -32,6 +32,11 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
 - `receiveSessionAdapter` — Adds method accessors over
   `sdk/swaps.ReceiveSession` so both production code and tests share the same
   interface without exposing struct fields.
+- `arkChannelPaymentBridge` — Adapts `sdk/swaps.ArkChannelPaymentBridge` to
+  `waved.RPCServer`'s process-owned native lnd channel controller
+  (`PrepareArkChannelIncomingPayment`, `RegisterArkChannelIncomingPayment`,
+  `WaitArkChannelIncomingPayment`) without an in-process gRPC loop. Installed
+  with `SwapClient.SetArkChannelPaymentBridge` during service construction.
 - `creditServerBridge` / `creditDaemonBridge` — Adapt the subserver and the
   in-process Ark/daemon facade to the `credit` package's `CreditServer` /
   `CreditDaemon` interfaces, so the credit durable-actor subsystem reuses this
@@ -46,6 +51,9 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
   `MailboxOutSwapEventReceiver` (empty mailbox ID — receiver derives the
   per-swap mailbox from client identity + payment hash) on the
   `SwapClient` so out-swap HTLC events flow over the mailbox transport,
+  installs the `arkChannelPaymentBridge`, publishes the authenticated
+  swapdk-server mailbox edge as `cfg.Swap.ArkChannelMailbox` (cleared again
+  on cleanup) so `waved`'s Ark-channel process can reuse the same transport,
   publishes `cfg.Swap.Backend`/`CreditServer`/`CreditDaemon` bridges,
   registers the gRPC subserver, calls `resumePending` (unless
   `cfg.Swap.SuppressResume`), and returns a cleanup function.
@@ -69,6 +77,8 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
 
 - **Depends on**: `sdk/swaps` (swap FSM, `SwapClient`, `Store`, session,
   credit types), `sdk/ark` (`WrapDaemonServer`, in-process Ark facade),
+  `arkchannel` (`arkchannel.ID` returned by the channel bridge),
+  `mailbox/pb` (mailbox method names for the wait-for-ready interceptor),
   `waved` (`RPCServer`, `Config`, `SwapConfig`, `SwapSubsystem`), `credit`
   (`CreditServer`/`CreditDaemon` interfaces bridged for the credit actor
   subsystem), `rpc/swapclientrpc` (generated gRPC stubs + proto types).
@@ -88,6 +98,13 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
 - Worker ownership is process-local and mutex-guarded: at most one goroutine
   drives a given payment hash at any time. `markActive` is the admission gate;
   `markInactive` releases it on goroutine exit.
+- A process-local resume or `Wait` error is not itself terminal. The worker
+  reads the durable summary and retries while the FSM remains pending; it
+  releases ownership only after terminal state, successful completion, missing
+  durable state, or daemon shutdown. `runSwapWorker` is the shared loop for
+  both directions and paces retries with `swapClientService.workerRetryDelay`
+  (`defaultWorkerRetryDelay`, 1s), kept on the service so tests can shorten it
+  without moving retry policy into the swap FSM.
 - The daemon uses `rootCtx` (not the individual RPC contexts) for all
   `ResumePayViaLightning` / `ResumeReceiveViaLightning` calls. A CLI
   disconnect does not cancel an admitted swap.
@@ -128,6 +145,15 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
   "no filesystem here". It mirrors `waved.ensureDataDir`; keep the two in
   step, since a Node host given an unwritable path should fail there rather
   than at the first database open.
+- `swapServerOperationWaitsForReady` gates gRPC `WaitForReady` on methods that
+  create or advance protocol state. Mailbox `Send` is in that set — a receive
+  ack must survive a swapdk-server reconnect — while mailbox `Pull`, quotes,
+  and credit snapshots stay fail-fast so a poll loop does not block on a dead
+  connection. Add new state-advancing swap or mailbox RPCs to the switch.
+- `SetArkChannelPaymentBridge`, like `SetOutSwapEventReceiver`, must be
+  installed before `resumePending`: the bridge decides whether a receive races
+  the native channel rail against the mailbox vHTLC rail, so a late install
+  would leave revived sessions on the mailbox-only path.
 - `SetOutSwapEventReceiver` must run before any receive worker is started:
   `SwapClient` captures the receiver into the per-swap worker at start time,
   so a late install would leave already-running workers using whatever
diff --git a/swapclientserver/CLAUDE.md b/swapclientserver/CLAUDE.md
index 3277b4db..19e3f69d 100644
--- a/swapclientserver/CLAUDE.md
+++ b/swapclientserver/CLAUDE.md
@@ -32,6 +32,11 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
 - `receiveSessionAdapter` — Adds method accessors over
   `sdk/swaps.ReceiveSession` so both production code and tests share the same
   interface without exposing struct fields.
+- `arkChannelPaymentBridge` — Adapts `sdk/swaps.ArkChannelPaymentBridge` to
+  `waved.RPCServer`'s process-owned native lnd channel controller
+  (`PrepareArkChannelIncomingPayment`, `RegisterArkChannelIncomingPayment`,
+  `WaitArkChannelIncomingPayment`) without an in-process gRPC loop. Installed
+  with `SwapClient.SetArkChannelPaymentBridge` during service construction.
 - `creditServerBridge` / `creditDaemonBridge` — Adapt the subserver and the
   in-process Ark/daemon facade to the `credit` package's `CreditServer` /
   `CreditDaemon` interfaces, so the credit durable-actor subsystem reuses this
@@ -46,6 +51,9 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
   `MailboxOutSwapEventReceiver` (empty mailbox ID — receiver derives the
   per-swap mailbox from client identity + payment hash) on the
   `SwapClient` so out-swap HTLC events flow over the mailbox transport,
+  installs the `arkChannelPaymentBridge`, publishes the authenticated
+  swapdk-server mailbox edge as `cfg.Swap.ArkChannelMailbox` (cleared again
+  on cleanup) so `waved`'s Ark-channel process can reuse the same transport,
   publishes `cfg.Swap.Backend`/`CreditServer`/`CreditDaemon` bridges,
   registers the gRPC subserver, calls `resumePending` (unless
   `cfg.Swap.SuppressResume`), and returns a cleanup function.
@@ -69,6 +77,8 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
 
 - **Depends on**: `sdk/swaps` (swap FSM, `SwapClient`, `Store`, session,
   credit types), `sdk/ark` (`WrapDaemonServer`, in-process Ark facade),
+  `arkchannel` (`arkchannel.ID` returned by the channel bridge),
+  `mailbox/pb` (mailbox method names for the wait-for-ready interceptor),
   `waved` (`RPCServer`, `Config`, `SwapConfig`, `SwapSubsystem`), `credit`
   (`CreditServer`/`CreditDaemon` interfaces bridged for the credit actor
   subsystem), `rpc/swapclientrpc` (generated gRPC stubs + proto types).
@@ -91,7 +101,10 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
 - A process-local resume or `Wait` error is not itself terminal. The worker
   reads the durable summary and retries while the FSM remains pending; it
   releases ownership only after terminal state, successful completion, missing
-  durable state, or daemon shutdown.
+  durable state, or daemon shutdown. `runSwapWorker` is the shared loop for
+  both directions and paces retries with `swapClientService.workerRetryDelay`
+  (`defaultWorkerRetryDelay`, 1s), kept on the service so tests can shorten it
+  without moving retry policy into the swap FSM.
 - The daemon uses `rootCtx` (not the individual RPC contexts) for all
   `ResumePayViaLightning` / `ResumeReceiveViaLightning` calls. A CLI
   disconnect does not cancel an admitted swap.
@@ -132,6 +145,15 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`.
   "no filesystem here". It mirrors `waved.ensureDataDir`; keep the two in
   step, since a Node host given an unwritable path should fail there rather
   than at the first database open.
+- `swapServerOperationWaitsForReady` gates gRPC `WaitForReady` on methods that
+  create or advance protocol state. Mailbox `Send` is in that set — a receive
+  ack must survive a swapdk-server reconnect — while mailbox `Pull`, quotes,
+  and credit snapshots stay fail-fast so a poll loop does not block on a dead
+  connection. Add new state-advancing swap or mailbox RPCs to the switch.
+- `SetArkChannelPaymentBridge`, like `SetOutSwapEventReceiver`, must be
+  installed before `resumePending`: the bridge decides whether a receive races
+  the native channel rail against the mailbox vHTLC rail, so a late install
+  would leave revived sessions on the mailbox-only path.
 - `SetOutSwapEventReceiver` must run before any receive worker is started:
   `SwapClient` captures the receiver into the per-swap worker at start time,
   so a late install would leave already-running workers using whatever
diff --git a/swaprpc/AGENTS.md b/swaprpc/AGENTS.md
index c6c377ca..e8710cd5 100644
--- a/swaprpc/AGENTS.md
+++ b/swaprpc/AGENTS.md
@@ -88,6 +88,10 @@ because they are part of the wire contract, not of either side's logic.
 - `SettlementType.SETTLEMENT_TYPE_UNSPECIFIED` (0) is treated as Lightning
   for backward compatibility with older server responses; do not repurpose
   the zero value.
+- `RequestChannelIdRequest` field 7 and `RequestChannelIdResponse` field 10
+  are `reserved` under the retired name `channel_backing_fee_sat` — receives
+  no longer negotiate a legacy channel fee reserve on the wire. Reserved
+  numbers and names are part of the wire contract; never reuse them.
 - `SwapMailboxEvent` is a proto oneof: read the populated variant, don't
   assume `OutSwapHtlcEvent` is the only case as new event kinds are added.
 
diff --git a/swaprpc/CLAUDE.md b/swaprpc/CLAUDE.md
index c6c377ca..e8710cd5 100644
--- a/swaprpc/CLAUDE.md
+++ b/swaprpc/CLAUDE.md
@@ -88,6 +88,10 @@ because they are part of the wire contract, not of either side's logic.
 - `SettlementType.SETTLEMENT_TYPE_UNSPECIFIED` (0) is treated as Lightning
   for backward compatibility with older server responses; do not repurpose
   the zero value.
+- `RequestChannelIdRequest` field 7 and `RequestChannelIdResponse` field 10
+  are `reserved` under the retired name `channel_backing_fee_sat` — receives
+  no longer negotiate a legacy channel fee reserve on the wire. Reserved
+  numbers and names are part of the wire contract; never reuse them.
 - `SwapMailboxEvent` is a proto oneof: read the populated variant, don't
   assume `OutSwapHtlcEvent` is the only case as new event kinds are added.

What drifted

  • swapclientserver/AGENTS.md — this PR edited CLAUDE.md (the new
    worker-retry invariant) but did not cp it to the sibling AGENTS.md, so
    the pair is out of sync on main's doc-pairing rule.
  • sdk/swaps — new exported surface (ArkChannelPaymentBridge,
    SetArkChannelPaymentBridge, SettlementTypeArkChannel,
    SwapSummary.ChannelID/ReservedSCID, ReceiveResult.ChannelID/
    SettlementType), a new InvoiceCreated → Completed receive-FSM edge, the
    dual-rail waitForChannelOrVHTLC race, and LatestMigrationVersion 1 → 2.
  • swapclientserver — new arkChannelPaymentBridge type, the
    cfg.Swap.ArkChannelMailbox publish/clear in Register, the shared
    runSwapWorker retry loop, and mailbox Send joining the wait-for-ready set.
  • rpc/swapclientrpc / rpc/wavewalletrpc / swaprpc — new
    ARK_CHANNEL settlement value, channel_id / reserved_scid fields, and
    the channel_backing_fee_sat reserved field numbers.

No changes proposed for sdk/swaps/sqlc or swapwallet: their docs describe
the generated row types and the inspection facade at a granularity the new
columns and forwarded trace fields do not invalidate.

How to apply

Save the diff above to a file and git apply it, or run the doc-gardening
skill locally over just these packages:

/doc-gardening sdk/swaps
/doc-gardening swapclientserver
/doc-gardening rpc/swapclientrpc
/doc-gardening rpc/wavewalletrpc
/doc-gardening swaprpc

Either way, finish with make doc-check.


This check is advisory and never fails the build.
Run: https://github.com/lightninglabs/wavelength/pull/1139/checks

@litbot-9000

Copy link
Copy Markdown
Collaborator

@bhandras: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@darioAnongba darioAnongba left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Receive is genuinely transparent to apps: hub-driven rail selection, the client races both rails, completed receives just carry settlement_type=ark_channel and a channel_id. Nice.

The problem: the bridge is now a hard dependency of every Lightning receive, so a transient channel-runtime failure durably fails receives the vHTLC rail would have settled. That's an availability regression vs today and I'd fix it before merge, together with the two Codex P1s. Inline.

+1 on both Codex P1s (zero channel ID during PhaseActivating, one-shot syncReceiveIntent); on the same block WaitIncomingPayment also swallows a GetChannel error into zero-ID success.

Note for the description: send-side rail selection is still manual (channel pay is its own verb), so "invisible plumbing" only covers receives for now. Fine as scope, worth saying.

Long version: https://ark-channels.lightning.wiki/

Comment thread swapclientserver/service.go Outdated
swapClients.server, daemonConn, log, invoiceGen, store,
)
swapClient.SetChainParams(chainParams)
swapClient.SetArkChannelPaymentBridge(&arkChannelPaymentBridge{

@darioAnongba darioAnongba Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking: installed unconditionally, and prepareInvoice calls PrepareIncomingPayment/RegisterIncomingPayment on the critical path with plain wrapped errors, which handleFailure classifies as durably Failed. Hub without channel support, directory unreachable, runtime unhealthy: every new receive fails, none falls back to vHTLC, and there's no config to turn the rail off. Make bridge prep errors advisory (skip the rail for this receive) or at least retryable, and add a kill switch.

Comment thread sdk/swaps/out_swap.go Outdated
_, supportsInArkCredit :=
s.client.outEvents.(IncomingVHTLCEventReceiver)
if s.client.channelBridge != nil {
if err := s.client.channelBridge.PrepareIncomingPayment(

@darioAnongba darioAnongba Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the critical-path call; see the service.go comment.

Comment thread sdk/swaps/out_swap.go Outdated
)
}

channelResult = nil

@darioAnongba darioAnongba Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A channel-settled receive can end up durably Expired with the sats in the channel: the invoice auto-settles (AddInvoiceWithPreimage(..., false)) and nothing ever cancels it. Crash after private settle but before Completed persists, then on resume past the deadline you only get the overdue grace; if the channel arm errors once (hub briefly down during ensureClientStarted) it's disabled right here, grace elapses, errSwapExpired. Or manifestation finishes after our wait aborted: hub pays privately, invoice settles, payer is debited, our record says Expired, and no API shows the funds. Cancel the invoice on terminal non-completion (a hold invoice would be cleaner) and reconcile settled intents at startup.

Comment thread sdk/swaps/client.go
RegisterIncomingPayment(context.Context, lntypes.Hash, btcutil.Amount,
uint64) error

WaitIncomingPayment(context.Context,

@darioAnongba darioAnongba Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No cancel on the bridge interface, which is what makes the Expired-but-settled case unrecoverable from the SDK. A CancelIncomingPayment here would close it.

Comment thread sdk/swaps/out_swap.go Outdated
// waitForChannelOrVHTLC races lnd's durable private invoice against the
// ordinary mailbox vHTLC rail. Exactly one rail can reveal the shared
// preimage; cancellation only stops the losing local subscription.
func (s *ReceiveSession) waitForChannelOrVHTLC(

@darioAnongba darioAnongba Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every receive settled on another rail leaks a non-terminal KindReceiveIntent on the client: RegisterIncomingPayment always creates it, the reaper skips it (funder is the hub), and mirrorReceiveIntentFailure only runs while syncReceiveIntent lives, which this cancels as soon as either rail settles. Direct delivery leaves it in PhaseRequested forever, rescanned every 30s and replayed every start. Terminalize it when the swap completes elsewhere, or let the reaper expire hub-funded intents after the deadline.

Comment thread sdk/swaps/store_sessions.go Outdated
AttachedCreditSat: int64(s.attachedCreditSat),
DustLimitSat: int64(s.dustLimitSat),
ReservedScid: encodeReceiveSCID(s.reservedSCID),
ChannelBackingFeeSat: 0,

@darioAnongba darioAnongba Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: channel_backing_fee_sat is always 0 but still added into receiveExpectedVHTLCSat and validated. Drop the column or stop folding it in.

@sputn1ck
sputn1ck requested a review from Roasbeef as a code owner September 8, 2026 10:03
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch from be7d740 to 9352416 Compare September 8, 2026 19:32
sputn1ck added a commit that referenced this pull request Sep 8, 2026
Replace the obsolete backing-fee reserve with the durable ownership bit
needed to reconcile hold invoices and receive intents after restart.

Target-PR: #1139
sputn1ck added a commit that referenced this pull request Sep 8, 2026
Hold the known-preimage invoice until the swap SDK selects a winning
rail, require channel activation before reporting readiness, and cancel
pre-PONR receive intents on fallback.

Target-PR: #1139
sputn1ck added a commit that referenced this pull request Sep 8, 2026
Keep vHTLC receive available when optional Ark channel setup fails.
Persist the selected channel rail before settlement and reconcile it on
restart. Resolve losing hold invoices before terminal results or mailbox
acknowledgment so only one rail can reveal the shared preimage.

Target-PR: #1139
@litbot-9000

litbot-9000 commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

📚 Per-package doc advisory

This PR's Go changes touch rpc/swapclientrpc, rpc/wavewalletrpc, sdk/swaps, sdk/swaps/sqlc, swapclientserver, swaprpc, and swapwallet. Those docs are already largely updated, but sdk/swaps has drifted: its CLAUDE.md and AGENTS.md are no longer byte-identical (make doc-check fails on it), and the surviving wording overstates when ReceiveResult.ChannelID is populated.

ReceiveResult.ChannelID is only set when the receive manifested a new channel — completeArkChannelReceive guards the assignment on manifested, and the field's GoDoc says it is zero when the payment reused an existing channel. So "channel settlements return a nonzero ChannelID" is wrong in both files.

Proposed changes
diff --git a/sdk/swaps/AGENTS.md b/sdk/swaps/AGENTS.md
index f7dde4db..2e028261 100644
--- a/sdk/swaps/AGENTS.md
+++ b/sdk/swaps/AGENTS.md
@@ -99,9 +99,10 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
   DTOs. `SwapSummary` — flat list view for persisted sessions; receive rows
   include `ChannelID` for a manifested channel and `ReservedSCID` for the
   virtual SCID advertised in the invoice.
-- `ReceiveResult` — Successful receive result. Channel settlements return a
-  nonzero `ChannelID` and `SettlementTypeArkChannel`; vHTLC settlements return
-  their claimed `VTXOOutpoint` instead.
+- `ReceiveResult` — Successful receive result. Channel settlements return
+  `SettlementTypeArkChannel`, with `ChannelID` set only when this receive
+  manifested a new channel and zero when it reused an existing one; vHTLC
+  settlements return their claimed `VTXOOutpoint` instead.
 - `RecoveryPolicy` / `DefaultRecoveryPolicy` — governs auto-escalation
   from cooperative vHTLC retry to daemon-owned on-chain recovery
   (arm/escalate/cancel via `DaemonConn`'s VHTLC recovery RPCs). Also
diff --git a/sdk/swaps/CLAUDE.md b/sdk/swaps/CLAUDE.md
index 76986cca..2e028261 100644
--- a/sdk/swaps/CLAUDE.md
+++ b/sdk/swaps/CLAUDE.md
@@ -99,9 +99,10 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap
   DTOs. `SwapSummary` — flat list view for persisted sessions; receive rows
   include `ChannelID` for a manifested channel and `ReservedSCID` for the
   virtual SCID advertised in the invoice.
-- `ReceiveResult` — Successful receive result. Channel settlements return a
-  nonzero `ChannelID` and `SettlementTypeArkChannel`; vHTLC settlements return
-  their claimed `VTXOOutpoint` instead.
+- `ReceiveResult` — Successful receive result. Channel settlements return
+  `SettlementTypeArkChannel`, with `ChannelID` set only when this receive
+  manifested a new channel and zero when it reused an existing one; vHTLC
+  settlements return their claimed `VTXOOutpoint` instead.
 - `RecoveryPolicy` / `DefaultRecoveryPolicy` — governs auto-escalation
   from cooperative vHTLC retry to daemon-owned on-chain recovery
   (arm/escalate/cancel via `DaemonConn`'s VHTLC recovery RPCs). Also
@@ -209,10 +210,11 @@ channel readiness barrier against the mailbox vHTLC notification.
 - **The SDK resolves the losing receive rail before committing the winner.**
   A vHTLC notification is validated and persisted, then the channel invoice
   and pre-point-of-no-return intent are canceled before the mailbox ACK can
-  authorize vHTLC funding. A channel-ready result records its nonzero channel
-  ID and `SettlementTypeArkChannel` before releasing the hold invoice. If a
-  vHTLC notification arrived concurrently, it takes precedence and the
-  channel rail is canceled.
+  authorize vHTLC funding. A channel-ready result records
+  `SettlementTypeArkChannel` before releasing the hold invoice, and records a
+  channel ID only when this receive manifested that channel. If a vHTLC
+  notification arrived concurrently, it takes precedence and the channel rail
+  is canceled.
 - Channel settlement and cancellation use detached, bounded contexts. A
   failure remains retryable and does not discard `channel_receive_enabled` or
   the recorded channel ID. On restart, a receive with a channel ID retries

How to apply — save the block above and git apply it, or re-run the doc-gardening skill locally (/doc-gardening sdk/swaps) followed by cp sdk/swaps/CLAUDE.md sdk/swaps/AGENTS.md.

No changes proposed for the other six scoped packages. Their docs already cover this PR's ARK_CHANNEL settlement type, the SwapSummary / ActivitySwapTrace channel correlators, the reserved proto fields, the ArkChannelPaymentBridge, and the ArkChannelReceiveEnabled opt-in. sdk/swaps/sqlc and swapwallet only gained struct fields and passthrough wiring that their docs do not enumerate.

Out of scope, pre-existing — make doc-check still reports two failures this PR did not introduce, in packages it did not change: ./.claude-pr/AGENTS.md is missing, and docs/channel-storage.md is not listed in docs/index.md. Both arrive with the base of this branch, and fixing them here would mean creating a doc file outside the scoped set.


Advisory only — this check does not fail on drift. Logs are under this PR's Checks tab, in the doc-gardening workflow run. (The run URL could not be embedded: this job's sandbox blocks reading the workflow environment.)

sputn1ck added a commit that referenced this pull request Sep 8, 2026
Replace the obsolete backing-fee reserve with the durable ownership bit
needed to reconcile hold invoices and receive intents after restart.

Target-PR: #1139
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch from f0136b5 to e08342b Compare November 9, 2026 21:00
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch 3 times, most recently from 8258a99 to b3295a5 Compare November 10, 2026 17:02
@litbot-9000

Copy link
Copy Markdown
Collaborator

@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch 2 times, most recently from ae1273a to b1b8b30 Compare November 17, 2026 21:46
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch from b1b8b30 to db8bc55 Compare November 17, 2026 21:58
@litbot-9000

Copy link
Copy Markdown
Collaborator

@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch 3 times, most recently from 0803301 to 9e7931a Compare November 18, 2026 19:04
@sputn1ck
sputn1ck force-pushed the kon/modular-ark-channels branch 2 times, most recently from 60c68ac to ced674e Compare November 19, 2026 16:25
@sputn1ck

sputn1ck commented Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

Current validation target: 631755fef433ee48dd6d2ed07e92b28a12043076 on kon/ark-channel-verified-20261124-03. External Go resolution: root v0.0.2-alpha.0.20261124193101-631755fef433, baselib v0.0.0-20261124193101-631755fef433. #1192 now owns the two-endpoint readiness barrier for explicit promotion. Prior #2 CI and E2E are historical evidence, not #3 verification. Exact-head tagged daemon/native unit tests passed locally. Cross-daemon E2E, hosted CI, and platform artifact results are separate. Integration only; no merge or release clearance.

Persist the selected rail and expose it to callers without changing
ordinary receive semantics.
Keep generated wallet, SDK and storage bindings aligned with the
explicit channel request and settlement types.
Persist the channel chosen for a receive so recovery cannot switch
rails after restart. Separate permission for new invoices from the
bridge that must finish an existing payment.
Bind the invoice to an admitted channel with inbound liquidity. Ordinary
receives retain their original rail and do not open a channel. Resume
pending settlement independently of permission for a new invoice.
Pass the same default-off admission option through embedded Go, mobile
and WASM. A wallet that omits it still protects durable channel state;
ordinary invoice and payment APIs do not change their rail.
@sputn1ck

Copy link
Copy Markdown
Member Author

Default-compatibility verification at 631755f: the published wallet ran against unmodified SwapDK master 4e08de56 and Lumos master d567e8e5. A 30,000-sat receive and 20,000-sat send settled at both ends. The 15,000-sat cooperative refund was live at height 148 (timeout 534). All three server mailbox counters (Send, Pull, AckUpTo) were zero before wallet startup, after boarding, and after 45 s idle. The default test took 127.14 s; no channel flags were passed.

Separately, the standalone wallet refused to start with protection disabled on two real snapshots: active funding and a closed channel with an outstanding cooperative payout. Its packaged WASM API respected the default-off action flag. This is not a claim that the all-enabled suite or hosted CI is green, and it does not waive the upstream LND dependency gate in #1641.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants