feat: on-chain zap splits

Extends NIP-BC onchain zaps to honor a note's NIP-57 zap-split tags: one
Bitcoin transaction pays every pubkey-based recipient atomically, and
one kind:8333 receipt is published per recipient (each receipt carries
the recipient's pubkey + sat share and shares the same i:<txid>).

quartz / OnchainZapBuilder
- new buildSplit(recipients = listOf(pubkey to sats), ...) produces a
  PSBT with one output per recipient + optional change output
- existing build(...) now delegates to buildSplit; coin selection and
  change-vs-dust logic are unchanged for the single-recipient path

commons / new OnchainZapSplitter
- distribute(totalSats, splits, dustThreshold) does the weighted
  integer-math allocation, dropping the rounding remainder onto the
  largest-weight recipient first so the per-recipient sats sum exactly
  to totalSats
- throws DustRecipientException if any share lands below dust; the
  caller surfaces that as a build-stage failure before the tx is built
- unit tests cover equal weights, fractional weights, remainder
  distribution, dust rejection, and input-order preservation

commons / OnchainZapSender.sendSplit
- mirrors send() but takes the precomputed shares, builds via
  buildSplit, and publishes N receipts using the same txid; if one
  receipt publish fails the broadcast txid + already-published receipt
  ids are surfaced in the Failure result

amethyst / Account.sendOnchainZapWithSplits
- thin wrapper that hands off to OnchainZapSender.sendSplit using the
  signer's pubkey

amethyst / OnchainZapSendDialog
- detects pubkey-based zap splits on the zappedEvent and, when present,
  defaults to split mode: a SplitsRecipientSection renders one row per
  recipient with weight % and live per-recipient sats preview
- lnAddress-only splits are filtered out (no pubkey -> no Taproot
  address); a short note tells the user how many recipients were
  skipped
- the send button label switches to "Send X sats, N ways"; an opt-out
  button lets the user fall back to single-recipient mode
- on send: shares are recomputed via OnchainZapSplitter; below-dust
  configurations surface as a BUILDING-stage failure before signing
This commit is contained in:
Claude
2026-05-20 19:55:15 +00:00
parent 360dea9de9
commit 3ed2245d8c
6 changed files with 669 additions and 55 deletions
@@ -60,15 +60,20 @@ sealed interface OnchainZapSendResult {
* The transaction was broadcast and the zap receipt was published.
*
* @property txid The broadcast Bitcoin transaction id.
* @property receiptEventId The id of the published kind:8333 event.
* @property receiptEventId The id of the first published kind:8333 event.
* For a split zap, additional receipts (one per recipient) are also
* published; see [extraReceiptEventIds].
* @property feeSats Miner fee paid.
* @property changeSats Change returned to the sender (0 if none).
* @property extraReceiptEventIds Receipt ids for the remaining recipients
* when this was a split zap. Empty for a single-recipient zap.
*/
data class Success(
val txid: String,
val receiptEventId: HexKey,
val feeSats: Long,
val changeSats: Long,
val extraReceiptEventIds: List<HexKey> = emptyList(),
) : OnchainZapSendResult
/**
@@ -232,6 +237,141 @@ object OnchainZapSender {
)
}
/**
* Send an onchain split zap: pays N recipients with one Bitcoin transaction
* (one output per recipient) and publishes one kind:8333 receipt per
* recipient, all sharing the same `i <txid>` tag.
*
* Per-recipient shares MUST be precomputed (e.g. via
* [OnchainZapSplitter.distribute]) so the on-chain output amounts and the
* `amount` tags on the receipts agree exactly.
*
* Failure semantics: if any receipt fails to publish, the transaction is
* already on-chain; the result reports the broadcast txid, the ids of any
* receipts that *did* publish, and the publishing-stage failure.
*/
suspend fun sendSplit(
backend: OnchainBackend,
signer: NostrSigner,
senderPubKey: HexKey,
recipients: List<OnchainZapShare>,
feeRateSatPerVByte: Double,
comment: String,
zappedEvent: EventHintBundle<out Event>?,
publish: suspend (EventTemplate<OnchainZapEvent>) -> Event,
): OnchainZapSendResult {
require(recipients.isNotEmpty()) { "recipients must be non-empty" }
// 1. Load the sender's UTXOs.
val utxos =
try {
val address = TaprootAddress.fromPubKey(senderPubKey)
backend.getUtxosForAddress(address)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
return fail(OnchainZapSendStage.LOADING_UTXOS, "Could not load your Bitcoin balance", e)
}
// 2. Coin-select and assemble the multi-output PSBT.
val built =
try {
OnchainZapBuilder.buildSplit(
senderPubKey = senderPubKey,
recipients = recipients.map { it.recipientPubKey to it.sats },
feeRateSatPerVByte = feeRateSatPerVByte,
availableUtxos = utxos,
)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
return fail(OnchainZapSendStage.BUILDING, e.message ?: "Could not build the transaction", e)
}
// 3. Sign, verify, and finalize. Same fund-safety contract as [send].
val rawTxHex =
try {
val signedHex = signer.signPsbt(built.psbt.toHex())
val signedPsbt = Psbt.parse(signedHex)
val expectedTx = built.psbt.global.get(Psbt.PSBT_GLOBAL_UNSIGNED_TX)
val returnedTx = signedPsbt.global.get(Psbt.PSBT_GLOBAL_UNSIGNED_TX)
if (expectedTx == null || returnedTx == null || !expectedTx.contentEquals(returnedTx)) {
return fail(
OnchainZapSendStage.SIGNING,
"The signer returned a different transaction than the one it was asked to sign",
)
}
built.psbt.unsignedTx.inputs.indices.forEach { i ->
val sig =
signedPsbt.inputTapKeySig(i)
?: return fail(
OnchainZapSendStage.SIGNING,
"The signer did not sign every input",
)
built.psbt.setInputTapKeySig(i, sig)
}
if (!PsbtSignatureVerifier.verifyAllKeyPathInputs(built.psbt)) {
return fail(
OnchainZapSendStage.SIGNING,
"The signed transaction has invalid signatures",
)
}
PsbtFinalizer.finalizeToHex(built.psbt)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
return fail(OnchainZapSendStage.SIGNING, e.message ?: "Could not sign the transaction", e)
}
// 4. Broadcast.
val txid =
try {
backend.broadcast(rawTxHex)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
return fail(OnchainZapSendStage.BROADCASTING, "Could not broadcast the transaction", e)
}
// 5. Publish one receipt per recipient. If any one fails, surface the
// failure but keep the txid + receipts that did publish so the user
// (and any retry tooling) has the full picture.
val publishedIds = ArrayList<HexKey>(recipients.size)
for (share in recipients) {
try {
val template =
if (zappedEvent != null) {
OnchainZapEvent.build(txid, share.recipientPubKey, share.sats, zappedEvent, comment)
} else {
OnchainZapEvent.buildProfileZap(txid, share.recipientPubKey, share.sats, comment)
}
publishedIds.add(publish(template).id)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
return OnchainZapSendResult.Failure(
stage = OnchainZapSendStage.PUBLISHING,
message =
"Payment sent (${publishedIds.size} of ${recipients.size} receipts published), " +
"but the next receipt could not be published",
cause = e,
broadcastTxid = txid,
)
}
}
return OnchainZapSendResult.Success(
txid = txid,
receiptEventId = publishedIds.first(),
feeSats = built.feeSats,
changeSats = built.changeSats,
extraReceiptEventIds = publishedIds.drop(1),
)
}
private fun fail(
stage: OnchainZapSendStage,
message: String,
@@ -0,0 +1,93 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.onchain
import com.vitorpamplona.quartz.nip01Core.core.HexKey
/** A per-recipient share of an onchain split zap. */
data class OnchainZapShare(
val recipientPubKey: HexKey,
val sats: Long,
val weight: Double,
)
/** Thrown when one or more recipient shares fall below the configured dust threshold. */
class DustRecipientException(
val belowDust: List<OnchainZapShare>,
val dustThresholdSats: Long,
) : RuntimeException(
"Recipients below dust threshold ($dustThresholdSats sats): " +
belowDust.joinToString { "${it.recipientPubKey.take(8)}…=${it.sats}" },
)
/**
* Distributes a total amount of sats across weighted recipients using integer
* math, leaving every share `>= dustThresholdSats` or throwing.
*
* Distribution rules:
* - share_i = floor(totalSats * weight_i / totalWeight)
* - the rounding remainder is added one-sat at a time to the recipients with
* the largest weights (largest first; ties broken by input order) so the
* sum of shares equals `totalSats` exactly
* - any share that lands below dust is reported via [DustRecipientException]
*/
object OnchainZapSplitter {
fun distribute(
totalSats: Long,
splits: List<Pair<HexKey, Double>>,
dustThresholdSats: Long,
): List<OnchainZapShare> {
require(totalSats > 0) { "total must be positive" }
require(splits.isNotEmpty()) { "splits must be non-empty" }
require(splits.none { it.second <= 0.0 }) { "weights must be positive" }
val totalWeight = splits.sumOf { it.second }
// Floor every share, then distribute the leftover one sat at a time in
// descending-weight order — gives the largest recipients the rounding
// benefit and avoids drifting the small ones below dust by accident.
val shares = LongArray(splits.size)
var assigned = 0L
splits.forEachIndexed { i, (_, weight) ->
val s = (totalSats * weight / totalWeight).toLong()
shares[i] = s
assigned += s
}
val remainder = totalSats - assigned
if (remainder > 0) {
val orderByWeight =
splits.indices.sortedWith(
compareByDescending<Int> { splits[it].second }.thenBy { it },
)
for (k in 0 until remainder.toInt()) {
shares[orderByWeight[k % orderByWeight.size]] += 1
}
}
val result =
splits.mapIndexed { i, (pubKey, weight) ->
OnchainZapShare(recipientPubKey = pubKey, sats = shares[i], weight = weight)
}
val belowDust = result.filter { it.sats < dustThresholdSats }
if (belowDust.isNotEmpty()) throw DustRecipientException(belowDust, dustThresholdSats)
return result
}
}
@@ -0,0 +1,128 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.onchain
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class OnchainZapSplitterTest {
private val a = "a".repeat(64)
private val b = "b".repeat(64)
private val c = "c".repeat(64)
@Test
fun equalWeightsSplitEvenly() {
val shares =
OnchainZapSplitter.distribute(
totalSats = 30_000L,
splits = listOf(a to 1.0, b to 1.0, c to 1.0),
dustThresholdSats = 330L,
)
assertEquals(listOf(10_000L, 10_000L, 10_000L), shares.map { it.sats })
assertEquals(30_000L, shares.sumOf { it.sats })
}
@Test
fun weightedSplitMatchesRatio() {
val shares =
OnchainZapSplitter.distribute(
totalSats = 100_000L,
splits = listOf(a to 3.0, b to 1.0),
dustThresholdSats = 330L,
)
assertEquals(75_000L, shares[0].sats)
assertEquals(25_000L, shares[1].sats)
assertEquals(100_000L, shares.sumOf { it.sats })
}
@Test
fun roundingRemainderGoesToLargestWeight() {
// 10_001 / (2+1+1) = 2500.25 each. Floors: 5000, 2500, 2500 → 2 sats left.
// Both extra sats go to the largest-weight recipient (index 0).
val shares =
OnchainZapSplitter.distribute(
totalSats = 10_001L,
splits = listOf(a to 2.0, b to 1.0, c to 1.0),
dustThresholdSats = 330L,
)
assertEquals(5001L, shares[0].sats)
assertEquals(2500L, shares[1].sats)
assertEquals(2500L, shares[2].sats)
assertEquals(10_001L, shares.sumOf { it.sats })
}
@Test
fun belowDustThrows() {
// 1000 sats split 1:99 → 10 sats and 990 sats. 10 is below 330 dust.
val ex =
assertFailsWith<DustRecipientException> {
OnchainZapSplitter.distribute(
totalSats = 1000L,
splits = listOf(a to 1.0, b to 99.0),
dustThresholdSats = 330L,
)
}
assertEquals(1, ex.belowDust.size)
assertEquals(a, ex.belowDust[0].recipientPubKey)
}
@Test
fun preservesInputOrder() {
val shares =
OnchainZapSplitter.distribute(
totalSats = 30_000L,
splits = listOf(c to 1.0, a to 1.0, b to 1.0),
dustThresholdSats = 330L,
)
assertEquals(c, shares[0].recipientPubKey)
assertEquals(a, shares[1].recipientPubKey)
assertEquals(b, shares[2].recipientPubKey)
}
@Test
fun singleRecipientGetsEverything() {
val shares =
OnchainZapSplitter.distribute(
totalSats = 50_000L,
splits = listOf(a to 1.0),
dustThresholdSats = 330L,
)
assertEquals(1, shares.size)
assertEquals(50_000L, shares[0].sats)
}
@Test
fun fractionalWeightsWork() {
val shares =
OnchainZapSplitter.distribute(
totalSats = 100_000L,
splits = listOf(a to 0.5, b to 0.3, c to 0.2),
dustThresholdSats = 330L,
)
assertEquals(100_000L, shares.sumOf { it.sats })
// a:b:c roughly 5:3:2
assertTrue(shares[0].sats in 49_900..50_100)
assertTrue(shares[1].sats in 29_900..30_100)
assertTrue(shares[2].sats in 19_900..20_100)
}
}