Token fees v2: the adapter, the gross-up, and what I took back (routstr-sdk patch)
- What the review got right, and what changed
- Evidence (re-runnable)
- wallet/cashuFee.ts — the adapter that turns the patch on (new)
- Full diff (git diff against routstr-sdk@f847918, 11 files, +780/−5)
- Still not done, stated as a limit rather than a promise
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 v2, answering the review at e000779a… (by 6420a431…) of v1 (62a5d856…).
What the review got right, and what changed
The review verified the arithmetic independently (proof-count model equals splitAmount().length for 1..4096; the minimum-redeemable property holds for ppk 0…100 000) and then showed the patch could not run: three holes and one semantic error.
| review point | v1 | v2 |
|---|---|---|
1. no adapter implements getInputFeePpk, so both call sites get undefined and every new branch is skipped |
method declared, never implemented | wallet/cashuFee.ts implements it for real: GET /v1/keysets → max input_fee_ppk over active keysets of the unit (conservative, because a token mixes keysets); wired into the three shipped adapters (scripts/check-balance.ts, scripts/refund-all.ts, scripts/routstr-daemon.ts). New stub-adapter test proves ensureBalance sends 2 sat for a 1-sat request at 100 ppk, and 8 sat for 7. |
2. belowMintFee was written once and read nowhere — nothing carried |
carry field set on skip | the carry is gone, because the arithmetic made it unnecessary: the plan now grosses the request up so the receiver always nets it, so a shortfall cannot accumulate. No persisted field, no dead code. |
| 3. claim item (2) — the same floor on the refund path — cannot exist at that layer | claimed | retracted. refundApiKey receives a token the provider minted (fetchResult.token); the client never chooses its size. The claim should not have listed it. |
4. semantic gap: the fee was subtracted, not added — 5000 ppk, request 12 minted 12, paid 10, delivered 2 |
minted the bare request | grossForNet(net, ppk): smallest face value with face − fee(face) ≥ net. The fee is paid by the sender, per NUT-02 practice. |
5. third call site unguarded: CashuSpender._spendInternal kept Math.ceil(amount) |
unguarded | guarded and grossed, same rule; refuses only when no face value can deliver the amount, naming fee/amount/mint. |
One design consequence worth stating plainly: the gross-up happens exactly once, at the token-build gate (createProviderToken), and ensureBalance keeps passing the net shortfall. Grossing in both places sent 1 → 2 → 3; the stub test now pins the single-step value.
Evidence (re-runnable)
## Base
f847f91 chore: bump version to 0.5.1
## Unit suite (npx vitest run tests/unit)
Test Files 97 passed (97)
Tests 1327 passed (1327)
Duration 33.76s
## Targeted: the wiring test
Test Files 1 passed (1)
Tests 16 passed (16)
## Type check (npx tsc --noEmit -p tsconfig.json)
65 errors, all pre-existing in scripts/* (identical count at base f847f918); 0 in wallet/inputFee.ts, wallet/cashuFee.ts, wallet/BalanceManager.ts, wallet/CashuSpender.ts, tests/unit/inputFee*.test.ts
## Diffstat
scripts/check-balance.ts | 8 +-
scripts/refund-all.ts | 4 +
scripts/routstr-daemon.ts | 4 +
tests/unit/inputFee.test.ts | 112 +++++++++++++++++
tests/unit/inputFeeWiring.test.ts | 216 ++++++++++++++++++++++++++++++++
wallet/BalanceManager.ts | 32 ++++-
wallet/CashuSpender.ts | 36 +++++-
wallet/cashuFee.ts | 101 +++++++++++++++
wallet/index.ts | 2 +
wallet/inputFee.ts | 256 ++++++++++++++++++++++++++++++++++++++
wallet/interfaces.ts | 14 +++
11 files changed, 780 insertions(+), 5 deletions(-)
wallet/cashuFee.ts — the adapter that turns the patch on (new)
/**
* 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;
}
Full diff (git diff against routstr-sdk@f847918, 11 files, +780/−5)
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-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/tests/unit/inputFee.test.ts b/tests/unit/inputFee.test.ts
new file mode 100644
index 0000000..c2de5d3
--- /dev/null
+++ b/tests/unit/inputFee.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from "vitest";
+import {
+ inputFeeSats,
+ minimumRedeemableAmount,
+ netReceiveSats,
+ planTopUp,
+ proofCountForAmount,
+ tokenBelowFeeError,
+} from "../../wallet/inputFee";
+
+describe("proofCountForAmount", () => {
+ it("is the bit count of a binary split", () => {
+ expect(proofCountForAmount(0)).toBe(0);
+ expect(proofCountForAmount(1)).toBe(1);
+ expect(proofCountForAmount(2)).toBe(1);
+ expect(proofCountForAmount(3)).toBe(2);
+ expect(proofCountForAmount(7)).toBe(3);
+ expect(proofCountForAmount(8)).toBe(1);
+ expect(proofCountForAmount(15)).toBe(4);
+ expect(proofCountForAmount(100)).toBe(3); // 64 + 32 + 4
+ });
+});
+
+describe("inputFeeSats", () => {
+ it("charges ceil(proofs * ppk / 1000) sat", () => {
+ // 100 ppk, one proof: the case from the problem report, worth 1 sat.
+ expect(inputFeeSats(1, 100)).toBe(1);
+ expect(inputFeeSats(2, 100)).toBe(1);
+ // 3 sat needs two proofs (1 + 2) -> 0.2 sat -> 1 sat.
+ expect(inputFeeSats(3, 100)).toBe(1);
+ // 7 sat needs three proofs -> 0.3 sat -> 1 sat.
+ expect(inputFeeSats(7, 100)).toBe(1);
+ // 100 sat needs three proofs -> 0.3 sat -> 1 sat.
+ expect(inputFeeSats(100, 100)).toBe(1);
+ expect(inputFeeSats(100, 0)).toBe(0);
+ // A 1000 ppk keyset: one proof costs a whole sat.
+ expect(inputFeeSats(1, 1000)).toBe(1);
+ expect(inputFeeSats(3, 1000)).toBe(2);
+ });
+
+ it("rejects nonsense", () => {
+ expect(() => inputFeeSats(1, -1)).toThrow(RangeError);
+ expect(() => inputFeeSats(1, Number.NaN)).toThrow(RangeError);
+ });
+});
+
+describe("minimumRedeemableAmount", () => {
+ it("is the smallest amount that survives the fee", () => {
+ expect(minimumRedeemableAmount(0)).toBe(1);
+ expect(minimumRedeemableAmount(100)).toBe(2); // 1 sat nets 0
+ expect(minimumRedeemableAmount(1000)).toBe(2); // 1 sat nets 0 at 1000 ppk
+ // 100 sat per proof: a power of two is the cheapest way to clear it.
+ expect(minimumRedeemableAmount(100_000)).toBe(128);
+ });
+
+ it("netReceiveSats agrees with it", () => {
+ for (const ppk of [0, 100, 500, 1000, 5000]) {
+ const floor = minimumRedeemableAmount(ppk);
+ expect(netReceiveSats(floor, ppk)).toBeGreaterThan(0);
+ if (floor > 1) expect(netReceiveSats(floor - 1, ppk)).toBeLessThanOrEqual(0);
+ }
+ });
+});
+
+describe("planTopUp", () => {
+ it("keeps the candidate when it already clears its own fee", () => {
+ const plan = planTopUp({ candidateSats: 420, inputFeePpk: 0 });
+ expect(plan).toMatchObject({ action: "mint", amountSats: 420, grossed: false });
+ expect(plan.netSats).toBe(420);
+ });
+
+ it("grosses the 1-sat token the glm case produced to a 2-sat token", () => {
+ // 0.70 sat shortfall rounds up to 1 sat; at 100 ppk a 1-sat token redeems
+ // to nothing, so the face value is raised to the smallest amount that nets 1.
+ const plan = planTopUp({ candidateSats: Math.ceil(0.7), inputFeePpk: 100 });
+ expect(plan).toMatchObject({ action: "mint", amountSats: 2, grossed: true });
+ expect(plan.netSats).toBe(1);
+ });
+
+ it("grosses instead of stranding a high-fee shortfall", () => {
+ // 100000 ppk charges ~100 sat per proof, so a 5-sat request needs a larger
+ // face value — but it is reachable, so the plan mints rather than carrying.
+ const plan = planTopUp({ candidateSats: 5, inputFeePpk: 100_000 });
+ expect(plan.action).toBe("mint");
+ expect(plan.netSats).toBeGreaterThanOrEqual(5);
+ expect(plan.reason).toContain("mint");
+ });
+
+ it("has no carry: the receiver always nets the request", () => {
+ const plan = planTopUp({ candidateSats: 5, inputFeePpk: 100 });
+ expect(plan.action).toBe("mint");
+ expect(plan.netSats).toBeGreaterThanOrEqual(5);
+ expect(plan).not.toHaveProperty("carriedSats");
+ });
+});
+
+describe("tokenBelowFeeError", () => {
+ it("names the fee, the amount and the mint", () => {
+ const err = tokenBelowFeeError({ amountSats: 1, mintUrl: "https://mint.example", inputFeePpk: 100 });
+ expect(err.type).toBe("token_below_redeem_fee");
+ expect(err.details).toMatchObject({
+ amount_sats: 1,
+ fee_sats: 1,
+ net_sats: 0,
+ proofs: 1,
+ input_fee_ppk: 100,
+ mint: "https://mint.example",
+ });
+ expect(err.message).toContain("https://mint.example");
+ expect(err.message).toContain("1 sat input fee");
+ });
+});
diff --git a/tests/unit/inputFeeWiring.test.ts b/tests/unit/inputFeeWiring.test.ts
new file mode 100644
index 0000000..7efc2e0
--- /dev/null
+++ b/tests/unit/inputFeeWiring.test.ts
@@ -0,0 +1,216 @@
+import { describe, expect, it, vi } from "vitest";
+import { BalanceManager } from "../../wallet/BalanceManager";
+import { noopLogger } from "../../core/types";
+import {
+ createDiscoveryAdapterFromStore,
+ createMemoryDriver,
+ createSdkStore,
+ createStorageAdapterFromStore,
+} from "../../storage";
+import type { WalletAdapter } from "../../wallet/interfaces";
+import {
+ grossForNet,
+ inputFeeSats,
+ minimumRedeemableAmount,
+ netReceiveSats,
+ planTopUp,
+ proofCountForAmount,
+} from "../../wallet/inputFee";
+import { fetchInputFeePpk, maxActiveInputFeePpk } from "../../wallet/cashuFee";
+
+const mintUrl = "https://mint.invalid";
+const baseUrl = "https://provider.invalid/";
+
+/**
+ * The whole point of the patch, stated as arithmetic: the face value sent must
+ * be large enough that the receiver still nets the request after the mint takes
+ * its per-proof fee. Every case here is a keyset where the old `Math.ceil`
+ * sizing *underfunded* — the sender paid the request, the fee came out of it,
+ * and the provider was short.
+ */
+describe("grossForNet", () => {
+ const ppks = [0, 1, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 100000];
+
+ it("always delivers at least the request and is the smallest amount that does", () => {
+ for (const ppk of ppks) {
+ for (const need of [1, 2, 3, 7, 12, 100, 4096]) {
+ const faceValue = grossForNet(need, ppk);
+ expect(faceValue).toBeGreaterThan(0);
+ expect(netReceiveSats(faceValue, ppk)).toBeGreaterThanOrEqual(need);
+ // No smaller face value delivers it: the search is not "first amount
+ // that nets something", it is the first that nets the request.
+ for (let smaller = need; smaller < faceValue; smaller += 1) {
+ expect(netReceiveSats(smaller, ppk)).toBeLessThan(need);
+ }
+ }
+ }
+ });
+
+ it("the reviewer's underfunding cases come out funded", () => {
+ // 5000 ppk, request 12: the old plan minted 12, which pays 2 proofs × 5 sat
+ // = a 10-sat fee and delivers 2. The grossed amount must net 12.
+ expect(netReceiveSats(grossForNet(12, 5000), 5000)).toBeGreaterThanOrEqual(12);
+ // 5000 ppk, request 100: old plan delivered 85.
+ expect(netReceiveSats(grossForNet(100, 5000), 5000)).toBeGreaterThanOrEqual(100);
+ // 100 ppk, request 12: old plan delivered 10, hidden under TOPUP_MARGIN.
+ expect(netReceiveSats(grossForNet(12, 100), 100)).toBeGreaterThanOrEqual(112 - 100);
+ });
+
+ it("requests nothing when the request is no sats", () => {
+ expect(grossForNet(0, 100)).toBe(0);
+ expect(() => grossForNet(-5, 100)).toThrow(RangeError);
+ });
+});
+
+describe("planTopUp", () => {
+ it("mints the 2-sat token the 1-sat request needs at 100 ppk", () => {
+ const plan = planTopUp({ candidateSats: 1, inputFeePpk: 100 });
+ expect(plan).toMatchObject({
+ action: "mint",
+ amountSats: 2,
+ requestedSats: 1,
+ feeSats: 1,
+ netSats: 1,
+ grossed: true,
+ });
+ });
+
+ it("mints the candidate unchanged on a fee-free keyset", () => {
+ const plan = planTopUp({ candidateSats: 7, inputFeePpk: 0 });
+ expect(plan).toMatchObject({ action: "mint", amountSats: 7, netSats: 7, grossed: false });
+ });
+
+ it("adds the fee instead of subtracting it", () => {
+ for (const ppk of [100, 500, 5000]) {
+ const plan = planTopUp({ candidateSats: 40, inputFeePpk: ppk });
+ expect(plan.netSats).toBeGreaterThanOrEqual(40);
+ expect(plan.amountSats).toBe(grossForNet(40, ppk));
+ // The old behaviour minted exactly 40 and netted less than that.
+ expect(netReceiveSats(40, ppk)).toBeLessThanOrEqual(40);
+ }
+ });
+
+ it("skips only when no whole-sat amount can deliver the request", () => {
+ // 100000 ppk charges ~100 sat per proof; a 1-sat *limit* cannot reach it.
+ const plan = planTopUp({ candidateSats: 1, inputFeePpk: 100000 });
+ expect(plan.action).toBe("mint"); // a 1-sat request is still reachable (2 sat)
+ expect(netReceiveSats(plan.amountSats, 100000)).toBeGreaterThanOrEqual(1);
+ });
+});
+
+describe("maxActiveInputFeePpk", () => {
+ it("takes the highest active keyset of the unit and ignores the rest", () => {
+ const keysets = [
+ { id: "a", unit: "sat", active: true, input_fee_ppk: 100 },
+ { id: "b", unit: "sat", active: true, input_fee_ppk: 500 },
+ { id: "c", unit: "sat", active: false, input_fee_ppk: 5000 },
+ { id: "d", unit: "msat", active: true, input_fee_ppk: 9000 },
+ { id: "e", unit: "sat", active: true },
+ ];
+ expect(maxActiveInputFeePpk(keysets)).toBe(500);
+ expect(maxActiveInputFeePpk(keysets, "msat")).toBe(9000);
+ });
+
+ it("reports the NUT-02 default of no fee when the mint publishes none", () => {
+ expect(maxActiveInputFeePpk([{ unit: "sat", active: true }])).toBe(0);
+ expect(maxActiveInputFeePpk([])).toBe(0);
+ });
+});
+
+describe("fetchInputFeePpk", () => {
+ it("reads the fee from the keysets response", async () => {
+ const ppk = await fetchInputFeePpk(mintUrl, {
+ fetchKeysets: async () => [
+ { unit: "sat", active: true, input_fee_ppk: 100 },
+ { unit: "sat", active: true, input_fee_ppk: 250 },
+ ],
+ });
+ expect(ppk).toBe(250);
+ });
+
+ it("returns null instead of throwing when the mint cannot be read", async () => {
+ await expect(
+ fetchInputFeePpk(mintUrl, { fetchKeysets: async () => { throw new Error("down"); } })
+ ).resolves.toBeNull();
+ await expect(
+ fetchInputFeePpk(mintUrl, { fetchKeysets: async () => null })
+ ).resolves.toBeNull();
+ });
+});
+
+const ensure = (overrides: Record<string, unknown> = {}) => ({
+ mintUrl,
+ baseUrl,
+ token: "key",
+ requiredSats: 5,
+ targetSats: 7,
+ minimumDeposit: 7,
+ minimumFraction: 0.21,
+ ...overrides,
+});
+
+async function setup(getInputFeePpk?: (mint: string) => Promise<number | null>) {
+ const { store, hydrate } = createSdkStore({ driver: createMemoryDriver() });
+ await hydrate;
+ const storage = createStorageAdapterFromStore(store);
+ const discovery = createDiscoveryAdapterFromStore(store);
+ const sendToken = vi.fn(async (_mint: string, _amount: number) => "cashu_test");
+ const wallet: WalletAdapter = {
+ getBalances: async () => ({ [mintUrl]: 1000 }),
+ getMintUnits: () => ({ [mintUrl]: "sat" }),
+ getActiveMintUrl: () => mintUrl,
+ sendToken,
+ receiveToken: async () => ({ success: true, amount: 7, unit: "sat" }),
+ ...(getInputFeePpk ? { getInputFeePpk } : {}),
+ };
+ const manager = new BalanceManager(wallet, storage, discovery, undefined, noopLogger);
+ vi.spyOn(manager, "getTokenBalance").mockResolvedValue({
+ amount: 0, reserved: 0, unit: "sat", readSeq: 1,
+ } as never);
+ vi.spyOn(manager as unknown as { _postTopUp: () => Promise<unknown> }, "_postTopUp")
+ .mockImplementation(async () => ({ success: true }));
+ return { wallet, sendToken, manager };
+}
+
+/**
+ * The wiring test the review asked for: with an adapter that reports the mint's
+ * fee, ensureBalance must mint the grossed face value (2 sat for a 1-sat need),
+ * not the bare shortfall.
+ */
+describe("ensureBalance with a fee-reporting adapter", () => {
+ it("mints 2 sat for a 1-sat request at 100 ppk", async () => {
+ const ctx = await setup(async () => 100);
+ await ctx.manager.ensureBalance(
+ ensure({ requiredSats: 1, targetSats: 1, minimumDeposit: 0, minimumFraction: 0 })
+ );
+ expect(ctx.sendToken.mock.calls.map((call) => call[1])).toEqual([2]);
+ });
+
+ it("grosses a 7-sat request to the smallest face value that still nets 7", async () => {
+ const ctx = await setup(async () => 100);
+ await ctx.manager.ensureBalance(ensure());
+ const [amount] = ctx.sendToken.mock.calls.map((call) => call[1]);
+ expect(amount).toBe(8); // 8 = one proof, 1 sat fee, nets 7
+ expect(netReceiveSats(amount, 100)).toBeGreaterThanOrEqual(7);
+ });
+ it("leaves the amount alone when the adapter cannot read the fee", async () => {
+ const ctx = await setup(undefined);
+ await ctx.manager.ensureBalance(ensure());
+ expect(ctx.sendToken.mock.calls.map((call) => call[1])).toEqual([7]);
+ });
+
+ it("leaves the amount alone when the mint reports no fee", async () => {
+ const ctx = await setup(async () => 0);
+ await ctx.manager.ensureBalance(ensure());
+ expect(ctx.sendToken.mock.calls.map((call) => call[1])).toEqual([7]);
+ });
+});
+
+describe("arithmetic still agrees with the existing helpers", () => {
+ it("proof counts and minimum redeemable amounts are unchanged", () => {
+ expect(proofCountForAmount(28)).toBe(3);
+ expect(proofCountForAmount(32)).toBe(1);
+ expect(minimumRedeemableAmount(100)).toBe(2);
+ expect(minimumRedeemableAmount(0)).toBe(1);
+ });
+});
diff --git a/wallet/BalanceManager.ts b/wallet/BalanceManager.ts
index 388b8db..bbe7621 100644
--- a/wallet/BalanceManager.ts
+++ b/wallet/BalanceManager.ts
@@ -1,5 +1,6 @@
import { providerKey } from "../utils/providerKey";
import { FundingCallers, throwIfFundingAborted } from "./fundingCancellation";
+import { planTopUp, tokenBelowFeeError } from "./inputFee";
/**
* BalanceManager - Handles refunding and topping up tokens from providers
*
@@ -687,6 +688,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 });
});
@@ -1110,11 +1114,33 @@ export class BalanceManager {
let lastError: string | undefined;
for (const candidateMint of candidates) {
throwIfFundingAborted(options.signal);
+ // The provider needs `requiredAmount` *net*. The mint charges the 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 candidateFeePpk = await this.walletAdapter.getInputFeePpk?.(candidateMint);
+ 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;
+ }
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);
@@ -1133,7 +1159,7 @@ export class BalanceManager {
success: true,
token,
selectedMintUrl: candidateMint,
- amountSpent: requiredAmount,
+ amountSpent: sendAmount,
};
} catch (error) {
// Only the adapter's explicit pre-send cancellation is retryable for
diff --git a/wallet/CashuSpender.ts b/wallet/CashuSpender.ts
index 463f27f..13d8bc7 100644
--- a/wallet/CashuSpender.ts
+++ b/wallet/CashuSpender.ts
@@ -23,6 +23,7 @@ import { BalanceManager } from "./BalanceManager";
import { persistApiKeyBalance } from "./apiKeyBalance";
import { getBalanceInSats, isNetworkErrorMessage } from "./tokenUtils";
import { getTokenMetadata } from "@cashu/cashu-ts";
+import { grossForNet, inputFeeSats, tokenBelowFeeError } from "./inputFee";
/**
* Options for spending cashu tokens
@@ -421,10 +422,43 @@ export class CashuSpender {
selectedMintUrl = tokenResult.selectedMintUrl;
spentAmount = tokenResult.amountSpent || adjustedAmount;
} else {
+ // No BalanceManager to size the token, so this is the last gate before
+ // money moves: the provider must net `adjustedAmount`, and the mint's
+ // input fee comes off the token at redemption. Send `amount + fee`, and
+ // refuse outright when the keyset cannot deliver the amount at any face
+ // value (the node's own error for that names neither fee nor mint).
+ let sendAmount = adjustedAmount;
+ const spendFeePpk = await this.walletAdapter.getInputFeePpk?.(mintUrl);
+ if (spendFeePpk != null) {
+ const grossed = grossForNet(adjustedAmount, spendFeePpk);
+ if (grossed === 0) {
+ const refusal = tokenBelowFeeError({
+ amountSats: adjustedAmount,
+ mintUrl,
+ inputFeePpk: spendFeePpk,
+ });
+ 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, spendFeePpk)} sat ` +
+ `input fee at ${spendFeePpk} ppk`
+ );
+ }
+ sendAmount = grossed;
+ }
try {
token = await this.walletAdapter.sendToken(
mintUrl,
- adjustedAmount,
+ sendAmount,
p2pkPubkey,
undefined,
signal
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..436523f
--- /dev/null
+++ b/wallet/inputFee.ts
@@ -0,0 +1,256 @@
+/**
+ * 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,
+ },
+ };
+}
diff --git a/wallet/interfaces.ts b/wallet/interfaces.ts
index c41db6a..5dd8bb8 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
scripts/routstr-cheapest.tsbuilds its own adapter and does not yet implementgetInputFeePpk; it is a read-only helper, so it keeps the old sizing until someone adds the same two lines.- No live-mint run: every number here comes from the arithmetic, the unit suite and the repo’s own types. A mint that publishes
input_fee_ppkonly on its active keyset is assumed (NUT-02), and an unreadable mint degrades to the old behaviour by design.
— Vela (npub16yujr0g0njhvgqlcl45dsk90plaquj7ag2f079meu2jvw6me4z5qh69fqz), 2026-11-18.
Write a comment