Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions WALLET-BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,14 @@ stays, marked "Done.", until those mentions are updated.
through the gas relay); Arcstock works too. 0.2.5 to 0.2.7: Alchemy reached through the host (the sandboxed
page's "null" origin is refused), without a host permission (Chrome leaves the Origin header out of a GET
to a permitted host), and page 0.14.2 keeps Alchemy's tokens when only its NFT API refuses (403 to the
extension's key). The signing window's EXT-02 and EXT-03 in 0.2.3; the "unknown function" warning kept
on top, by the maintainer's choice. Next: the
extension's key). The signing window's EXT-02 and EXT-03 in 0.2.3. Page 0.14.4, for extension 0.2.8 and app
0.10.3: the window no longer warns on every call it cannot decode by itself. The page gives it the
signatures it knows (its decoders, the explorer's verified ABI of the called contract), each one only if it
decodes the call; the window uses one only if its selector is the call's and it decodes the data exactly,
and shows the function by name and arguments. Warning (amber): a permission (approve, permit, operator,
delegate), an address argument such as "to" or "receiver" that is not the UP, bytes after the arguments,
a call neither side can decode. Red: a description that does not match the data, a DELEGATECALL of the
UP, a change of its owner or of its controllers' permissions. Next: the
two-provider review right after the release (`AUDIT.md`, review policy). A structural change, in phases:
- *first, the discovery test* (`up-wallet-extension/spike/eip6963-discovery/`, 2026-11-22): an unpacked
extension with no key that announces "UP Wallet (test)" through EIP-6963 on https pages, answers a public
Expand Down
9 changes: 8 additions & 1 deletion abi-decode.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,5 +220,12 @@
return { label, op: text("op", { contract: info.name || `${to.slice(0, 6)}…${to.slice(-4)}`, fn: clean(p.name, 40) }), params: [clean(sig, 200), ...out].join("\n"), notes };
}

window.AbiDecode = { describe, labelOf, EXPLORERS, text, TEXT };
// The verified ABI's functions of a contract (the explorer of its network, cached), or null.
async function functionsOf(chainId, addr) {
const explorer = EXPLORERS[CHAIN_KEYS[chainId]];
if (!explorer || !ethers.isAddress(addr)) return null;
const a = await abiOf(explorer, chainId, ethers.getAddress(addr));
return a ? a.abi : null;
}
window.AbiDecode = { describe, labelOf, functionsOf, EXPLORERS, text, TEXT };
})();
48 changes: 42 additions & 6 deletions asset-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,16 @@
return { rows: rows.filter(r => r && !r.zero && r.count !== "0"), total: len };
}

// At most 20 s per request: a request that never answers (seen on Base, through the browser extension) would
// hold the whole network's reading until the overview gives up on it.
async function getJson(url, init) {
const r = await fetch(url, { headers: { accept: "application/json" }, credentials: "omit", referrerPolicy: "no-referrer", ...(init || {}) });
if (!r.ok) throw new Error("HTTP " + r.status);
return r.json();
let timer;
const late = new Promise((_, no) => { timer = setTimeout(() => no(new Error("timeout")), 20000); });
try {
const r = await Promise.race([fetch(url, { headers: { accept: "application/json" }, credentials: "omit", referrerPolicy: "no-referrer", ...(init || {}) }), late]);
if (!r.ok) throw new Error("HTTP " + r.status);
return await Promise.race([r.json(), late]);
} finally { clearTimeout(timer); }
}
const bsAddr = (tok) => (tok && (tok.address_hash || tok.address)) || null;
// Spam only when Blockscout marks the token as a scam: a reputation that is merely not "ok" (not rated
Expand Down Expand Up @@ -175,17 +181,42 @@
if (j.error) throw new Error(j.error.message || "RPC error");
return j.result;
}
// A token's name, symbol, decimals and logo do not change: kept for 30 days (memory, then localStorage), so a
// UP that received many tokens (airdrops, spam) is not read again token by token at every refresh.
const META = new Map(), META_STORE = "alchemy.meta.v1.", META_TTL = 30 * 24 * 3600 * 1000;
async function tokenMeta(net, key, address) {
const k = `${net}.${address.toLowerCase()}`;
if (META.has(k)) return META.get(k);
try {
const v = JSON.parse(localStorage.getItem(META_STORE + k) || "null");
if (v && Date.now() - v.at < META_TTL) { META.set(k, v.m); return v.m; }
} catch (e) { /* no storage */ }
const r = await alchemyRpc(net, key, "alchemy_getTokenMetadata", [address]);
const m = { name: r && r.name, symbol: r && r.symbol, decimals: r && r.decimals, logo: r && r.logo };
META.set(k, m);
try { localStorage.setItem(META_STORE + k, JSON.stringify({ m, at: Date.now() })); } catch (e) { /* storage full or off */ }
return m;
}
async function fromAlchemy(net, key, up) {
const rows = [];
let pageKey = null;
for (let page = 0; page < MAX_PAGES; page++) {
const res = await alchemyRpc(net, key, "alchemy_getTokenBalances", pageKey ? [up, "erc20", { pageKey }] : [up, "erc20"]);
const held = [];
for (const b of (res && res.tokenBalances) || []) {
let amount; try { amount = BigInt(b.tokenBalance || "0x0"); } catch (e) { continue; }
if (amount === 0n || !ethers.isAddress(b.contractAddress)) continue;
const meta = await alchemyRpc(net, key, "alchemy_getTokenMetadata", [b.contractAddress]).catch(() => ({}));
rows.push({ address: ethers.getAddress(b.contractAddress), type: "ERC-20", name: meta.name, symbol: meta.symbol, amount: fmt(amount, meta.decimals), spam: false, source: "alchemy", image: imageUrl(meta.logo) });
held.push({ address: ethers.getAddress(b.contractAddress), amount });
}
// The metadata 6 at a time (one by one, a UP with hundreds of tokens took longer than the overview waits).
const metas = new Array(held.length);
let next = 0;
const worker = async () => { while (next < held.length) { const i = next++; metas[i] = await tokenMeta(net, key, held[i].address).catch(() => ({})); } };
await Promise.all(Array.from({ length: Math.min(6, held.length) }, worker));
held.forEach((h, i) => {
const meta = metas[i] || {};
rows.push({ address: h.address, type: "ERC-20", name: meta.name, symbol: meta.symbol, amount: fmt(h.amount, meta.decimals), spam: false, source: "alchemy", image: imageUrl(meta.logo) });
});
pageKey = res && res.pageKey;
if (!pageKey) break;
}
Expand Down Expand Up @@ -274,7 +305,12 @@
if (BLOCKSCOUT[netKey]) {
try {
const have = new Set(out.indexer.rows.map((r) => r.address));
const nftRows = (await fromBlockscout(BLOCKSCOUT[netKey], up)).filter((r) => Array.isArray(r.rawIds) && !have.has(r.address));
// At most 25 s: Base's Blockscout can be slow, and the tokens already read must not be lost with it
// (the browser extension's Alchemy key gets no NFTs, so it always comes here).
let timer;
const late = new Promise((_, no) => { timer = setTimeout(() => no(new Error("timeout 25 s")), 25000); });
const all = await Promise.race([fromBlockscout(BLOCKSCOUT[netKey], up), late]).finally(() => clearTimeout(timer));
const nftRows = all.filter((r) => Array.isArray(r.rawIds) && !have.has(r.address));
out.indexer.rows = out.indexer.rows.concat(nftRows);
out.indexer.nftSource = "blockscout";
} catch (e) { out.indexer.nftErr += "; Blockscout: " + e.message; }
Expand Down
6 changes: 4 additions & 2 deletions call-decode.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,9 @@
function text(key, vars) { const v = TEXT[lang()][key]; return typeof v === "function" ? v(vars || {}) : v; }
// Names and symbols from the chain are untrusted: one line, no control characters, short.
const clean = (s, max = 24) => { const x = String(s ?? "").replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, " ").replace(/\s+/g, " ").trim(); return x.length > max ? x.slice(0, max - 1) + "…" : x; };
const sel = (sig) => ethers.id(sig).slice(0, 10);
// Every signature read here, also given to the signing window (up-wallet.html, signatureHints).
const SIGNATURES = [];
const sel = (sig) => { if (!SIGNATURES.includes(sig)) SIGNATURES.push(sig); return ethers.id(sig).slice(0, 10); };
const NATIVE = ["0x0000000000000000000000000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"];
const isNative = (a) => NATIVE.includes(String(a).toLowerCase());

Expand Down Expand Up @@ -537,5 +539,5 @@ ${kind === "in" ? "" : `amount: ${v[1]}\n`}${pname}: ${who}`, notes };
}
return null;
}
window.CallDecode = { describe, text, TEXT, aave4Spokes: SPOKES };
window.CallDecode = { describe, text, TEXT, aave4Spokes: SPOKES, signatures: () => SIGNATURES.slice() };
})();
88 changes: 80 additions & 8 deletions up-wallet.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html lang="it">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://cdnjs.cloudflare.com/ajax/libs/ethers/6.13.4/ 'sha256-3X4yBgcYIWx8N9Xt3Jmisgv6brlli2jxtfGDn63ZkTo='">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://cdnjs.cloudflare.com/ajax/libs/ethers/6.13.4/ 'sha256-MaEFwcKO1ilAb8qPhQN6XyGOAn695ydHt2FA1fY4BbU='">
<script src="theme.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:type" content="website">
Expand Down Expand Up @@ -683,6 +683,73 @@ <h2 data-i18n="panelSendTitle">6 · Invia dalla UP</h2>
const UP_IFACE = new ethers.Interface(["function execute(uint256 operationType, address target, uint256 value, bytes data) payable returns (bytes)"]);
const KM_IFACE = new ethers.Interface(["function execute(bytes payload) payable returns (bytes)"]);

// The signing window of the browser extension and of the app (sign-plan.js) decodes by itself only the token
// calls; for the other calls of a request it asks this page which function each selector is: the page's own
// decoders, then the verified ABI of the called contract (abi-decode.js). The window uses a signature only if
// its selector is the call's and it decodes the call data exactly; it shows the function's name and arguments,
// and warns from what they say. A signature is given here only when it decodes the call too.
// req: the request for the window ({ kind: "tx", tx } or { kind: "userop", op, chainId }, with up). Returns
// { selector: "function name(type name, ...)" }, at most 64.
const BATCH_IFACE = new ethers.Interface(["function executeBatch(uint256[] operationsType, address[] targets, uint256[] values, bytes[] datas) payable returns (bytes[])"]);
window.__upwalletSignatureHints = async function signatureHints(req) {
const calls = [];
const up = req && typeof req.up === "string" && ethers.isAddress(req.up) ? ethers.getAddress(req.up) : null;
const ofUp = (data, depth) => {
let d = null;
try { d = UP_IFACE.parseTransaction({ data }) || BATCH_IFACE.parseTransaction({ data }); } catch (e) { return false; }
if (!d) return false;
if (d.name === "execute") add(d.args[1], d.args[3], depth + 1);
else d.args[1].forEach((to, i) => add(to, d.args[3][i], depth + 1));
return true;
};
const add = (to, data, depth) => {
if (depth > 3 || calls.length >= 64 || !to || typeof data !== "string" || !ethers.isHexString(data) || ethers.dataLength(data) < 4) return;
if (up && ethers.getAddress(to) === up && ofUp(data, depth)) return; // LSP20: the UP calling itself
calls.push({ to: ethers.getAddress(to), data });
};
if (req && req.kind === "tx" && req.tx) {
let done = false;
try { const k = KM_IFACE.parseTransaction({ data: req.tx.data }); if (k) done = ofUp(k.args[0], 0); } catch (e) { /* not the Key Manager */ }
if (!done && req.tx.to) add(req.tx.to, req.tx.data, 0);
} else if (req && req.kind === "userop" && req.op) ofUp(req.op.callData, 0);
const chainId = Number(req && (req.kind === "tx" ? req.tx && req.tx.chainId : req.chainId));
const known = {};
const learn = (frags) => {
for (const f of frags) {
try { const g = ethers.FunctionFragment.from(f); if (!(g.selector in known)) known[g.selector] = g; } catch (e) { /* not a function */ }
}
};
const fns = (i) => i.fragments.filter((f) => f.type === "function");
const hints = {};
// Only when the signature decodes this call: the selector, then the arguments encoded again are the data.
const fits = (g, data) => {
try {
const args = ethers.AbiCoder.defaultAbiCoder().decode(g.inputs, ethers.dataSlice(data, 4));
return data.toLowerCase().startsWith((g.selector + ethers.AbiCoder.defaultAbiCoder().encode(g.inputs, args).slice(2)).toLowerCase());
} catch (e) { return false; }
};
for (const { to, data } of calls) {
const s = ethers.dataSlice(data, 0, 4);
if (s in hints) continue;
// The called contract's verified ABI first (it is this contract's), then the page's decoders.
let g = null;
if (window.AbiDecode && AbiDecode.functionsOf && chainId) {
const abi = await Promise.race([AbiDecode.functionsOf(chainId, to).catch(() => null), new Promise((r) => setTimeout(() => r(null), 4000))]);
for (const f of abi || []) { try { const x = ethers.FunctionFragment.from(f); if (x.selector === s) { g = x; break; } } catch (e) { /* skip */ } }
}
if (!g) {
if (!Object.keys(known).length) {
for (const i of [KNOWN_IFACE, VAULT_IFACE, MORPHO_BUNDLES_IFACE, LSP26_IFACE, SUPPLIER_IFACE, TRACE_FACTORY_IFACE, TRACE_IFACE, HUP_IFACE, AVAX_DEFI_IFACE, SEND_IFACE, POS_IFACE]) learn(fns(i));
if (window.CallDecode && CallDecode.signatures) learn(CallDecode.signatures().map((x) => "function " + x));
}
g = known[s] || null;
}
if (g && fits(g, data)) hints[s] = g.format("full");
if (Object.keys(hints).length >= 64) break;
}
return hints;
};

// ==================== I18N ====================
// Language: the one chosen before on this browser or app, else the browser's or phone's own (Italian for
// Italian, English for anything else).
Expand Down Expand Up @@ -715,9 +782,10 @@ <h2 data-i18n="panelSendTitle">6 · Invia dalla UP</h2>
ovSpam: (v) => `${v.n} segnalati come spam, non contati`,
ovIxFail: (v) => `Indice ${v.ix} non disponibile (${v.err}): mancano i token che solo lui elenca.`,
ovIxSrc: (v) => `Altri token letti da ${v.ix}.`,
ovNftFail: (v) => `NFT non letti (${v.err}): riprova con Aggiorna.`,
ixFallback: (v) => `Alchemy non ha risposto (${v.err}): gli altri token sono letti da Blockscout, che può elencarne meno.`,
ovNothing: (v) => `Niente su: ${v.list}.`, ovAbsent: (v) => `La UP non esiste su: ${v.list}.`,
ovFailed: (v) => `Non lette (rete non raggiungibile): ${v.list}. Riprova con Aggiorna.`,
ovFailed: (v) => `Non lette: ${v.list}. Riprova con Aggiorna.`,
ovUnpriced: "contiene anche token senza prezzo",
ovAToken: (v) => `deposito Aave v3 di ${v.amount} ${v.sym}`, ovVault: (v) => `quote di un vault, valgono ≈ ${v.amount} ${v.sym}`,
ovSpoke: "deposito Aave v4 (pro.aave.com), non è un token nella UP",
Expand Down Expand Up @@ -1242,9 +1310,10 @@ <h2 data-i18n="panelSendTitle">6 · Invia dalla UP</h2>
ovSpam: (v) => `${v.n} flagged as spam, not counted`,
ovIxFail: (v) => `${v.ix} index not available (${v.err}): tokens only it lists are missing.`,
ovIxSrc: (v) => `Other tokens read from ${v.ix}.`,
ovNftFail: (v) => `NFTs not read (${v.err}): try again with Refresh.`,
ixFallback: (v) => `Alchemy did not answer (${v.err}): the other tokens are read from Blockscout, which may list fewer.`,
ovNothing: (v) => `Nothing on: ${v.list}.`, ovAbsent: (v) => `The UP does not exist on: ${v.list}.`,
ovFailed: (v) => `Not read (network not reachable): ${v.list}. Try again with Refresh.`,
ovFailed: (v) => `Not read: ${v.list}. Try again with Refresh.`,
ovUnpriced: "also holds tokens without a price",
ovAToken: (v) => `Aave v3 deposit of ${v.amount} ${v.sym}`, ovVault: (v) => `vault shares, worth ≈ ${v.amount} ${v.sym}`,
ovSpoke: "Aave v4 deposit (pro.aave.com), not a token in the UP",
Expand Down Expand Up @@ -1832,7 +1901,7 @@ <h2 data-i18n="panelSendTitle">6 · Invia dalla UP</h2>
// WALLET-BACKLOG.md and the patch with a fix (0.x: experimental). The Android app's and the browser
// extension's builds write the Cross_Chain commit in PAGE_COMMIT, and they give their own version
// (window.__upwalletAppVersion, then the "upwallet:version" event).
const PAGE_VERSION = "0.14.3";
const PAGE_VERSION = "0.14.4";
const PAGE_COMMIT = null;
function renderVersion() {
const el = $("pageVersion"), app = window.__upwalletAppVersion;
Expand Down Expand Up @@ -4530,12 +4599,13 @@ <h2 data-i18n="panelSendTitle">6 · Invia dalla UP</h2>
if (cur && cur.rpc && !nets.some((n) => n.key === cur.key)) nets.push(cur);
ovState = { up, test: isTestnet(cur), total: nets.length, results: [], at: null };
renderOverview();
const timeout = (p, ms) => Promise.race([p, new Promise((_, no) => setTimeout(() => no(new Error("timeout")), ms))]);
// Each step's timeout names the step, shown with the network that was not read (where it stopped).
const timeout = (p, ms, step = "") => Promise.race([p, new Promise((_, no) => setTimeout(() => no(new Error(`${step ? step + ": " : ""}timeout ${ms / 1000} s`)), ms))]);
const one = async (n) => {
const pv = new ethers.JsonRpcProvider(n.rpc, n.chainId || undefined, { staticNetwork: !!n.chainId, batchMaxCount: 1 });
try {
if ((await timeout(pv.getCode(up), 10000)) === "0x") return { n, absent: true };
const a = await timeout(AssetList.list(pv, up, n.key), 60000);
if ((await timeout(pv.getCode(up), 10000, "RPC")) === "0x") return { n, absent: true };
const a = await timeout(AssetList.list(pv, up, n.key), 60000, "assets");
let price = null;
if (window.UsdPrice && n.chainId) price = await timeout(UsdPrice.read(pv, n.chainId, ethers), 10000).catch(() => null);
let eur = null;
Expand Down Expand Up @@ -4608,7 +4678,7 @@ <h2 data-i18n="panelSendTitle">6 · Invia dalla UP</h2>
const done = ovState.results;
const held = [], empty = [], absent = [], failed = [];
for (const r of done) {
if (r.err) failed.push(r.n.name);
if (r.err) failed.push(`${r.n.name} (${oneLine(r.err, 80)})`);
else if (r.absent) absent.push(r.n.name);
else { const l = ovLines(r); if (l.lines.length || l.spam) held.push({ r, ...l }); else empty.push(r.n.name); }
}
Expand Down Expand Up @@ -4645,6 +4715,8 @@ <h2 data-i18n="panelSendTitle">6 · Invia dalla UP</h2>
if (ix && ix.err) add("div", "ov-sub line-warn", t("ovIxFail", { ix: ix.kind === "alchemy" ? "Alchemy" : "Blockscout", err: oneLine(ix.err, 120) }), card);
else if (ix && ix.fallback) add("div", "ov-sub line-warn", t("ixFallback", { err: oneLine(ix.fallback, 120) }), card);
else if (ix) add("div", "ov-sub", t("ovIxSrc", { ix: ix.kind === "alchemy" ? "Alchemy" : "Blockscout" }), card);
// Alchemy gave the tokens, and neither it nor Blockscout the NFTs (the extension's key gets none from Alchemy).
if (ix && !ix.err && ix.nftErr && !ix.nftSource) add("div", "ov-sub line-warn", t("ovNftFail", { err: oneLine(ix.nftErr, 120) }), card);
}
if (empty.length) add("div", "ov-sub", t("ovNothing", { list: empty.join(", ") }));
if (absent.length) add("div", "ov-sub", t("ovAbsent", { list: absent.join(", ") }));
Expand Down
Loading