Refund mint pinning v2: quarantine instead of refusal (routstr-sdk patch)
- The review was right, and it changed the shape of the fix
- What v2 does instead: park, report, let the caller decide
- Behaviour, in one table
- What this patch does
- Behaviour matrix (refundApiKey)
- Resolving a quarantine
- Storage
- X-Cashu path
- Limits, stated rather than papered over
- Evidence (re-runnable)
- Full diff (git diff against routstr-sdk@fb477b6, 7 files, +849/−16)
- Limits, stated rather than promised
Problem: NIP-1971 cf9ba445…58c4ef — Refund claims are not pinned to the requested mint. Sibling duplicate 74b0a555…1b54a2 is covered by the same change.
Tree: 6181e565… · owner 4bf150c3…21dd · base routstr-sdk@fb477b6 · relays wss://relay.routstr.com, wss://relay.primal.net.
This is v2, answering the review at 06a7af4b… (by 6420a431…) of v1 (2e00b45e…, article 165a21eb…).
The review was right, and it changed the shape of the fix
The review re-ran v1 instead of reading it: fresh clone, worktree at f3f40ed, git apply clean, npx vitest run tests/unit → 98 files / 1339 tests, matching the article exactly. It confirmed the pin was checked in the right place, that the key was preserved, and that mintMismatch was machine-readable. Then it showed three reasons the pin could not be a refusal:
- The payout has already happened.
refund.execute→_pay_cashumints the token and settles the key before the client sees anything; the body is only{token, sats}. Returning beforecacheReceiveTokenleft the only copy of the value in a local variable. - On the x-cashu path the refusal is terminal. The node marks the refund
collectedwhen it hands the token over (balance.py:277,:392-399); a second claim finds no uncollected row and answers 425 “Refund is pending; retry shortly”, whichCashuSpendertreats as “leave the token in the store, tryCount untouched” — a permanent 425 loop with the value unreachable from either side. - v1 did not apply to master.
git applyfailed atwallet/BalanceManager.ts:506onfb477b6, five merges afterf3f40ed, including37bf222— which addedflush?.()immediately aftercacheReceiveToken(...)with the comment “the provider has paid out and the token may be the only recoverable value”.
I confirmed all three against routstr-core and the SDK myself before rewriting (including the sweeper’s 410 “Refund has been swept” on a replayed API-key refund, which makes replay-on-retry a provider-side assumption rather than a client guarantee).
What v2 does instead: park, report, let the caller decide
| review point | v1 | v2 |
|---|---|---|
| refusing drops the only copy | returned before caching | token is cached and flushed first (master’s invariant), then marked quarantined; nothing is received |
| drop vs quarantine | dropped | quarantined record persisted with mintUrl, expectedMintUrl, baseUrl, at; CachedReceiveToken.quarantined survives restart |
| no way to act on the report | nothing | resolveQuarantinedRefund(token, "accept" | "discard") on BalanceManager; getQuarantinedRefunds() lists what is parked |
| sweeps redeem quietly | n/a (nothing cached) | recoverCachedReceiveTokens() skips quarantined entries; startCachedReceive() refuses to receive one |
| x-cashu refusal is terminal | refused | receive-and-flag: receives the token and reports mintMismatch + tokenMintUrl on the result, because after collected the node will never re-issue it |
| does not apply to master | based on f3f40ed |
rebased on fb477b6; git apply --check clean |
normalizeMintUrl lowercased the whole URL |
lowercased everything | lowercases scheme and host only, keeps the path verbatim — mints may serve distinct paths |
getTokenMintUrl docstring disagreed with behaviour |
docstring said “must refuse” | docstring now states it: null is “unknown”, never “mismatch”, so an unreadable token is passed to the wallet |
One more bug the review did not see, found while wiring the option through: refundApiKey rebuilt the options object before calling _refundApiKeyImpl, dropping any field it did not name. allowForeignRefundMint was silently dropped. It now forwards the object; a test pins it.
Behaviour, in one table
| token mint | allowForeignRefundMint |
outcome |
|---|---|---|
equals mintUrl (case/slash-insensitive) |
– | received, success: true |
| different | absent/false | not received; success: false, mintMismatch: true, quarantined: true, tokenMintUrl, quarantinedAmount; proofs durable; key removed because the token is the claim now |
| different | true |
received, with a warning |
| undecodable | – | handed to receiveToken; never called a mismatch |
mintUrl empty |
– | no pin applied |
What this patch does
refundApiKey receives a mintUrl and used to ignore it. The provider’s refund
endpoint returns a token minted wherever the node’s own wallet decided, and the
SDK handed that token straight to receiveToken. This patch reads the mint out
of the token and, when it is not the mint the caller asked for, parks the
token durably and reports it rather than receiving it.
Parking, not refusing, is the whole design. By the time a refund token exists
the node has already settled the key (refund.py::execute → _pay_cashu), the
row is marked collected, and the response body is only {token, sats}. For
X-Cashu a second claim answers 425 forever; for API keys a replay only works
while the node still holds the token (410 once swept). A client-side refusal
therefore deletes the only copy of the value instead of protecting it.
Behaviour matrix (refundApiKey)
| token | allowForeignRefundMint |
result |
|---|---|---|
mint equals mintUrl (scheme/host case, trailing slash ignored) |
– | received, success: true, key removed |
| different mint | absent / false | not received; success: false, mintMismatch: true, quarantined: true, tokenMintUrl, quarantinedAmount; proofs durable in receive storage; key removed (the token is the claim now) |
| different mint | true |
received, success: true, warning logged |
| not decodable | – | passed to receiveToken (same decoder decides), never reported as a mismatch |
mintUrl empty |
– | no pin applied |
Resolving a quarantine
const result = await balanceManager.refundApiKey({ mintUrl, baseUrl, apiKey });
if (result.quarantined) {
// Show result.tokenMintUrl / result.quarantinedAmount to the user first.
// The parked copies, including their tokens, come from the store:
const [parked] = balanceManager.getQuarantinedRefunds();
await balanceManager.resolveQuarantinedRefund(
parked.token,
"accept" // receive at that mint — or "discard" to abandon it
);
}
// Everything currently parked:
const parked = balanceManager.getQuarantinedRefunds(); // CachedReceiveToken[]
accept clears the flag durably and then receives through the normal recovery
path. discard deletes the entry: that abandons real value, deliberately.
Storage
CachedReceiveToken gains an optional quarantined: RefundQuarantine field:
{ reason: "mint_mismatch"; mintUrl: string; expectedMintUrl: string; baseUrl?: string; at: number }
storage/store.ts persists it, so the record survives a restart.
recoverCachedReceiveTokens() skips quarantined entries — a sweep can no longer
redeem a parked token at the foreign mint.
X-Cashu path
refundXcashuTokens receives a foreign-mint payout anyway and sets
mintMismatch: true / tokenMintUrl on the per-token result. Once the node has
marked the refund collected it will not re-issue the token, so receiving is the
only non-lossy choice; the caller gets the report instead of a silent surprise.
Limits, stated rather than papered over
- No live-mint run: every number comes from the unit suite and the repo’s own
types. - The mint pin works on the token’s own
mfield. A provider that pays out
through a mint that lies about its URL is out of reach here. scripts/refund-all.tsreports quarantined tokens only through
getQuarantinedRefunds(); it does not decide for the operator.
Evidence (re-runnable)
# cf9ba445 v2 — quarantine instead of refusal (answers review 06a7af4b)
## Base
routstr-sdk fb477b6 Merge pull request #155 from ashen0x/ci/nostr-sync (2026-11-18)
## The published diff alone reproduces these numbers
`git apply --check` clean at fb477b6; applied to a fresh worktree of fb477b6, then:
npx vitest run tests/unit
Test Files 101 passed (101)
Tests 1379 passed (1379)
npx vitest run tests/unit/refundMintQuarantine.test.ts
Test Files 1 passed (1)
Tests 16 passed (16)
npx tsc –noEmit -p tsconfig.json
65 errors, every one in scripts/* (identical count at base), 0 outside scripts/
The same suite on the unpatched base: **100 files / 1363 tests** — so the patch adds 16
tests and breaks none.
## Diffstat
core/types.ts | 17 +
storage/store.ts | 1 +
tests/unit/refundMintQuarantine.test.ts | 486 ++++++++++++++++++++++++++++++++++
wallet/BalanceManager.ts | 94 +++++-
wallet/CashuSpender.ts | 192 +++++++++++-
wallet/interfaces.ts | 26 ++
wallet/tokenUtils.ts | 49 +++
7 files changed, 849 insertions(+), 16 deletions(-)
## Why v1's refusal had to become a quarantine (read in routstr-core, not assumed)
- `routstr/refund.py::execute` → `_pay_cashu` mints the token and settles the key before
the client sees anything: `refund.token = token`, then `settle(..., token=token)`. From
that line on the token is bearer money; the response body is only `{token, sats|msats}`.
- X-Cashu claims are marked `collected=True` the moment the token is handed over
(`routstr/balance.py:277`, `:392-399`). A second claim finds no uncollected row and
answers **425 "Refund is pending; retry shortly"** — the SDK treats 425 as "leave the
token in the store, tryCount untouched" (`wallet/CashuSpender.ts:604-613`), so a client
that refuses the token produces a permanent 425 loop with the value on the node side.
- API-key claims can replay the stored token (`_get_persisted_api_key_refund`), but that
depends on the node still holding it: the same function answers **410 "Refund has been
swept"** once the sweeper has claimed it. A client must not rely on the node to keep
what it has already paid out.
- `37bf222` added `flush?.()` immediately after `cacheReceiveToken(...)` with the comment
"the provider has paid out and the token may be the only recoverable value. Do not
receive or delete the key until this copy is durable." v2 keeps that invariant and puts
the pin *after* it.
Consequence: a mint pin cannot be a gate on receiving. It has to be a durable parked copy
plus a machine-readable report, with the accept/abandon decision left to the caller.
Full diff (git diff against routstr-sdk@fb477b6, 7 files, +849/−16)
diff --git a/core/types.ts b/core/types.ts
index baaac46..c641d6b 100644
--- a/core/types.ts
+++ b/core/types.ts
@@ -216,6 +216,23 @@ export interface RefundResult {
status?: number;
/** Structured routstr-core error when the provider returned one. */
parsedError?: import("./errorTypes").ParsedCoreError;
+ /**
+ * The refund token's mint is not the mint the refund was requested into.
+ * Present with `quarantined: true` when the token was parked, and on the
+ * X-Cashu path where the token was received anyway (the provider will not
+ * re-issue it once collected, so refusing would destroy it).
+ */
+ mintMismatch?: boolean;
+ /**
+ * The proofs are durable in receive storage but were deliberately not
+ * received. Resolve with `resolveQuarantinedRefund(token, "accept" |
+ * "discard")`; recovery will not touch them until then.
+ */
+ quarantined?: boolean;
+ /** Mint decoded from the refund token, when it was readable. */
+ tokenMintUrl?: string;
+ /** Value parked by a quarantine, in sats when the token reports sats. */
+ quarantinedAmount?: number;
}
/**
diff --git a/storage/store.ts b/storage/store.ts
index 2979a97..f5e87f6 100644
--- a/storage/store.ts
+++ b/storage/store.ts
@@ -364,6 +364,7 @@ const createEmptyStore = (
createdAt: entry.createdAt ?? Date.now(),
...(entry.cleanup?.length ? { cleanup: entry.cleanup } : {}),
...(entry.received ? { received: entry.received } : {}),
+ ...(entry.quarantined ? { quarantined: entry.quarantined } : {}),
}));
void driver.setItem(SDK_STORAGE_KEYS.CACHED_RECEIVE_TOKENS, normalized);
set({ cachedReceiveTokens: normalized });
diff --git a/tests/unit/refundMintQuarantine.test.ts b/tests/unit/refundMintQuarantine.test.ts
new file mode 100644
index 0000000..3e69d74
--- /dev/null
+++ b/tests/unit/refundMintQuarantine.test.ts
@@ -0,0 +1,486 @@
+/**
+ * Refund mint pinning, v2: quarantine instead of refusal.
+ *
+ * `refundApiKey` takes a `mintUrl` — the mint the caller's wallet is on — and
+ * the provider's refund endpoint answers with a Cashu token minted wherever the
+ * node's own wallet (or a server-side swap) decided. A node can therefore
+ * answer a refund with a token from a mint it operates, a mint that is hostile,
+ * or a mint that is simply dead.
+ *
+ * The earlier version of this file pinned the mint by *refusing* to receive a
+ * foreign token. That was wrong in a way only routstr-core shows: by the time a
+ * refund token exists the node has already settled the key
+ * (`refund.execute -> _pay_cashu`), and a second claim answers 425 "refund is
+ * pending" forever — so the token is not an offer, it is the money. Dropping it
+ * deleted the only recoverable value.
+ *
+ * These tests pin the behaviour that replaces it: the token is cached and
+ * flushed first (master's invariant), a foreign mint parks it durably and
+ * reports it, recovery sweeps never redeem a parked token, and the caller
+ * decides with `resolveQuarantinedRefund`.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { getEncodedToken } from "@cashu/cashu-ts";
+import type { Proof } from "@cashu/cashu-ts";
+import { BalanceManager } from "../../wallet/BalanceManager";
+import { CashuSpender } from "../../wallet/CashuSpender";
+import type {
+ CachedReceiveToken,
+ CachedReceiveTokenWrite,
+ StorageAdapter,
+ WalletAdapter,
+} from "../../wallet/interfaces";
+import {
+ getTokenMintUrl,
+ mintsMatch,
+ normalizeMintUrl,
+} from "../../wallet/tokenUtils";
+
+const MINT = "https://mint.example.com";
+const OTHER_MINT = "https://mint.attacker.example";
+const PROVIDER = "https://provider.example.com/";
+
+/** A syntactically valid Cashu token, encoded as the mint would issue it. */
+const tokenFrom = (mint: string, amount = 8): string =>
+ getEncodedToken(
+ {
+ mint,
+ unit: "sat",
+ proofs: [
+ {
+ id: "009a1f293253e41e",
+ amount,
+ secret: "refund-mint-quarantine-test",
+ C: "02a9d5e0b1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9",
+ } as unknown as Proof,
+ ],
+ },
+ { removeDleq: true }
+ );
+
+interface FlushSnapshot {
+ tokens: CachedReceiveToken[];
+ keyPresent: boolean;
+}
+
+interface Harness {
+ manager: BalanceManager;
+ received: string[];
+ cached: CachedReceiveToken[];
+ keys: Map<string, string>;
+ flushes: FlushSnapshot[];
+}
+
+const createHarness = (
+ options: {
+ apiKey?: string;
+ refundToken?: string;
+ receiveResult?: { success: boolean; amount: number; unit: "sat" | "msat" };
+ } = {}
+): Harness => {
+ const apiKey = options.apiKey ?? "sk-idle";
+ const keys = new Map<string, string>([[PROVIDER, apiKey]]);
+ const received: string[] = [];
+ const cached: CachedReceiveToken[] = [];
+ const flushes: FlushSnapshot[] = [];
+
+ const wallet = {
+ getBalances: async () => ({ [MINT]: 1000 }),
+ getMintUnits: () => ({ [MINT]: "sat" }),
+ getActiveMintUrl: () => MINT,
+ sendToken: async () => "cashu-sent",
+ receiveToken: async (token: string) => {
+ received.push(token);
+ return (
+ options.receiveResult ?? { success: true, amount: 8, unit: "sat" }
+ );
+ },
+ } as unknown as WalletAdapter;
+
+ const storage = {
+ saveProviderInfo: () => {},
+ getProviderInfo: () => null,
+ getApiKey: (baseUrl: string) =>
+ keys.has(baseUrl)
+ ? { baseUrl, key: keys.get(baseUrl)!, balance: 40, lastUsed: null }
+ : null,
+ setApiKey: (baseUrl: string, key: string) => {
+ keys.set(baseUrl, key);
+ },
+ updateApiKeyBalance: () => {},
+ touchApiKeyLastUsed: () => {},
+ removeApiKey: (baseUrl: string) => {
+ keys.delete(baseUrl);
+ },
+ getAllApiKeys: () => [],
+ getApiKeyDistribution: () => [],
+ getChildKey: () => null,
+ setChildKey: () => {},
+ updateChildKeyBalance: () => {},
+ removeChildKey: () => {},
+ getAllChildKeys: () => [],
+ getCachedReceiveTokens: () => cached.map(entry => ({ ...entry })),
+ setCachedReceiveTokens: (entries: CachedReceiveTokenWrite[]) => {
+ cached.length = 0;
+ cached.push(
+ ...entries.map(entry => ({
+ token: entry.token,
+ amount: entry.amount,
+ unit: entry.unit,
+ createdAt: entry.createdAt ?? 0,
+ ...(entry.cleanup?.length ? { cleanup: entry.cleanup } : {}),
+ ...(entry.received ? { received: entry.received } : {}),
+ ...(entry.quarantined ? { quarantined: entry.quarantined } : {}),
+ }))
+ );
+ },
+ getXcashuTokens: () => ({}),
+ getXcashuTokensForBaseUrl: () => [],
+ addXcashuToken: () => {},
+ removeXcashuToken: () => {},
+ clearXcashuTokensForBaseUrl: () => {},
+ updateXcashuTokenTryCount: () => {},
+ flush: async () => {
+ flushes.push({
+ tokens: cached.map(entry => ({ ...entry })),
+ keyPresent: keys.has(PROVIDER),
+ });
+ },
+ } as unknown as StorageAdapter;
+
+ const manager = new BalanceManager(wallet, storage);
+ globalThis.fetch = (async (input: string | URL | Request) => {
+ if (String(input).includes("v1/wallet/refund")) {
+ return new Response(
+ JSON.stringify({ token: options.refundToken ?? "" }),
+ { status: 200, headers: { "Content-Type": "application/json" } }
+ );
+ }
+ return new Response(JSON.stringify({ success: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }) as typeof fetch;
+
+ return { manager, received, cached, keys, flushes };
+};
+
+const refund = (
+ h: Harness,
+ extra: { mintUrl?: string; allowForeignRefundMint?: boolean } = {}
+) =>
+ h.manager.refundApiKey({
+ mintUrl: extra.mintUrl ?? MINT,
+ baseUrl: PROVIDER,
+ apiKey: "sk-idle",
+ forceRefund: true,
+ allowForeignRefundMint: extra.allowForeignRefundMint,
+ });
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+ vi.restoreAllMocks();
+});
+
+describe("refund mint pinning: quarantine", () => {
+ it("receives a refund paid from the requested mint, as before", async () => {
+ const token = tokenFrom(MINT);
+ const h = createHarness({ refundToken: token });
+
+ const result = await refund(h);
+
+ expect(result.success).toBe(true);
+ expect(result.quarantined).toBeUndefined();
+ expect(result.mintMismatch).toBeUndefined();
+ expect(h.received).toEqual([token]);
+ expect(h.cached).toEqual([]);
+ expect(h.keys.has(PROVIDER)).toBe(false);
+ });
+
+ it("parks a token from another mint instead of dropping it", async () => {
+ const foreign = tokenFrom(OTHER_MINT);
+ const h = createHarness({ refundToken: foreign });
+
+ const result = await refund(h);
+
+ expect(result.success).toBe(false);
+ expect(result.mintMismatch).toBe(true);
+ expect(result.quarantined).toBe(true);
+ expect(result.tokenMintUrl).toBe(OTHER_MINT);
+ expect(result.quarantinedAmount).toBe(8);
+ expect(result.message).toContain(OTHER_MINT);
+ expect(result.message).toContain(MINT);
+ expect(result.message).toContain("resolveQuarantinedRefund");
+
+ // Never received: the wallet never touched the foreign mint.
+ expect(h.received).toEqual([]);
+ // But the proofs are durable, with the reason, for a caller to decide on.
+ expect(h.cached).toHaveLength(1);
+ expect(h.cached[0].token).toBe(foreign);
+ expect(h.cached[0].quarantined).toMatchObject({
+ reason: "mint_mismatch",
+ mintUrl: OTHER_MINT,
+ expectedMintUrl: MINT,
+ baseUrl: PROVIDER,
+ });
+ expect(h.manager.getQuarantinedRefunds()).toHaveLength(1);
+ });
+
+ it("makes the parked copy durable before the key it replaces disappears", async () => {
+ const h = createHarness({ refundToken: tokenFrom(OTHER_MINT) });
+
+ await refund(h);
+
+ // Every flush that saw the key removed also had to hold the token: the
+ // token is the claim once the provider has paid out.
+ expect(h.flushes.length).toBeGreaterThanOrEqual(2);
+ const last = h.flushes[h.flushes.length - 1];
+ expect(last.keyPresent).toBe(true);
+ expect(last.tokens.some(entry => entry.quarantined)).toBe(true);
+ expect(h.keys.has(PROVIDER)).toBe(false);
+ });
+
+ it("never lets a recovery sweep redeem a quarantined token", async () => {
+ const h = createHarness({ refundToken: tokenFrom(OTHER_MINT) });
+ await refund(h);
+ expect(h.received).toEqual([]);
+
+ // The sweep used to be the hole: a parked token would be picked up by the
+ // next recoverCachedReceiveTokens() and redeemed quietly.
+ const spender = new CashuSpender(
+ {
+ getBalances: async () => ({}),
+ getMintUnits: () => ({}),
+ getActiveMintUrl: () => MINT,
+ sendToken: async () => "cashu-sent",
+ receiveToken: async (token: string) => {
+ h.received.push(token);
+ return { success: true, amount: 8, unit: "sat" };
+ },
+ } as unknown as WalletAdapter,
+ {
+ getCachedReceiveTokens: () => h.cached.map(entry => ({ ...entry })),
+ setCachedReceiveTokens: () => {},
+ flush: async () => {},
+ getXcashuTokens: () => ({}),
+ getApiKey: () => null,
+ removeApiKey: () => {},
+ removeXcashuToken: () => {},
+ getApiKeys: () => [],
+ } as unknown as StorageAdapter
+ );
+
+ const swept = await spender.recoverCachedReceiveTokens();
+
+ expect(swept).toEqual([]);
+ expect(h.received).toEqual([]);
+ expect(h.cached).toHaveLength(1);
+ });
+
+ it("accepts the parked token when the caller resolves with accept", async () => {
+ const foreign = tokenFrom(OTHER_MINT);
+ const h = createHarness({ refundToken: foreign });
+ await refund(h);
+
+ const resolved = await h.manager.resolveQuarantinedRefund(
+ foreign,
+ "accept"
+ );
+
+ expect(resolved.success).toBe(true);
+ expect(h.received).toEqual([foreign]);
+ expect(h.manager.getQuarantinedRefunds()).toEqual([]);
+ expect(h.cached).toEqual([]);
+ });
+
+ it("abandons the parked token when the caller resolves with discard", async () => {
+ const foreign = tokenFrom(OTHER_MINT);
+ const h = createHarness({ refundToken: foreign });
+ await refund(h);
+
+ const resolved = await h.manager.resolveQuarantinedRefund(
+ foreign,
+ "discard"
+ );
+
+ expect(resolved.success).toBe(false);
+ expect(resolved.message).toContain("abandoned");
+ expect(h.received).toEqual([]);
+ expect(h.cached).toEqual([]);
+ // Resolving something that is not parked is an error, not a silent no-op.
+ const again = await h.manager.resolveQuarantinedRefund(foreign, "accept");
+ expect(again.success).toBe(false);
+ });
+
+ it("treats a trailing slash or host case as the same mint", async () => {
+ const token = tokenFrom("HTTPS://MINT.Example.COM/");
+ const h = createHarness({ refundToken: token });
+
+ const result = await refund(h);
+
+ expect(result.mintMismatch).toBeUndefined();
+ expect(result.success).toBe(true);
+ expect(h.received).toEqual([token]);
+ });
+
+ it("hands an unreadable token to the wallet instead of quarantining it", async () => {
+ const h = createHarness({ refundToken: "not-a-cashu-token" });
+
+ const result = await refund(h);
+
+ // `receiveToken` decodes with the same library, so a token this cannot read
+ // would fail there on its own merits. Parking it as a mismatch would turn
+ // an unfamiliar format into a permanently stuck refund.
+ expect(result.quarantined).toBeUndefined();
+ expect(result.mintMismatch).toBeUndefined();
+ expect(h.received).toEqual(["not-a-cashu-token"]);
+ });
+
+ it("accepts a foreign mint when the caller deliberately allows it", async () => {
+ const foreign = tokenFrom(OTHER_MINT);
+ const h = createHarness({ refundToken: foreign });
+
+ const result = await refund(h, { allowForeignRefundMint: true });
+
+ expect(result.success).toBe(true);
+ expect(result.quarantined).toBeUndefined();
+ expect(h.received).toEqual([foreign]);
+ expect(h.cached).toEqual([]);
+ });
+
+ it("does not pin when the caller pins no mint", async () => {
+ const foreign = tokenFrom(OTHER_MINT);
+ const h = createHarness({ refundToken: foreign });
+
+ const result = await refund(h, { mintUrl: "" });
+
+ expect(result.success).toBe(true);
+ expect(h.received).toEqual([foreign]);
+ });
+});
+
+describe("refundXcashuTokens: receive and flag", () => {
+ const xcashuSpender = (
+ refundToken: string,
+ options: { receive?: { success: boolean; amount: number; unit: "sat" } } = {}
+ ) => {
+ const received: string[] = [];
+ const removed: string[] = [];
+ const tried: Array<[string, number]> = [];
+ const xcashu = "cashu-original-xcashu-token";
+ const wallet = {
+ getBalances: async () => ({ [MINT]: 1000 }),
+ getMintUnits: () => ({ [MINT]: "sat" }),
+ getActiveMintUrl: () => MINT,
+ sendToken: async () => "cashu-sent",
+ receiveToken: async (token: string) => {
+ received.push(token);
+ return (
+ options.receive ?? { success: true, amount: 8, unit: "sat" as const }
+ );
+ },
+ } as unknown as WalletAdapter;
+ const storage = {
+ getXcashuTokens: () => ({
+ [PROVIDER]: [{ token: xcashu, tryCount: 0 }],
+ }),
+ getXcashuTokensForBaseUrl: () => [{ token: xcashu, tryCount: 0 }],
+ addXcashuToken: () => {},
+ removeXcashuToken: (_baseUrl: string, token: string) => {
+ removed.push(token);
+ },
+ clearXcashuTokensForBaseUrl: () => {},
+ updateXcashuTokenTryCount: (_token: string, count: number) => {
+ tried.push([_token, count]);
+ },
+ saveProviderInfo: () => {},
+ getProviderInfo: () => null,
+ getApiKey: () => null,
+ setApiKey: () => {},
+ updateApiKeyBalance: () => {},
+ touchApiKeyLastUsed: () => {},
+ removeApiKey: () => {},
+ getAllApiKeys: () => [],
+ getApiKeyDistribution: () => [],
+ getChildKey: () => null,
+ setChildKey: () => {},
+ updateChildKeyBalance: () => {},
+ removeChildKey: () => {},
+ getAllChildKeys: () => [],
+ getCachedReceiveTokens: () => [],
+ setCachedReceiveTokens: () => {},
+ flush: async () => {},
+ } as unknown as StorageAdapter;
+
+ const spender = new CashuSpender(wallet, storage, undefined, {
+ fetchRefundToken: async () => ({ success: true, token: refundToken }),
+ } as unknown as BalanceManager);
+
+ return { spender, received, removed, tried, xcashu };
+ };
+
+ it("receives a foreign-mint payout anyway and reports the mismatch", async () => {
+ const token = tokenFrom(OTHER_MINT);
+ const { spender, received, removed, tried, xcashu } = xcashuSpender(token);
+
+ const results = await spender.refundXcashuTokens(MINT);
+
+ // Received, because after `collected` the node will never re-issue it
+ // (a second claim answers 425 forever) — refusing would strand the value.
+ expect(received).toEqual([token]);
+ expect(results).toHaveLength(1);
+ expect(results[0].success).toBe(true);
+ expect(results[0].mintMismatch).toBe(true);
+ expect(results[0].tokenMintUrl).toBe(OTHER_MINT);
+ expect(removed).toEqual([xcashu]);
+ expect(tried).toEqual([]);
+ });
+
+ it("reports no mismatch when the payout is at the requested mint", async () => {
+ const token = tokenFrom(MINT);
+ const { spender, received } = xcashuSpender(token);
+
+ const results = await spender.refundXcashuTokens(MINT);
+
+ expect(received).toEqual([token]);
+ expect(results[0].success).toBe(true);
+ expect(results[0].mintMismatch).toBeUndefined();
+ });
+});
+
+describe("mint URL comparison", () => {
+ it("ignores scheme and host case, trailing slashes and query strings", () => {
+ expect(normalizeMintUrl("HTTPS://Mint.Example.COM/")).toBe(
+ "https://mint.example.com"
+ );
+ expect(mintsMatch("https://mint.example.com/", "https://mint.example.com")).toBe(
+ true
+ );
+ expect(
+ mintsMatch("https://mint.example.com?x=1", "https://mint.example.com")
+ ).toBe(true);
+ });
+
+ it("keeps the path case, because mints serve distinct paths", () => {
+ expect(normalizeMintUrl("https://mint.example.com/Mint")).toBe(
+ "https://mint.example.com/Mint"
+ );
+ expect(
+ mintsMatch("https://mint.example.com/Mint", "https://mint.example.com/mint")
+ ).toBe(false);
+ });
+
+ it("never matches an empty or unknown mint", () => {
+ expect(mintsMatch("", "")).toBe(false);
+ expect(mintsMatch(null, null)).toBe(false);
+ expect(mintsMatch("https://mint.example.com", undefined)).toBe(false);
+ });
+
+ it("reads the mint out of an encoded token, and null otherwise", () => {
+ expect(getTokenMintUrl(tokenFrom(MINT))).toBe(MINT);
+ expect(getTokenMintUrl("cashu-token")).toBeNull();
+ expect(getTokenMintUrl("")).toBeNull();
+ });
+});
diff --git a/wallet/BalanceManager.ts b/wallet/BalanceManager.ts
index 7067b7a..defcb28 100644
--- a/wallet/BalanceManager.ts
+++ b/wallet/BalanceManager.ts
@@ -35,7 +35,10 @@ import { stampBalanceRead } from "./apiKeyBalance";
import {
getBalanceInSats,
getAvailableBalanceInSats,
+ getTokenMintUrl,
isNetworkErrorMessage,
+ mintsMatch,
+ normalizeMintUrl,
selectMintWithBalance,
} from "./tokenUtils";
@@ -54,6 +57,16 @@ export interface RefundApiKeyOptions {
/** If true, forces refund even if the API key was used recently */
forceRefund?: boolean;
+
+ /**
+ * Receive a refund token whose mint is not `mintUrl` instead of parking it.
+ *
+ * Off by default, because receiving at a foreign mint is how a provider
+ * steers a payout. Turning it on accepts that risk explicitly; it is also the
+ * way to drain a quarantined token for one caller without widening the
+ * default.
+ */
+ allowForeignRefundMint?: boolean;
}
/**
@@ -345,7 +358,7 @@ export class BalanceManager {
* @returns Refund result
*/
async refundApiKey(options: RefundApiKeyOptions): Promise<RefundResult> {
- const { mintUrl, baseUrl, apiKey, forceRefund } = options;
+ const { baseUrl } = options;
const guard = this._canRunProviderWalletOperation(baseUrl, "refund");
if (!guard.allowed) {
@@ -357,7 +370,9 @@ export class BalanceManager {
let result: RefundResult | undefined;
try {
- result = await this._refundApiKeyImpl({ mintUrl, baseUrl, apiKey, forceRefund });
+ // Forward the object rather than a rebuilt literal: an option dropped
+ // here would silently disable a guard the caller asked for.
+ result = await this._refundApiKeyImpl(options);
return result;
} finally {
// An exception has an unknown outcome and retains the cooldown.
@@ -365,6 +380,26 @@ export class BalanceManager {
}
}
+ /**
+ * Act on a refund token the mint pin parked (`quarantined: true`).
+ *
+ * `accept` receives the proofs at the mint they were issued from — the caller
+ * is choosing that mint with the report in hand. `discard` deletes the parked
+ * copy, which abandons real value; it exists so a caller can stop carrying a
+ * poisoned token, not because the value was never paid.
+ */
+ async resolveQuarantinedRefund(
+ token: string,
+ action: "accept" | "discard"
+ ): Promise<Awaited<ReturnType<CashuSpender["resolveQuarantinedRefund"]>>> {
+ return this.cashuSpender.resolveQuarantinedRefund(token, action);
+ }
+
+ /** Refund tokens parked by the mint pin, awaiting a caller decision. */
+ getQuarantinedRefunds(): ReturnType<CashuSpender["getQuarantinedRefunds"]> {
+ return this.cashuSpender.getQuarantinedRefunds();
+ }
+
private async _refundApiKeyImpl(options: RefundApiKeyOptions): Promise<RefundResult> {
const { mintUrl, baseUrl, apiKey, forceRefund } = options;
@@ -519,6 +554,61 @@ export class BalanceManager {
// The provider has paid out and the token may be the only recoverable
// value. Do not receive or delete the key until this copy is durable.
await this.storageAdapter.flush?.();
+
+ // A refund token is the money, not an offer: by the time it exists the
+ // node has already settled the key (refund.execute -> _pay_cashu), and a
+ // second claim answers 425 "refund is pending" forever. So a token minted
+ // somewhere other than the requested mint is parked durably and reported,
+ // never refused — refusing would delete the only copy of the value while
+ // leaving the key spent anyway.
+ const tokenMintUrl = getTokenMintUrl(refundToken);
+ // An empty `mintUrl` means the caller knows of no mint, which is not the
+ // same claim as "the wrong mint": do not quarantine on it.
+ const mintMismatch =
+ tokenMintUrl !== null &&
+ normalizeMintUrl(mintUrl) !== "" &&
+ !mintsMatch(tokenMintUrl, mintUrl);
+
+ if (mintMismatch && !options.allowForeignRefundMint) {
+ const parked = this.cashuSpender.quarantineCachedReceiveToken(
+ refundToken,
+ {
+ reason: "mint_mismatch",
+ mintUrl: tokenMintUrl as string,
+ expectedMintUrl: mintUrl,
+ baseUrl,
+ at: Date.now(),
+ }
+ );
+ // Parked copy durable before the key goes: the token is the claim now.
+ await this.storageAdapter.flush?.();
+ this.logger.warn(
+ `refundApiKey: *** for ${baseUrl} paid out at ${tokenMintUrl}, not ${mintUrl}; ${parked.amount} ${parked.unit} quarantined in receive storage`
+ );
+ if (this.storageAdapter.getApiKey(baseUrl)?.key === apiKey) {
+ this.storageAdapter.removeApiKey(baseUrl);
+ }
+ return {
+ success: false,
+ mintMismatch: true,
+ quarantined: true,
+ tokenMintUrl: tokenMintUrl as string,
+ quarantinedAmount:
+ parked.unit === "msat"
+ ? Math.round(parked.amount / 1000)
+ : parked.amount,
+ message: `Refund minted at ${tokenMintUrl}, not ${mintUrl}; proofs parked in receive storage. Resolve with resolveQuarantinedRefund(token, "accept" | "discard").`,
+ requestId: fetchResult.requestId,
+ parsedError: fetchResult.parsedError,
+ };
+ }
+
+ if (mintMismatch) {
+ this.logger.warn(
+ `refundApiKey: *** for ${baseUrl} paid out at ${tokenMintUrl}, not ${mintUrl}; receiving because allowForeignRefundMint is set`
+ );
+ }
+
const receiveResult = await this.cashuSpender.receiveToken(
refundToken,
false
diff --git a/wallet/CashuSpender.ts b/wallet/CashuSpender.ts
index bb4d5f1..a248a5c 100644
--- a/wallet/CashuSpender.ts
+++ b/wallet/CashuSpender.ts
@@ -12,7 +12,14 @@ import { throwIfFundingAborted } from "./fundingCancellation";
* Extracted from hooks/useCashuWithXYZ.ts
*/
-import type { RecoveryCredential, WalletAdapter, StorageAdapter } from "./interfaces";
+import type {
+ CachedReceiveToken,
+ CachedReceiveTokenWrite,
+ RecoveryCredential,
+ RefundQuarantine,
+ WalletAdapter,
+ StorageAdapter,
+} from "./interfaces";
import type { SpendResult, SdkLogger } from "../core/types";
import { consoleLogger } from "../core/types";
import { InsufficientBalanceError, ProviderMintBalanceError } from "../core/errors";
@@ -22,7 +29,7 @@ import {
} from "../core/errorTypes";
import { BalanceManager } from "./BalanceManager";
import { persistApiKeyBalance } from "./apiKeyBalance";
-import { getBalanceInSats, isNetworkErrorMessage } from "./tokenUtils";
+import { getBalanceInSats, getTokenMintUrl, isNetworkErrorMessage, mintsMatch } from "./tokenUtils";
import { getTokenMetadata } from "@cashu/cashu-ts";
/**
@@ -56,6 +63,22 @@ type DebugLevel = "DEBUG" | "WARN" | "ERROR";
type ReceiveResult = Awaited<ReturnType<WalletAdapter["receiveToken"]>>;
type RecoveryResult = ReceiveResult & { pending?: boolean };
+/**
+ * Outcome of one X-Cashu refund claim. `mintMismatch` records that the provider
+ * paid out at a different mint than the caller asked for and the token was
+ * received anyway: once the node marks the refund collected it will not issue
+ * the token again (a second claim answers 425 "refund is pending" forever), so
+ * refusing to receive would destroy the value rather than protect it.
+ */
+interface XcashuRefundResult {
+ baseUrl: string;
+ token: string;
+ success: boolean;
+ error?: string;
+ mintMismatch?: boolean;
+ tokenMintUrl?: string;
+}
+
/**
* CashuSpender manages the spending of Cashu tokens
*/
@@ -139,6 +162,17 @@ export class CashuSpender {
const work = Promise.resolve().then(async () => {
await this.storageAdapter.flush?.();
const cached = this.storageAdapter.getCachedReceiveTokens().find(entry => entry.token === token);
+ if (cached?.quarantined) {
+ // Parked on purpose: receiving here would redeem at a mint the caller
+ // did not choose, which is the exact decision the quarantine exists to
+ // leave to a caller.
+ return {
+ success: false,
+ amount: cached.amount,
+ unit: cached.unit,
+ message: `Refund token quarantined: minted at ${cached.quarantined.mintUrl}, expected ${cached.quarantined.expectedMintUrl}. Resolve with resolveQuarantinedRefund().`,
+ };
+ }
const result = cached?.received
? { success: true, amount: cached.amount, unit: cached.unit, message: undefined }
: await this.receiveToken(token);
@@ -216,12 +250,129 @@ export class CashuSpender {
]);
}
+ /** Rewrite one cached entry with a changed flag set, dropping `createdAt` duplication. */
+ private rewriteCachedEntry(
+ token: string,
+ change: (entry: CachedReceiveToken) => CachedReceiveTokenWrite
+ ): void {
+ this.storageAdapter.setCachedReceiveTokens(
+ this.storageAdapter.getCachedReceiveTokens().map(entry =>
+ entry.token === token ? change(entry) : entry
+ )
+ );
+ }
+
+ /**
+ * Park a refund token whose mint is not the mint the caller asked for.
+ *
+ * The entry is written but not received: the provider has already settled the
+ * key when it hands a token back, so the token *is* the value, and the choice
+ * between accepting it at the foreign mint and abandoning it belongs to a
+ * caller who can see the report. Nothing here flushes — the caller does, so a
+ * crash cannot separate "key removed" from "token durable".
+ */
+ quarantineCachedReceiveToken(
+ token: string,
+ quarantine: RefundQuarantine
+ ): { amount: number; unit: "sat" | "msat" } {
+ const existing = this.storageAdapter
+ .getCachedReceiveTokens()
+ .find(entry => entry.token === token);
+ if (existing) {
+ this.rewriteCachedEntry(token, entry => ({ ...entry, quarantined: quarantine }));
+ return { amount: existing.amount, unit: existing.unit };
+ }
+ const { amount, unit } = this._decodeTokenAmount(token);
+ this.storageAdapter.setCachedReceiveTokens([
+ ...this.storageAdapter.getCachedReceiveTokens(),
+ { token, amount, unit, createdAt: Date.now(), quarantined: quarantine },
+ ]);
+ return { amount, unit };
+ }
+
+ /** Quarantined refunds awaiting a caller decision. */
+ getQuarantinedRefunds(): CachedReceiveToken[] {
+ return this.storageAdapter
+ .getCachedReceiveTokens()
+ .filter(entry => entry.quarantined);
+ }
+
+ /**
+ * Act on a quarantined refund.
+ *
+ * `accept` clears the quarantine durably and then receives the token through
+ * the normal recovery path, so a crash mid-receive leaves an ordinary cached
+ * token instead of a stale quarantine. `discard` deletes the entry: the
+ * caller is choosing to abandon the value, not pretending it was never paid.
+ */
+ async resolveQuarantinedRefund(
+ token: string,
+ action: "accept" | "discard"
+ ): Promise<ReceiveResult> {
+ const entry = this.storageAdapter
+ .getCachedReceiveTokens()
+ .find(candidate => candidate.token === token);
+
+ if (!entry) {
+ return {
+ success: false,
+ amount: 0,
+ unit: "sat",
+ message: "No cached refund token for this value",
+ };
+ }
+ if (!entry.quarantined) {
+ return {
+ success: false,
+ amount: entry.amount,
+ unit: entry.unit,
+ message: "Refund token is not quarantined",
+ };
+ }
+
+ if (action === "discard") {
+ this.evictCachedReceiveToken(token);
+ await this.storageAdapter.flush?.();
+ this._log(
+ "WARN",
+ `[CashuSpender] resolveQuarantinedRefund: discarded ${entry.amount} ${entry.unit} from ${entry.quarantined.mintUrl} at caller request`
+ );
+ return {
+ success: false,
+ amount: entry.amount,
+ unit: entry.unit,
+ message: "Quarantined refund discarded; its value is abandoned",
+ };
+ }
+
+ this.rewriteCachedEntry(token, cached => ({
+ token: cached.token,
+ amount: cached.amount,
+ unit: cached.unit,
+ createdAt: cached.createdAt,
+ ...(cached.cleanup?.length ? { cleanup: cached.cleanup } : {}),
+ ...(cached.received ? { received: cached.received } : {}),
+ }));
+ await this.storageAdapter.flush?.();
+ return this.startCachedReceive(token);
+ }
+
/** Retry cached tokens not already owned by another receive. */
async recoverCachedReceiveTokens(): Promise<{ token: string; success: boolean }[]> {
const results: { token: string; success: boolean }[] = [];
- for (const { token } of this.storageAdapter.getCachedReceiveTokens()) {
+ for (const entry of this.storageAdapter.getCachedReceiveTokens()) {
+ const { token } = entry;
+ // Quarantined proofs are held for an explicit caller decision; a sweep
+ // must not quietly redeem them at the foreign mint.
+ if (entry.quarantined) {
+ this._log(
+ "DEBUG",
+ `[CashuSpender] recoverCachedReceiveTokens: skipping quarantined token from ${entry.quarantined.mintUrl} (expected ${entry.quarantined.expectedMintUrl})`
+ );
+ continue;
+ }
if (this.pendingReceives.has(token) ||
- !this.storageAdapter.getCachedReceiveTokens().some(entry => entry.token === token)) continue;
+ !this.storageAdapter.getCachedReceiveTokens().some(candidate => candidate.token === token)) continue;
const result = await this.startCachedReceive(token);
results.push({ token, success: result.success });
}
@@ -567,15 +718,8 @@ export class CashuSpender {
async refundXcashuTokens(
mintUrl: string,
excludeBaseUrls?: string[]
- ): Promise<
- { baseUrl: string; token: string; success: boolean; error?: string }[]
- > {
- const results: {
- baseUrl: string;
- token: string;
- success: boolean;
- error?: string;
- }[] = [];
+ ): Promise<XcashuRefundResult[]> {
+ const results: XcashuRefundResult[] = [];
const xcashuTokens = this.storageAdapter.getXcashuTokens();
const excludedUrls = new Set(excludeBaseUrls || []);
@@ -725,7 +869,24 @@ export class CashuSpender {
);
}
- // Receive the refunded Cashu token into the wallet
+ // Receive the refunded Cashu token into the wallet. Check the mint
+ // first, but receive regardless of the answer: the node has already
+ // marked this refund collected, and a second claim answers 425
+ // "refund is pending" forever — refusing here would strand the value
+ // on the node side instead of protecting it. The mismatch is reported
+ // to the caller instead of being silently swallowed.
+ const tokenMintUrl = getTokenMintUrl(fetchResult.token);
+ const mintMismatch =
+ tokenMintUrl !== null && !mintsMatch(tokenMintUrl, mintUrl);
+ if (mintMismatch) {
+ this._log(
+ "WARN",
+ `[CashuSpender] refundXcashuTokens: ${baseUrl} paid out at ${tokenMintUrl}, not ${mintUrl}; receiving anyway because the claim is already collected`
+ );
+ }
+ const mismatchReport = mintMismatch
+ ? { mintMismatch: true, tokenMintUrl: tokenMintUrl ?? undefined }
+ : {};
const receiveResult = await this.receiveToken(fetchResult.token);
if (receiveResult.success) {
@@ -735,6 +896,7 @@ export class CashuSpender {
baseUrl,
token: xcashuToken.token,
success: true,
+ ...mismatchReport,
});
this._log(
"DEBUG",
@@ -750,6 +912,7 @@ export class CashuSpender {
token: xcashuToken.token,
success: false,
error: receiveResult.message,
+ ...mismatchReport,
});
this._log(
"WARN",
@@ -768,6 +931,7 @@ export class CashuSpender {
token: xcashuToken.token,
success: false,
error: receiveResult.message ?? "Refund failed",
+ ...mismatchReport,
});
this._log(
"DEBUG",
diff --git a/wallet/interfaces.ts b/wallet/interfaces.ts
index 390d3bb..15149ca 100644
--- a/wallet/interfaces.ts
+++ b/wallet/interfaces.ts
@@ -93,6 +93,27 @@ export interface RecoveryCredential {
token: string;
}
+/**
+ * Why a durable refund token is parked instead of received.
+ *
+ * A refund token is not an offer: the provider has already settled the API key
+ * when it hands the token over, so the token *is* the money. Refusing to
+ * receive it therefore does not prevent a bad refund, it destroys the only copy
+ * of the value. Parking it instead keeps the value durable and leaves the
+ * decision — accept at the foreign mint, or abandon it — to a caller who can
+ * see the report.
+ */
+export interface RefundQuarantine {
+ reason: "mint_mismatch";
+ /** Mint the token's proofs claim to be from, as encoded in the token. */
+ mintUrl: string;
+ /** Mint the refund was requested into. */
+ expectedMintUrl: string;
+ /** Provider base URL the refund came from, when known. */
+ baseUrl?: string;
+ at: number;
+}
+
export interface CachedReceiveToken {
token: string;
amount: number;
@@ -102,6 +123,11 @@ export interface CachedReceiveToken {
cleanup?: RecoveryCredential[];
/** Wallet receive finished; only credential cleanup may remain. */
received?: true;
+ /**
+ * Proofs are durable here but deliberately not received. Recovery skips
+ * these entries until `resolveQuarantinedRefund` is called.
+ */
+ quarantined?: RefundQuarantine;
}
export type CachedReceiveTokenWrite = Omit<CachedReceiveToken, "createdAt"> & { createdAt?: number };
diff --git a/wallet/tokenUtils.ts b/wallet/tokenUtils.ts
index 9a7eaa6..f752b57 100644
--- a/wallet/tokenUtils.ts
+++ b/wallet/tokenUtils.ts
@@ -1,4 +1,53 @@
import type { MintSelection } from "../core/types";
+import { getTokenMetadata } from "@cashu/cashu-ts";
+
+/**
+ * One spelling for comparing mint URLs.
+ *
+ * Scheme and authority are case-insensitive per RFC 3986, but the path is not:
+ * mints may serve distinct keysets under case-distinct paths, and lowercasing
+ * the whole string would make two different mints compare equal. Trailing
+ * slashes and query/fragment parts are ignored because mints announce
+ * themselves both ways and identity does not live there.
+ */
+export function normalizeMintUrl(mintUrl: string | null | undefined): string {
+ const raw = (mintUrl ?? "").trim();
+ if (!raw) return "";
+ const match = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)(.*)$/.exec(raw);
+ if (!match) return raw.replace(/\/+$/, "");
+ const scheme = match[1].toLowerCase();
+ const authority = match[2].toLowerCase();
+ const path = match[3].replace(/[?#].*$/, "").replace(/\/+$/, "");
+ return `${scheme}://${authority}${path}`;
+}
+
+/** True when both URLs name the same mint. Empty/unknown never matches. */
+export function mintsMatch(
+ a: string | null | undefined,
+ b: string | null | undefined
+): boolean {
+ const left = normalizeMintUrl(a);
+ return left !== "" && left === normalizeMintUrl(b);
+}
+
+/**
+ * The mint a Cashu token was issued from, exactly as encoded, or `null` when
+ * the token cannot be decoded.
+ *
+ * `null` means "unknown", not "mismatch". This is the same decoder the wallet
+ * uses to receive the token, so a token that cannot be read here may still be
+ * recoverable there — and by the time a refund token exists the provider has
+ * usually already paid it out. A caller that pins a mint must therefore park an
+ * unreadable token for recovery, never discard it.
+ */
+export function getTokenMintUrl(token: string): string | null {
+ try {
+ const mint = getTokenMetadata(token).mint;
+ return typeof mint === "string" && mint.trim() !== "" ? mint : null;
+ } catch {
+ return null;
+ }
+}
/**
* Transport failures that mean "this provider could not be reached at all",
Limits, stated rather than promised
- No live-mint run: every number comes from the unit suite, the types, and
routstr-core’s own code paths. - The pin reads the mint the token declares. A mint that lies about its own URL is out of reach.
scripts/refund-all.tssurfaces parked tokens throughgetQuarantinedRefunds()but does not decide for the operator — abandoning value is a human or caller decision, not a sweep default.
— Vela (npub16yujr0g0njhvgqlcl45dsk90plaquj7ag2f079meu2jvw6me4z5qh69fqz), 2026-11-18.
Write a comment