fix: an open popup follows a network switch the background saves (closes #650)
check / check (push) Waiting to run
e2e / e2e-chrome (push) Waiting to run
e2e / e2e-firefox (push) Waiting to run

When the background saves a network switch after the user approves a
site's request, or another popup page saves one, an open popup now
notices the stored record change and takes the new network from it,
holding the lock, inside a save. It then leaves the page as a switch in
Settings does: the stack is cut, every screen counts as not yet
rendered, and the screen on top is drawn again. The cut and the redraw
are now two functions in the Settings view that both paths call. A
record already on the popup's network, such as its own Settings switch,
changes nothing. The popup never switches the network itself.

Model: opus-5-5
This commit is contained in:
2026-10-20 21:46:36 +00:00
parent e517219038
commit 59d8f478ae
15 changed files with 420 additions and 61 deletions
+20 -14
View File
@@ -1562,20 +1562,26 @@ such as an edit typed into Settings and not yet saved. Home is the one screen
"Back" always re-renders, so the wallet list reflects anything that changed "Back" always re-renders, so the wallet list reflects anything that changed
while the user was away from it. while the user was away from it.
A network switch in Settings leaves every screen beneath Settings showing the A network switch leaves every screen on the page showing the previous network.
previous network, so after it "Back" behaves as in a reopened popup: every The user makes it in Settings, or approves a site's request and the background
screen on the stack counts as not yet rendered, and the stack is cut at the saves it. Any other popup open meanwhile takes the switch from the stored
first screen that cannot be rendered from saved state, such as Send or AddToken, record, and never switches the network itself. After either, "Back" behaves as
or at AddressToken for any token but the native one, because that token was in a reopened popup: every screen on the stack counts as not yet rendered, and
picked on the previous network. The cut stack is saved with the switch, so a the stack is cut at the first screen that cannot be rendered from saved state,
popup closed straight after it and reopened onto Settings lands in the same such as Send or AddToken, or at AddressToken for any token but the native one,
place. "Back" then renders the screen it lands on for the new network, and because that token was picked on the previous network and is no longer selected.
anything typed there and not saved, which belonged to the previous network, is The cut stack is saved with the popup's new network, so a popup closed straight
dropped. ConfirmTx, WaitTx, SuccessTx, ErrorTx and TransactionDetail are after and reopened lands in the same place. The screen on top is drawn again for
rendered instead for the network of the transaction they show: the network it the new network: Settings in place, and any other screen as a reopened popup
was reviewed on for ConfirmTx, and the network it was sent on for the others. draws it, so Home takes the place of one that cannot be rendered from saved
Without a wallet the stack is not cut, because it starts at Welcome, which shows state or of AddressToken for a token no longer selected. "Back" then renders the
nothing from a network. screen it lands on for the new network, and anything typed there and not saved,
which belonged to the previous network, is dropped. ConfirmTx, WaitTx,
SuccessTx, ErrorTx and TransactionDetail are rendered instead for the network of
the transaction they show: the network it was reviewed on for ConfirmTx, and the
network it was sent on for the others. Without a wallet the stack is not cut and
only Settings is drawn again, because the stack starts at Welcome, and Welcome
and AddWallet show nothing from a network.
Every screen that holds secret material in the page registers a cleanup with Every screen that holds secret material in the page registers a cleanup with
`onViewLeave()` (`src/popup/views/helpers.js`), which `showView()` runs on every `onViewLeave()` (`src/popup/views/helpers.js`), which `showView()` runs on every
+37 -7
View File
@@ -9,8 +9,9 @@ const {
} = require("../shared/state"); } = require("../shared/state");
const { StateUnusableError } = require("../shared/stateSchema"); const { StateUnusableError } = require("../shared/stateSchema");
const { log, setRuntimeDebug } = require("../shared/log"); const { log, setRuntimeDebug } = require("../shared/log");
const { refreshPrices } = require("../shared/prices"); const { refreshPrices, clearPrices } = require("../shared/prices");
const { refreshBalances } = require("../shared/balances"); const { refreshBalances } = require("../shared/balances");
const { copyChainSwitchFields } = require("../shared/chainSwitchFields");
const { const {
$, $,
showView, showView,
@@ -22,6 +23,7 @@ const {
} = require("./views/helpers"); } = require("./views/helpers");
const { applyTheme } = require("./theme"); const { applyTheme } = require("./theme");
const { const {
onStorageChanged,
tabsGetCurrent, tabsGetCurrent,
tabsGetZoom, tabsGetZoom,
windowsGetCurrent, windowsGetCurrent,
@@ -72,12 +74,13 @@ let refreshTimer = null;
// lock, its results are copied onto the address records in `state` only if the // lock, its results are copied onto the address records in `state` only if the
// network it ran on is still the active one, on this page and in the stored // network it ran on is still the active one, on this page and in the stored
// record; the background's switch, after the user approves a site's request, // record; the background's switch, after the user approves a site's request,
// changes only the stored record. A switch while the refresh ran cleared every // reaches this page only after the stored record (followNetworkSwitch() below).
// address's balances (applyChainSwitchFields() in // A switch while the refresh ran cleared every address's balances
// src/shared/chainSwitchFields.js), and the previous network's must not come // (applyChainSwitchFields() in src/shared/chainSwitchFields.js), and the
// back over them (https://git.eeqj.de/sneak/AutistMask/issues/577). A dropped // previous network's must not come back over them
// refresh is not recorded as done. Results are copied by address, so an address // (https://git.eeqj.de/sneak/AutistMask/issues/577). A dropped refresh is not
// added or removed meanwhile is left as it is. // recorded as done. Results are copied by address, so an address added or
// removed meanwhile is left as it is.
async function doRefreshAndRender() { async function doRefreshAndRender() {
if (refreshInFlight) return; if (refreshInFlight) return;
refreshInFlight = true; refreshInFlight = true;
@@ -147,6 +150,7 @@ const ctx = {
renderWalletList, renderWalletList,
doRefreshAndRender, doRefreshAndRender,
startRefresh, startRefresh,
restoreView,
pageClosed: pageClosed.signal, pageClosed: pageClosed.signal,
showAddWalletView: () => { showAddWalletView: () => {
pushCurrentView(); pushCurrentView();
@@ -214,6 +218,30 @@ function fallbackView() {
showView("main"); showView("main");
} }
// When the background saves a network switch, once the user approves a site's
// request, or another popup page saves one, this page follows the stored
// record. It takes the new network from the record as a save reads it, holding
// the lock, so no later save of this page writes the previous network back, and
// then leaves the page as a switch in Settings leaves it. Only a record naming
// a network other than this page's is followed: the one this page's own switch
// in Settings saves names the network it already has, and a record naming none
// is no switch.
async function followNetworkSwitch(changes) {
const written = changes.autistmask && changes.autistmask.newValue;
if (!written || !written.networkId) return;
if (written.networkId === state.networkId) return;
let switched = false;
// A failed save is reported by saveState() itself: see onSaveFailure().
await saveState((stored) => {
if (stored.networkId === state.networkId) return false;
settings.cutViewStack();
copyChainSwitchFields(state, stored);
clearPrices();
switched = true;
}).catch(() => {});
if (switched) settings.showNewNetwork();
}
// The background opens the approval window as wide as the page, but the // The background opens the approval window as wide as the page, but the
// browser counts the window's frame in that width, and a screen taller than // browser counts the window's frame in that width, and a screen taller than
// the window takes a vertical scrollbar out of it too. So once the screen is // the window takes a vertical scrollbar out of it too. So once the screen is
@@ -358,6 +386,8 @@ async function init() {
settingsAddToken.init(ctx); settingsAddToken.init(ctx);
deleteAddress.init(ctx); deleteAddress.init(ctx);
onStorageChanged(followNetworkSwitch);
if (!state.hasWallet) { if (!state.hasWallet) {
showView("welcome"); showView("welcome");
} else { } else {
+2 -2
View File
@@ -39,8 +39,8 @@ function markViewRendered(view) {
} }
// Begin a fresh page-load scope. The popup gets one by being loaded, and // Begin a fresh page-load scope. The popup gets one by being loaded, and
// asks for one when the user switches the network, because every screen // asks for one after a network switch, because every screen then on the page
// then on the page shows the previous network (views/settings.js); the // shows the previous network (showNewNetwork() in views/settings.js); the
// unit tests, which simulate several page loads against one module // unit tests, which simulate several page loads against one module
// instance, ask for one too. // instance, ask for one too.
function resetRenderedViews() { function resetRenderedViews() {
+56 -27
View File
@@ -38,6 +38,8 @@ const {
const { notify, sendMessage } = require("../../shared/browserApi"); const { notify, sendMessage } = require("../../shared/browserApi");
let ctx;
let versionClickCount = 0; let versionClickCount = 0;
let versionClickTimer = null; let versionClickTimer = null;
@@ -243,7 +245,51 @@ async function renderSiteLists() {
); );
} }
function init(ctx) { // A network switch, made by the user here or saved by the background once the
// user approved a site's request (src/popup/index.js), leaves every screen on
// the page showing the previous network. These two leave the page as README's
// Screen Map describes, the first before the switch is saved, so that save
// keeps the cut for a popup closed straight after, the second once `state`
// holds the new network.
//
// The stack is cut at the first screen that cannot be rendered from saved
// state, such as Send or AddToken, and at AddressToken unless it shows the
// native token: any other token there was picked on the previous network, so
// it is no longer selected either. Without a wallet the stack starts at
// Welcome, which that cut would drop, and Welcome shows nothing from a network.
function cutViewStack() {
if (!state.hasWallet) return;
if (state.selectedToken !== "ETH") {
const tokenView = state.viewStack.indexOf("address-token");
if (tokenView !== -1) {
state.viewStack = state.viewStack.slice(0, tokenView);
}
state.selectedToken = null;
}
state.viewStack = restorableStack(state.viewStack, state.currentView);
}
// Every screen counts as not yet rendered, so "Back" renders the one it lands
// on for the new network. Settings on top is brought up to date in place;
// any other screen is drawn again as a reopened popup draws it, which is Home
// for one that cannot be rendered from saved state. Without a wallet any other
// screen is Welcome or AddWallet, which show nothing from a network.
function showNewNetwork() {
resetRenderedViews();
if (state.currentView === "settings") {
markViewRendered("settings");
$("settings-network").value = state.networkId;
$("settings-rpc").value = state.rpcUrl;
$("settings-blockscout").value = state.blockscoutUrl;
renderTrackedTokens();
} else if (state.hasWallet) {
ctx.restoreView();
}
updateDebugBanner(state.currentView);
}
function init(_ctx) {
ctx = _ctx;
deleteWallet.init(ctx); deleteWallet.init(ctx);
showPhrase.init(); showPhrase.init();
@@ -321,35 +367,12 @@ function init(ctx) {
networkSelect.addEventListener("change", async () => { networkSelect.addEventListener("change", async () => {
const newId = networkSelect.value; const newId = networkSelect.value;
if (newId === state.networkId) return; if (newId === state.networkId) return;
// The screens beneath Settings show the previous network, so Back cutViewStack();
// finds them as it does in a reopened popup: each is rendered again
// when Back lands on it, and the stack is cut at the first one that
// cannot be rendered from saved state, such as Send or AddToken. It
// is cut at AddressToken too, unless that shows the native token: any
// other token there was picked on the previous network. Without a
// wallet the stack starts at Welcome, which that cut would drop, and
// Welcome shows nothing from a network. The cut comes before the
// switch so that the switch's save keeps it for a popup closed
// straight after.
if (state.hasWallet) {
const tokenView = state.viewStack.indexOf("address-token");
if (tokenView !== -1 && state.selectedToken !== "ETH") {
state.viewStack = state.viewStack.slice(0, tokenView);
}
state.viewStack = restorableStack(state.viewStack, "settings");
}
const net = await onChainSwitch(newId); const net = await onChainSwitch(newId);
// Open pages are told by the background, as after a site's approved // Open pages are told by the background, as after a site's approved
// switch request. // switch request.
notify({ type: "AUTISTMASK_NETWORK_CHANGED", chainId: net.chainId }); notify({ type: "AUTISTMASK_NETWORK_CHANGED", chainId: net.chainId });
resetRenderedViews(); showNewNetwork();
// Settings itself, and the testnet banner above it, are brought up
// to date for the new network here.
markViewRendered("settings");
$("settings-rpc").value = state.rpcUrl;
$("settings-blockscout").value = state.blockscoutUrl;
renderTrackedTokens();
updateDebugBanner(state.currentView);
showFlash("Switched to " + net.name + "."); showFlash("Switched to " + net.name + ".");
}); });
@@ -484,4 +507,10 @@ function init(ctx) {
}); });
} }
module.exports = { init, show, renderSiteLists }; module.exports = {
init,
show,
renderSiteLists,
cutViewStack,
showNewNetwork,
};
+14
View File
@@ -224,6 +224,19 @@ function storageRemove(keys) {
return Promise.resolve(storage.remove(keys)); return Promise.resolve(storage.remove(keys));
} }
/**
* Call `listener` after every write to `storage.local`, whether this page,
* another page or the background made it, with what the write changed, as the
* browser reports it: `{ [key]: { oldValue, newValue } }`.
*
* @param {function(Object): void} listener
*/
function onStorageChanged(listener) {
namespaceMember("storage").onChanged.addListener((changes, areaName) => {
if (areaName === "local") listener(changes);
});
}
/** /**
* Run `fn` while holding the browser's lock called `name` * Run `fn` while holding the browser's lock called `name`
* (`navigator.locks`), and settle as `fn` settles. Every page of the extension * (`navigator.locks`), and settle as `fn` settles. Every page of the extension
@@ -385,6 +398,7 @@ module.exports = {
getPlatformInfo, getPlatformInfo,
hasBrowserNamespace, hasBrowserNamespace,
notify, notify,
onStorageChanged,
runtimeApi, runtimeApi,
sendMessage, sendMessage,
sessionStorageGet, sessionStorageGet,
+30 -2
View File
@@ -7,7 +7,7 @@
// the singleton and saves; the background applies it to the detached record of // the singleton and saves; the background applies it to the detached record of
// its own read-modify-write (src/background/state.js). // its own read-modify-write (src/background/state.js).
// //
// Everything here is synchronous and touches nothing but the object it is // Everything here is synchronous and touches nothing but the objects it is
// given: no storage, no caches, no imports beyond the network table. That is // given: no storage, no caches, no imports beyond the network table. That is
// what makes it usable on a record that has been read fresh from storage // what makes it usable on a record that has been read fresh from storage
// microseconds earlier and is about to be written back. // microseconds earlier and is about to be written back.
@@ -76,4 +76,32 @@ function applyChainSwitchFields(s, newNetworkId) {
return net; return net;
} }
module.exports = { applyChainSwitchFields }; // Give `s` every field applyChainSwitchFields() sets, as `switched` holds it:
// the popup takes a switch the background saved from the stored record this
// way, rather than performing it again (src/popup/index.js). Balances are
// taken by address, and an address `switched` does not have keeps none.
function copyChainSwitchFields(s, switched) {
s.networkEndpoints = switched.networkEndpoints;
s.networkTrackedTokens = switched.networkTrackedTokens;
s.trackedTokens = switched.trackedTokens;
s.networkId = switched.networkId;
s.rpcUrl = switched.rpcUrl;
s.blockscoutUrl = switched.blockscoutUrl;
s.lastBalanceRefresh = switched.lastBalanceRefresh;
s.tokenHolderCache = switched.tokenHolderCache;
s.fraudContracts = switched.fraudContracts;
const stored = new Map();
for (const wallet of switched.wallets) {
for (const addr of wallet.addresses) stored.set(addr.address, addr);
}
for (const wallet of s.wallets) {
for (const addr of wallet.addresses) {
const got = stored.get(addr.address);
addr.balance = got ? got.balance : "0";
addr.tokenBalances = got ? got.tokenBalances : [];
}
}
}
module.exports = { applyChainSwitchFields, copyChainSwitchFields };
+3 -1
View File
@@ -466,7 +466,9 @@ function mergeNetworkEndpoints(base, ours, theirs) {
// exists to remove, just delayed and confined to one page instead of two // exists to remove, just delayed and confined to one page instead of two
// (caught by tests/txStatus.test.js). A page's live picture of a field it // (caught by tests/txStatus.test.js). A page's live picture of a field it
// does not own goes on being whatever its last loadState() saw, same as // does not own goes on being whatever its last loadState() saw, same as
// before this fix; only the persisted record is guaranteed current. // before this fix; only the persisted record is guaranteed current. The
// network is the exception: the popup takes a switch another context saved
// through `beforeWrite` (followNetworkSwitch() in src/popup/index.js).
async function saveStateOnce(beforeWrite) { async function saveStateOnce(beforeWrite) {
const result = await storageGet("autistmask"); const result = await storageGet("autistmask");
// The record in storage right now is about to be merged into and written // The record in storage right now is about to be merged into and written
+2 -1
View File
@@ -145,7 +145,8 @@ test("a refresh that returns after the background switched the network writes no
const refresh = await holdRefresh(page); const refresh = await holdRefresh(page);
// The background writes the switch to Sepolia, as its updateState() does // The background writes the switch to Sepolia, as its updateState() does
// once the user approves a site's request. This page is not told. // once the user approves a site's request. This page is not told of it
// yet.
const record = page.storage.read("autistmask"); const record = page.storage.read("autistmask");
applyChainSwitchFields(record, "sepolia"); applyChainSwitchFields(record, "sepolia");
page.storage.write("autistmask", record); page.storage.write("autistmask", record);
+4 -1
View File
@@ -446,7 +446,10 @@ describe("switching the network in Settings tells every open tab", () => {
global.chrome.runtime.sendMessage = (msg) => { global.chrome.runtime.sendMessage = (msg) => {
bg.send(msg, POPUP); bg.send(msg, POPUP);
}; };
await require("../src/shared/state").loadState(); const { state, loadState } = require("../src/shared/state");
await loadState();
// Set by showView(), which is mocked above.
state.currentView = "settings";
require("../src/popup/views/settings").init({ require("../src/popup/views/settings").init({
pageClosed: new AbortController().signal, pageClosed: new AbortController().signal,
}); });
+12
View File
@@ -867,6 +867,14 @@ step(
"the page was not told of the approved switch: " + "the page was not told of the approved switch: " +
JSON.stringify(events), JSON.stringify(events),
); );
// The popup, open all along, shows the new network
// (https://git.eeqj.de/sneak/AutistMask/issues/650).
await d.switchToWindow(env.popupWindow);
await d.waitFor(
"the open popup to show the testnet banner",
`const banner = document.getElementById("debug-banner");
return banner !== null && banner.textContent === "[TESTNET]";`,
);
await openNetworkPrompt(env, "switch-restore", sepolia, mainnet); await openNetworkPrompt(env, "switch-restore", sepolia, mainnet);
await d.click("#btn-approve-network"); await d.click("#btn-approve-network");
@@ -881,6 +889,10 @@ step(
isDeepStrictEqual(await storedNetwork(env), before), isDeepStrictEqual(await storedNetwork(env), before),
"switching back did not restore the mainnet network and endpoints", "switching back did not restore the mainnet network and endpoints",
); );
await d.waitFor(
"the open popup to drop the testnet banner",
`return document.getElementById("debug-banner") === null;`,
);
await d.switchToWindow(env.dappWindow); await d.switchToWindow(env.dappWindow);
}, },
); );
+9
View File
@@ -4865,6 +4865,12 @@ test("a site's network switch changes nothing until the user approves it (#408)"
"the page was not told of the approved switch: " + "the page was not told of the approved switch: " +
JSON.stringify(events), JSON.stringify(events),
); );
// The popup, open all along, shows the new network
// (https://git.eeqj.de/sneak/AutistMask/issues/650).
await env.page.waitForFunction(() => {
const banner = document.getElementById("debug-banner");
return banner !== null && banner.textContent === "[TESTNET]";
});
const restored = await openNetworkPrompt( const restored = await openNetworkPrompt(
env, env,
@@ -4886,6 +4892,9 @@ test("a site's network switch changes nothing until the user approves it (#408)"
isDeepStrictEqual(await storedNetwork(env.page), before), isDeepStrictEqual(await storedNetwork(env.page), before),
"switching back did not restore the mainnet network and endpoints", "switching back did not restore the mainnet network and endpoints",
); );
await env.page.waitForFunction(
() => document.getElementById("debug-banner") === null,
);
}); });
// Switching the network in Settings tells the page too, as an approved site // Switching the network in Settings tells the page too, as an approved site
+199
View File
@@ -0,0 +1,199 @@
// An open popup follows a network switch the background saves once the user
// approves a site's request: it takes the new network from the stored record
// and draws the screen it is on for it, as a switch in Settings does
// (https://git.eeqj.de/sneak/AutistMask/issues/650). Driven through the real
// popup over a stored profile on Ethereum Mainnet. The background's write is
// the storage stub's set, which the stub reports to the page as the browser
// does.
const {
bootPopup,
cleanupPopup,
unversionedValidProfile,
TOKEN_ADDRESS,
} = require("./support/popupBoot");
const {
applyChainSwitchFields,
copyChainSwitchFields,
} = require("../src/shared/chainSwitchFields");
const { NETWORKS } = require("../src/shared/networks");
const { STATE_SCHEMA_VERSION } = require("../src/shared/stateSchema");
afterEach(() => {
cleanupPopup();
});
const SEPOLIA_TOKEN = {
address: TOKEN_ADDRESS,
symbol: "TST",
decimals: 18,
name: "Test Token",
};
const MAINNET_TOKEN = {
address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
symbol: "DAI",
decimals: 18,
name: "Dai Stablecoin",
};
// The popup reopened onto AddressDetail on Ethereum Mainnet, with DAI tracked
// there and TST tracked on Sepolia.
function bootOnAddress() {
return bootPopup(
unversionedValidProfile({
currentView: "address",
viewStack: ["main"],
selectedWallet: 0,
selectedAddress: 0,
trackedTokens: [MAINNET_TOKEN],
networkTrackedTokens: { sepolia: [SEPOLIA_TOKEN] },
}),
);
}
// The background saves a switch to `networkId`, as its updateState() does
// once the user approves a site's request.
async function backgroundSwitch(page, networkId) {
const record = page.storage.read("autistmask");
applyChainSwitchFields(record, networkId);
await page.storage.local.set({ autistmask: record });
await page.settle();
await page.settle();
}
test("the popup open on AddressDetail shows the new network and its balances", async () => {
const page = await bootOnAddress();
expect(page.pageErrors).toEqual([]);
expect(page.visibleViews()).toEqual(["address"]);
expect(page.node("address-balances").innerHTML).toContain("DAI");
expect(page.node("debug-banner")).toBeNull();
await backgroundSwitch(page, "sepolia");
const { state } = require("../src/shared/state");
expect(state.networkId).toBe("sepolia");
expect(state.rpcUrl).toBe(NETWORKS.sepolia.defaultRpcUrl);
expect(page.visibleViews()).toEqual(["address"]);
const balances = page.node("address-balances").innerHTML;
expect(balances).toContain("TST");
expect(balances).toContain("SepoliaETH");
expect(balances).not.toContain("DAI");
expect(page.text("debug-banner")).toBe("[TESTNET]");
// Its next refresh runs on Sepolia, and what it fetched is stored.
await page.tick();
const { refreshBalances } = require("../src/shared/balances");
expect(refreshBalances.mock.lastCall[4]).toBe("sepolia");
const stored = page.storage.read("autistmask");
expect(stored.networkId).toBe("sepolia");
expect(stored.lastBalanceRefresh).toBeGreaterThan(0);
});
test("the popup open on Settings shows the new network, and Back draws the screen beneath for it", async () => {
const page = await bootOnAddress();
await page.click("btn-settings");
expect(page.visibleViews()).toEqual(["settings"]);
await backgroundSwitch(page, "sepolia");
expect(page.visibleViews()).toEqual(["settings"]);
expect(page.value("settings-network")).toBe("sepolia");
expect(page.value("settings-rpc")).toBe(NETWORKS.sepolia.defaultRpcUrl);
expect(page.node("settings-tracked-tokens").innerHTML).toContain("TST");
expect(page.text("debug-banner")).toBe("[TESTNET]");
await page.click("btn-settings-back");
expect(page.visibleViews()).toEqual(["address"]);
expect(page.node("address-balances").innerHTML).not.toContain("DAI");
});
// Neither can be drawn again for the new network: Send cannot be rendered from
// saved state, and DAI was picked on Ethereum Mainnet, where alone it is
// tracked. A reopened popup goes to Home in their place.
test.each([
["Send", (page) => page.click("btn-send")],
[
"AddressToken for DAI",
async (page) => {
const { state } = require("../src/shared/state");
state.selectedToken = MAINNET_TOKEN.address;
require("../src/popup/views/helpers").pushCurrentView();
require("../src/popup/views/addressToken").show();
await page.settle();
},
],
])("the popup open on %s goes to Home", async (_view, open) => {
const page = await bootOnAddress();
await open(page);
expect(page.visibleViews()).not.toEqual(["address"]);
await backgroundSwitch(page, "sepolia");
expect(page.visibleViews()).toEqual(["main"]);
expect(page.text("total-value")).toBe("0.0000 SepoliaETH");
});
// The report of the switch's own save names the network the page already has.
test("a switch in Settings is not taken a second time when its save is reported", async () => {
const page = await bootOnAddress();
await page.click("btn-settings");
const { get, set } = page.storage.local;
const reads = get.mock.calls.length;
const writes = set.mock.calls.length;
const select = page.node("settings-network");
select.value = "sepolia";
for (const fn of select.listeners.change) await fn();
await page.settle();
await page.settle();
expect(get).toHaveBeenCalledTimes(reads + 1);
expect(set).toHaveBeenCalledTimes(writes + 1);
expect(page.text("flash-msg")).toBe("Switched to Sepolia Testnet.");
});
// Such as one a newer build wrote, which this build cannot read. Nothing reads
// or writes the stored record for it: the popup's next save finds it, as
// before.
test("a record that names no network is not followed", async () => {
const page = await bootOnAddress();
const { get, set } = page.storage.local;
const reads = get.mock.calls.length;
await set({
autistmask: {
schemaVersion: STATE_SCHEMA_VERSION + 1,
wallets: [{ type: "hd", name: "Main", addresses: [] }],
},
});
await page.settle();
expect(get).toHaveBeenCalledTimes(reads);
expect(page.visibleViews()).toEqual(["address"]);
});
// A record that takes the switch from the switched record ends up as that
// record, balances the background fetched since included.
test("copyChainSwitchFields() takes every field applyChainSwitchFields() sets", () => {
const before = unversionedValidProfile({
trackedTokens: [MAINNET_TOKEN],
networkTrackedTokens: { sepolia: [SEPOLIA_TOKEN] },
networkEndpoints: {
sepolia: {
rpcUrl: "http://127.0.0.1:8545",
blockscoutUrl: "http://127.0.0.1:4000/api/v2",
},
},
lastBalanceRefresh: 1,
tokenHolderCache: { [MAINNET_TOKEN.address]: 5000 },
fraudContracts: ["0x1111111111111111111111111111111111111111"],
});
const switched = structuredClone(before);
applyChainSwitchFields(switched, "sepolia");
switched.wallets[0].addresses[0].balance = "2.0";
const follower = structuredClone(before);
copyChainSwitchFields(follower, switched);
expect(follower).toEqual(switched);
});
+1 -1
View File
@@ -311,7 +311,7 @@ async function bootPopup(stored, options) {
const windowListeners = {}; const windowListeners = {};
globalThis.chrome = { globalThis.chrome = {
storage: { local: storage.local }, storage: { local: storage.local, onChanged: storage.onChanged },
runtime: { runtime: {
sendMessage: jest.fn(async () => ({})), sendMessage: jest.fn(async () => ({})),
getURL: (p) => "chrome-extension://autistmask/" + p, getURL: (p) => "chrome-extension://autistmask/" + p,
+30 -5
View File
@@ -18,7 +18,9 @@
// a storage stub by hand. // a storage stub by hand.
// One storage area: get, set and remove over its own store, cloning both ways. // One storage area: get, set and remove over its own store, cloning both ways.
function makeArea(store, tick) { // `changed` is handed what each set or remove changed, in the shape
// storage.onChanged reports it.
function makeArea(store, tick, changed) {
const get = jest.fn(async (key) => { const get = jest.fn(async (key) => {
tick(); tick();
if (key === undefined || key === null) return structuredClone(store); if (key === undefined || key === null) return structuredClone(store);
@@ -34,14 +36,25 @@ function makeArea(store, tick) {
const set = jest.fn(async (items) => { const set = jest.fn(async (items) => {
tick(); tick();
const changes = {};
for (const k of Object.keys(items)) { for (const k of Object.keys(items)) {
changes[k] = structuredClone({
oldValue: store[k],
newValue: items[k],
});
store[k] = structuredClone(items[k]); store[k] = structuredClone(items[k]);
} }
changed(changes);
}); });
const remove = jest.fn(async (key) => { const remove = jest.fn(async (key) => {
tick(); tick();
for (const k of Array.isArray(key) ? key : [key]) delete store[k]; const changes = {};
for (const k of Array.isArray(key) ? key : [key]) {
changes[k] = { oldValue: store[k] };
delete store[k];
}
changed(changes);
}); });
return { get, set, remove }; return { get, set, remove };
@@ -54,12 +67,22 @@ function makeArea(store, tick) {
function makeStorageStub(initial, onOp) { function makeStorageStub(initial, onOp) {
const store = initial ? structuredClone(initial) : {}; const store = initial ? structuredClone(initial) : {};
const tick = onOp || (() => {}); const tick = onOp || (() => {});
const local = makeArea(store, tick); // storage.onChanged: after a set or remove has finished, every listener is
// called with what it changed and the area's name, as the browser calls
// them for a write by any page or the background.
const listeners = [];
const announce = (areaName) => (changes) => {
Promise.resolve().then(() => {
for (const fn of listeners) fn(structuredClone(changes), areaName);
});
};
const local = makeArea(store, tick, announce("local"));
return { return {
// Drop this straight in as chrome.storage. // Drop this straight in as chrome.storage.
local, local,
session: makeArea({}, tick), session: makeArea({}, tick, announce("session")),
onChanged: { addListener: (fn) => listeners.push(fn) },
get: local.get, get: local.get,
set: local.set, set: local.set,
remove: local.remove, remove: local.remove,
@@ -71,7 +94,9 @@ function makeStorageStub(initial, onOp) {
? structuredClone(store) ? structuredClone(store)
: structuredClone(store[key]), : structuredClone(store[key]),
// Seed or replace a record without going through the module under // Seed or replace a record without going through the module under
// test — for standing in as "another page wrote this". // test — for standing in as "another page wrote this". Nothing is
// announced to storage.onChanged, so it also stands in for the time
// before the browser tells this page of such a write.
write: (key, value) => { write: (key, value) => {
store[key] = structuredClone(value); store[key] = structuredClone(value);
}, },
+1
View File
@@ -161,6 +161,7 @@ test("a token added by contract address on Sepolia is tracked on Sepolia only",
); );
expect(stored().trackedTokens).toEqual([SEPOLIA_TOKEN]); expect(stored().trackedTokens).toEqual([SEPOLIA_TOKEN]);
await boot.click("btn-settings");
await chooseNetwork(boot, "mainnet"); await chooseNetwork(boot, "mainnet");
expect(stored().networkId).toBe("mainnet"); expect(stored().networkId).toBe("mainnet");
expect(stored().trackedTokens).toEqual([MAINNET_TOKEN]); expect(stored().trackedTokens).toEqual([MAINNET_TOKEN]);