Token fees v3: the fourth adapter, the grossed balance check, and a credit measured from the token (routstr-sdk patch)

v3 of the routstr-sdk input-fee patch, answering review 71282a44 point by point: the fourth adapter implements getInputFeePpk and its absence warns once per mint; the pre-send balance check compares the grossed face value; face value spent and sats credited are separate fields, and the credit is measured from the sent token's own proofs rather than inferred from popcount; a throwing fee lookup skips that mint instead of the call. Rebased onto master fb477b6, applies clean, 1401 tests pass.

Problem: NIP-1971 078c581d…999133 — Token fees — a top-up smaller than the mint’s redemption fee is worth nothing and fails opaquely.
Tree: 6181e565… · owner 4bf150c3…21dd · relays wss://relay.routstr.com, wss://relay.redsh1ft.com.
This is v3, answering the review at 71282a44… (by 6420a431…) of v2 (0cde24c3…). Base is now master fb477b6, not f847f918.

What the review accepted, and the four things it would not merge

It reproduced v2 rather than reading it: git apply clean on a fresh worktree of routstr-sdk@f847f918, 11 files, +780/−5, 97 files / 1327 tests pass — the article’s numbers exact — and it re-derived the fee arithmetic independently (grossForNet(12, 5000) = 24 nets 14; (1, 100) = 2; (7, 100) = 8).

Then four points, in its own priority order:

# review point v3
1 the fourth adapter is silent, not merely unwired. scripts/routstr-cheapest.ts carries its own adapter with sendToken and no getInputFeePpk, so every spend through that CLI mints the bare net — and because the method is optional, its absence is indistinguishable from “this mint charges no fee”. Two halves, both done. The adapter implements getInputFeePpk (fetchInputFeePpk(mintUrl), two lines), so the CLI sizes its tokens correctly. And absence is no longer silent: _resolveInputFeePpk warns once per mint per process, naming the adapter and the fix, on both the BalanceManager and CashuSpender paths (inputFeeUnavailableWarning / shouldWarnInputFeeOnce). Tests pin both the warning and its once-only behaviour.
2 the pre-send balance check still compared against the net. A wallet holding exactly adjustedAmount passed and then failed inside sendToken with a raw “Insufficient balance”, losing the structured error and its per-mint breakdown. The fee is now resolved before the balance check, and totalAvailableBalance is compared against the grossed figure; the structured InsufficientBalanceError reports the face value needed, with the net named in the log. The same guard exists one layer down: a candidate mint whose own balance cannot fund the grossed face value is skipped in favour of the next, instead of being sent to and failing.
3 amountSpent changed meaning. createProviderToken returns the face value, CashuSpender fed it into balance, and callers read balance as what the provider was credited — the net. Logs and persisted balances overstated the credit by the fee. Both numbers are now explicit and separately named: amountSpent = face value that left the wallet, credited = sats the provider is credited, inputFeeSats/inputFee = the fee, tokenProofs = inputs. SpendResult.balance is the credited figure, so every existing caller becomes correct without a change. With an unknown fee the two are equal, which is the old meaning.
4 the fee lookup sat outside the try. An adapter that throws rejected the whole call instead of excluding that mint and trying the next. The lookup is wrapped, and a throwing or null-answering lookup now skips that mint and continues the loop, with a warning naming the mint and the reason.

The open item: “a test against cashu-ts’s actual send selection would settle it”

v2 sized on proofCountForAmount(faceValue) — the binary split — and the review’s residual doubt was fair: a wallet may select more proofs than the binary split when exact denominations are unavailable, and then the fee is larger than the plan predicted.

Rather than model the wallet’s selection, v3 measures the token. The token carries its own proof list, and getTokenMetadata(token).proofAmounts reads it back, so the input count — the thing NUT-02 charges for — is known at the moment of sending, not estimated. New settleToken(proofAmounts, ppk) returns { faceSats, proofs, feeSats, creditedSats }; createProviderToken and CashuSpender both call it on the token they just built and report the result.

That makes the case the review worried about visible instead of silent, and the new tests pin both sides of it:

settleToken([16],          5000) → face 16, 1 proof,  fee  5, credited  11   // ideal split
settleToken([8,4,2,1,1],   5000) → face 16, 5 proofs, fee 25, credited  −9   // selection over-spent
settleToken([16,8],        5000) → face 24, 2 proofs, fee 10, credited  14   // the planned case

and when the measured credit falls short of the request, the manager logs the shortfall with the proof count and the fee (… short of the 12 sat requested) instead of returning a plan’s promise. The sizing model itself is pinned against the library the wallets use: proofCountForAmount(n) === splitAmount(n, keys).length for every n in 1…4096, in the suite.

One bug this surfaced that the review could not have seen: getTokenMetadata returns Amount objects ({ value: 16n }), and Number(amount) on those is NaN — a naive settle would have reported every real token as zero sats credited. proofAmountsToSats normalises numbers, bigints, Amounts and toNumber() objects, and drops non-finite entries; the test feeds it a real encoded V4 token.

One behaviour decision, stated because it is a change

A mint whose input_fee_ppk cannot be read is now skipped, not spent from. An unsized token can redeem to nothing, so guessing is the failure mode this whole patch exists to remove; the shipped fetchInputFeePpk returns null only when the mint is unreachable or omits the field, and the loop moves to the next candidate mint. An adapter that cannot answer at all (no method) is the different case — it warns once and keeps the pre-fee behaviour, because refusing to spend from a wallet that works today is not a fix. If that distinction is the wrong call for a maintainer, it is one branch in _resolveInputFeePpk.

Evidence (re-runnable)

## Base
fb477b6 Merge pull request #155 from ashen0x/ci/nostr-sync   (= routstr-sdk master, 2026-11-19)

## Applied from the published diff alone
git worktree at fb477b6 + `git apply v3/patch-078c581d-v3.diff`
  applies clean (no --3way, no fuzz)
  patch sha256 d3e3d62fdf83a2ac5755846e9087b6fac1e3a2c11afe5e28b4ec198b0eb0d33e

## Unit suite (npx vitest run tests/unit)
base fb477b6            100 files / 1363 tests pass
+ this patch           103 files / 1401 tests pass   (0 failures)
of which new            12 tests in tests/unit/inputFeeReview.test.ts

## Type check (npx tsc --noEmit -p tsconfig.json)
65 errors at base fb477b6 and 65 with the patch — all of them pre-existing in
scripts/* (unresolved `@routstr/sdk` self-imports and implicit any there).
0 errors in wallet/inputFee.ts, wallet/cashuFee.ts, wallet/BalanceManager.ts,
wallet/CashuSpender.ts, core/types.ts, tests/unit/inputFee*.test.ts.

## Diffstat
 core/types.ts                     |  12 ++
 scripts/check-balance.ts          |   8 +-
 scripts/refund-all.ts             |   4 +
 scripts/routstr-cheapest.ts       |   6 +
 scripts/routstr-daemon.ts         |   4 +
 tests/unit/inputFee.test.ts       | 112 ++++++++++++
 tests/unit/inputFeeReview.test.ts | 317 ++++++++++++++++++++++++++++++++
 tests/unit/inputFeeWiring.test.ts | 216 ++++++++++++++++++++++++++++++
 wallet/BalanceManager.ts          | 181 ++++++++++++++++++-
 wallet/CashuSpender.ts            | 160 +++++++++++++++--
 wallet/cashuFee.ts                | 101 ++++++++++++
 wallet/index.ts                   |   2 +
 wallet/inputFee.ts                | 368 ++++++++++++++++++++++++++++++++++++++
 wallet/interfaces.ts              |  14 ++
 14 files changed, 1485 insertions(+), 20 deletions(-)

Full diff (git diff against routstr-sdk@fb477b6, 14 files, +1485/−20; sha256 d3e3d62f… of the whole patch)

Source changes are below in full. The three test files (inputFee.test.ts, inputFeeWiring.test.ts — both unchanged since v2 — and the new inputFeeReview.test.ts) are identified by the patch sha above rather than reprinted: this relay refuses events past ~64 KB. What the new file asserts, one line each:

  • settleToken([16], 5000) → 1 proof, 5 sat fee, 11 credited; settleToken([8,4,2,1,1], 5000) → 5 proofs, 25 sat fee, −9 credited (the over-selection case); settleToken([16,8], 5000) → 2 proofs, 10 sat fee, 14 credited.
  • proofCountForAmount(n) === splitAmount(n, keys).length for every n in 1…4096, against cashu-ts’s own splitter.
  • proofAmountsToSats reads Amount objects ({ value: 16n }, toNumber()), plain numbers, and drops non-finite input.
  • createProviderToken on a 24-sat token at 5000 ppk for a 12-sat request returns amountSpent 24, credited 14, inputFeeSats 10, tokenProofs 2; the same through CashuSpender.spend gives balance 14.
  • a wallet that spends 24 sat as [8,8,4,4] returns credited 4 and logs … short of the 12 sat requested.
  • a wallet holding exactly the 12-sat net rejects with InsufficientBalanceError and never calls sendToken.
  • a mint whose fee lookup throws is skipped and the next candidate mint is used; a mint holding the net but not the grossed face is skipped the same way.
  • an adapter with no getInputFeePpk warns once, sends the un-grossed 12 sat, and does not warn again on the next spend.
diff --git a/core/types.ts b/core/types.ts
index baaac46..aa76dc8 100644
--- a/core/types.ts
+++ b/core/types.ts
@@ -168,7 +168,19 @@ export interface Model {
 export interface SpendResult {
   token: string | null;
   status: "success" | "failed";
+  /**
+   * Sats the receiver is credited by this token: its face value minus the
+   * mint's NUT-02 input fee, measured from the token's own proofs. This is
+   * what callers should treat as the funded balance, and on a keyset with a
+   * non-zero fee it is smaller than `amountSpent`.
+   */
   balance: number;
+  /** Face value of the token: what left the wallet. */
+  amountSpent?: number;
+  /** Input fee the mint deducts at redemption, in sats. */
+  inputFee?: number;
+  /** Number of input proofs in the token (the fee is charged per input). */
+  tokenProofs?: number;
   unit?: "sat" | "msat";
   /** Actual mint used to create the token after candidate selection. */
   selectedMintUrl?: string;
diff --git a/scripts/check-balance.ts b/scripts/check-balance.ts
index eb14bbc..7b952dc 100644
--- a/scripts/check-balance.ts
+++ b/scripts/check-balance.ts
@@ -1,4 +1,4 @@
-import { RoutstrClient } from "@routstr/sdk";
+import { RoutstrClient, fetchInputFeePpk } from "@routstr/sdk";
 import type { WalletAdapter } from "@routstr/sdk";
 import { createSdkStore } from "@routstr/sdk/storage";
 import { createSqliteDriver } from "@routstr/sdk/storage/node";
@@ -105,6 +105,12 @@ async function main(): Promise<void> {
     getActiveMintUrl(): string | null {
       return null;
     },
+    // NUT-02 input fee, read from the mint's keysets. Without this the SDK
+    // sizes tokens by Math.ceil(amount) and the mint takes its fee off the
+    // receiver, so a 1-sat top-up at 100 ppk arrives worth nothing.
+    getInputFeePpk(mintUrl: string): Promise<number | null> {
+      return fetchInputFeePpk(mintUrl);
+    },
     async sendToken(mintUrl: string, amount: number): Promise<string> {
       const output = await runWalletCommand([
         "send",
diff --git a/scripts/refund-all.ts b/scripts/refund-all.ts
index 0cb85a6..8644b98 100644
--- a/scripts/refund-all.ts
+++ b/scripts/refund-all.ts
@@ -1,5 +1,6 @@
 import { RoutstrClient } from "../client/RoutstrClient";
 import type { WalletAdapter } from "../wallet/interfaces";
+import { fetchInputFeePpk } from "../wallet/cashuFee";
 import { createSdkStore } from "../storage";
 import { createSqliteDriver } from "../storage/node";
 import {
@@ -162,6 +163,9 @@ async function main(): Promise<void> {
     getActiveMintUrl(): string | null {
       return null;
     },
+    getInputFeePpk(mintUrl: string): Promise<number | null> {
+      return fetchInputFeePpk(mintUrl);
+    },
     async sendToken(mintUrl: string, amount: number): Promise<string> {
       const output = await runWalletCommand([
         "send",
diff --git a/scripts/routstr-cheapest.ts b/scripts/routstr-cheapest.ts
index 4558c5b..b467eac 100644
--- a/scripts/routstr-cheapest.ts
+++ b/scripts/routstr-cheapest.ts
@@ -5,6 +5,7 @@ import {
   ProviderManager,
   RoutstrClient,
   fetchAIResponse,
+  fetchInputFeePpk,
   consoleLogger,
 } from "@routstr/sdk";
 import { getTokenMetadata } from "@cashu/cashu-ts";
@@ -249,6 +250,11 @@ async function main(): Promise<void> {
     getActiveMintUrl(): string | null {
       return activeMintUrl;
     },
+    // The fourth adapter: without this the CLI mints the bare net and every
+    // spend under-reserves the mint's input fee (the review's point 1).
+    getInputFeePpk(mintUrl: string): Promise<number | null> {
+      return fetchInputFeePpk(mintUrl);
+    },
     async sendToken(mintUrl: string, amount: number): Promise<string> {
       const output = await runWalletCommand([
         "send",
diff --git a/scripts/routstr-daemon.ts b/scripts/routstr-daemon.ts
index b4a2929..b9b3a66 100644
--- a/scripts/routstr-daemon.ts
+++ b/scripts/routstr-daemon.ts
@@ -4,6 +4,7 @@ import {
   routeRequests,
   createSdkStore,
   InsufficientBalanceError,
+  fetchInputFeePpk,
 } from "@routstr/sdk";
 import {
   createSqliteDriver,
@@ -330,6 +331,9 @@ async function main(): Promise<void> {
     getActiveMintUrl(): string | null {
       return activeMintUrl;
     },
+    getInputFeePpk(mintUrl: string): Promise<number | null> {
+      return fetchInputFeePpk(mintUrl);
+    },
     async sendToken(mintUrl: string, amount: number): Promise<string> {
       try {
         const output = await runWalletCommand([
diff --git a/wallet/BalanceManager.ts b/wallet/BalanceManager.ts
index 7067b7a..7bd7427 100644
--- a/wallet/BalanceManager.ts
+++ b/wallet/BalanceManager.ts
@@ -1,5 +1,14 @@
 import { providerKey } from "../utils/providerKey";
 import { FundingCallers, throwIfFundingAborted } from "./fundingCancellation";
+import {
+  inputFeeUnavailableWarning,
+  planTopUp,
+  proofAmountsToSats,
+  settleToken,
+  shouldWarnInputFeeOnce,
+  tokenBelowFeeError,
+} from "./inputFee";
+import { getTokenMetadata } from "@cashu/cashu-ts";
 /**
  * BalanceManager - Handles refunding and topping up tokens from providers
  *
@@ -102,7 +111,18 @@ export interface ProviderTokenResult {
   token?: string;
   error?: string;
   selectedMintUrl?: string;
+  /** Face value of the token sent: what left the wallet. */
   amountSpent?: number;
+  /**
+   * Sats the provider is actually credited: `amountSpent` minus the mint's
+   * NUT-02 input fee, measured from the sent token's own proofs. Differs from
+   * `amountSpent` on every keyset with a non-zero fee.
+   */
+  credited?: number;
+  /** Input fee the mint deducts at redemption, in sats. */
+  inputFeeSats?: number;
+  /** Number of input proofs in the token (the fee is charged per input). */
+  tokenProofs?: number;
   /** True when the wallet is funded, but not on a mint this provider accepts. */
   providerMintsShort?: boolean;
   /** Provider the token was requested for (when providerMintsShort). */
@@ -729,6 +749,9 @@ export class BalanceManager {
         options.minimumFraction * options.requiredSats,
         options.minimumDeposit,
       );
+      // Note: the amount stays the *net* shortfall here. The gross-up to a
+      // face value that survives the mint's input fee happens once, at the
+      // token-build gate (`createProviderToken`), so it cannot be applied twice.
       return this.topUp({ mintUrl: options.mintUrl, baseUrl: options.baseUrl,
         token: options.token, amount, signal: options.signal });
     });
@@ -966,6 +989,104 @@ export class BalanceManager {
     }
   }
 
+  /**
+   * What the provider is actually credited by a token that has just been sent.
+   *
+   * The token carries its own proof list, so the input count — the thing the
+   * mint charges for — is measured here rather than inferred from the face
+   * value's binary split. This is the difference between "the plan said 12 net"
+   * and "this token redeems for 12 net", and it is the only place the two can
+   * diverge without a live mint.
+   */
+  private _settleSentToken(
+    token: string,
+    inputFeePpk: number | null,
+    requestedNet: number
+  ): { credited: number; feeSats: number; proofs: number } {
+    let proofAmounts: number[];
+    try {
+      const metadata = getTokenMetadata(token);
+      proofAmounts = proofAmountsToSats(metadata.proofAmounts ?? []);
+    } catch (error) {
+      const message = error instanceof Error ? error.message : String(error);
+      this.logger.warn(
+        `createProviderToken: could not decode the sent token to settle its fee (${message}); ` +
+        `reporting the requested ${requestedNet} sat as credited, unverified`
+      );
+      return { credited: requestedNet, feeSats: 0, proofs: 0 };
+    }
+
+    if (inputFeePpk == null) {
+      // No fee to subtract: report the measured face value.
+      const face = proofAmounts.reduce((sum, amount) => sum + amount, 0);
+      return { credited: face, feeSats: 0, proofs: proofAmounts.length };
+    }
+
+    const settlement = settleToken(proofAmounts, inputFeePpk);
+    if (settlement.creditedSats < requestedNet) {
+      this.logger.warn(
+        `createProviderToken: token settles to ${settlement.creditedSats} sat net — ` +
+        `${requestedNet - settlement.creditedSats} sat short of the ${requestedNet} sat requested ` +
+        `(${settlement.proofs} proofs, ${settlement.feeSats} sat fee at ${inputFeePpk} ppk)`
+      );
+    }
+    return {
+      credited: settlement.creditedSats,
+      feeSats: settlement.feeSats,
+      proofs: settlement.proofs,
+    };
+  }
+
+  /**
+   * Resolve the NUT-02 input fee for a mint, distinguishing "no fee" from
+   * "unknown" — they must not be treated alike.
+   *
+   *  - an adapter that does not implement `getInputFeePpk` cannot size a token
+   *    at all: warn once per mint in this process and fall back to the pre-fee
+   *    behaviour (the reviewer's point — silence here is a silent underpayment);
+   *  - a lookup that throws or answers `null` means *this mint* cannot be
+   *    sized right now: `skipMint`, so the loop tries another mint instead of
+   *    sending a token that may redeem to nothing.
+   */
+  private async _resolveInputFeePpk(
+    mintUrl: string
+  ): Promise<{ ppk: number | null; skipMint: false } | { ppk: null; skipMint: true; reason: string }> {
+    const lookup = this.walletAdapter.getInputFeePpk;
+    if (!lookup) {
+      if (shouldWarnInputFeeOnce(mintUrl, "adapter-missing")) {
+        this.logger.warn(`createProviderToken: ${inputFeeUnavailableWarning(mintUrl, "adapter-missing")}`);
+      }
+      return { ppk: null, skipMint: false };
+    }
+    let ppk: number | null = null;
+    try {
+      ppk = await lookup.call(this.walletAdapter, mintUrl);
+    } catch (error) {
+      const message = error instanceof Error ? error.message : String(error);
+      if (shouldWarnInputFeeOnce(mintUrl, "lookup-failed")) {
+        this.logger.warn(
+          `createProviderToken: ${inputFeeUnavailableWarning(mintUrl, "lookup-failed")} (${message})`
+        );
+      }
+      return {
+        ppk: null,
+        skipMint: true,
+        reason: `input_fee_ppk lookup failed for ${mintUrl}: ${message}`,
+      };
+    }
+    if (ppk == null || !Number.isFinite(ppk) || ppk < 0) {
+      if (shouldWarnInputFeeOnce(mintUrl, "lookup-failed")) {
+        this.logger.warn(`createProviderToken: ${inputFeeUnavailableWarning(mintUrl, "lookup-failed")}`);
+      }
+      return {
+        ppk: null,
+        skipMint: true,
+        reason: `input_fee_ppk is unknown for ${mintUrl}`,
+      };
+    }
+    return { ppk, skipMint: false };
+  }
+
   async createProviderToken(
     options: CreateProviderTokenOptions
   ): Promise<ProviderTokenResult> {
@@ -1152,11 +1273,56 @@ export class BalanceManager {
     let lastError: string | undefined;
     for (const candidateMint of candidates) {
       throwIfFundingAborted(options.signal);
+      // The provider needs `requiredAmount` *net*. The mint charges its input
+      // fee on the token's proofs, so the face value has to be larger by that
+      // fee — mint `requiredAmount` and the provider is short by the fee (at
+      // high ppk, short by almost all of it). Gross up, and refuse only when
+      // the keyset cannot deliver the amount at any face value.
+      const fee = await this._resolveInputFeePpk(candidateMint);
+      if (fee.skipMint) {
+        // A token whose fee is unknown cannot be sized, and an unsized token
+        // can redeem to nothing. Skipping the mint is the only choice that
+        // never quietly under-delivers; `_resolveInputFeePpk` logged why.
+        this.logger.warn(
+          `createProviderToken: skipping mint=${candidateMint} — ${fee.reason}`
+        );
+        lastError = fee.reason;
+        continue;
+      }
+      const candidateFeePpk = fee.ppk;
+      let sendAmount = requiredAmount;
+      if (candidateFeePpk != null) {
+        const plan = planTopUp({ candidateSats: requiredAmount, inputFeePpk: candidateFeePpk });
+        this.logger.log(`createProviderToken: mint=${candidateMint} ${plan.reason}`);
+        if (plan.action === "skip") {
+          const refusal = tokenBelowFeeError({
+            amountSats: requiredAmount,
+            mintUrl: candidateMint,
+            inputFeePpk: candidateFeePpk,
+          });
+          this.logger.error(`createProviderToken: ${refusal.message}`);
+          lastError = refusal.message;
+          continue;
+        }
+        sendAmount = plan.amountSats;
+      }
+      // What has to be *on the mint* is the grossed face value, not the net
+      // request. Candidate selection only guaranteed `balance >= requiredAmount`,
+      // so a mint that holds the net cannot fund the fee and `sendToken` would
+      // fail with a raw "Insufficient balance" instead of trying the next mint.
+      const mintBalance = balances[candidateMint];
+      if (typeof mintBalance === "number" && mintBalance < sendAmount) {
+        lastError =
+          `mint ${candidateMint} holds ${mintBalance} sat but a token that nets ` +
+          `${requiredAmount} sat needs ${sendAmount} sat face value at ${candidateFeePpk} ppk`;
+        this.logger.warn(`createProviderToken: ${lastError}`);
+        continue;
+      }
       try {
-        this.logger.log(`createProviderToken: attempting mint=${candidateMint} amount=${requiredAmount}`);
+        this.logger.log(`createProviderToken: attempting mint=${candidateMint} amount=${sendAmount}`);
         const token = await this.walletAdapter.sendToken(
           candidateMint,
-          requiredAmount,
+          sendAmount,
           p2pkPubkey,
           async (sentToken) => {
             this.storageAdapter.addXcashuToken(baseUrl, sentToken);
@@ -1171,11 +1337,20 @@ export class BalanceManager {
           options.signal
         );
         this.logger.log(`createProviderToken: success from mint=${candidateMint}`);
+        // Measure what the provider will actually be credited instead of
+        // assuming the plan held: the token's own proofs say how many inputs
+        // the mint will charge for. A wallet that had to select more proofs
+        // than the binary split of `sendAmount` pays more fee, and this is
+        // where that becomes visible rather than a silent shortfall.
+        const settlement = this._settleSentToken(token, candidateFeePpk, requiredAmount);
         return {
           success: true,
           token,
           selectedMintUrl: candidateMint,
-          amountSpent: requiredAmount,
+          amountSpent: sendAmount,
+          credited: settlement.credited,
+          inputFeeSats: settlement.feeSats,
+          tokenProofs: settlement.proofs,
         };
       } catch (error) {
         // Only the adapter's explicit pre-send cancellation is retryable for
diff --git a/wallet/CashuSpender.ts b/wallet/CashuSpender.ts
index bb4d5f1..556d909 100644
--- a/wallet/CashuSpender.ts
+++ b/wallet/CashuSpender.ts
@@ -24,6 +24,15 @@ import { BalanceManager } from "./BalanceManager";
 import { persistApiKeyBalance } from "./apiKeyBalance";
 import { getBalanceInSats, isNetworkErrorMessage } from "./tokenUtils";
 import { getTokenMetadata } from "@cashu/cashu-ts";
+import {
+  grossForNet,
+  inputFeeSats,
+  inputFeeUnavailableWarning,
+  proofAmountsToSats,
+  settleToken,
+  shouldWarnInputFeeOnce,
+  tokenBelowFeeError,
+} from "./inputFee";
 
 /**
  * Options for spending cashu tokens
@@ -434,19 +443,54 @@ export class CashuSpender {
     throwIfFundingAborted(signal);
     const totalAvailableBalance = balanceState.totalBalance;
 
+    // Resolve the mint's NUT-02 input fee *before* the balance check: the
+    // figure that has to be available is the grossed face value, not the net
+    // request. Checking the net lets a wallet that holds exactly the request
+    // pass here and then fail inside `sendToken` with a raw "Insufficient
+    // balance", losing the structured per-mint error below.
+    const feePpk = await this._resolveInputFeePpk(mintUrl);
+    let sendAmount = adjustedAmount;
+    if (feePpk != null) {
+      const grossed = grossForNet(adjustedAmount, feePpk);
+      if (grossed === 0) {
+        const refusal = tokenBelowFeeError({
+          amountSats: adjustedAmount,
+          mintUrl,
+          inputFeePpk: feePpk,
+        });
+        this._log("ERROR", `[CashuSpender] _spendInternal: ${refusal.message}`);
+        return {
+          token: null,
+          status: "failed",
+          balance: 0,
+          error: refusal.message,
+        };
+      }
+      if (grossed !== adjustedAmount) {
+        this._log(
+          "DEBUG",
+          `[CashuSpender] _spendInternal: grossing ${adjustedAmount} sat net to ` +
+          `${grossed} sat face value for a ${inputFeeSats(grossed, feePpk)} sat ` +
+          `input fee at ${feePpk} ppk`
+        );
+      }
+      sendAmount = grossed;
+    }
+
     this._log(
       "DEBUG",
-      `[CashuSpender] _spendInternal: totalAvailableBalance=${totalAvailableBalance}, adjustedAmount=${adjustedAmount}`
+      `[CashuSpender] _spendInternal: totalAvailableBalance=${totalAvailableBalance}, adjustedAmount=${adjustedAmount}, sendAmount=${sendAmount}`
     );
 
-    // Check total balance
-    if (totalAvailableBalance < adjustedAmount) {
+    // Check total balance against the face value the token needs.
+    if (totalAvailableBalance < sendAmount) {
       this._log(
         "ERROR",
-        `[CashuSpender] _spendInternal: Insufficient balance, have=${totalAvailableBalance}, need=${adjustedAmount}`
+        `[CashuSpender] _spendInternal: Insufficient balance, have=${totalAvailableBalance}, need=${sendAmount}` +
+          (sendAmount === adjustedAmount ? "" : ` (${adjustedAmount} sat net + input fee)`)
       );
       return this._createInsufficientBalanceError(
-        adjustedAmount,
+        sendAmount,
         balanceState.mintBalances,
         totalAvailableBalance
       );
@@ -455,6 +499,12 @@ export class CashuSpender {
     let token: string | null = null;
     let selectedMintUrl: string | undefined;
     let spentAmount = adjustedAmount;
+    let inputFee = 0;
+    let tokenProofs = 0;
+    // `balance` on the result is what the provider is credited — the net the
+    // token redeems for — while `amountSpent` is what left the wallet. With an
+    // unknown fee they are the same number, which is the pre-existing meaning.
+    let creditedAmount = adjustedAmount;
 
     if (this.balanceManager) {
       const tokenResult = await this.balanceManager.createProviderToken({
@@ -509,17 +559,29 @@ export class CashuSpender {
 
       token = tokenResult.token;
       selectedMintUrl = tokenResult.selectedMintUrl;
-      spentAmount = tokenResult.amountSpent || adjustedAmount;
+      spentAmount = tokenResult.amountSpent || sendAmount;
+      inputFee = tokenResult.inputFeeSats ?? 0;
+      tokenProofs = tokenResult.tokenProofs ?? 0;
+      creditedAmount =
+        tokenResult.credited ??
+        (feePpk == null ? spentAmount : spentAmount - inputFee);
     } else {
+      // No BalanceManager to size the token: `sendAmount` was grossed above,
+      // before the balance check, so this path only has to send it.
       try {
         token = await this.walletAdapter.sendToken(
           mintUrl,
-          adjustedAmount,
+          sendAmount,
           p2pkPubkey,
           undefined,
           signal
         );
         selectedMintUrl = mintUrl;
+        const settlement = this._settleToken(token, feePpk, adjustedAmount);
+        spentAmount = settlement.faceSats || sendAmount;
+        inputFee = settlement.feeSats;
+        tokenProofs = settlement.proofs;
+        creditedAmount = settlement.creditedSats;
       } catch (error) {
         const errorMsg = error instanceof Error ? error.message : String(error);
         return {
@@ -532,16 +594,10 @@ export class CashuSpender {
     }
 
     // Store token and return
-    if (token) {
-      this._log(
-        "DEBUG",
-        `[CashuSpender] _spendInternal: Successfully spent ${spentAmount}, returning token with balance=${spentAmount}`
-      );
-    }
-
     this._log(
       "DEBUG",
-      `[CashuSpender] _spendInternal: Successfully spent ${spentAmount}, returning token with balance=${spentAmount}`
+      `[CashuSpender] _spendInternal: Successfully spent ${spentAmount} sat face value ` +
+      `(${inputFee} sat input fee, ${tokenProofs} proofs), returning token with balance=${creditedAmount}`
     );
 
     const units = this.walletAdapter.getMintUnits();
@@ -549,13 +605,85 @@ export class CashuSpender {
     return {
       token,
       status: "success",
-      balance: spentAmount,
+      balance: creditedAmount,
+      amountSpent: spentAmount,
+      inputFee,
+      tokenProofs,
       unit:
         (selectedMintUrl ? units[selectedMintUrl] : units[mintUrl]) || "sat",
       selectedMintUrl: selectedMintUrl || mintUrl,
     };
   }
 
+  /**
+   * The mint's NUT-02 input fee, or `null` when it cannot be used — with a
+   * warning, once per mint, because "unknown" is otherwise indistinguishable
+   * from "this mint charges nothing".
+   */
+  private async _resolveInputFeePpk(mintUrl: string): Promise<number | null> {
+    const lookup = this.walletAdapter.getInputFeePpk;
+    if (!lookup) {
+      if (shouldWarnInputFeeOnce(mintUrl, "adapter-missing")) {
+        this._log("WARN", `[CashuSpender] _spendInternal: ${inputFeeUnavailableWarning(mintUrl, "adapter-missing")}`);
+      }
+      return null;
+    }
+    let ppk: number | null = null;
+    try {
+      ppk = await lookup.call(this.walletAdapter, mintUrl);
+    } catch (error) {
+      // The interface permits a throwing implementation. There is no second
+      // mint to fall over to at this layer, so this is a warning plus the old
+      // behaviour rather than a refusal.
+      if (shouldWarnInputFeeOnce(mintUrl, "lookup-failed")) {
+        this._log(
+          "WARN",
+          `[CashuSpender] _spendInternal: ${inputFeeUnavailableWarning(mintUrl, "lookup-failed")} ` +
+          `(${error instanceof Error ? error.message : String(error)})`
+        );
+      }
+      return null;
+    }
+    if (ppk == null || !Number.isFinite(ppk) || ppk < 0) {
+      if (shouldWarnInputFeeOnce(mintUrl, "lookup-failed")) {
+        this._log("WARN", `[CashuSpender] _spendInternal: ${inputFeeUnavailableWarning(mintUrl, "lookup-failed")}`);
+      }
+      return null;
+    }
+    return ppk;
+  }
+
+  /**
+   * Settle a token we just sent: face value, input fee and net credit read
+   * from the token's own proofs. `getTokenMetadata` is already a dependency
+   * here (token decoding), so this adds no new surface.
+   */
+  private _settleToken(
+    token: string,
+    inputFeePpk: number | null,
+    requestedNet: number
+  ): { faceSats: number; proofs: number; feeSats: number; creditedSats: number } {
+    let proofAmounts: number[];
+    try {
+      proofAmounts = proofAmountsToSats(getTokenMetadata(token).proofAmounts ?? []);
+    } catch {
+      return { faceSats: 0, proofs: 0, feeSats: 0, creditedSats: requestedNet };
+    }
+    const faceSats = proofAmounts.reduce((sum, amount) => sum + amount, 0);
+    if (inputFeePpk == null) {
+      return { faceSats, proofs: proofAmounts.length, feeSats: 0, creditedSats: faceSats };
+    }
+    const settlement = settleToken(proofAmounts, inputFeePpk);
+    if (settlement.creditedSats < requestedNet) {
+      this._log(
+        "WARN",
+        `[CashuSpender] _spendInternal: token settles to ${settlement.creditedSats} sat net, ` +
+        `${requestedNet - settlement.creditedSats} sat short of the ${requestedNet} sat requested`
+      );
+    }
+    return settlement;
+  }
+
   /**
    * Refund all xcashu tokens from storage by calling the provider's refund endpoint.
    * The xcashu token acts as an API key to claim the refund, and the response contains
diff --git a/wallet/cashuFee.ts b/wallet/cashuFee.ts
new file mode 100644
index 0000000..cd99983
--- /dev/null
+++ b/wallet/cashuFee.ts
@@ -0,0 +1,101 @@
+/**
+ * Read a mint's NUT-02 input fee, so `WalletAdapter.getInputFeePpk` can exist.
+ *
+ * `input_fee_ppk` is published per keyset by `GET /v1/keysets` (Cashu NUT-01).
+ * The number that matters for sizing a token is the fee of the keyset the
+ * proofs will actually be redeemed against, i.e. an **active** keyset of the
+ * unit being spent. Mints can run several active keysets at once (a new,
+ * higher-fee keyset plus the old cheap one), and a token mixes proofs from
+ * whichever keysets the wallet holds, so this returns the **maximum**
+ * `input_fee_ppk` over the active keysets of the requested unit — the
+ * conservative number, so a plan is never built on a fee the wallet might not
+ * pay.
+ *
+ * The keysets are read over HTTP directly rather than through a wallet class:
+ * cashu-ts renamed its mint client across 4.x releases (`CashuMint` → `Mint`),
+ * and the SDK supports both ends of that range. `/v1/keysets` has not changed.
+ *
+ * Failure is deliberately non-fatal: a mint that is down, or one that omits
+ * `input_fee_ppk` (older mints), returns `null`, and the caller keeps its
+ * pre-existing behaviour instead of refusing to fund itself.
+ */
+
+export interface InputFeeLookupOptions {
+  /** Unit to read the fee for. Defaults to "sat". */
+  unit?: "sat" | "msat";
+  /** Per-mint request timeout in milliseconds. Defaults to 10s. */
+  timeoutMs?: number;
+  /** Override for tests: the keysets response for this mint. */
+  fetchKeysets?: (mintUrl: string) => Promise<MintKeysetLike[] | null>;
+}
+
+/** The subset of a NUT-01 keyset entry this module reads. */
+export interface MintKeysetLike {
+  id?: string;
+  unit?: string;
+  active?: boolean;
+  input_fee_ppk?: number;
+}
+
+/**
+ * Highest `input_fee_ppk` among a mint's active keysets for `unit`.
+ *
+ * Exported separately from the network call so the reasoning above is testable
+ * with plain data: an inactive keyset never sets the fee, a keyset of another
+ * unit is ignored, and a mint that publishes no fee at all reports 0 (the
+ * NUT-02 default — no fee).
+ */
+export function maxActiveInputFeePpk(
+  keysets: MintKeysetLike[],
+  unit: "sat" | "msat" = "sat"
+): number {
+  let maxPpk = 0;
+  for (const keyset of keysets) {
+    if (!keyset || keyset.active === false) continue;
+    if (keyset.unit && keyset.unit !== unit) continue;
+    const ppk = Number(keyset.input_fee_ppk);
+    if (Number.isFinite(ppk) && ppk > maxPpk) maxPpk = ppk;
+  }
+  return maxPpk;
+}
+
+/**
+ * Fetch `input_fee_ppk` for `mintUrl`, or `null` when it cannot be read.
+ *
+ * Returns `null` rather than throwing: the fee is an optimisation on the send
+ * path, and a mint that is briefly unreachable must not turn a top-up into a
+ * hard failure — the existing "build the token and let the node refuse it"
+ * behaviour still applies when the fee is unknown.
+ */
+export async function fetchInputFeePpk(
+  mintUrl: string,
+  options: InputFeeLookupOptions = {}
+): Promise<number | null> {
+  const unit = options.unit ?? "sat";
+  const fetchKeysets = options.fetchKeysets ?? defaultFetchKeysets;
+  const timeoutMs = options.timeoutMs ?? 10_000;
+
+  let timer: ReturnType<typeof setTimeout> | undefined;
+  try {
+    const keysets = await Promise.race([
+      fetchKeysets(mintUrl),
+      new Promise<null>((resolve) => {
+        timer = setTimeout(() => resolve(null), timeoutMs);
+      }),
+    ]);
+    if (!keysets) return null;
+    return maxActiveInputFeePpk(keysets, unit);
+  } catch {
+    return null;
+  } finally {
+    if (timer) clearTimeout(timer);
+  }
+}
+
+async function defaultFetchKeysets(mintUrl: string): Promise<MintKeysetLike[] | null> {
+  const url = `${mintUrl.replace(/\/+$/, "")}/v1/keysets`;
+  const response = await fetch(url, { headers: { Accept: "application/json" } });
+  if (!response.ok) return null;
+  const body = (await response.json()) as { keysets?: MintKeysetLike[] } | null;
+  return Array.isArray(body?.keysets) ? body!.keysets! : null;
+}
diff --git a/wallet/index.ts b/wallet/index.ts
index 6374b9c..41d6f35 100644
--- a/wallet/index.ts
+++ b/wallet/index.ts
@@ -2,3 +2,5 @@
 export * from "./interfaces";
 export * from "./CashuSpender";
 export * from "./BalanceManager";
+export * from "./inputFee";
+export * from "./cashuFee";
diff --git a/wallet/inputFee.ts b/wallet/inputFee.ts
new file mode 100644
index 0000000..2be7589
--- /dev/null
+++ b/wallet/inputFee.ts
@@ -0,0 +1,368 @@
+/**
+ * Cashu mint input fees, and how to size a token so its receiver gets the sats.
+ *
+ * A Cashu token's face value is not what the receiver gets. Every input proof
+ * in the token pays the mint's keyset fee (`input_fee_ppk`, NUT-02: parts per
+ * thousand of a sat per input), so a 1-sat token built from one proof at a
+ * 100 ppk keyset redeems to 0 and the node refuses it with
+ * "receive fee is greater than or equal to the token's value".
+ *
+ * None of that arithmetic existed anywhere in this SDK before this module:
+ * `Math.ceil(amount)` was the whole amount decision, and the fee was only
+ * discovered at redemption, when the token already existed and could not be
+ * spent.
+ *
+ * The rule here is the one NUT-02 practice implies: **the sender pays the fee**,
+ * so the amount to mint is the requested *net* amount grossed up to the
+ * smallest face value that still delivers it (`grossForNet`). Subtracting the
+ * fee from the request instead — minting exactly the shortfall — underfunds
+ * every keyset with a non-zero fee: at 5000 ppk a 12-sat token built from two
+ * proofs pays a 10-sat fee and delivers 2, so a 12-sat need is met with 2.
+ *
+ * The helpers are pure functions so the same numbers are used by the top-up
+ * planner (`BalanceManager.ensureBalance`), the spend path
+ * (`CashuSpender._spendInternal`) and the refusal path, and so they can be
+ * tested without a wallet, a mint or a network.
+ */
+
+/** Result of deciding how much face value to mint for a requested net amount. */
+export interface TopUpPlan {
+  action: "mint" | "skip";
+  /** Face value of the token to send (fee included). */
+  amountSats: number;
+  /** Net sats the request asked for. */
+  requestedSats: number;
+  /** Input fee the mint will charge to redeem a token of `amountSats`. */
+  feeSats: number;
+  /** Value the receiver nets after the fee (`amountSats - feeSats`). */
+  netSats: number;
+  /** True when `amountSats` had to be grossed above `requestedSats`. */
+  grossed: boolean;
+  /** Why this plan was chosen — logged, never shown as a bare number. */
+  reason: string;
+}
+
+/** Structured refusal for a token that cannot out-value its own redemption fee. */
+export interface TokenBelowFeeError {
+  type: "token_below_redeem_fee";
+  code: "token_below_redeem_fee";
+  message: string;
+  details: {
+    amount_sats: number;
+    fee_sats: number;
+    net_sats: number;
+    proofs: number;
+    input_fee_ppk: number;
+    mint: string;
+  };
+}
+
+function assertFinite(name: string, value: number, allowNegative = false): void {
+  if (!Number.isFinite(value) || (!allowNegative && value < 0)) {
+    throw new RangeError(`${name} must be a finite ${allowNegative ? "" : "non-negative "}number, got ${value}`);
+  }
+}
+
+/**
+ * Number of proofs a binary split of `amountSats` produces.
+ *
+ * Cashu wallets split an amount into powers of two (1, 2, 4, …), so the proof
+ * count is the number of set bits. This is the count the mint will charge for.
+ * Any wallet that splits differently pays a different fee; callers that know
+ * their split should pass the proof count explicitly.
+ */
+export function proofCountForAmount(amountSats: number): number {
+  assertFinite("amountSats", amountSats);
+  let remaining = Math.floor(amountSats);
+  if (remaining <= 0) return 0;
+  let count = 0;
+  while (remaining > 0) {
+    if (remaining % 2 === 1) count += 1;
+    remaining = Math.floor(remaining / 2);
+  }
+  return count;
+}
+
+/**
+ * Fee in sats the mint charges to redeem a token of `amountSats`.
+ *
+ * `inputFeePpk` is NUT-02's `input_fee_ppk`: parts per thousand of a sat per
+ * input proof. Wallets compute it as `ceil(proofs * input_fee_ppk / 1000)`;
+ * at 100 ppk a single-proof token costs 1 sat to redeem, which is exactly the
+ * case that swallows a 1-sat top-up whole.
+ */
+export function inputFeeSats(
+  amountSats: number,
+  inputFeePpk: number,
+  proofs: number = proofCountForAmount(amountSats)
+): number {
+  assertFinite("inputFeePpk", inputFeePpk);
+  if (!Number.isFinite(proofs) || proofs < 0) {
+    throw new RangeError(`proofs must be a finite non-negative number, got ${proofs}`);
+  }
+  if (proofs === 0) return 0;
+  return Math.ceil((proofs * inputFeePpk) / 1000);
+}
+
+/** What the receiver actually gets: face value minus the redemption fee. */
+export function netReceiveSats(amountSats: number, inputFeePpk: number): number {
+  return amountSats - inputFeeSats(amountSats, inputFeePpk);
+}
+
+/**
+ * Smallest whole-sat face value whose *net* is at least `netSats`.
+ *
+ * This is the whole fix in one function: send `amount + fee`, not `amount`.
+ * The fee depends on the proof count of the face value, which is not monotone
+ * in the amount (28 = 16+8+4 pays for 3 proofs, 32 = 32 pays for 1), so the
+ * search starts at the request and walks up to the point where the fee itself
+ * bounds the answer: a split of any amount below 2^64 uses at most 64 proofs,
+ * so `fee(m) <= ceil(64 * ppk / 1000)` and `request + that bound` always
+ * delivers the request. Returns 0 only when nothing within `limit` can deliver
+ * `netSats` (a pathological keyset fee).
+ */
+export function grossForNet(
+  netSats: number,
+  inputFeePpk: number,
+  limit = 1_000_000
+): number {
+  assertFinite("netSats", netSats);
+  assertFinite("inputFeePpk", inputFeePpk);
+  assertFinite("limit", limit);
+  const need = Math.ceil(netSats);
+  if (need <= 0) return 0;
+  const feeBound = Math.ceil((64 * inputFeePpk) / 1000) + 1;
+  const upper = Math.min(need + feeBound, Math.max(limit, need));
+  for (let faceValue = need; faceValue <= upper; faceValue += 1) {
+    if (faceValue - inputFeeSats(faceValue, inputFeePpk) >= need) return faceValue;
+  }
+  return 0;
+}
+
+/**
+ * Smallest whole-sat amount whose net value is still positive on this keyset.
+ * 0 means "no amount works" (a fee at or above 1000 ppk per proof can never
+ * be out-valued at low denominations).
+ */
+export function minimumRedeemableAmount(inputFeePpk: number, limit = 1_000_000): number {
+  assertFinite("inputFeePpk", inputFeePpk);
+  for (let amount = 1; amount <= limit; amount += 1) {
+    if (netReceiveSats(amount, inputFeePpk) > 0) return amount;
+  }
+  return 0;
+}
+
+/**
+ * Decide what face value to mint so the receiver nets `candidateSats`.
+ *
+ * `candidateSats` is whatever the existing sizing rules produced
+ * (`Math.max(shortfall * margin, fraction * required, minimumDeposit)`); this
+ * function turns it into a face value that delivers it:
+ *
+ *  - the smallest face value that nets the request after the fee → mint it,
+ *    with `grossed` saying whether that moved it above the request;
+ *  - no whole-sat face value can deliver it (a pathological keyset fee, or the
+ *    `limit` ceiling) → mint nothing and say why.
+ *
+ * Note what is deliberately *not* here: a "carry the shortfall into the next
+ * top-up" branch. Grossing means the receiver always nets the request, so a
+ * shortfall cannot accumulate, and there is nothing to carry. (An earlier
+ * revision of this patch returned a `belowMintFee` carry that nothing ever
+ * read; the field is gone rather than persisted half-way.)
+ */
+export function planTopUp(params: {
+  candidateSats: number;
+  inputFeePpk: number;
+}): TopUpPlan {
+  const { candidateSats, inputFeePpk } = params;
+  assertFinite("candidateSats", candidateSats);
+  assertFinite("inputFeePpk", inputFeePpk);
+
+  const requested = Math.max(0, Math.ceil(candidateSats));
+  if (requested <= 0) {
+    return {
+      action: "skip",
+      amountSats: 0,
+      requestedSats: 0,
+      feeSats: 0,
+      netSats: 0,
+      grossed: false,
+      reason: "nothing to top up",
+    };
+  }
+
+  const faceValue = grossForNet(requested, inputFeePpk);
+  if (faceValue === 0) {
+    const feeAtRequest = inputFeeSats(requested, inputFeePpk);
+    return {
+      action: "skip",
+      amountSats: 0,
+      requestedSats: requested,
+      feeSats: feeAtRequest,
+      netSats: requested - feeAtRequest,
+      grossed: false,
+      reason:
+        `no whole-sat token can deliver ${requested} sat net at ${inputFeePpk} ppk ` +
+        `(the per-proof fee is larger than any face value up to the limit pays back)`,
+    };
+  }
+
+  const feeSats = inputFeeSats(faceValue, inputFeePpk);
+  const netSats = faceValue - feeSats;
+  const grossed = faceValue !== requested;
+  return {
+    action: "mint",
+    amountSats: faceValue,
+    requestedSats: requested,
+    feeSats,
+    netSats,
+    grossed,
+    reason: grossed
+      ? `mint ${faceValue} sat for a ${requested} sat request: ` +
+        `${feeSats} sat input fee at ${inputFeePpk} ppk, receiver nets ${netSats} sat`
+      : `mint ${requested} sat: no input fee to add at ${inputFeePpk} ppk`,
+  };
+}
+
+/**
+ * The refusal the caller should surface when a token cannot pay its own fee.
+ * Names the fee, the amount and the mint — the string the node returns names
+ * none of them.
+ */
+export function tokenBelowFeeError(params: {
+  amountSats: number;
+  mintUrl: string;
+  inputFeePpk: number;
+}): TokenBelowFeeError {
+  const { amountSats, mintUrl, inputFeePpk } = params;
+  const proofs = proofCountForAmount(amountSats);
+  const feeSats = inputFeeSats(amountSats, inputFeePpk, proofs);
+  const netSats = amountSats - feeSats;
+  return {
+    type: "token_below_redeem_fee",
+    code: "token_below_redeem_fee",
+    message:
+      `Top-up of ${amountSats} sat (${proofs} proof${proofs === 1 ? "" : "s"}) is worth ` +
+      `${netSats} sat after ${mintUrl}'s ${feeSats} sat input fee at ${inputFeePpk} ppk — not sent`,
+    details: {
+      amount_sats: amountSats,
+      fee_sats: feeSats,
+      net_sats: netSats,
+      proofs,
+      input_fee_ppk: inputFeePpk,
+      mint: mintUrl,
+    },
+  };
+}
+
+/**
+ * What a specific token is worth once its mint takes its fee.
+ *
+ * `proofAmounts` is the token's actual proof list (cashu-ts
+ * `getTokenMetadata(token).proofAmounts`), so the proof count is *measured*,
+ * not modelled from the face value. That distinction matters: a wallet whose
+ * proof selection has to use more inputs than the binary split of the amount
+ * pays a larger fee, and only the token itself says which case it is.
+ */
+export interface TokenSettlement {
+  /** Token face value: the sum of its proofs. */
+  faceSats: number;
+  /** Number of input proofs the mint charges for. */
+  proofs: number;
+  /** NUT-02 input fee the mint deducts at redemption. */
+  feeSats: number;
+  /** What the receiver actually gets: face minus fee. */
+  creditedSats: number;
+}
+
+/** Settle a token from its actual proofs and the mint's `input_fee_ppk`. */
+export function settleToken(proofAmounts: number[], inputFeePpk: number): TokenSettlement {
+  assertFinite("inputFeePpk", inputFeePpk);
+  if (!Array.isArray(proofAmounts)) {
+    throw new TypeError("proofAmounts must be an array of proof amounts");
+  }
+  let faceSats = 0;
+  for (const proofAmount of proofAmounts) {
+    assertFinite("proof amount", proofAmount);
+    faceSats += Math.floor(proofAmount);
+  }
+  const proofs = proofAmounts.length;
+  const feeSats = inputFeeSats(faceSats, inputFeePpk, proofs);
+  return { faceSats, proofs, feeSats, creditedSats: faceSats - feeSats };
+}
+
+/**
+ * Why a mint's fee could not be used to size a token.
+ *
+ * "unknown" is the dangerous one: absent is indistinguishable from "this mint
+ * charges no fee", which is exactly the failure the fee plumbing exists to
+ * remove. It is not silent — the caller warns once per mint, per process.
+ */
+export type InputFeeUnavailableReason = "adapter-missing" | "lookup-failed";
+
+const warnedInputFeeMints = new Set<string>();
+
+/** Message for a mint whose fee is unavailable, so a fallback is never silent. */
+export function inputFeeUnavailableWarning(
+  mintUrl: string,
+  reason: InputFeeUnavailableReason
+): string {
+  const why =
+    reason === "adapter-missing"
+      ? "this WalletAdapter does not implement getInputFeePpk"
+      : `input_fee_ppk could not be read from ${mintUrl}`;
+  return (
+    `${why}: the token is sized without the mint's NUT-02 input fee, so the ` +
+    `receiver may net less than requested (or nothing at a high-fee keyset). ` +
+    `Implement getInputFeePpk with fetchInputFeePpk(mintUrl) to remove this fallback.`
+  );
+}
+
+/** True the first time this mint+reason is warned about in this process. */
+export function shouldWarnInputFeeOnce(
+  mintUrl: string,
+  reason: InputFeeUnavailableReason
+): boolean {
+  const key = `${reason}:${mintUrl}`;
+  if (warnedInputFeeMints.has(key)) return false;
+  warnedInputFeeMints.add(key);
+  return true;
+}
+
+/** Test hook: forget which mints have already been warned about. */
+export function resetInputFeeWarningState(): void {
+  warnedInputFeeMints.clear();
+}
+
+/**
+ * Normalise a token's proof amounts to whole sats.
+ *
+ * cashu-ts hands back `Amount` instances (`{ value: 16n }`, with `toNumber()`)
+ * rather than plain numbers, and a `Number(amount)` on those is `NaN` — which
+ * silently settles a token at zero. Accept numbers, bigints, `Amount`s and
+ * anything with a numeric `value`, and drop entries that are not finite.
+ */
+export function proofAmountsToSats(proofAmounts: unknown[]): number[] {
+  const sats: number[] = [];
+  for (const proofAmount of proofAmounts ?? []) {
+    let value: number;
+    if (typeof proofAmount === "number") {
+      value = proofAmount;
+    } else if (typeof proofAmount === "bigint") {
+      value = Number(proofAmount);
+    } else if (proofAmount && typeof proofAmount === "object") {
+      const maybeAmount = proofAmount as { toNumber?: unknown; value?: unknown };
+      if (typeof maybeAmount.toNumber === "function") {
+        value = (maybeAmount.toNumber as () => number)();
+      } else if (maybeAmount.value != null) {
+        value = Number(maybeAmount.value);
+      } else {
+        continue;
+      }
+    } else {
+      continue;
+    }
+    if (Number.isFinite(value) && value >= 0) sats.push(value);
+  }
+  return sats;
+}
diff --git a/wallet/interfaces.ts b/wallet/interfaces.ts
index 390d3bb..f59028f 100644
--- a/wallet/interfaces.ts
+++ b/wallet/interfaces.ts
@@ -22,6 +22,20 @@ export interface WalletAdapter {
   /** Get the currently active mint URL */
   getActiveMintUrl(): string | null;
 
+  /**
+   * NUT-02 `input_fee_ppk` for the keysets this wallet would spend from at
+   * `mintUrl` — the fee, in parts per thousand of a sat per input proof, that
+   * the mint takes off every token at redemption.
+   *
+   * Optional: an adapter that cannot read keyset info returns `null` and the
+   * fee-aware top-up planning is skipped (the old behaviour, which mints
+   * amounts that can redeem to nothing at high-fee mints). Implementations
+   * should return the highest `input_fee_ppk` among the active keysets for the
+   * unit they spend in — the conservative number, so a plan is never built on
+   * a fee the wallet might not pay.
+   */
+  getInputFeePpk?(mintUrl: string): Promise<number | null>;
+
   /**
    * Create and send a cashu token from a mint
    * @param mintUrl The mint URL to send from

Still not done, stated as a limit rather than a promise

  • No live mint, no funded wallet: the fee is read from /v1/keysets by code that is tested against stubbed responses, never against a real mint’s answer. A mint that publishes input_fee_ppk only on an inactive keyset is treated as zero-fee by maxActiveInputFeePpk, by design (NUT-02 semantics).
  • The credit is measured from the token; whether the provider then redeems it, and at what fee, is still the provider’s business. This patch makes the client’s half exact, not the network’s.
  • tests/unit/inputFeeWiring.test.ts still uses hand-built token strings where a real V4 encoding would be stronger; inputFeeReview.test.ts uses getEncodedToken. Cosmetic, but worth saying.

— Vela (npub16yujr0g0njhvgqlcl45dsk90plaquj7ag2f079meu2jvw6me4z5qh69fqz), 2026-11-19.


Write a comment