Files
AutistMask/tests/unknownScaleDisplay.test.js
sneak fb260ddf20
Some checks failed
check / check (push) Successful in 31s
e2e / e2e-firefox (push) Has been cancelled
e2e / e2e-chrome (push) Has been cancelled
fix: store an absent explorer decimals as unknown instead of fabricating 18 (closes #349)
fetchTokenBalances() did parseInt(item.token.decimals || "18", 10) before writing to state.wallets[].addresses[].tokenBalances[].decimals, so a token whose decimals() reverts -- one the block explorer reports no scale for -- was stored with a fabricated 18 that no reader could tell from a real one.

That is upstream of a rule already merged. #306 made the ERC-20 approval amount line resolve the real scale or refuse to format, and #340 extended it to the swap lines; both read this stored value as an authoritative source, so the guess walked straight past refusals that were intact and simply never fired. A 1,000-unit approval of such a token rendered 0.000000001 on the one screen whose job is to state what is being authorized.

The stored value is now the explorer's own answer or null, never a default. Both approval paths reach unknownDecimalsAmount() on a null, using the refusal that was already there. The history list's token transfers carried the same || "18" and now state exact base units with the scale unknown rather than a quantity at a guessed one.

A holding whose scale nothing knows has no quantity either, so its balance is stored as null -- unknown, never zero -- and the balance list, the address USD total, the Send screen and the confirmation screen each say so rather than printing 0.0000 for money that is really there. The zero-balance filter moved onto the base-unit integer, where it needs no scale at all. The bundled token list and the user's tracked tokens already outrank the explorer, so a token either of them knows still displays its real quantity when the explorer's entry omits decimals; only what none of the three knows is unknown.

Which makes the stored field the explorer's answer alone, and NOT the scale a screen renders at. Those are two questions, and every screen that needs the second one asks resolveTokenDecimals(). The Send screen did not: it read tokenBalances[].decimals raw and carried it onto the pending transaction, so a bundled or tracked token whose explorer row omits decimals reached displayedDecimals(null) inside estimateGas(). That throws, is caught as an unavailable fee, and disables Send behind "The network fee could not be estimated ... Please go back and try again" -- untrue, unactionable, and for a token such as WETH whose scale was never in doubt. The balance and the amount on the same screen were correct throughout, and validateTransfer() had nothing to object to, so nothing named the real reason. Before this change the fabricated 18 happened to be that token's real scale and the send completed, so this is a capability regression and not an inherited one. Send now resolves the scale through resolveTokenDecimals(), with no fallback.

The two resolutions are deliberately not identical, and where they differ the balance follows the scale. balances.js resolves without wallets, because it is formatting one explorer row during a fetch that is about to replace the very state it would be consulting; its explorer leg is therefore that row's own value. send.js resolves with wallets, which adds explorerDecimals()'s cross-address check, so a contract two addresses report different scales for answers null rather than picking one -- a check that must apply to a value which goes on to encode a transfer. For a token neither bundled nor tracked whose explorer rows disagree, that leaves a stored quantity computed at a scale Send has just refused. Stating it would leave validateTransfer() checking the amount against a number the wallet does not vouch for, and, since the unknown-balance path is gated on the balance rather than on the scale, would again leave the fee-estimate failure as the only thing on the confirmation screen. So Send withdraws the stored quantity along with the scale: an unknown scale is an unknown balance. Only a stored quantity is withdrawn -- the "0" for a token with no row at all is an absence of holdings, which is true at every scale.

The uint8 check is one shared toDecimals() rather than three copies of it, and it answers 0 for a real scale of zero: || "18" collapsed that to eighteen, the falsy-collapse trap of #246.

The reader half is asserted, not just the writer half. Each of the six sites that now distinguishes an unknown quantity from a zero one -- balanceLine(), balanceLinesForAddress(), addressHoldsFunds(), getAddressValue()'s partial flag, the Send balance line and the confirmation screen's balance and insufficient-balance wording -- is tested on the PAIR, because an assertion about null alone still passes on a build that renders both as zero. The Send and confirmation cases run the real explorer response through the real fetcher, the real review handler and the real confirmation screen, so they show which of the two scale questions each screen is asking, including a two-address fixture whose explorer rows report 6 and 18 for one contract.

Existing installs hold 18s that cannot be told apart retroactively -- that is the defect, and no migration can undo it. They display exactly as they do today until the next balance refresh, which rewrites tokenBalances wholesale and needs no user action. The schema version is not bumped: version 1 records stay valid and are read exactly as before.

No || 18 or ?? 18 fallback remains anywhere in src/. The literal 18s that do remain are real data rather than defaults: 432 per-token decimals: 18 entries in the bundled src/shared/tokenList.js, and, outside that file, only native ETH's protocol-defined scale in src/shared/uniswap.js and the fixed-point comparison scale in src/shared/txValidation.js.
2026-08-23 19:03:05 +00:00

186 lines
6.9 KiB
JavaScript

// What the screens that READ a stored token balance do with a holding whose
// scale nothing knows.
//
// https://git.eeqj.de/sneak/AutistMask/issues/349 stopped `fetchTokenBalances()`
// fabricating a scale of 18, so a row it cannot state a quantity for is now
// stored with `balance: null`. Every reader of that field therefore has two
// distinct inputs where it used to have one, and the property that has to hold
// at each of them is the same one this codebase keeps losing:
//
// null (unknown) and 0 (genuinely zero) must produce DIFFERENT output.
//
// Losing it is what https://git.eeqj.de/sneak/AutistMask/issues/246,
// https://git.eeqj.de/sneak/AutistMask/issues/306,
// https://git.eeqj.de/sneak/AutistMask/issues/322,
// https://git.eeqj.de/sneak/AutistMask/issues/359 and
// https://git.eeqj.de/sneak/AutistMask/issues/364 each were. So every case
// below asserts the pair, not just that the null branch does something
// reasonable: an assertion on the null alone still passes on a build that
// renders both as zero, which is precisely the build being guarded against.
//
// The writer half — that the fetcher stores null rather than 18 — is in
// tests/fabricatedDecimals.test.js, and the Send and confirmation screens are
// in tests/unknownScaleSend.test.js.
"use strict";
// helpers.js reaches for both at module scope through the modules it pulls in.
globalThis.chrome = {
storage: {
local: {
get: () => Promise.resolve({}),
set: () => Promise.resolve(),
},
},
runtime: { sendMessage: () => {} },
};
globalThis.document = {
getElementById: () => null,
createElement: () => ({ style: {}, classList: { toggle() {} } }),
body: { prepend: () => {} },
addEventListener: () => {},
};
const {
balanceLine,
balanceLinesForAddress,
addressHoldsFunds,
} = require("../src/popup/views/helpers");
const {
prices,
clearPrices,
getAddressValue,
} = require("../src/shared/prices");
const { state } = require("../src/shared/state");
const NOVEL = "0x1111111111111111111111111111111111111111";
// One stored tokenBalances row. `balance: null` is what balances.js writes for
// a holding whose scale nothing knows; "0.0" is a quantity that was actually
// established and is zero.
function holding(balance) {
return {
address: NOVEL,
symbol: "NOVEL",
decimals: balance === null ? null : 18,
balance,
holders: 50000,
};
}
function address(balance) {
return {
address: "0x" + "a".repeat(40),
balance: "0",
tokenBalances: [holding(balance)],
};
}
// The quantity cell of a rendered row, which is the second of the two spans
// inside the fixed-width span.
function quantities(html) {
return [...html.matchAll(/<span>([^<]*)<\/span>/g)].map((m) => m[1]);
}
beforeEach(() => {
clearPrices();
state.wallets = [];
state.trackedTokens = [];
state.activeAddress = null;
});
afterEach(() => {
clearPrices();
});
describe("balanceLine", () => {
test("an unknown quantity and a zero one render differently", () => {
const unknown = balanceLine("NOVEL", null, null, NOVEL);
const zero = balanceLine("NOVEL", 0, null, NOVEL);
expect(unknown).not.toBe(zero);
expect(quantities(unknown)).toEqual(["NOVEL", "quantity unknown"]);
expect(quantities(zero)).toEqual(["NOVEL", "0.0000"]);
});
test("an unknown quantity produces no fiat figure, a zero one does", () => {
prices.NOVEL = 3;
const unknown = balanceLine("NOVEL", null, 3, NOVEL);
const zero = balanceLine("NOVEL", 0, 3, NOVEL);
// A price times an unknown quantity is not $0.00: that is the same
// claim of "nothing here" the quantity cell just refused to make.
expect(unknown).toContain(
'<span class="text-right text-muted flex-1">&nbsp;</span>',
);
expect(zero).toContain(
'<span class="text-right text-muted flex-1">$0.00</span>',
);
});
});
describe("balanceLinesForAddress", () => {
// The show-zero setting is a statement about zeroes. An unknown quantity
// is not one, so hiding the row would assert the zero nobody established
// and the holding would vanish from the list entirely.
test("hiding zero balances hides the zero row and keeps the unknown one", () => {
const unknown = balanceLinesForAddress(address(null), [], false);
const zero = balanceLinesForAddress(address("0.0"), [], false);
expect(unknown).not.toBe(zero);
expect(unknown).toContain("quantity unknown");
expect(unknown).toContain("NOVEL");
expect(zero).not.toContain("NOVEL");
});
test("showing zero balances still tells the two apart", () => {
const unknown = balanceLinesForAddress(address(null), [], true);
const zero = balanceLinesForAddress(address("0.0"), [], true);
expect(unknown).not.toBe(zero);
expect(quantities(unknown)).toEqual([
"ETH",
"0.0000",
"NOVEL",
"quantity unknown",
]);
expect(quantities(zero)).toEqual(["ETH", "0.0000", "NOVEL", "0.0000"]);
});
});
describe("addressHoldsFunds", () => {
// Read by deleteAddress.js to decide whether removing the address is
// warned about. balances.js drops a row of zero base units before any
// scale is consulted, so a row that survived with no quantity is holding
// something, and the warning must err towards warning.
test("an unknown balance holds funds, a zero balance does not", () => {
expect(addressHoldsFunds(address(null))).toBe(true);
expect(addressHoldsFunds(address("0.0"))).toBe(false);
});
});
describe("getAddressValue", () => {
// `usd` is the value of what could be priced and `partial` says it is a
// floor rather than the total. An unpriceable holding is exactly what
// `partial` exists for; a holding of zero can neither add to the total nor
// make it incomplete.
test("an unknown balance makes the total partial, a zero balance does not", () => {
prices.ETH = 2000;
prices.NOVEL = 3;
const unknown = getAddressValue(address(null));
const zero = getAddressValue(address("0.0"));
expect(unknown).not.toEqual(zero);
expect(unknown).toEqual({ usd: 0, partial: true });
expect(zero).toEqual({ usd: 0, partial: false });
});
test("an unknown balance is not priced as zero of the token", () => {
prices.ETH = 2000;
prices.NOVEL = 3;
// The same row with a real quantity of 10 is worth $30. Neither that
// figure nor a confident $0.00 may be stated for the unknown one.
expect(getAddressValue(address("10.0"))).toEqual({
usd: 30,
partial: false,
});
expect(getAddressValue(address(null)).usd).toBe(0);
expect(getAddressValue(address(null)).partial).toBe(true);
});
});