Author SHA1 Message Date
clawbot bdaf821be2 fix: the bundled token list names tokens on Ethereum Mainnet only (closes #632)
check / check (push) Waiting to run
e2e / e2e-chrome (push) Waiting to run
e2e / e2e-firefox (push) Waiting to run
bundledToken(address, chainId) in tokenList.js answers only for Ethereum
Mainnet's chain id. Every reader of the bundled list now goes through it,
with the chain id of the transaction, balance or history entry it draws.
The token sources the screens build carry that chain id. The Uniswap
decoder sets the transaction's chain id on them. fetchTokenBalances()
takes the chain id of the network it asks about.

Seven existing tests read the bundled list without naming a network. Each
now names Ethereum Mainnet.

Model: opus-5-5
2026-10-27 17:27:58 +00:00
clawbot 08e47c39ad fix: a network switch in Settings keeps another page's token on the network it was added on (closes #692)
check / check (push) Waiting to run
e2e / e2e-chrome (push) Waiting to run
e2e / e2e-firefox (push) Waiting to run
A network switch in Settings filed under the new network a token or fraud contract that another page stored since this page's last save, because the switch's save writes only the fields this page changed. Before the switch, onChainSwitch() now takes the stored tracked tokens into the page's own list with takeStoredTrackedTokens(), matched by contract address, so a token either page added or removed stays as that page left it. The switch then files that list under the previous network. When the stored record is on another network, no tokens are taken. Fraud contracts are cleared on every switch, as before.

Model: opus-5-5
2026-10-27 18:05:01 +01:00
21 changed files with 438 additions and 316 deletions
+6 -7
View File
@@ -1188,11 +1188,12 @@ The wallet takes the `decimals` from these sources, in this order
"Use Blockscout" is on (`tokenSourcesByChainId()` in
`src/popup/views/helpers.js`).
The token's name comes from the same sources. While "Use Blockscout" is off, a
token gets a line under it when the bundled list and the tracked tokens lack its
name or decimals. The line says "Blockscout's report of your balances is not
used to name this token, because "Use Blockscout" is off in Settings." These
screens show the line:
The token's name comes from the same sources. The bundled token list is used
only for a token on Ethereum Mainnet. While "Use Blockscout" is off, a token
gets a line under it when the bundled list and the tracked tokens lack its name
or decimals. The line says "Blockscout's report of your balances is not used to
name this token, because "Use Blockscout" is off in Settings." These screens
show the line:
- TxApproval and SignApproval
- WaitTx, SuccessTx and ErrorTx, which follow TxApproval
@@ -2282,8 +2283,6 @@ view would leave a wallet one click from deletion.
- Either "Save" stores its URL only if the input still shows that URL when
the endpoint answers. Otherwise a flash message says that the URL was not
saved
- If the user taps the same "Save" again before the endpoint answers, the
earlier tap stores nothing and shows no flash message
- Etherscan:
- "Check recipients on Etherscan" checkbox, unticked until the user
ticks it
+4 -2
View File
@@ -22,7 +22,7 @@ const {
timeAgo,
} = require("./helpers");
const { state, saveState, currentNetwork } = require("../../shared/state");
const { TOKEN_BY_ADDRESS, resolveSymbol } = require("../../shared/tokenList");
const { bundledToken, resolveSymbol } = require("../../shared/tokenList");
const { formatUsd, getPrice } = require("../../shared/prices");
const {
fetchRecentTransactions,
@@ -52,7 +52,8 @@ function show() {
// Determine token symbol and balance
let symbol, amount, price;
const knownToken = TOKEN_BY_ADDRESS.get(tokenId.toLowerCase());
const chainId = currentNetwork().chainId;
const knownToken = bundledToken(tokenId, chainId);
if (tokenId === "ETH") {
symbol = nativeCurrency();
amount = parseFloat(addr.balance || "0");
@@ -65,6 +66,7 @@ function show() {
tokenId,
addr.tokenBalances,
state.trackedTokens,
chainId,
);
// null when the scale is unknown: no quantity to show, and none to
// price. balanceLine() states that rather than printing 0.0000.
+5 -2
View File
@@ -313,14 +313,17 @@ function nativeCurrency() {
// The wallets' balances hold what Blockscout reported for each token. So the
// wallets are returned only while "Use Blockscout" is on.
function tokenSourcesByChainId(chainId) {
const net = chainId ? networkByChainId(chainId) : currentNetwork();
const chainIdOrActive = chainId || currentNetwork().chainId;
const net = networkByChainId(chainIdOrActive);
if (net && net.id === state.networkId) {
return {
chainId: chainIdOrActive,
trackedTokens: state.trackedTokens,
wallets: state.useBlockscout ? state.wallets : [],
};
}
return {
chainId: chainIdOrActive,
trackedTokens: (net && state.networkTrackedTokens[net.id]) || [],
wallets: [],
};
@@ -351,7 +354,7 @@ function blockscoutOffTokenNoteHtml(token, chainId) {
// The symbol shown for a token line, from these sources in order:
//
// - the bundled list
// - the bundled list, for a token on Ethereum Mainnet
// - the tokens the user tracks
// - the explorer's report, while "Use Blockscout" is on
//
+3 -1
View File
@@ -12,7 +12,7 @@ const {
goBack,
tokenSourcesByChainId,
} = require("./helpers");
const { state, currentAddress } = require("../../shared/state");
const { state, currentAddress, currentNetwork } = require("../../shared/state");
let ctx;
const { getProvider } = require("../../shared/balances");
const { resolveTokenDecimals } = require("../../shared/approvalAmount");
@@ -230,6 +230,7 @@ function updateSendBalance() {
token,
addr.tokenBalances,
state.trackedTokens,
currentNetwork().chainId,
);
// A null balance is a holding whose scale is unknown. Saying a figure
// for it would be a claim about the amount, so it reads as the
@@ -385,6 +386,7 @@ function init(_ctx) {
token,
addr.tokenBalances,
state.trackedTokens,
currentNetwork().chainId,
);
({ tokenDecimals } = tokenBalanceAndDecimals(addr, token));
}
+3 -30
View File
@@ -50,11 +50,6 @@ let versionClickTimer = null;
// not the one in `state`.
let shownNetwork = null;
// Each endpoint "Save" counts its taps here, under the field that it stores. A
// tap stores its URL and shows a flash message only while it is the latest tap
// of its "Save".
const saveTaps = { rpcUrl: 0, blockscoutUrl: 0 };
// One row per site origin, however many addresses it appears under, each with
// an [x] that hands it to onRemove.
function renderSiteList(containerId, origins, onRemove) {
@@ -352,16 +347,10 @@ function showNewSettings() {
// shows `url`, nothing is saved. The flash message then says that the URL was
// changed during the check. The save compares the input and sets `url` in
// `state` in one step. So a redraw after the comparison shows `url`.
//
// `tap` is the number of the "Save" tap that checked `url`. If the user taps
// the same "Save" again before this save holds the lock, nothing is stored. If
// the user taps the same "Save" again before the write ends, no flash message
// is shown.
async function saveEndpoint(field, input, url, networkId, tap) {
async function saveEndpoint(field, input, url, networkId) {
let refused = false;
let inputChanged = false;
await saveState((stored) => {
if (saveTaps[field] !== tap) return false;
refused =
state.networkId !== networkId || stored.networkId !== networkId;
inputChanged = $(input).value.trim() !== url;
@@ -369,7 +358,6 @@ async function saveEndpoint(field, input, url, networkId, tap) {
state[field] = url;
stored[field] = url;
});
if (saveTaps[field] !== tap) return;
if (refused) {
showFlash("The URL was not saved because the network changed.");
} else if (inputChanged) {
@@ -387,8 +375,6 @@ function init(_ctx) {
showPhrase.init();
$("btn-save-rpc").addEventListener("click", async () => {
saveTaps.rpcUrl++;
const tap = saveTaps.rpcUrl;
const url = $("settings-rpc").value.trim();
if (!url) {
showFlash("Please enter an RPC URL.");
@@ -409,8 +395,6 @@ function init(_ctx) {
}),
});
const json = await resp.json();
// The user has tapped this "Save" again since the check began.
if (tap !== saveTaps.rpcUrl) return;
if (json.error) {
log.errorf("RPC validation error:", json.error);
showFlash("Endpoint returned an error.");
@@ -424,7 +408,6 @@ function init(_ctx) {
// Cancelled by the popup closing, not failed: see pageClosed in
// src/popup/index.js.
if (ctx.pageClosed.aborted) return;
if (tap !== saveTaps.rpcUrl) return;
// Not the error's message: fetch puts the whole URL, password and
// key included, in the message of the error it throws for a URL
// with a user name and password or one it cannot parse.
@@ -432,12 +415,10 @@ function init(_ctx) {
showFlash("Could not reach endpoint.");
return;
}
await saveEndpoint("rpcUrl", "settings-rpc", url, net.id, tap);
await saveEndpoint("rpcUrl", "settings-rpc", url, net.id);
});
$("btn-save-blockscout").addEventListener("click", async () => {
saveTaps.blockscoutUrl++;
const tap = saveTaps.blockscoutUrl;
const url = $("settings-blockscout").value.trim();
if (!url) {
showFlash("Please enter a Blockscout API URL.");
@@ -447,26 +428,18 @@ function init(_ctx) {
showFlash("Testing endpoint...");
try {
const resp = await debugFetch(url + "/stats");
if (tap !== saveTaps.blockscoutUrl) return;
if (!resp.ok) {
showFlash("Endpoint returned HTTP " + resp.status + ".");
return;
}
} catch {
if (ctx.pageClosed.aborted) return;
if (tap !== saveTaps.blockscoutUrl) return;
// Not the error's message, as for the RPC check above.
log.errorf("Blockscout validation failed:", urlOrigin(url));
showFlash("Could not reach endpoint.");
return;
}
await saveEndpoint(
"blockscoutUrl",
"settings-blockscout",
url,
net.id,
tap,
);
await saveEndpoint("blockscoutUrl", "settings-blockscout", url, net.id);
});
// Each change is made inside the save, holding the lock. So
+7 -5
View File
@@ -29,7 +29,7 @@
// string, and a token the user added by hand carries whatever lookupTokenInfo()
// got back, so the accepted types are enumerated rather than coerced.
const { toDecimals } = require("./transferAmount");
const { TOKEN_BY_ADDRESS } = require("./tokenList");
const { bundledToken } = require("./tokenList");
const { isSpoofedSymbol } = require("./symbolSpoof");
// Every decimals the explorer reported for this contract, across all the
@@ -53,12 +53,14 @@ function explorerDecimals(lower, wallets) {
}
// The decimals to render a token amount with, or null when nothing knows.
// `sources` is { trackedTokens, wallets }, both shaped as they are on `state`.
// `sources` is { chainId, trackedTokens, wallets }. `chainId` is the chain id
// of the token's network. The bundled list is read only when that network is
// Ethereum Mainnet. `trackedTokens` and `wallets` are shaped as on `state`.
function resolveTokenDecimals(tokenAddress, sources) {
const lower = (tokenAddress || "").toLowerCase();
if (!lower) return null;
const bundled = TOKEN_BY_ADDRESS.get(lower);
const bundled = bundledToken(lower, sources && sources.chainId);
if (bundled) {
const d = toDecimals(bundled.decimals);
if (d !== null) return d;
@@ -100,7 +102,7 @@ function explorerSymbol(lower, wallets) {
// explorer reported: the same sources and the same precedence
// resolveTokenDecimals() uses, so a token's name and its scale are drawn from
// the same place and the two can no longer disagree about which sources they
// trust. `sources` is { trackedTokens, wallets }, shaped as on `state`.
// trust. `sources` is as for resolveTokenDecimals().
//
// A tracked or explorer-reported symbol is attacker-influenced text, so it is
// held to the spoof rule (symbolSpoof.js): a candidate that wears a bundled or
@@ -111,7 +113,7 @@ function resolveTokenSymbol(tokenAddress, sources) {
const lower = (tokenAddress || "").toLowerCase();
if (!lower) return null;
const bundled = TOKEN_BY_ADDRESS.get(lower);
const bundled = bundledToken(lower, sources && sources.chainId);
if (bundled && bundled.symbol) return bundled.symbol;
const tracked = ((sources && sources.trackedTokens) || []).find(
+16 -5
View File
@@ -17,7 +17,7 @@ const { ERC20_ABI } = require("./constants");
const { NETWORKS } = require("./networks");
const { log, debugFetch, urlOrigin } = require("./log");
const { deriveAddressFromXpub } = require("./wallet");
const { TOKEN_BY_ADDRESS } = require("./tokenList");
const { bundledToken } = require("./tokenList");
const { LOW_HOLDER_THRESHOLD, parseHoldersCount } = require("./holders");
const { isSpoofedSymbol } = require("./symbolSpoof");
const { toDecimals } = require("./transferAmount");
@@ -106,6 +106,9 @@ function rawUnits(value) {
// balance is read through the RPC endpoint instead, and its row here gives that
// entry its holder count and `decimals` (fetchTrackedTokenBalances()).
//
// `chainId` is the chain id of the network `blockscoutUrl` serves. The known
// token list is used only when that network is Ethereum Mainnet.
//
// `decimals` and `balance` are each null when the answer is unknown, the same
// way `holders` already is. Absence is never filled in here: this is the
// upstream of every screen that displays a token amount, so a value invented
@@ -117,6 +120,7 @@ async function fetchTokenBalances(
address,
blockscoutUrl,
trackedTokens,
chainId,
signal,
) {
if (!(await storedSettingIsOn("useBlockscout"))) return [];
@@ -175,7 +179,10 @@ async function fetchTokenBalances(
// either way: copying another source into it would make
// explorerDecimals()'s disagreement check compare something other
// than explorer values.
const known = resolveTokenDecimals(tokenAddr, { trackedTokens });
const known = resolveTokenDecimals(tokenAddr, {
chainId,
trackedTokens,
});
const scale = known !== null ? known : decimals;
// null is a holding of an amount that cannot be stated, which is
// not the same as a holding of zero, and must never render as one.
@@ -191,7 +198,7 @@ async function fetchTokenBalances(
// through to the views, where the two low-holder filters treat
// an unknown count as "do not judge" rather than as zero.
const holders = parseHoldersCount(item.token.holders_count);
const isKnown = TOKEN_BY_ADDRESS.has(tokenAddr);
const isKnown = bundledToken(tokenAddr, chainId) !== null;
const isTracked = trackedSet.has(tokenAddr);
const hasEnoughHolders = holders >= LOW_HOLDER_THRESHOLD;
@@ -249,13 +256,14 @@ async function fetchTokenBalances(
// zero from the tracked list. A token whose symbol the spoof rule refuses gets
// no entry either, as in fetchTokenBalances().
//
// `signal` is as for fetchTokenBalances().
// `chainId` and `signal` are as for fetchTokenBalances().
async function fetchTrackedTokenBalances(
provider,
address,
trackedTokens,
previous,
explorerRequest,
chainId,
signal,
) {
const listed = trackedTokens.filter(
@@ -301,7 +309,7 @@ async function fetchTrackedTokenBalances(
if (raw === 0n) return;
const entry = entryIn(reported);
const decimals = entry ? entry.decimals : null;
const known = resolveTokenDecimals(lower, { trackedTokens });
const known = resolveTokenDecimals(lower, { chainId, trackedTokens });
const scale = known !== null ? known : decimals;
rows.push({
address: token.address,
@@ -330,6 +338,7 @@ async function refreshBalances(
) {
log.debugf("refreshBalances start, rpc:", urlOrigin(rpcUrl));
const provider = getProvider(rpcUrl, networkId);
const { chainId } = requireNetworkId(networkId);
const tracked = trackedTokens || [];
const trackedSet = new Set(tracked.map((t) => t.address.toLowerCase()));
const updates = [];
@@ -393,6 +402,7 @@ async function refreshBalances(
addr.address,
blockscoutUrl,
tracked,
chainId,
signal,
);
updates.push(
@@ -403,6 +413,7 @@ async function refreshBalances(
tracked,
previous,
explorerRequest,
chainId,
signal,
),
explorerRequest,
+18 -5
View File
@@ -53,18 +53,31 @@ function clearPopupCaches() {
// change. So the switch also resets these fields in the stored record:
//
// - every address's balance and token balances;
// - the time of the last balance refresh.
// - the time of the last balance refresh;
// - the fraud contracts.
//
// A balance that the background or another page stored since this page's last
// save is then not kept under the new network
// (https://git.eeqj.de/sneak/AutistMask/issues/653).
// A balance or a fraud contract that the background or another page stored
// since this page's last save is then not kept under the new network
// (https://git.eeqj.de/sneak/AutistMask/issues/653,
// https://git.eeqj.de/sneak/AutistMask/issues/692).
//
// Before the switch, `state` takes the tracked tokens that another page stored
// since this page's last save (takeStoredTrackedTokens() in state.js). The
// switch then puts them away under the previous network, the network they were
// added on. When the stored record is on another network, a switch saved
// elsewhere has not reached this page yet. The stored record's tokens are then
// that network's, and none are taken.
async function onChainSwitch(newNetworkId) {
const { state, saveState } = require("./state");
const { state, saveState, takeStoredTrackedTokens } = require("./state");
let net = null;
await saveState((stored) => {
if (state.networkId === newNetworkId) return false;
if (stored.networkId === state.networkId) {
takeStoredTrackedTokens(stored);
}
net = applyChainSwitchFields(state, newNetworkId);
stored.lastBalanceRefresh = 0;
stored.fraudContracts = [];
for (const wallet of stored.wallets) {
for (const addr of wallet.addresses) {
addr.balance = "0";
+33 -7
View File
@@ -125,11 +125,12 @@ function currentNetwork() {
return networkById(state.networkId);
}
// The persisted fields as this page held them when its last loadState()
// finished, or when its last successful saveState() began, with any network
// switch saved elsewhere that this page has taken since (takeStoredNetwork()).
// saveState() diffs the live state against this to find only the fields THIS
// page changed since.
// `baseline` holds the persisted fields as this page held them when its last
// loadState() finished, or when its last successful saveState() began.
// takeStoredNetwork() and takeStoredTrackedTokens() also write into it what
// this page has taken from the stored record since then. saveState() diffs the
// live state against `baseline` to find only the fields THIS page changed
// since.
//
// Deep-cloned, not a reference: callers mutate persisted objects and arrays
// in place (state.wallets.push(...)), and a reference baseline would mutate
@@ -442,8 +443,10 @@ function mergeNetworkEndpoints(base, ours, theirs) {
// milder than the other two.
//
// Every other persisted field stays a whole-field diff:
// `trackedTokens`/`fraudContracts`/`viewStack` are arrays of scalars with no
// per-element identity to merge by; `networkTrackedTokens` is diffed whole like
// `fraudContracts`/`viewStack` are arrays of scalars with no per-element
// identity to merge by; a save diffs `trackedTokens` whole, and a switch in
// Settings first merges that list by contract address
// (takeStoredTrackedTokens()); `networkTrackedTokens` is diffed whole like
// `trackedTokens` and `networkId`, the two fields a network switch moves
// together with it; `tokenHolderCache` is a map shaped like the ones above,
// but nothing in src/ ever writes an entry into it — it is only ever reset
@@ -615,6 +618,28 @@ function takeStoredNetwork(stored) {
copyChainSwitchFields(baseline, structuredClone(stored));
}
// Give this page the tracked tokens of `stored`, a record on this page's
// network that a save of this page has just read (onChainSwitch() in
// src/shared/chainSwitch.js calls this from `beforeWrite`):
//
// - A token that another page tracked or removed since this page's last save
// is tracked or removed in `state` too.
// - A token that this page tracked or removed since then stays as this page
// has it.
//
// `baseline` takes the stored list, so the save stores the list in `state`
// whenever the two differ.
function takeStoredTrackedTokens(stored) {
rawState.trackedTokens = mergeListByIdentity(
baseline.trackedTokens,
rawState.trackedTokens,
stored.trackedTokens,
(token) => token.address.toLowerCase(),
(base, ours) => ours,
);
baseline.trackedTokens = structuredClone(stored.trackedTokens);
}
// Rejects with StateUnusableError for a stored record this build cannot make
// sense of. Nothing is assigned and `loaded` stays false in that case, so a
// caller that ignores the rejection gets StateNotLoadedError on the first
@@ -661,6 +686,7 @@ module.exports = {
saveState,
onSaveFailure,
takeStoredNetwork,
takeStoredTrackedTokens,
loadState,
currentAddress,
currentNetwork,
+14 -3
View File
@@ -3953,6 +3953,15 @@ for (const t of TOKENS) {
TOKEN_BY_ADDRESS.set(t.address.toLowerCase(), t);
}
// The bundled list's entry for the contract at `address` on the network with
// chain id `chainId`, or null. The list holds Ethereum Mainnet contracts only.
// A contract at the same address on another network is another token, so any
// other chain id gets null.
function bundledToken(address, chainId) {
if (chainId !== NETWORKS.mainnet.chainId) return null;
return TOKEN_BY_ADDRESS.get((address || "").toLowerCase()) || null;
}
// Build a map of symbol (uppercased) -> the set of contract addresses
// (lowercased) that legitimately bear it. Used for spoofed-symbol detection.
// "ETH" maps to null: the native asset has no contract, so no contract may
@@ -3988,14 +3997,15 @@ for (const t of TOKENS) {
}
}
// Resolve a token symbol from multiple sources, never returning "?".
function resolveSymbol(tokenAddress, tokenBalances, trackedTokens) {
// Resolve a token symbol from multiple sources, never returning "?". The token
// is a contract on the network with chain id `chainId`.
function resolveSymbol(tokenAddress, tokenBalances, trackedTokens, chainId) {
const lower = (tokenAddress || "").toLowerCase();
const tb = (tokenBalances || []).find(
(t) => t.address.toLowerCase() === lower,
);
if (tb && tb.symbol) return tb.symbol;
const known = TOKEN_BY_ADDRESS.get(lower);
const known = bundledToken(lower, chainId);
if (known && known.symbol) return known.symbol;
const tracked = (trackedTokens || []).find(
(t) => t.address.toLowerCase() === lower,
@@ -4012,5 +4022,6 @@ module.exports = {
USD_PRICE_FEEDS,
PRICE_FEED_BY_ADDRESS,
getTopTokens,
bundledToken,
resolveSymbol,
};
+2 -2
View File
@@ -8,7 +8,7 @@
const { formatEther, formatUnits } = require("ethers");
const { log, debugFetch } = require("./log");
const { TOKEN_BY_ADDRESS } = require("./tokenList");
const { bundledToken } = require("./tokenList");
const { parseHoldersCount, isLowHolderCount } = require("./holders");
const { isSpoofedSymbol } = require("./symbolSpoof");
const { nativeCurrencyByChainId } = require("./networks");
@@ -47,7 +47,7 @@ function parseTx(tx, addrLower, chainId) {
let direction = normalizeAddress(from) === addrLower ? "sent" : "received";
let directionLabel = direction === "sent" ? "Sent" : "Received";
if (toIsContract && method && method !== "transfer") {
const token = TOKEN_BY_ADDRESS.get(normalizeAddress(to));
const token = bundledToken(to, chainId);
if (token) {
symbol = token.symbol;
}
+20 -11
View File
@@ -452,8 +452,8 @@ const ADDRESS_THIS = "0x0000000000000000000000000000000000000002";
// `decimals` is null when nothing knows this token's scale. It is not
// defaulted to 18: the swap lines land on the same approval screen as the
// ERC-20 line, and a scale guessed there is what showed a 1,000 USDT swap as
// 0.000000000001. `sources` is { trackedTokens, wallets }, shaped as they are
// on `state`; resolveTokenDecimals() reads the bundled list, then those.
// 0.000000000001. `sources` is as for resolveTokenDecimals(), which reads the
// bundled list on Ethereum Mainnet, then the tracked tokens and the wallets.
//
// A null `address` means UNDETERMINED — the calldata named no currency for
// that side — and is refused rather than named. It is not native ETH: Uniswap
@@ -1240,6 +1240,9 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
const release = routerRelease(toAddress, chainId);
if (release === null) return null;
const { commandTypeMask, commands, allowRevert } = release;
// The swap's tokens are contracts on the network with `chainId`, so they
// are named and scaled for that network.
const tokenSources = { ...sources, chainId };
try {
const parsed = ROUTER_IFACE.parseTransaction({ data });
if (!parsed) return null;
@@ -2208,11 +2211,11 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
// Any other output keeps its own token and figure: a swap that pays
// its WETH to the user and then unwraps receives WETH, and one that
// buys USDC and then unwraps the WETH it did not spend receives USDC.
const inInfo = tokenInfo(inputToken, sources);
const inInfo = tokenInfo(inputToken, tokenSources);
const outInfo =
outputUnwrapped || (hasUnwrapWeth && !outputEstablished)
? { symbol: "ETH", decimals: 18, address: null }
: tokenInfo(outputToken, sources);
: tokenInfo(outputToken, tokenSources);
const inSymbol = inInfo.symbol;
const outSymbol = outInfo.symbol;
@@ -2337,13 +2340,19 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
details.push({
label: "Moved from the sender",
value: present(s.amount)
? spentText(s.amount, tokenInfo(s.token, sources), s.atMost)
.display
? spentText(
s.amount,
tokenInfo(s.token, tokenSources),
s.atMost,
).display
: UNDECODED_CURRENCY,
});
if (present(s.token)) {
details.push(
tokenMovedLine("Token moved", tokenInfo(s.token, sources)),
tokenMovedLine(
"Token moved",
tokenInfo(s.token, tokenSources),
),
);
details.push({
label: "Moved to",
@@ -2355,7 +2364,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
// What each PERMIT2_TRANSFER_FROM moves: its amount, its token and
// where it goes, an address on a line of its own.
for (const m of movedFromSender) {
const info = permit2TokenInfo(m.token, sources);
const info = permit2TokenInfo(m.token, tokenSources);
details.push({
label: "Moved from the sender",
value: amountText(m.amount, info).display,
@@ -2390,7 +2399,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
});
continue;
}
const info = permit2TokenInfo(p.token, sources);
const info = permit2TokenInfo(p.token, tokenSources);
details.push({
label: "Permit2 allowance",
value:
@@ -2456,7 +2465,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
paidTo.push({ label: "Paid to", value: PAID_TO_BRIDGE });
}
for (const m of movedIntoRouter) {
const info = permit2TokenInfo(m.token, sources);
const info = permit2TokenInfo(m.token, tokenSources);
paidTo.push({
label: "Paid to",
value:
@@ -2481,7 +2490,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
paidTo.push(
tokenMovedLine(
"Token moved into the router",
tokenInfo(getAddress(token), sources),
tokenInfo(getAddress(token), tokenSources),
),
);
}
+5 -2
View File
@@ -90,9 +90,11 @@ beforeEach(() => {
});
describe("resolveTokenDecimals", () => {
// The bundled list is read only for a token on Ethereum Mainnet.
test("prefers the bundled list", () => {
state.trackedTokens = [{ address: USDC, symbol: "USDC", decimals: 2 }];
expect(resolveTokenDecimals(USDC, state)).toBe(6);
const sources = { chainId: "0x1", trackedTokens: state.trackedTokens };
expect(resolveTokenDecimals(USDC, sources)).toBe(6);
});
test("reads a token the user tracks", () => {
@@ -124,7 +126,8 @@ describe("resolveTokenDecimals", () => {
// answers 0 is used rather than fallen past like the unusable entry above.
test("uses a bundled scale of zero", () => {
state.trackedTokens = [{ address: SLP, symbol: "SLP", decimals: 18 }];
expect(resolveTokenDecimals(SLP, state)).toBe(0);
const sources = { chainId: "0x1", trackedTokens: state.trackedTokens };
expect(resolveTokenDecimals(SLP, sources)).toBe(0);
});
test("uses a tracked scale of zero", () => {
+157
View File
@@ -0,0 +1,157 @@
// The approval screen for a site's Sepolia transfer of the contract at USDC's
// mainnet address, while Sepolia is active.
//
// The bundled token list holds Ethereum Mainnet contracts. The contract at the
// same address on Sepolia is another token, but the screen named it USDC and
// scaled its amount at USDC's decimals
// (https://git.eeqj.de/sneak/AutistMask/issues/632). The bundled list now names
// a token only on Ethereum Mainnet.
//
// Driven through the real approval screen, against the minimal DOM stub
// tests/approvalTokenNetwork.test.js uses.
globalThis.chrome = {
storage: { local: { get: async () => ({}), set: async () => {} } },
};
const { Interface } = require("ethers");
const { state } = require("../src/shared/state");
const { NETWORKS } = require("../src/shared/networks");
const approval = require("../src/popup/views/approval");
const FROM = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266";
const RECIPIENT = "0x711e691962E5c054b78071C789A0C8CE657377aD";
// USDC's address on Ethereum Mainnet, where the bundled list names it.
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
// FROM sends 1234500000 base units to RECIPIENT.
const TRANSFER_DATA = new Interface([
"function transfer(address to, uint256 amount)",
]).encodeFunctionData("transfer", [RECIPIENT, 1234500000n]);
function makeElement(id) {
const classes = new Set();
const el = {
id,
textContent: "",
value: "",
innerHTML: "",
disabled: false,
style: {},
dataset: {},
listeners: {},
classList: {
add: (...names) => names.forEach((n) => classes.add(n)),
remove: (...names) => names.forEach((n) => classes.delete(n)),
contains: (n) => classes.has(n),
toggle: (n, force) => {
const on = force === undefined ? !classes.has(n) : force;
if (on) classes.add(n);
else classes.delete(n);
return on;
},
},
addEventListener: (name, fn) => {
el.listeners[name] = el.listeners[name] || [];
el.listeners[name].push(fn);
},
querySelectorAll: () => [],
appendChild: () => {},
};
// Views reach for .parentElement to hide whole sections.
Object.defineProperty(el, "parentElement", {
get: () => node(id + "-parent"),
});
return el;
}
function makeDocument() {
const els = new Map();
return {
getElementById(id) {
// The debug banner is created on demand by helpers.js; absent
// is the state a non-debug, non-testnet popup is in.
if (id === "debug-banner") return null;
if (!els.has(id)) els.set(id, makeElement(id));
return els.get(id);
},
createElement: () => makeElement("created"),
body: { prepend: () => {} },
};
}
function node(id) {
return globalThis.document.getElementById(id);
}
// One line of the decoded details: its label and what is drawn under it.
function decodedLine(label) {
return node("approve-tx-decoded-details")
.innerHTML.split('<div class="mb-2">')
.find((line) =>
line.startsWith(`<div class="text-muted">${label}</div>`),
);
}
// Open the approval screen, with Sepolia active, for the site's Sepolia
// transaction sending TRANSFER_DATA to the contract at USDC's address.
async function showSepoliaTransfer() {
globalThis.document = makeDocument();
globalThis.window = { location: { search: "" }, close: () => {} };
globalThis.chrome.runtime = {
connect: () => ({ postMessage: () => {} }),
sendMessage: (msg, reply) => {
if (!reply) return;
reply({
type: "tx",
origin: "https://dapp.example",
isPhishingDomain: false,
approvedFrom: FROM,
approvedTx: {
type: 2,
from: FROM,
chainId: NETWORKS.sepolia.chainId,
nonce: "0x7",
gasLimit: "0x30d40",
maxPriorityFeePerGas: "0x3b9aca00",
maxFeePerGas: "0x77359400",
to: USDC,
value: "0x0",
data: TRANSFER_DATA,
accessList: [],
},
});
},
};
state.networkId = "sepolia";
state.trackedTokens = [];
state.networkTrackedTokens = {};
state.activeAddress = FROM;
state.wallets = [
{
type: "hd",
name: "Wallet 1",
xpub: "xpub-wallet-1",
encryptedSecret: "encrypted-secret-1",
nextIndex: 1,
addresses: [
{ address: FROM, index: 0, balance: "0", tokenBalances: [] },
],
},
];
state.currentView = null;
approval.init({});
await approval.show(1);
}
test("names no token, and states the amount in base units", async () => {
await showSepoliaTransfer();
expect(state.currentView).toBe("approve-tx");
expect(node("approve-tx-to").innerHTML).not.toContain("USDC");
expect(decodedLine("Token")).toContain(
'<div class="font-bold">Unknown token</div>',
);
expect(decodedLine("Amount")).toContain(
'<div class="font-bold">1234500000 base units (decimals unknown)</div>',
);
});
+3 -1
View File
@@ -111,13 +111,15 @@ function respondWith(items) {
}
// Fetch and place the result exactly where refreshBalances() places it, so the
// approval screens read what a real refresh would have left on state.
// approval screens read what a real refresh on Ethereum Mainnet would have
// left on state.
async function fetchOnto(items, trackedTokens = []) {
respondWith(items);
const balances = await fetchTokenBalances(
HOLDER,
BLOCKSCOUT,
trackedTokens,
"0x1",
);
state.trackedTokens = trackedTokens;
state.wallets = [
+7 -1
View File
@@ -192,7 +192,13 @@ describe("the balance-list spam gate", () => {
},
}),
]);
const balances = await fetchTokenBalances(HOLDER, BLOCKSCOUT, []);
// On Ethereum Mainnet, the only network the known-token list covers.
const balances = await fetchTokenBalances(
HOLDER,
BLOCKSCOUT,
[],
"0x1",
);
expect(balances).toHaveLength(1);
expect(balances[0].holders).toBeNull();
});
+4 -2
View File
@@ -67,13 +67,15 @@ beforeEach(() => {
});
describe("resolveTokenSymbol", () => {
// The bundled list is read only for a token on Ethereum Mainnet.
test("reads the bundled list", () => {
expect(resolveTokenSymbol(USDC, state)).toBe("USDC");
expect(resolveTokenSymbol(USDC, { chainId: "0x1" })).toBe("USDC");
});
test("prefers the bundled list over a tracked entry", () => {
state.trackedTokens = [{ address: USDC, symbol: "NOTUSDC" }];
expect(resolveTokenSymbol(USDC, state)).toBe("USDC");
const sources = { chainId: "0x1", trackedTokens: state.trackedTokens };
expect(resolveTokenSymbol(USDC, sources)).toBe("USDC");
});
test("reads a token the user tracks", () => {
-224
View File
@@ -167,227 +167,3 @@ test.each([
);
},
);
// This answer passes both endpoint checks on Ethereum Mainnet.
const PASSING_ANSWER = {
ok: true,
json: async () => ({ result: NETWORKS.mainnet.chainId }),
};
// Both endpoint checks read this answer as an error. The RPC check reads the
// answer's `error`. The Blockscout check reads the answer's `ok`.
const ERROR_ANSWER = {
ok: false,
status: 500,
json: async () => ({ error: { code: -32603, message: "Internal error" } }),
};
// The user types a URL in Settings and taps "Save". Before the endpoint answers,
// the user types a second URL and taps "Save" again. The second check passes
// first. The second URL is stored, and the flash message reads "Saved.". The
// first check then ends in one of three ways:
//
// - It passes.
// - It fails, because fetch cannot reach the endpoint.
// - It gets an answer that holds an error.
//
// None of the three changes the stored URL or the flash message
// (https://git.eeqj.de/sneak/AutistMask/issues/698).
test.each([
{
button: "btn-save-rpc",
input: "settings-rpc",
field: "rpcUrl",
first: "passes",
},
{
button: "btn-save-rpc",
input: "settings-rpc",
field: "rpcUrl",
first: "fails",
},
{
button: "btn-save-rpc",
input: "settings-rpc",
field: "rpcUrl",
first: "answers with an error",
},
{
button: "btn-save-blockscout",
input: "settings-blockscout",
field: "blockscoutUrl",
first: "passes",
},
{
button: "btn-save-blockscout",
input: "settings-blockscout",
field: "blockscoutUrl",
first: "fails",
},
{
button: "btn-save-blockscout",
input: "settings-blockscout",
field: "blockscoutUrl",
first: "answers with an error",
},
])(
"$button keeps the second tap's result when the first check $first last",
async ({ button, input, field, first }) => {
const page = await bootPopup(unversionedValidProfile());
await page.click("btn-settings");
const checks = [];
globalThis.fetch.mockImplementation(
() =>
new Promise((resolve, reject) => {
checks.push({ resolve, reject });
}),
);
const secondUrl = "https://second.example.invalid";
page.node(input).value = "https://first.example.invalid";
const firstTap = page.node(button).listeners.click.map((fn) => fn());
await page.settle();
page.node(input).value = secondUrl;
const secondTap = page.node(button).listeners.click.map((fn) => fn());
await page.settle();
checks[1].resolve(PASSING_ANSWER);
await Promise.all(secondTap);
await page.settle();
expect(page.text("flash-msg")).toBe("Saved.");
if (first === "passes") {
checks[0].resolve(PASSING_ANSWER);
} else if (first === "answers with an error") {
checks[0].resolve(ERROR_ANSWER);
} else {
// fetch rejects when it cannot reach the endpoint.
checks[0].reject(new TypeError("Failed to fetch"));
}
await Promise.all(firstTap);
await page.settle();
expect(checks).toHaveLength(2);
expect(page.storage.read("autistmask")[field]).toBe(secondUrl);
expect(page.text("flash-msg")).toBe("Saved.");
},
);
// The user types a URL in Settings and taps "Save". Another write holds the
// lock. So the save waits for the lock once the check passes. The user then
// taps "Save" again on the same URL. When the lock is free, the first save
// stores nothing and shows no flash message. The second check then passes, and
// the second save stores the URL.
test.each([
{ button: "btn-save-rpc", input: "settings-rpc", field: "rpcUrl" },
{
button: "btn-save-blockscout",
input: "settings-blockscout",
field: "blockscoutUrl",
},
])(
"$button stores nothing for an earlier tap still waiting for the lock",
async ({ button, input, field }) => {
const page = await bootPopup(unversionedValidProfile());
await page.click("btn-settings");
const storedUrl = page.value(input);
const checks = [];
globalThis.fetch.mockImplementation(
() =>
new Promise((resolve) => {
checks.push(resolve);
}),
);
const typedUrl = "https://typed.example.invalid";
page.node(input).value = typedUrl;
const firstTap = page.node(button).listeners.click.map((fn) => fn());
await page.settle();
let releaseLock;
const lockHeld = navigator.locks.request(
"autistmask",
() =>
new Promise((resolve) => {
releaseLock = resolve;
}),
);
checks[0](PASSING_ANSWER);
await page.settle();
const secondTap = page.node(button).listeners.click.map((fn) => fn());
await page.settle();
releaseLock();
await lockHeld;
await Promise.all(firstTap);
await page.settle();
expect(page.storage.read("autistmask")[field]).toBe(storedUrl);
expect(page.text("flash-msg")).toBe("Testing endpoint...");
checks[1](PASSING_ANSWER);
await Promise.all(secondTap);
await page.settle();
expect(checks).toHaveLength(2);
expect(page.storage.read("autistmask")[field]).toBe(typedUrl);
expect(page.text("flash-msg")).toBe("Saved.");
},
);
// The user taps "Save", and the check passes. The save then begins its storage
// write, and this test keeps the write waiting. The user taps "Save" again, and
// the second check cannot reach the endpoint. When the write ends, the flash
// message still reads "Could not reach endpoint.". The write stores the URL
// anyway, because the write began before the second tap.
test.each([
{ button: "btn-save-rpc", input: "settings-rpc", field: "rpcUrl" },
{
button: "btn-save-blockscout",
input: "settings-blockscout",
field: "blockscoutUrl",
},
])(
"$button keeps the second tap's message when tapped again during the write",
async ({ button, input, field }) => {
const page = await bootPopup(unversionedValidProfile());
await page.click("btn-settings");
const checks = [];
globalThis.fetch.mockImplementation(
() =>
new Promise((resolve, reject) => {
checks.push({ resolve, reject });
}),
);
const typedUrl = "https://typed.example.invalid";
page.node(input).value = typedUrl;
const firstTap = page.node(button).listeners.click.map((fn) => fn());
await page.settle();
const { set } = page.storage.local;
const write = set.getMockImplementation();
let writeBegan = false;
let releaseWrite;
const writeHeld = new Promise((resolve) => {
releaseWrite = resolve;
});
set.mockImplementationOnce(async (items) => {
writeBegan = true;
await writeHeld;
await write(items);
});
checks[0].resolve(PASSING_ANSWER);
await page.settle();
expect(writeBegan).toBe(true);
const secondTap = page.node(button).listeners.click.map((fn) => fn());
await page.settle();
// fetch rejects when it cannot reach the endpoint.
checks[1].reject(new TypeError("Failed to fetch"));
await Promise.all(secondTap);
await page.settle();
expect(page.text("flash-msg")).toBe("Could not reach endpoint.");
releaseWrite();
await Promise.all(firstTap);
await page.settle();
expect(checks).toHaveLength(2);
expect(page.storage.read("autistmask")[field]).toBe(typedUrl);
expect(page.text("flash-msg")).toBe("Could not reach endpoint.");
},
);
+93 -4
View File
@@ -5,6 +5,9 @@
// a contract lookup that answers after one. Driven through the real popup over
// a stored profile; the same switch made by the background is in
// tests/coldWorkerChainSwitch.test.js.
//
// The tests of what another page stored before a switch in Settings cover a
// fraud contract too (https://git.eeqj.de/sneak/AutistMask/issues/692).
const {
bootPopup,
@@ -178,9 +181,8 @@ test("a token added by contract address on Sepolia is tracked on Sepolia only",
});
// Another popup page tracks DAI on Ethereum Mainnet after this page's last
// save. The switch's save writes only the token lists that this page changed.
// So DAI stays in `trackedTokens`, the active network's list.
test("a token another page tracked before a switch in Settings stays in trackedTokens", async () => {
// save. The switch to Sepolia puts DAI away under Ethereum Mainnet.
test("a token another page tracked before a switch in Settings stays tracked on Ethereum Mainnet", async () => {
const boot = await bootPopup(unversionedValidProfile());
expect(boot.pageErrors).toEqual([]);
boot.storage.write("autistmask", {
@@ -193,10 +195,97 @@ test("a token another page tracked before a switch in Settings stays in trackedT
const stored = boot.storage.read("autistmask");
expect(stored.networkId).toBe("sepolia");
expect(stored.trackedTokens).toEqual([MAINNET_TOKEN]);
expect(stored.trackedTokens).toEqual([]);
expect(stored.networkTrackedTokens.mainnet).toEqual([MAINNET_TOKEN]);
});
// Another popup page stops tracking DAI on Ethereum Mainnet after this page's
// last save. This page still holds DAI. The switch to Sepolia does not store
// DAI under Ethereum Mainnet again.
test("a token another page removed before a switch in Settings stays removed", async () => {
const boot = await bootPopup(
unversionedValidProfile({ trackedTokens: [MAINNET_TOKEN] }),
);
expect(boot.pageErrors).toEqual([]);
boot.storage.write("autistmask", {
...boot.storage.read("autistmask"),
trackedTokens: [],
});
await boot.click("btn-settings");
await chooseNetwork(boot, "sepolia");
const stored = boot.storage.read("autistmask");
expect(stored.networkId).toBe("sepolia");
expect(stored.trackedTokens).toEqual([]);
expect(stored.networkTrackedTokens.mainnet).toEqual([]);
});
// Another popup page removes DAI after this page's last save. That page then
// adds DAI again, typing the contract address in lower case. The two pages'
// entries for DAI match, because contract addresses are compared ignoring
// letter case. The switch to Sepolia keeps this page's entry under Ethereum
// Mainnet.
test("a token another page added again with a lower-case address keeps this page's entry", async () => {
const boot = await bootPopup(
unversionedValidProfile({ trackedTokens: [MAINNET_TOKEN] }),
);
expect(boot.pageErrors).toEqual([]);
boot.storage.write("autistmask", {
...boot.storage.read("autistmask"),
trackedTokens: [
{ ...MAINNET_TOKEN, address: MAINNET_TOKEN.address.toLowerCase() },
],
});
await boot.click("btn-settings");
await chooseNetwork(boot, "sepolia");
const stored = boot.storage.read("autistmask");
expect(stored.networkId).toBe("sepolia");
expect(stored.networkTrackedTokens.mainnet).toEqual([MAINNET_TOKEN]);
});
// Another popup page saves a switch to Sepolia after this page's last save.
// TST is tracked on Sepolia. This page has not taken that switch yet. A switch
// to Sepolia in this page's Settings keeps TST off Ethereum Mainnet's list.
test("a token tracked on Sepolia when another page switched there is not tracked on Ethereum Mainnet", async () => {
const boot = await bootPopup(unversionedValidProfile());
expect(boot.pageErrors).toEqual([]);
await boot.click("btn-settings");
boot.storage.write("autistmask", {
...boot.storage.read("autistmask"),
networkId: "sepolia",
trackedTokens: [SEPOLIA_TOKEN],
});
await chooseNetwork(boot, "sepolia");
const stored = boot.storage.read("autistmask");
expect(stored.networkId).toBe("sepolia");
expect(stored.trackedTokens).toEqual([SEPOLIA_TOKEN]);
expect(stored.networkTrackedTokens.mainnet).toEqual([]);
});
// Another popup page records a fraud contract on Ethereum Mainnet after this
// page's last save. The switch to Sepolia drops that fraud contract, as the
// switch drops this page's own.
test("a fraud contract another page recorded before a switch in Settings is not kept on Sepolia", async () => {
const boot = await bootPopup(unversionedValidProfile());
expect(boot.pageErrors).toEqual([]);
boot.storage.write("autistmask", {
...boot.storage.read("autistmask"),
fraudContracts: [NEW_TOKEN_ADDRESS],
});
await boot.click("btn-settings");
await chooseNetwork(boot, "sepolia");
const stored = boot.storage.read("autistmask");
expect(stored.networkId).toBe("sepolia");
expect(stored.fraudContracts).toEqual([]);
});
// The contract lookup on SettingsAddToken answers on Ethereum Mainnet while the
// switch to Sepolia waits for the lock. The page adds the token to Ethereum
// Mainnet's list. The switch then keeps that list for Ethereum Mainnet.
+35
View File
@@ -1495,6 +1495,41 @@ describe("fetchRecentTransactions merge and dedup", () => {
expect(mainnet[0].chainId).toBe("0x1");
});
// https://git.eeqj.de/sneak/AutistMask/issues/632: the bundled token list
// names a contract only on Ethereum Mainnet. On Sepolia, a call to the
// contract at USDC's mainnet address is labelled with the network's native
// currency. A call to any contract the wallet does not name gets that label.
test("a contract call on Sepolia is not named by the bundled list", async () => {
respondWith(
[
{
hash: "0x" + "b".repeat(64),
block_number: 21000095,
timestamp: TS,
from: { hash: VICTIM },
to: { hash: USDC_CONTRACT, is_contract: true },
value: "0",
method: "approve",
status: "ok",
},
],
[],
);
const sepolia = await fetchRecentTransactions(
VICTIM,
BLOCKSCOUT,
"0xaa36a7",
);
expect(sepolia[0].directionLabel).toBe("Approve");
expect(sepolia[0].symbol).toBe("SepoliaETH");
const mainnet = await fetchRecentTransactions(
VICTIM,
BLOCKSCOUT,
"0x1",
);
expect(mainnet[0].symbol).toBe("USDC");
});
test("the fake token transfer survives fetching and is then filtered", async () => {
respondWith(
[],
+3 -2
View File
@@ -167,7 +167,8 @@ function row(token = {}, value = FIVE_WETH) {
}
// Fetch the explorer's rows through the real fetcher and put them exactly where
// refreshBalances() puts them. The node reports the holding the explorer does.
// refreshBalances() puts them on Ethereum Mainnet. The node reports the holding
// the explorer does.
async function fetchOnto(items) {
mockProvider.tokenUnits = BigInt(items[0].value);
debugFetch.mockImplementation(async () => ({
@@ -176,7 +177,7 @@ async function fetchOnto(items) {
statusText: "OK",
json: async () => items,
}));
const balances = await fetchTokenBalances(HOLDER, BLOCKSCOUT, []);
const balances = await fetchTokenBalances(HOLDER, BLOCKSCOUT, [], "0x1");
state.wallets = [
{
name: "Wallet 1",