Author SHA1 Message Date
sneak 89ccb75654 RULES.md: state every action that asks for the password (closes #756)
check / check (push) Failing after 15m6s
e2e / e2e-chrome (push) Successful in 16m48s
e2e / e2e-firefox (push) Successful in 3m27s
Replace the Secrets & Storage line "Password only required for signing
operations" with the wording sneak approved: the password is required for
signing, deleting a wallet, and showing a recovery phrase or private key.

Model: opus-5-5
2026-11-13 18:43:49 +00:00
clawbot 3a8b309d7e test: replace jest workers past 200 MB so they exit in time (closes #766)
check / check (push) Successful in 6m7s
e2e / e2e-chrome (push) Successful in 14m38s
e2e / e2e-firefox (push) Failing after 14m19s
On a starved CPU, jest force-stopped worker processes that could not exit
within the 500 ms it allows, and script/lib/jest.js failed the run although
every test passed. No test leaks a handle; exit time grows with what a
worker holds, 380 to 970 MB at the end of the run.

workerIdleMemoryLimit in package.json replaces a worker whose heap is over
200 MB after a test file with a fresh one.

tests/jestRunner.test.js runs script/lib/jest.js on a fixture that leaves
an interval running and expects the force-stop to fail the run.

Model: opus-5-5
2026-11-11 09:37:12 +01:00
clawbot b77b04b714 fix: history rows show the ISO datetime and the age (closes #760)
check / check (push) Successful in 6m53s
e2e / e2e-chrome (push) Successful in 15m18s
e2e / e2e-firefox (push) Successful in 2m8s
Home, AddressDetail and AddressToken showed only the relative age, with
the datetime as a tooltip. Each row now shows the datetime and then the
age in parentheses, on a line of its own, through transactionTimeHtml()
in helpers.js, which TransactionDetail also uses. The direction label
moves to its own right-aligned line below. README.md and docs/README.md
describe the new row.

Model: opus-5-5
2026-11-11 07:53:41 +01:00
clawbot d909567ab9 fix: every balance is cut to four decimals (closes #757)
check / check (push) Successful in 6m7s
e2e / e2e-chrome (push) Successful in 15m1s
e2e / e2e-firefox (push) Successful in 2m44s
The balance lists and Home's ETH line rounded with toFixed(4), so 0.99996
ETH read 1.0000 there and 0.9999 on Send. Send's current balance and
ConfirmTx's balance line kept the nonzero floor, so 0.00004 USDC read
0.0000 in the lists and 0.00004 on Send. All four now cut the stored
decimal string with truncateAmount(), as the history rows do.
balanceLine() takes the stored balance string instead of a parsed number,
and escapes the quantity cell. The amounts, fees and allowances a screen
asks the user to approve keep the floor of truncateAmountNeverZero().

Disclosure: for a holding below 0.0001, ConfirmTx shows the amount sent
beside a balance that reads 0.0000.

Model: opus-5-5
2026-11-11 04:46:32 +01:00
clawbot 32b232db60 docs: TODO.md Next Step names open milestone work, not tagging (closes #771)
check / check (push) Successful in 8m15s
e2e / e2e-chrome (push) Successful in 16m6s
e2e / e2e-firefox (push) Successful in 2m55s
Tags and releases are the owner's call; no repo document tells him when
to tag.

Model: opus-5-5
2026-11-11 03:50:29 +01:00
clawbot 02f14143eb docs: TODO.md holds open work only (closes #769)
check / check (push) Successful in 5m59s
e2e / e2e-chrome (push) Successful in 15m8s
e2e / e2e-firefox (push) Successful in 2m27s
Removes the Completed Steps work log and the v0.1.0 tagging date from
Status. Every open item the log mentioned is a tracker issue. The
Workflow bullet that named the removed section now says to record no
finished work in this file.

Model: opus-5-5
2026-11-11 02:04:13 +01:00
clawbot b87c03be11 fix: build hashes and recovery-phrase entropy come from ethers (closes #758)
check / check (push) Successful in 7m42s
e2e / e2e-chrome (push) Successful in 15m17s
e2e / e2e-firefox (push) Successful in 2m44s
build.js and script/lib/package.js hash with sha256 from ethers, with the
0x prefix stripped so the build receipt and SHA256SUMS keep bare lowercase
hex. generateMnemonic() takes its 16 bytes of entropy from randomBytes in
ethers. The README Crypto policy no longer lists these as exceptions.

Model: opus-5-5
2026-11-11 00:42:18 +01:00
24 changed files with 358 additions and 2099 deletions

No files matched your search

+22 -16
View File
@@ -563,9 +563,10 @@ of a wallet is a block:
"Recent Transactions" lists up to 25 transactions across every address of every "Recent Transactions" lists up to 25 transactions across every address of every
wallet, deduplicated by hash and filtered (see Scam protection). Each row has wallet, deduplicated by hash and filtered (see Scam protection). Each row has
three lines: four lines:
- the age and the direction; - the ISO datetime and the relative age;
- the direction, on the right;
- the counterparty's colour dot and label, with the amount on the right; - the counterparty's colour dot and label, with the amount on the right;
- the counterparty's full address, as plain text. - the counterparty's full address, as plain text.
@@ -1185,21 +1186,28 @@ popup closes.
These helpers write one kind of value on every screen that shows it: These helpers write one kind of value on every screen that shows it:
- `formatUsd()` in `src/shared/prices.js`: USD values; - `formatUsd()` in `src/shared/prices.js`: USD values;
- `isoDate()` and `timeAgo()` in `src/popup/views/helpers.js`: transaction - `transactionTimeHtml()` in `src/popup/views/helpers.js`: transaction times;
times;
- `renderAddressHtml()` in the same file: most addresses. - `renderAddressHtml()` in the same file: most addresses.
Most screens show token and ETH amounts with four decimal places. History rows Most screens show token and ETH amounts with four decimal places. History rows
cut amounts to four decimals and never round up (`truncateAmount()` in cut amounts to four decimals and never round up (`truncateAmount()` in
`src/shared/amountDisplay.js`). The balance lists and Home's ETH balance cut `src/shared/amountDisplay.js`). These balances are cut the same way:
them the same way. The screens that state what is being authorized cut as the
history does, and extend an amount below 0.0001 to its first nonzero digit - the balance lists;
- Home's ETH balance;
- Send's current balance;
- ConfirmTx's balance line.
So a balance below 0.0001 reads `0.0000` there.
The screens that state what is being authorized cut as the history does, and
extend an amount below 0.0001 to its first nonzero digit
(`truncateAmountNeverZero()`). So a nonzero amount never reads as zero there. (`truncateAmountNeverZero()`). So a nonzero amount never reads as zero there.
Those screens are: Those screens are:
- TxApproval; - TxApproval;
- SignApproval's Permit warning; - SignApproval's Permit warning;
- ConfirmTx, and Send's current balance; - ConfirmTx's amount and network fee;
- WaitTx, SuccessTx and ErrorTx. - WaitTx, SuccessTx and ErrorTx.
TransactionDetail shows the exact amount and its base units. TransactionDetail shows the exact amount and its base units.
@@ -1266,9 +1274,8 @@ A native amount is labelled with the native currency of the transaction's chain:
`src/shared/networks.js`). The balance lists and Send use the active network's. `src/shared/networks.js`). The balance lists and Send use the active network's.
The decoded swap lines call the native currency `ETH` on both networks. The decoded swap lines call the native currency `ETH` on both networks.
TransactionDetail shows the time as an ISO datetime and a relative age. A TransactionDetail and every history row show the time as an ISO datetime and
history row shows the age, with the datetime as its tooltip. With "UTC then a relative age. With "UTC Timestamps" on, the datetime is in UTC.
Timestamps" on, the datetime is in UTC.
Every nonzero holding is stored exactly. A token holding below 0.000001 is left Every nonzero holding is stored exactly. A token holding below 0.000001 is left
out of: out of:
@@ -1647,11 +1654,10 @@ The development dependencies ship nowhere:
### Crypto policy ### Crypto policy
Hashing, key derivation, signing and encryption go through `ethers` or In the extension, hashing, key derivation, signing and encryption go through
`libsodium-wrappers-sumo`. No primitive is implemented in this repository. A new `ethers` or `libsodium-wrappers-sumo`. A new recovery phrase takes its random
recovery phrase draws its random bytes from the browser's bytes from `ethers`. `build.js` and `script/lib/package.js` also hash files with
`crypto.getRandomValues()`. The build tooling, `build.js` and `script/lib/`, `ethers`. No primitive is implemented in this repository.
hashes files with Node's `crypto`; none of it ships in the extension.
### Content Security Policy ### Content Security Policy
+2 -1
View File
@@ -99,7 +99,8 @@ contradicts either, the originals govern.
- [ ] Public data (xpubs, addresses, balances) stored unencrypted - [ ] Public data (xpubs, addresses, balances) stored unencrypted
- [ ] Private data (recovery phrases, private keys) encrypted at rest - [ ] Private data (recovery phrases, private keys) encrypted at rest
- [ ] Password only required for signing operations - [ ] Password required for signing, deleting a wallet, and showing a recovery
phrase or private key
- [ ] No secrets in `.env`, credentials, or API keys committed to repo - [ ] No secrets in `.env`, credentials, or API keys committed to repo
- [ ] `git add -A` / `git add .` never used - [ ] `git add -A` / `git add .` never used
+6 -1938
View File
File diff suppressed because it is too large. Load diff
+3 -5
View File
@@ -1,8 +1,8 @@
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const crypto = require("crypto");
const { execSync } = require("child_process"); const { execSync } = require("child_process");
const esbuild = require("esbuild"); const esbuild = require("esbuild");
const { sha256 } = require("ethers");
const { resolveVersion } = require("./script/lib/version"); const { resolveVersion } = require("./script/lib/version");
const { const {
BACKGROUND_ENTRY_PREFIX, BACKGROUND_ENTRY_PREFIX,
@@ -314,10 +314,8 @@ function copyIcons(distDir) {
} }
function sha256File(absPath) { function sha256File(absPath) {
return crypto // ethers prefixes the hex with 0x; the receipt holds bare hex.
.createHash("sha256") return sha256(fs.readFileSync(absPath)).slice(2);
.update(fs.readFileSync(absPath))
.digest("hex");
} }
// Write the receipt for the files this build emitted. Deliberately records no // Write the receipt for the files this build emitted. Deliberately records no
+4 -3
View File
@@ -415,9 +415,10 @@ the setting is off, each history list shows one line saying so.
Each row shows: Each row shows:
- the age and the direction, "Sent" or "Received". A transaction can also ask a - the time, as a date and time and as an age;
contract to do something; that is a contract call. A row for a contract call - the direction, "Sent" or "Received", on the line below. A transaction can also
shows the call's name instead, such as "Approve" or "Swap"; ask a contract to do something; that is a contract call. A row for a contract
call shows the call's name instead, such as "Approve" or "Swap";
- the amount. A contract call row shows an amount only when the call moved a - the amount. A contract call row shows an amount only when the call moved a
token. A swap row shows the amount received, or the amount paid in when no token. A swap row shows the amount received, or the amount paid in when no
token came back. A row with no amount shows only a symbol, such as `USDC` or token came back. A row with no amount shows only a symbol, such as `USDC` or
+7 -2
View File
@@ -135,9 +135,14 @@ module.exports = [
}, },
}, },
// Unit tests, and the helpers they require: jest on node. // Unit tests, the helpers they require, and the test files they hand to
// jest: jest on node.
{ {
files: ["tests/**/*.test.js", "tests/support/**/*.js"], files: [
"tests/**/*.test.js",
"tests/support/**/*.js",
"tests/fixtures/**/*.js",
],
languageOptions: { languageOptions: {
...commonjs, ...commonjs,
globals: { ...globals.node, ...globals.jest }, globals: { ...globals.node, ...globals.jest },
+2 -1
View File
@@ -16,7 +16,8 @@
"jest": { "jest": {
"setupFiles": [ "setupFiles": [
"<rootDir>/tests/support/navigatorLocks.js" "<rootDir>/tests/support/navigatorLocks.js"
] ],
"workerIdleMemoryLimit": "200MB"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "10.0.1", "@eslint/js": "10.0.1",
+9 -3
View File
@@ -25,9 +25,9 @@
"use strict"; "use strict";
const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const ethers = require("ethers");
const { readZip, writeZip } = require("./zip"); const { readZip, writeZip } = require("./zip");
const { resolveVersion } = require("./version"); const { resolveVersion } = require("./version");
@@ -60,8 +60,9 @@ function fail(message) {
throw new Error(message); throw new Error(message);
} }
// Lowercase hex without the 0x prefix ethers adds, as sha256sum prints it.
function sha256(buf) { function sha256(buf) {
return crypto.createHash("sha256").update(buf).digest("hex"); return ethers.sha256(buf).slice(2);
} }
// Every regular file under dir, as archive-root-relative forward-slashed // Every regular file under dir, as archive-root-relative forward-slashed
@@ -291,4 +292,9 @@ if (require.main === module) {
} }
} }
module.exports = { checkSelfContained, htmlReferences, manifestReferences }; module.exports = {
checkSelfContained,
htmlReferences,
manifestReferences,
sha256,
};
+5 -5
View File
@@ -12,8 +12,7 @@ const {
attachCopyHandlers, attachCopyHandlers,
goBack, goBack,
pushCurrentView, pushCurrentView,
isoDate, transactionTimeHtml,
timeAgo,
} = require("./helpers"); } = require("./helpers");
const { state, saveState, currentNetwork } = require("../../shared/state"); const { state, saveState, currentNetwork } = require("../../shared/state");
const { formatAddressTotal, getAddressValue } = require("../../shared/prices"); const { formatAddressTotal, getAddressValue } = require("../../shared/prices");
@@ -236,10 +235,11 @@ function renderTransactions(txs) {
const nameStr = escapeHtml(title || ensName || ""); const nameStr = escapeHtml(title || ensName || "");
const err = tx.isError ? " (failed)" : ""; const err = tx.isError ? " (failed)" : "";
const opacity = tx.isError ? " opacity-50" : ""; const opacity = tx.isError ? " opacity-50" : "";
const ago = escapeHtml(timeAgo(tx.timestamp));
const iso = escapeHtml(isoDate(tx.timestamp));
html += `<div class="tx-row py-2 border-b border-border-light text-xs cursor-pointer hover:bg-hover${opacity}" data-tx="${i}">`; html += `<div class="tx-row py-2 border-b border-border-light text-xs cursor-pointer hover:bg-hover${opacity}" data-tx="${i}">`;
html += `<div class="flex justify-between"><span class="text-muted" title="${iso}">${ago}</span><span>${dirLabel}${err}</span></div>`; // The time has a line of its own, so a long time or direction label
// never pushes the other onto a second line.
html += `<div class="text-muted">${transactionTimeHtml(tx.timestamp)}</div>`;
html += `<div class="text-right">${dirLabel}${err}</div>`;
html += txCounterpartyHtml(counterparty, nameStr, amountStr); html += txCounterpartyHtml(counterparty, nameStr, amountStr);
html += `</div>`; html += `</div>`;
i++; i++;
+5 -5
View File
@@ -18,8 +18,7 @@ const {
attachCopyHandlers, attachCopyHandlers,
goBack, goBack,
pushCurrentView, pushCurrentView,
isoDate, transactionTimeHtml,
timeAgo,
} = require("./helpers"); } = require("./helpers");
const { state, saveState, currentNetwork } = require("../../shared/state"); const { state, saveState, currentNetwork } = require("../../shared/state");
const { bundledToken, resolveSymbol } = require("../../shared/tokenList"); const { bundledToken, resolveSymbol } = require("../../shared/tokenList");
@@ -329,10 +328,11 @@ function renderTransactions(txs) {
const nameStr = escapeHtml(title || ensName || ""); const nameStr = escapeHtml(title || ensName || "");
const err = tx.isError ? " (failed)" : ""; const err = tx.isError ? " (failed)" : "";
const opacity = tx.isError ? " opacity-50" : ""; const opacity = tx.isError ? " opacity-50" : "";
const ago = escapeHtml(timeAgo(tx.timestamp));
const iso = escapeHtml(isoDate(tx.timestamp));
html += `<div class="tx-row py-2 border-b border-border-light text-xs cursor-pointer hover:bg-hover${opacity}" data-tx="${i}">`; html += `<div class="tx-row py-2 border-b border-border-light text-xs cursor-pointer hover:bg-hover${opacity}" data-tx="${i}">`;
html += `<div class="flex justify-between"><span class="text-muted" title="${iso}">${ago}</span><span>${dirLabel}${err}</span></div>`; // The time has a line of its own, so a long time or direction label
// never pushes the other onto a second line.
html += `<div class="text-muted">${transactionTimeHtml(tx.timestamp)}</div>`;
html += `<div class="text-right">${dirLabel}${err}</div>`;
html += txCounterpartyHtml(counterparty, nameStr, amountStr); html += txCounterpartyHtml(counterparty, nameStr, amountStr);
html += `</div>`; html += `</div>`;
i++; i++;
+7 -4
View File
@@ -43,9 +43,12 @@ const {
transferAmountUnits, transferAmountUnits,
} = require("../../shared/transferAmount"); } = require("../../shared/transferAmount");
const { assertWithinCeilings } = require("../../shared/approvalVerify"); const { assertWithinCeilings } = require("../../shared/approvalVerify");
// The amount, the balance line and the fee reserve go through it, as the // The amount and the fee reserve keep the nonzero floor, as the approval
// approval screen's amounts do. // screen's amounts do. The balance line is cut as the balance lists cut it.
const { truncateAmountNeverZero } = require("../../shared/amountDisplay"); const {
truncateAmount,
truncateAmountNeverZero,
} = require("../../shared/amountDisplay");
const { const {
CODES, CODES,
FEE_PENDING, FEE_PENDING,
@@ -160,7 +163,7 @@ function renderBalance(txInfo) {
const price = getPrice(txInfo.token, txInfo.chainId); const price = getPrice(txInfo.token, txInfo.chainId);
const balUsd = price ? parseFloat(bal) * price : null; const balUsd = price ? parseFloat(bal) * price : null;
$("confirm-balance").textContent = valueWithUsd( $("confirm-balance").textContent = valueWithUsd(
truncateAmountNeverZero(bal) + " " + symbol, truncateAmount(bal) + " " + symbol,
balUsd, balUsd,
); );
} }
+14 -7
View File
@@ -378,8 +378,8 @@ function formatFee(wei, symbol, chainId) {
// whose scale nothing knows // whose scale nothing knows
// (https://git.eeqj.de/sneak/AutistMask/issues/349), and for a balance no // (https://git.eeqj.de/sneak/AutistMask/issues/349), and for a balance no
// refresh has read. There is no quantity to print for it and no fiat value to // refresh has read. There is no quantity to print for it and no fiat value to
// derive from one, and printing 0.0000 for a real holding is the failure this // derive from one. A holding whose amount is unknown is shown as
// whole rule exists to prevent, so the row says so instead. // `quantity unknown` rather than as a zero.
function balanceLine(symbol, balance, price, tokenId) { function balanceLine(symbol, balance, price, tokenId) {
const amount = unknownableAmount(balance); const amount = unknownableAmount(balance);
const qty = amount === null ? "quantity unknown" : truncateAmount(balance); const qty = amount === null ? "quantity unknown" : truncateAmount(balance);
@@ -615,9 +615,8 @@ function formatAddressHtml(address, ensName, maxLen, title) {
return renderAddressHtml(address, { title, ensName, maxLen }); return renderAddressHtml(address, { title, ensName, maxLen });
} }
// A transaction's time as every screen shows it (README, Amounts): the ISO // The ISO datetime of a transaction's time, in UTC when the UTC Timestamps
// datetime, in UTC when the UTC Timestamps setting is on, and the relative age. // setting is on. Views show it through transactionTimeHtml().
// Views import these two; they keep no copies.
function isoDate(timestamp) { function isoDate(timestamp) {
const d = new Date(timestamp * 1000); const d = new Date(timestamp * 1000);
const pad = (n) => String(n).padStart(2, "0"); const pad = (n) => String(n).padStart(2, "0");
@@ -674,6 +673,15 @@ function timeAgo(timestamp) {
return years + " year" + (years !== 1 ? "s" : "") + " ago"; return years + " year" + (years !== 1 ? "s" : "") + " ago";
} }
// A transaction's time as every screen shows it (README, Amounts): the ISO
// datetime, then the relative age in parentheses. With copyable set, the
// datetime is click-to-copy, and the caller attaches the copy handlers.
function transactionTimeHtml(timestamp, { copyable = false } = {}) {
const iso = isoDate(timestamp);
const isoHtml = copyable ? copyableHtml(iso) : escapeHtml(iso);
return isoHtml + " (" + escapeHtml(timeAgo(timestamp)) + ")";
}
// Shared external-link icon SVG used across all views. // Shared external-link icon SVG used across all views.
const EXT_ICON = const EXT_ICON =
`<span class="inline-block w-[10px] h-[10px] ml-[4px] align-middle">` + `<span class="inline-block w-[10px] h-[10px] ml-[4px] align-middle">` +
@@ -869,6 +877,5 @@ module.exports = {
reviewedNetworkProvider, reviewedNetworkProvider,
EXT_ICON, EXT_ICON,
truncateMiddle, truncateMiddle,
isoDate, transactionTimeHtml,
timeAgo,
}; };
+5 -5
View File
@@ -5,8 +5,7 @@ const {
balanceLinesForAddress, balanceLinesForAddress,
unknownableAmount, unknownableAmount,
markTrackedTokensNotFetched, markTrackedTokensNotFetched,
isoDate, transactionTimeHtml,
timeAgo,
addressDotHtml, addressDotHtml,
txCounterpartyHtml, txCounterpartyHtml,
HISTORY_OFF_TEXT, HISTORY_OFF_TEXT,
@@ -150,10 +149,11 @@ function renderHomeTxList(ctx) {
const titleStr = title ? escapeHtml(title) : ""; const titleStr = title ? escapeHtml(title) : "";
const err = tx.isError ? " (failed)" : ""; const err = tx.isError ? " (failed)" : "";
const opacity = tx.isError ? " opacity-50" : ""; const opacity = tx.isError ? " opacity-50" : "";
const ago = escapeHtml(timeAgo(tx.timestamp));
const iso = escapeHtml(isoDate(tx.timestamp));
html += `<div class="home-tx-row py-2 border-b border-border-light text-xs cursor-pointer hover:bg-hover${opacity}" data-tx="${i}">`; html += `<div class="home-tx-row py-2 border-b border-border-light text-xs cursor-pointer hover:bg-hover${opacity}" data-tx="${i}">`;
html += `<div class="flex justify-between"><span class="text-muted" title="${iso}">${ago}</span><span>${dirLabel}${err}</span></div>`; // The time has a line of its own, so a long time or direction label
// never pushes the other onto a second line.
html += `<div class="text-muted">${transactionTimeHtml(tx.timestamp)}</div>`;
html += `<div class="text-right">${dirLabel}${err}</div>`;
html += txCounterpartyHtml(counterparty, titleStr, amountStr); html += txCounterpartyHtml(counterparty, titleStr, amountStr);
html += `</div>`; html += `</div>`;
i++; i++;
+5 -8
View File
@@ -24,7 +24,7 @@ const { resolveSymbol } = require("../../shared/tokenList");
const { isLowHolderCount } = require("../../shared/holders"); const { isLowHolderCount } = require("../../shared/holders");
const { isSpoofedSymbol } = require("../../shared/symbolSpoof"); const { isSpoofedSymbol } = require("../../shared/symbolSpoof");
const { const {
truncateAmountNeverZero, truncateAmount,
isBelowOneMillionth, isBelowOneMillionth,
} = require("../../shared/amountDisplay"); } = require("../../shared/amountDisplay");
const { const {
@@ -239,7 +239,7 @@ function updateSendBalance() {
addr.balance == null addr.balance == null
? "Current balance: unknown (" + nativeCurrency() + ")" ? "Current balance: unknown (" + nativeCurrency() + ")"
: "Current balance: " + : "Current balance: " +
truncateAmountNeverZero(addr.balance) + truncateAmount(addr.balance) +
" " + " " +
nativeCurrency(); nativeCurrency();
} else { } else {
@@ -258,18 +258,15 @@ function updateSendBalance() {
$("send-balance").textContent = $("send-balance").textContent =
bal == null bal == null
? "Current balance: unknown (" + symbol + ")" ? "Current balance: unknown (" + symbol + ")"
: "Current balance: " + : "Current balance: " + truncateAmount(bal) + " " + symbol;
truncateAmountNeverZero(bal) +
" " +
symbol;
} }
} }
// Fill the amount field with the most the selected holding can send: a // Fill the amount field with the most the selected holding can send: a
// token's whole balance (cut to 18 decimal places), or for ETH the exact // token's whole balance (cut to 18 decimal places), or for ETH the exact
// balance minus the fee reserve the confirmation screen checks against, never // balance minus the fee reserve the confirmation screen checks against, never
// the rounded balance the screen shows. Where there is nothing to fill in, a // the balance the screen shows, which is cut to four decimals. Where there is
// flash message says why. // nothing to fill in, a flash message says why.
async function fillMaxAmount() { async function fillMaxAmount() {
const addr = currentAddress(); const addr = currentAddress();
if (!addr) return; if (!addr) return;
+4 -5
View File
@@ -10,8 +10,7 @@ const {
CONTRACT_CREATION_TEXT, CONTRACT_CREATION_TEXT,
addressDotHtml, addressDotHtml,
escapeHtml, escapeHtml,
isoDate, transactionTimeHtml,
timeAgo,
renderAddressHtml, renderAddressHtml,
blockieHtml, blockieHtml,
attachCopyHandlers, attachCopyHandlers,
@@ -204,9 +203,9 @@ function render() {
); );
loadFullTxDetails(tx.hash, tx.chainId); loadFullTxDetails(tx.hash, tx.chainId);
const isoStr = isoDate(tx.timestamp); $("tx-detail-time").innerHTML = transactionTimeHtml(tx.timestamp, {
$("tx-detail-time").innerHTML = copyable: true,
copyableHtml(isoStr) + " (" + escapeHtml(timeAgo(tx.timestamp)) + ")"; });
$("tx-detail-status").textContent = tx.isError ? "Failed" : "Success"; $("tx-detail-status").textContent = tx.isError ? "Failed" : "Success";
showView("transaction"); showView("transaction");
attachCopyHandlers("view-transaction"); attachCopyHandlers("view-transaction");
+2 -5
View File
@@ -1,7 +1,7 @@
// Wallet operations: mnemonic generation, HD derivation, signing. // Wallet operations: mnemonic generation, HD derivation, signing.
// All crypto delegated to ethers.js. // All crypto delegated to ethers.js.
const { Mnemonic, HDNodeWallet, Wallet } = require("ethers"); const { Mnemonic, HDNodeWallet, Wallet, randomBytes } = require("ethers");
const { DEBUG, DEBUG_MNEMONIC, BIP44_ETH_PATH } = require("./constants"); const { DEBUG, DEBUG_MNEMONIC, BIP44_ETH_PATH } = require("./constants");
function generateMnemonic() { function generateMnemonic() {
@@ -10,10 +10,7 @@ function generateMnemonic() {
// settings toggle drives, which would let a user of a release build turn // settings toggle drives, which would let a user of a release build turn
// the hardcoded, publicly known test phrase back on for real wallets. // the hardcoded, publicly known test phrase back on for real wallets.
if (DEBUG) return DEBUG_MNEMONIC; if (DEBUG) return DEBUG_MNEMONIC;
const m = Mnemonic.fromEntropy( return Mnemonic.fromEntropy(randomBytes(16)).phrase;
globalThis.crypto.getRandomValues(new Uint8Array(16)),
);
return m.phrase;
} }
// Every extended key (xprv or xpub) entering the app goes through this. // Every extended key (xprv or xpub) entering the app goes through this.
+17 -3
View File
@@ -1,6 +1,6 @@
// The balance lists and Home's ETH line show a balance as the history rows do // The balance lists, Home's ETH line and Send's current balance show a balance
// (README.md, Amounts): cut to four decimal places, never rounded up // as the history rows do (README.md, Amounts): cut to four decimal places,
// (https://git.eeqj.de/sneak/AutistMask/issues/757). // never rounded up (https://git.eeqj.de/sneak/AutistMask/issues/757).
// //
// Driven through the real popup over a stored profile on Ethereum Mainnet. // Driven through the real popup over a stored profile on Ethereum Mainnet.
@@ -75,3 +75,17 @@ describe("Home", () => {
expect(quantity(homeRow(page, USDC.toLowerCase()))).toBe("0.0000"); expect(quantity(homeRow(page, USDC.toLowerCase()))).toBe("0.0000");
}); });
}); });
describe("Send", () => {
test("the current balance reads 0.00004 USDC as 0.0000", async () => {
const page = await bootHolding("0.99996", "0.00004");
await page.click("btn-main-send");
// USDC chosen in the dropdown, as the user does.
const dropdown = page.node("send-token");
dropdown.value = USDC;
for (const fn of dropdown.listeners.change) await fn();
expect(page.visibleViews()).toEqual(["send"]);
expect(page.text("send-balance")).toBe("Current balance: 0.0000 USDC");
});
});
+3 -3
View File
@@ -165,9 +165,9 @@ describe("the balance warning on the removal confirmation", () => {
}); });
// The sentence must not assert an amount, because any amount it could // The sentence must not assert an amount, because any amount it could
// assert has been rounded: "This address holds 0.0000 ETH." is what the // assert has been cut to four decimals: "This address holds 0.0000 ETH." is
// rounded form produces for an address that holds real money. // what the cut form produces for an address that holds real money.
test("the warning sentence asserts no rounded amount", () => { test("the warning sentence asserts no cut amount", () => {
for (const addr of [DUST, ETH_ONLY, TOKEN_ONLY]) { for (const addr of [DUST, ETH_ONLY, TOKEN_ONLY]) {
expect(balanceWarningHtml(addr)).not.toMatch( expect(balanceWarningHtml(addr)).not.toMatch(
/holds [\d.]+ (ETH|USDC)/, /holds [\d.]+ (ETH|USDC)/,
+65
View File
@@ -951,6 +951,71 @@ test("tap-to-copy on the transaction detail screen copies the address (#151)", a
); );
}); });
// ------------------------------------------ history row time (#760)
// A Home history row shows the ISO datetime and then the relative age, on a
// line of its own. Measured at the popup's size: the time line is one line
// high, and no line of a row is wider than the row or the popup.
test("a Home history row shows the datetime and the age, one line high, without overflow (#760)", async (env) => {
await goHome(env.page);
env.routeOpts.seedNativeTransfer = true;
const page = await openPopup(env.ctx, env.popupUrl);
try {
await page.setViewportSize(POPUP_VIEWPORT);
await visible(page, "#view-main");
await page.waitForFunction(
() =>
document.querySelectorAll("#home-tx-list .home-tx-row")
.length === 2,
null,
{ timeout: 30000 },
);
const rows = await page.evaluate(() => {
const popupRight = document.body.getBoundingClientRect().right;
return [
...document.querySelectorAll("#home-tx-list .home-tx-row"),
].map((row) => {
const time = row.firstElementChild;
return {
time: time.textContent,
timeHeight: time.getBoundingClientRect().height,
lineHeight: parseFloat(getComputedStyle(time).lineHeight),
overflowingLines: [...row.children].filter(
(line) =>
line.scrollWidth > line.clientWidth ||
line.getBoundingClientRect().right > popupRight,
).length,
};
});
});
console.log("# Home history rows: " + JSON.stringify(rows));
for (const row of rows) {
assert(
/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(Z|[+-]\d\d:\d\d) \(\d+ \w+ ago\)$/.test(
row.time,
),
"the time line is not the ISO datetime and then the age: " +
JSON.stringify(row.time),
);
assert(
row.timeHeight === row.lineHeight,
"the time line is " +
row.timeHeight +
"px high, not one line of " +
row.lineHeight +
"px",
);
assert(
row.overflowingLines === 0,
row.overflowingLines + " line(s) of a row overflow it",
);
}
} finally {
env.routeOpts.seedNativeTransfer = false;
await page.close();
}
});
// ------------------------- the last of the #150 and #151 items (#295) // ------------------------- the last of the #150 and #151 items (#295)
// //
// Add Token's confirm button, TransactionDetail opened from the token screen // Add Token's confirm button, TransactionDetail opened from the token screen
+7
View File
@@ -0,0 +1,7 @@
// A test file that starts an interval and never clears it.
// tests/jestRunner.test.js runs script/lib/jest.js on this file alone. The
// name does not end in .test.js, so the normal run never picks it up.
test("starts an interval and never clears it", () => {
setInterval(() => {}, 1000);
});
+29
View File
@@ -0,0 +1,29 @@
// script/lib/jest.js, which package.json's test scripts run, fails a run in
// which jest force-stopped a worker process because a test left an open
// handle.
const { spawnSync } = require("child_process");
const path = require("path");
const root = path.join(__dirname, "..");
test("a test that leaves an interval running fails the run", () => {
// The memory limit in package.json makes jest run even this one file in a
// worker process. The interval keeps that worker from exiting, so jest
// force-stops it after the run.
const result = spawnSync(
process.execPath,
[
"script/lib/jest.js",
"--maxWorkers=1",
"--testMatch",
"<rootDir>/tests/fixtures/leavesIntervalRunning.js",
],
{ cwd: root, encoding: "utf8", timeout: 20000 },
);
expect(result.signal).toBeNull();
expect(result.status).toBe(1);
expect(result.stderr).toContain("1 passed");
expect(result.stderr).toContain("jest force-stopped a worker process");
});
+13 -2
View File
@@ -1,4 +1,5 @@
// The release archives: the zip container, and the self-containment rule. // The release archives: the zip container, the self-containment rule, and the
// digest format in release/SHA256SUMS.
// //
// script/package produces one archive per browser and script/lib/package.js // script/package produces one archive per browser and script/lib/package.js
// decides what goes in it. The trap that rule exists for is real and specific: // decides what goes in it. The trap that rule exists for is real and specific:
@@ -11,12 +12,14 @@
// So the packager resolves every reference in the manifest and in every HTML // So the packager resolves every reference in the manifest and in every HTML
// document, and fails on any that leaves the extension root. These are the // document, and fails on any that leaves the extension root. These are the
// cases for that, plus the archive format itself — new code, and the thing the // cases for that, plus the archive format itself — new code, and the thing the
// artifact is made of. // artifact is made of. One more case checks the digest format in
// release/SHA256SUMS.
const { const {
checkSelfContained, checkSelfContained,
htmlReferences, htmlReferences,
manifestReferences, manifestReferences,
sha256,
} = require("../script/lib/package"); } = require("../script/lib/package");
const { readZip, writeZip } = require("../script/lib/zip"); const { readZip, writeZip } = require("../script/lib/zip");
@@ -142,6 +145,14 @@ describe("archive self-containment", () => {
}); });
}); });
// release/SHA256SUMS is checked with `sha256sum -c`, which needs the digest
// as bare lowercase hex. The expected value is the FIPS 180-2 digest of "abc".
test("sha256 prints the digest as sha256sum does", () => {
expect(sha256(Buffer.from("abc"))).toBe(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
);
});
describe("the zip container", () => { describe("the zip container", () => {
const files = [ const files = [
{ name: "manifest.json", data: Buffer.from('{"a":1}') }, { name: "manifest.json", data: Buffer.from('{"a":1}') },
+21 -16
View File
@@ -6,8 +6,10 @@
// balances and the fee were each cut to six decimal places, a rule of their // balances and the fee were each cut to six decimal places, a rule of their
// own, and a token holding cut to zero was dropped, while the approval screen // own, and a token holding cut to zero was dropped, while the approval screen
// showed the same fee through src/shared/amountDisplay.js with the nonzero // showed the same fee through src/shared/amountDisplay.js with the nonzero
// floor. The balances are now stored exactly, every nonzero token holding // floor. The balances are now stored exactly, and every nonzero token holding
// kept, and the screens show them and the fee through that helper. // is kept. The fee lines show the fee through that helper with the floor. The
// balance lines cut a balance to four decimals, as the balance lists do, so a
// balance below 0.0001 reads 0.0000.
// //
// Driven through the real refreshBalances(), Send screen, confirmation screen // Driven through the real refreshBalances(), Send screen, confirmation screen
// and approval screen, with only the node, the explorer and the DOM stubbed: a // and approval screen, with only the node, the explorer and the DOM stubbed: a
@@ -278,21 +280,22 @@ beforeEach(() => {
mockNode.feeData = { maxFeePerGas: 1n, gasPrice: 1n }; mockNode.feeData = { maxFeePerGas: 1n, gasPrice: 1n };
}); });
describe("an ETH balance below 0.000001 never renders as zero", () => { describe("an ETH balance below 0.0001 reads 0.0000", () => {
test("on the Send screen", async () => { test("on the Send screen", async () => {
await refreshWith(HALF_MICRO_ETH); await refreshWith(HALF_MICRO_ETH);
state.selectedToken = "ETH"; state.selectedToken = "ETH";
send.updateSendBalance(); send.updateSendBalance();
expect(text("send-balance")).toBe("Current balance: 0.0000005 ETH"); expect(text("send-balance")).toBe("Current balance: 0.0000 ETH");
expect(state.wallets[0].addresses[0].balance).toBe("0.0000005");
}); });
test("on the confirmation screen", async () => { test("on the confirmation screen", async () => {
await refreshWith(HALF_MICRO_ETH); await refreshWith(HALF_MICRO_ETH);
await confirmSend("0.0000001"); await confirmSend("0.0000001");
expect(text("confirm-balance")).toBe("0.0000005 ETH"); expect(text("confirm-balance")).toBe("0.0000 ETH");
}); });
test("while a balance above the floor keeps four decimals", async () => { test("while a larger balance is cut to four decimals", async () => {
await refreshWith(1234567890000000000n); await refreshWith(1234567890000000000n);
await confirmSend("0.1"); await confirmSend("0.1");
expect(text("confirm-balance")).toBe("1.2345 ETH"); expect(text("confirm-balance")).toBe("1.2345 ETH");
@@ -302,7 +305,7 @@ describe("an ETH balance below 0.000001 never renders as zero", () => {
// A token the user tracks stays on the balance list when the explorer's row is // A token the user tracks stays on the balance list when the explorer's row is
// dropped, so a holding of it below 0.000001 reached these screens as zero, and // dropped, so a holding of it below 0.000001 reached these screens as zero, and
// the send was checked against zero. // the send was checked against zero.
describe("a tracked token holding below 0.000001 never renders as zero", () => { describe("a tracked token holding below 0.000001 reads 0.0000", () => {
beforeEach(() => { beforeEach(() => {
state.trackedTokens = [ state.trackedTokens = [
{ address: TOKEN, symbol: "TOK", name: "Token", decimals: 18 }, { address: TOKEN, symbol: "TOK", name: "Token", decimals: 18 },
@@ -313,13 +316,17 @@ describe("a tracked token holding below 0.000001 never renders as zero", () => {
await refreshWith(10n ** 18n, [tokenRow(HALF_MICRO_ETH)]); await refreshWith(10n ** 18n, [tokenRow(HALF_MICRO_ETH)]);
state.selectedToken = TOKEN; state.selectedToken = TOKEN;
send.updateSendBalance(); send.updateSendBalance();
expect(text("send-balance")).toBe("Current balance: 0.0000005 TOK"); expect(text("send-balance")).toBe("Current balance: 0.0000 TOK");
const stored = state.wallets[0].addresses[0].tokenBalances.find(
(t) => t.address === TOKEN,
);
expect(stored.balance).toBe("0.0000005");
}); });
test("on the confirmation screen, which checks the send against it", async () => { test("on the confirmation screen, which checks the send against it", async () => {
await refreshWith(10n ** 18n, [tokenRow(HALF_MICRO_ETH)]); await refreshWith(10n ** 18n, [tokenRow(HALF_MICRO_ETH)]);
await confirmSend("0.0000005", TOKEN); await confirmSend("0.0000005", TOKEN);
expect(text("confirm-balance")).toBe("0.0000005 TOK"); expect(text("confirm-balance")).toBe("0.0000 TOK");
expect(errors()).toBe(""); expect(errors()).toBe("");
expect(balanceError()).toBe(""); expect(balanceError()).toBe("");
await confirmSend("0.0000006", TOKEN); await confirmSend("0.0000006", TOKEN);
@@ -347,11 +354,9 @@ describe("a tracked token holding below 0.000001 never renders as zero", () => {
await refreshWith(10n ** 18n, [tokenRow(1n, { decimals: "24" })]); await refreshWith(10n ** 18n, [tokenRow(1n, { decimals: "24" })]);
state.selectedToken = TOKEN; state.selectedToken = TOKEN;
send.updateSendBalance(); send.updateSendBalance();
expect(text("send-balance")).toBe( expect(text("send-balance")).toBe("Current balance: 0.0000 TOK");
"Current balance: 0.000000000000000000000001 TOK",
);
await confirmSend("0.000000000000000001", TOKEN); await confirmSend("0.000000000000000001", TOKEN);
expect(text("confirm-balance")).toBe("0.000000000000000000000001 TOK"); expect(text("confirm-balance")).toBe("0.0000 TOK");
expect(balanceError()).toContain( expect(balanceError()).toContain(
"Your TOK balance does not cover this amount.", "Your TOK balance does not cover this amount.",
); );
@@ -363,20 +368,20 @@ describe("a tracked token holding below 0.000001 never renders as zero", () => {
// selected while its own screen is open: after sending 2 of a 2.0000003 // selected while its own screen is open: after sending 2 of a 2.0000003
// holding, the user is back on that screen, and Send read the missing row as // holding, the user is back on that screen, and Send read the missing row as
// zero. // zero.
describe("an untracked token holding below 0.000001 never renders as zero", () => { describe("an untracked token holding below 0.000001 reads 0.0000", () => {
const row = () => tokenRow(HALF_MICRO_ETH, { holders_count: "50000" }); const row = () => tokenRow(HALF_MICRO_ETH, { holders_count: "50000" });
test("on the Send screen", async () => { test("on the Send screen", async () => {
await refreshWith(10n ** 18n, [row()]); await refreshWith(10n ** 18n, [row()]);
state.selectedToken = TOKEN; state.selectedToken = TOKEN;
send.updateSendBalance(); send.updateSendBalance();
expect(text("send-balance")).toBe("Current balance: 0.0000005 TOK"); expect(text("send-balance")).toBe("Current balance: 0.0000 TOK");
}); });
test("on the confirmation screen, which checks the send against it", async () => { test("on the confirmation screen, which checks the send against it", async () => {
await refreshWith(10n ** 18n, [row()]); await refreshWith(10n ** 18n, [row()]);
await confirmSend("0.0000005", TOKEN); await confirmSend("0.0000005", TOKEN);
expect(text("confirm-balance")).toBe("0.0000005 TOK"); expect(text("confirm-balance")).toBe("0.0000 TOK");
expect(errors()).toBe(""); expect(errors()).toBe("");
expect(balanceError()).toBe(""); expect(balanceError()).toBe("");
await confirmSend("0.0000006", TOKEN); await confirmSend("0.0000006", TOKEN);
+101 -62
View File
@@ -1,15 +1,14 @@
// A transaction's time is written by isoDate() and timeAgo() in // A transaction's time shows the ISO datetime and the relative age on every
// src/popup/views/helpers.js on every screen that shows one (README, Amounts; // screen that shows one (README, Amounts). Home, AddressDetail and AddressToken
// https://git.eeqj.de/sneak/AutistMask/issues/168). AddressDetail and // used to show only the age, with the datetime as a tooltip
// AddressToken used to define their own copies, so a fix to the shared pair // (https://git.eeqj.de/sneak/AutistMask/issues/760).
// would not have reached them.
// //
// The pair is replaced before the views are loaded, because a view takes it // The views run against a minimal DOM stub, as in
// when it loads. A view that writes the time with a copy of its own shows the // tests/historyAfterNetworkSwitch.test.js, and over
// real time instead of the replacement. // tests/support/storageStub.js.
//
// Driven against a minimal DOM stub in the shape const { makeStorageStub } = require("./support/storageStub");
// tests/contractCreation.test.js uses. const { STATE_SCHEMA_VERSION } = require("../src/shared/stateSchema");
jest.mock("../src/shared/log", () => ({ jest.mock("../src/shared/log", () => ({
log: { log: {
@@ -26,33 +25,78 @@ jest.mock("../src/shared/log", () => ({
})); }));
// The history lists ask the explorer for their transactions and resolve ENS // The history lists ask the explorer for their transactions and resolve ENS
// names for them; here the explorer answers with mockHistory and no name // names for them; here the explorer answers with mockHistory() and no name
// resolves. // resolves.
let mockHistory = [];
jest.mock("../src/shared/transactions", () => ({ jest.mock("../src/shared/transactions", () => ({
...jest.requireActual("../src/shared/transactions"), ...jest.requireActual("../src/shared/transactions"),
fetchRecentTransactions: async () => mockHistory, fetchRecentTransactions: async () => mockHistory(),
})); }));
jest.mock("../src/shared/ens", () => ({ jest.mock("../src/shared/ens", () => ({
...jest.requireActual("../src/shared/ens"), ...jest.requireActual("../src/shared/ens"),
resolveEnsNames: async () => new Map(), resolveEnsNames: async () => new Map(),
})); }));
globalThis.chrome = { const { state, loadState } = require("../src/shared/state");
storage: { local: { get: async () => ({}), set: async () => {} } }, const home = require("../src/popup/views/home");
};
const helpers = require("../src/popup/views/helpers");
jest.spyOn(helpers, "isoDate").mockReturnValue("SHARED-ISO-DATE");
jest.spyOn(helpers, "timeAgo").mockReturnValue("SHARED-TIME-AGO");
const { state } = require("../src/shared/state");
const addressDetail = require("../src/popup/views/addressDetail"); const addressDetail = require("../src/popup/views/addressDetail");
const addressToken = require("../src/popup/views/addressToken"); const addressToken = require("../src/popup/views/addressToken");
const transactionDetail = require("../src/popup/views/transactionDetail"); const transactionDetail = require("../src/popup/views/transactionDetail");
const FROM = "0x0000000000000000000000000000000000000a11"; const FROM = "0x0000000000000000000000000000000000000a11";
const RECIPIENT = "0x66133E8ea0f5D1d612D2502a968757D1048c214a"; const RECIPIENT = "0x66133E8ea0f5D1d612D2502a968757D1048c214a";
const TIMESTAMP = 1790000000;
// TIMESTAMP as shown with "UTC Timestamps" on, three hours after it.
const SHOWN_TIME = "2026-09-21T14:13:20Z (3 hours ago)";
// A profile on Ethereum Mainnet with one address, "Use Blockscout" and "UTC
// Timestamps" on.
function profile() {
return {
schemaVersion: STATE_SCHEMA_VERSION,
hasWallet: true,
wallets: [
{
type: "hd",
name: "Main",
xpub: "xpub-main",
encryptedSecret: "encrypted-secret",
nextIndex: 1,
addresses: [
{ address: FROM, balance: "1.0", tokenBalances: [] },
],
},
],
activeAddress: FROM,
networkId: "mainnet",
rpcUrl: "https://ethereum-rpc.publicnode.com",
blockscoutUrl: "https://eth.blockscout.com/api/v2",
useBlockscout: true,
utcTimestamps: true,
};
}
// A transfer of ETH from FROM, as Blockscout answers it.
function mockHistory() {
return [
{
hash: "0x85215772ed26ea8b39c2b3b18779030487efbe0b5fd7e882592b2f62b837be84",
blockNumber: 1,
from: FROM,
to: RECIPIENT,
value: "0.0000",
exactValue: "0.0",
rawAmount: "0",
rawUnit: "wei",
symbol: "ETH",
timestamp: TIMESTAMP,
isError: false,
directionLabel: "Sent",
direction: "sent",
contractAddress: null,
chainId: "0x1",
},
];
}
function makeElement(id) { function makeElement(id) {
const el = { const el = {
@@ -90,6 +134,7 @@ function makeDocument() {
return els.get(id); return els.get(id);
}, },
createElement: () => makeElement("created"), createElement: () => makeElement("created"),
addEventListener: () => {},
body: { prepend: () => {} }, body: { prepend: () => {} },
}; };
} }
@@ -98,64 +143,58 @@ function node(id) {
return globalThis.document.getElementById(id); return globalThis.document.getElementById(id);
} }
// A transaction FROM sent, as the history lists hold it. // Lets every promise that is not held open settle.
function historyTx() { function settle() {
return { return new Promise((resolve) => setTimeout(resolve, 0));
hash: "0x85215772ed26ea8b39c2b3b18779030487efbe0b5fd7e882592b2f62b837be84",
from: FROM,
to: RECIPIENT,
value: "0.0000",
exactValue: "0.0",
rawAmount: "0",
rawUnit: "wei",
symbol: "ETH",
timestamp: 1790000000,
isError: false,
directionLabel: "Sent",
direction: "sent",
contractAddress: null,
};
} }
beforeEach(() => { beforeEach(async () => {
const storage = makeStorageStub({ autistmask: profile() });
globalThis.chrome = {
storage: { local: storage.local, onChanged: storage.onChanged },
};
globalThis.document = makeDocument(); globalThis.document = makeDocument();
globalThis.window = { location: { search: "" } }; globalThis.window = { location: { search: "" } };
state.wallets = [ jest.spyOn(Date, "now").mockReturnValue((TIMESTAMP + 3 * 3600) * 1000);
{ await loadState();
name: "Main",
type: "key",
addresses: [{ address: FROM, balance: "0.0000" }],
},
];
state.trackedTokens = [];
state.viewData = {};
state.viewStack = []; state.viewStack = [];
state.currentView = null;
state.selectedWallet = 0; state.selectedWallet = 0;
state.selectedAddress = 0; state.selectedAddress = 0;
state.selectedToken = "ETH"; state.selectedToken = "ETH";
// The history is Blockscout's. const ctx = { pageClosed: new AbortController().signal };
state.useBlockscout = true; addressDetail.init(ctx);
addressToken.init(ctx);
});
afterEach(() => {
jest.restoreAllMocks();
delete globalThis.chrome;
delete globalThis.document;
delete globalThis.window;
}); });
describe.each([ describe.each([
[
"Home",
"home-tx-list",
() => home.render({ pageClosed: new AbortController().signal }),
],
["AddressDetail", "tx-list", () => addressDetail.show()], ["AddressDetail", "tx-list", () => addressDetail.show()],
["AddressToken", "address-token-tx-list", () => addressToken.show()], ["AddressToken", "address-token-tx-list", () => addressToken.show()],
])("a transaction history row on %s", (_name, listId, open) => { ])("a transaction history row on %s", (_name, listId, open) => {
test("shows the time written by the shared isoDate() and timeAgo()", async () => { test("shows the ISO datetime and then the relative age", async () => {
mockHistory = [historyTx()];
open(); open();
// The list is drawn once the history has been fetched. // The list is drawn once the history has been fetched.
await new Promise((resolve) => setTimeout(resolve, 0)); for (let i = 0; i < 10; i++) await settle();
const html = node(listId).innerHTML; const html = node(listId).innerHTML;
expect(html).toContain('title="SHARED-ISO-DATE"'); expect(html).toContain(">" + SHOWN_TIME + "<");
expect(html).toContain(">SHARED-TIME-AGO<"); expect(html).not.toContain("title=");
}); });
}); });
test("the transaction detail view shows the time written by the shared isoDate() and timeAgo()", () => { test("the transaction detail view shows the ISO datetime, copyable, and then the relative age", () => {
transactionDetail.show(historyTx()); transactionDetail.show(mockHistory()[0]);
const html = node("tx-detail-time").innerHTML; const html = node("tx-detail-time").innerHTML;
expect(html).toContain("SHARED-ISO-DATE"); expect(html).toContain('data-copy="2026-09-21T14:13:20Z"');
expect(html).toContain("(SHARED-TIME-AGO)"); expect(html).toContain(">2026-09-21T14:13:20Z</span> (3 hours ago)");
}); });