fix: consolidate chain-switching into onChainSwitch()
All checks were successful
check / check (push) Successful in 13s

Introduces src/shared/chainSwitch.js with a single onChainSwitch()
function that handles every state change required when switching
networks:

- Updates networkId, rpcUrl, blockscoutUrl from network config
- Clears price caches (testnet tokens are worthless)
- Resets lastBalanceRefresh to force immediate refresh
- Clears per-address balances and token balances
- Clears tokenHolderCache and fraudContracts (chain-specific)
- Persists state

Both callers (settings UI dropdown, background
wallet_switchEthereumChain) now go through this single code path.
Adding a new chain (e.g. ETC) requires only a new entry in
networks.js with no per-caller wiring.

Also adds defense-in-depth testnet checks in prices.js (getPrice,
getAddressValueUsd, etc.) and fixes a hardcoded etherscan.io link
in addressToken.js to use the network-aware explorer URL.

Closes #139
This commit is contained in:
clawbot
2026-03-01 11:24:16 -08:00
parent 6b40fa8836
commit c37ffcc864
5 changed files with 88 additions and 15 deletions

View File

@@ -2,6 +2,7 @@ const { $, showView, showFlash, escapeHtml } = require("./helpers");
const { applyTheme } = require("../theme");
const { state, saveState, currentNetwork } = require("../../shared/state");
const { NETWORKS, SUPPORTED_CHAIN_IDS } = require("../../shared/networks");
const { onChainSwitch } = require("../../shared/chainSwitch");
const { log, debugFetch } = require("../../shared/log");
const deleteWallet = require("./deleteWallet");
@@ -220,14 +221,9 @@ function init(ctx) {
if (networkSelect) {
networkSelect.addEventListener("change", async () => {
const newId = networkSelect.value;
const net = NETWORKS[newId];
if (!net) return;
state.networkId = newId;
state.rpcUrl = net.defaultRpcUrl;
state.blockscoutUrl = net.defaultBlockscoutUrl;
const net = await onChainSwitch(newId);
$("settings-rpc").value = state.rpcUrl;
$("settings-blockscout").value = state.blockscoutUrl;
await saveState();
showFlash("Switched to " + net.name + ".");
});
}