feat(cashu): NUT-02 input-fee math on swap / swap-to-locked / melt

Newer mints charge a per-input fee on swap and melt. Without reserving
it from the output total, the mint rejects every swap/melt with
"amount mismatch" the moment it has any fee configured. We were
reading input_fee_ppk into the KeysetSummaryDto but never threading
it through the actual ops math — fee-charging mints simply didn't
work for us.

Per NUT-02 the fee is `ceil(numInputs * input_fee_ppk / 1000)`. The
ceiling is load-bearing: floor undercharges by one sat in the common
case (numInputs * ppk not exactly divisible by 1000), which is also
exactly what mints reject. New `computeInputFee` helper does the
ceiling-division in pure Long math — `(n * ppk + 999) / 1000` — with
defensive zeroing for null / zero / negative ppk.

Applied in three paths:

- swap(): output total = inputs - fee. The change bucket shrinks by
  fee; the send bucket (when split) stays whole.
- swapToLocked() (nutzap send): change shrinks by fee, recipient
  still gets exactly targetSplit sats locked.
- meltProofs(): required inputs grow by fee (separate from
  quote.feeReserve, which bounds LN routing fees, not the mint's
  processing fee). Change-output upper bound shrinks accordingly.

Also exposes input_fee_ppk on the full KeysetDto (was only on the
summary) so the fee-aware paths can read it from the same /v1/keys
call we already make.

Tests: 10 cases on the ceiling-division helper covering null/zero
ppk, exact-divide boundaries (999 / 1000 / 1001 inputs at 1 ppk),
typical and large fees, and defensive negative-ppk handling.

https://claude.ai/code/session_01MdWddiar819f8XYt5N8BjP
This commit is contained in:
Claude
2026-05-27 15:17:43 +00:00
parent 6caaae460b
commit aa307bfb63
3 changed files with 150 additions and 8 deletions
@@ -84,6 +84,14 @@ data class KeysetDto(
val unit: String,
/** amount (as decimal string) → mint pubkey for that amount (33-byte compressed hex). */
val keys: Map<String, String>,
/**
* NUT-02 per-input fee, in parts-per-thousand of one input proof. The
* mint charges `ceil(numInputs * inputFeePpk / 1000)` extra atoms on
* every swap/melt — the wallet must reserve this from inputs or the
* mint rejects with "amount-mismatch". Older mints don't include this
* field; treat absent as zero fee.
*/
@SerialName("input_fee_ppk") val inputFeePpk: Long? = null,
)
@Serializable
@@ -101,12 +101,20 @@ class CashuMintOperations(
val keyset = fetchKeyset()
// NUT-02: reserve per-input fees from the output total. Without
// this, fee-charging mints reject the swap with "amount mismatch".
val feeAtoms = computeInputFee(proofs.size, keyset.inputFeePpk)
val outputTotal = total - feeAtoms
if (targetSplit != null && targetSplit > outputTotal) {
throw IllegalArgumentException("Target split $targetSplit exceeds outputs after fee ($outputTotal)")
}
if (outputTotal < 0L) throw IllegalArgumentException("Inputs $total don't cover NUT-02 fee $feeAtoms")
val sendOutputs =
if (targetSplit != null) splitAmounts(targetSplit).map { secretOutputFor(it, keyset) } else emptyList()
val keepAmount = if (targetSplit != null) outputTotal - targetSplit else outputTotal
val keepOutputs =
splitAmounts(
if (targetSplit != null) total - targetSplit else total,
).map { secretOutputFor(it, keyset) }
if (keepAmount > 0L) splitAmounts(keepAmount).map { secretOutputFor(it, keyset) } else emptyList()
val allOutputs = sendOutputs + keepOutputs
@@ -177,8 +185,16 @@ class CashuMintOperations(
if (targetSplit > total) throw IllegalArgumentException("Target split exceeds available proofs")
val keyset = fetchKeyset()
// NUT-02: reserve per-input fees; change shrinks by the fee, send
// amount stays whole (the recipient gets exactly targetSplit sats).
val feeAtoms = computeInputFee(proofs.size, keyset.inputFeePpk)
val keepAmount = total - targetSplit - feeAtoms
if (keepAmount < 0L) {
throw IllegalArgumentException("Inputs $total don't cover send $targetSplit + fee $feeAtoms")
}
val sendOutputs = splitAmounts(targetSplit).map { lockedOutputFor(it, keyset, recipientP2pkPubkeyHex) }
val keepOutputs = splitAmounts(total - targetSplit).map { secretOutputFor(it, keyset) }
val keepOutputs =
if (keepAmount > 0L) splitAmounts(keepAmount).map { secretOutputFor(it, keyset) } else emptyList()
val allOutputs = sendOutputs + keepOutputs
val response =
@@ -223,13 +239,18 @@ class CashuMintOperations(
inputs: List<CashuProof>,
): MeltResult {
val total = inputs.sumOf { it.amount }
val required = quote.amount + quote.feeReserve
val keyset = fetchKeyset()
// NUT-02 input fee — separate from quote.feeReserve, which is the
// upper bound on LN routing fees. The mint subtracts both from
// inputs before paying the invoice; we must reserve both.
val inputFee = computeInputFee(inputs.size, keyset.inputFeePpk)
val required = quote.amount + quote.feeReserve + inputFee
if (total < required) throw IllegalArgumentException("Inputs total $total < required $required")
val keyset = fetchKeyset()
// Pre-blind change outputs at the fee_reserve denominations so the
// mint can return whatever fees were not consumed.
val changeAmount = total - quote.amount // upper bound; mint will use ≤ this much
// mint can return whatever LN fees were not consumed. Upper bound
// excludes the (already-paid) NUT-02 input fee.
val changeAmount = total - quote.amount - inputFee
val changeOutputs =
if (changeAmount > 0) splitAmounts(changeAmount).map { secretOutputFor(it, keyset) } else emptyList()
@@ -353,6 +374,26 @@ class CashuMintOperations(
companion object {
/** Re-exported from [splitAmountIntoDenominations] for convenience. */
fun splitAmounts(amount: Long): List<Long> = splitAmountIntoDenominations(amount)
/**
* NUT-02 input-fee math. Total fee in atoms for [numInputs] proofs
* spent against a keyset with [inputFeePpk] parts-per-thousand:
* `ceil(numInputs * inputFeePpk / 1000)`. Absent (null) ppk means
* the mint is on an older NUT-02 release and charges no fee.
*
* Ceiling division avoids the underpay-by-one-sat case that mints
* reject as "amount-mismatch". `(a + b - 1) / b` is the standard
* positive-integer ceiling formula; no overflow concerns at the
* scales any wallet hits (numInputs * 1000 fits in Long).
*/
fun computeInputFee(
numInputs: Int,
inputFeePpk: Long?,
): Long {
val ppk = inputFeePpk ?: 0L
if (ppk <= 0L || numInputs <= 0) return 0L
return (numInputs.toLong() * ppk + 999L) / 1000L
}
}
private data class BlindOutput(
@@ -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.quartz.nip60Cashu.mintApi
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* NUT-02 input-fee math `ceil(numInputs * inputFeePpk / 1000)`.
*/
class NutTwoInputFeeTest {
@Test
fun `null ppk means no fee — older mints`() {
assertEquals(0L, CashuMintOperations.computeInputFee(numInputs = 10, inputFeePpk = null))
}
@Test
fun `zero ppk means no fee — fee-free mints`() {
assertEquals(0L, CashuMintOperations.computeInputFee(numInputs = 10, inputFeePpk = 0L))
}
@Test
fun `zero inputs means no fee — degenerate case`() {
assertEquals(0L, CashuMintOperations.computeInputFee(numInputs = 0, inputFeePpk = 100L))
}
@Test
fun `single input at 1000 ppk rounds to 1 sat`() {
// 1 * 1000 / 1000 = 1
assertEquals(1L, CashuMintOperations.computeInputFee(numInputs = 1, inputFeePpk = 1000L))
}
@Test
fun `single input at 1 ppk rounds up to 1 sat — ceiling not floor`() {
// 1 * 1 / 1000 = 0.001 → ceil → 1
// The whole point of ceiling division: undercharging by one sat is what
// mints actually reject as "amount mismatch".
assertEquals(1L, CashuMintOperations.computeInputFee(numInputs = 1, inputFeePpk = 1L))
}
@Test
fun `999 inputs at 1 ppk rounds up to 1 sat`() {
// 999 * 1 / 1000 = 0.999 → ceil → 1
assertEquals(1L, CashuMintOperations.computeInputFee(numInputs = 999, inputFeePpk = 1L))
}
@Test
fun `1000 inputs at 1 ppk equals 1 sat — exact division`() {
// 1000 * 1 / 1000 = 1
assertEquals(1L, CashuMintOperations.computeInputFee(numInputs = 1000, inputFeePpk = 1L))
}
@Test
fun `1001 inputs at 1 ppk rounds up to 2 sats`() {
// 1001 * 1 / 1000 = 1.001 → ceil → 2
assertEquals(2L, CashuMintOperations.computeInputFee(numInputs = 1001, inputFeePpk = 1L))
}
@Test
fun `typical case — 10 inputs at 100 ppk equals 1 sat`() {
// 10 * 100 / 1000 = 1.0 → 1
assertEquals(1L, CashuMintOperations.computeInputFee(numInputs = 10, inputFeePpk = 100L))
}
@Test
fun `large case — 20 inputs at 2500 ppk equals 50 sats`() {
// 20 * 2500 / 1000 = 50
assertEquals(50L, CashuMintOperations.computeInputFee(numInputs = 20, inputFeePpk = 2500L))
}
@Test
fun `negative ppk treated as zero — defensive against bad mint payloads`() {
assertEquals(0L, CashuMintOperations.computeInputFee(numInputs = 10, inputFeePpk = -5L))
}
}