Compare commits
6 Commits
issue-312-
...
a658fde62d
| Author | SHA1 | Date | |
|---|---|---|---|
| a658fde62d | |||
| 669c443bf9 | |||
| 12b0c4d1c6 | |||
| c36d8b6ddf | |||
| cef6aaab11 | |||
| 20e911059a |
18
Makefile
18
Makefile
@@ -60,19 +60,31 @@ hooks:
|
||||
# scrubbed from the build itself: with AUTISTMASK_DEBUG=1 exported, this target
|
||||
# compiles a debug bundle and then fails on it, loudly, rather than quietly
|
||||
# handing back something other than the release build that was asked for.
|
||||
#
|
||||
# Every step of this target is wrapped in script/discard-dist-on-failure, so a
|
||||
# release build that fails removes dist/ instead of leaving a complete, loadable
|
||||
# debug bundle there for whoever runs the build, sees it fail, and loads
|
||||
# dist/chrome/ anyway. A step that succeeds removes nothing, and build-debug is
|
||||
# deliberately not wrapped.
|
||||
build:
|
||||
@echo "Building extension..."
|
||||
@set -eu; \
|
||||
receipt="$$(mktemp "$${TMPDIR:-/tmp}/autistmask-build-receipt.XXXXXX")"; \
|
||||
trap 'rm -f "$$receipt"' EXIT INT TERM; \
|
||||
AUTISTMASK_BUILD_RECEIPT="$$receipt" yarn run build 2>&1; \
|
||||
env -u AUTISTMASK_DEBUG script/verify-build --expect release \
|
||||
script/discard-dist-on-failure \
|
||||
env AUTISTMASK_BUILD_RECEIPT="$$receipt" yarn run build 2>&1; \
|
||||
script/discard-dist-on-failure \
|
||||
env -u AUTISTMASK_DEBUG script/verify-build --expect release \
|
||||
--receipt "$$receipt"
|
||||
@script/check-censored --require-dist
|
||||
@script/discard-dist-on-failure script/check-censored --require-dist
|
||||
|
||||
# Development-only build: enables the red DEBUG / INSECURE banner and makes
|
||||
# the hardcoded test recovery phrase the output of wallet creation. Never
|
||||
# distribute the artifacts this produces.
|
||||
#
|
||||
# No discard-dist-on-failure here, on purpose: a debug build that fails is not
|
||||
# producing an artifact anyone could mistake for a release one, and its dist/ is
|
||||
# the evidence of what went wrong.
|
||||
build-debug:
|
||||
@echo "Building extension (DEBUG)..."
|
||||
@set -eu; \
|
||||
|
||||
114
README.md
114
README.md
@@ -63,8 +63,12 @@ that runs `make build`, that target compiles a debug bundle and then **fails**,
|
||||
because it tells `script/verify-build` in so many words that it was supposed to
|
||||
produce a release build. It used to be that the verifier read the same variable
|
||||
out of its own environment, agreed with itself, and reported a debug artifact as
|
||||
verified. The build prints which mode it used. See the
|
||||
[DEBUG Mode Policy](#debug-mode-policy) for what the flag changes. **Never
|
||||
verified. The build prints which mode it used. A release build that fails also
|
||||
**removes `dist/`**, and says so: the bundle it had already written is loadable,
|
||||
and a loud failure is no protection against someone loading `dist/chrome/`
|
||||
anyway. `make build-debug` keeps its `dist/` on failure — that output is not
|
||||
mistakable for a release build, and it is the evidence of what went wrong. See
|
||||
the [DEBUG Mode Policy](#debug-mode-policy) for what the flag changes. **Never
|
||||
distribute a debug build** — every wallet it creates gets the same publicly
|
||||
known test recovery phrase.
|
||||
|
||||
@@ -81,17 +85,21 @@ lives.
|
||||
one of the bundles containing `src/shared/constants.js` — into a build receipt,
|
||||
and `script/verify-build` checks `dist/` against that receipt: every recorded
|
||||
file present with exactly the recorded bytes, every audited bundle carrying the
|
||||
requested `DEBUG` marker, and nothing under `dist/` that the build did not
|
||||
write. The `Makefile` creates the receipt path with `mktemp` per invocation,
|
||||
outside the repo, and deletes it afterwards.
|
||||
requested `DEBUG` marker, and no regular file or symlink under `dist/` that the
|
||||
build did not write. The `Makefile` creates the receipt path with `mktemp` per
|
||||
invocation, outside the repo, and deletes it afterwards.
|
||||
|
||||
That is what ties the check to a build rather than to a directory. What it
|
||||
establishes is narrow and worth stating exactly: `dist/` is byte for byte the
|
||||
output of the `build.js` run that just finished, with nothing added, removed or
|
||||
altered in between. It establishes nothing about whether the source tree or
|
||||
`build.js` were honest, and it offers nothing to someone handed a `dist/` from
|
||||
elsewhere — without the receipt from its own build there is no input to the
|
||||
check. Verifiable provenance for a third party is signing, which this is not.
|
||||
output of the `build.js` run that just finished, with no regular file or symlink
|
||||
added, removed or altered in between. Regular files and symlinks are the whole
|
||||
of what the tree walk covers; fifos, sockets, device nodes and empty directories
|
||||
under `dist/` are not checked, because a build emits none of them, none can
|
||||
carry a shippable payload, and `grep` on a fifo would hang rather than fail. It
|
||||
establishes nothing about whether the source tree or `build.js` were honest, and
|
||||
it offers nothing to someone handed a `dist/` from elsewhere — without the
|
||||
receipt from its own build there is no input to the check. Verifiable provenance
|
||||
for a third party is signing, which this is not.
|
||||
|
||||
There is deliberately no target that re-verifies an existing `dist/` on its own.
|
||||
The list of files to check has to come from the build that produced them; read
|
||||
@@ -143,26 +151,35 @@ provide:
|
||||
serves. Run deliberately, never as part of a build: the output is committed
|
||||
and there is no runtime fetch, so the shipped list is as fresh as the last
|
||||
vendoring run that was released
|
||||
- `script/verify-build --expect release|debug --receipt PATH` — assert that
|
||||
`dist/` is exactly what the build that just ran emitted, and that the compiled
|
||||
`DEBUG` state of the bundles in it is the one that was asked for. Both
|
||||
arguments are required and neither has a default: the expected mode is stated
|
||||
by the caller rather than read from `AUTISTMASK_DEBUG`, and the file list
|
||||
comes from the build's receipt rather than from `dist/` (see
|
||||
- `script/verify-build --expect release|debug --receipt PATH` — assert that the
|
||||
regular files and symlinks under `dist/` are exactly what the build that just
|
||||
ran emitted (other file types are out of scope), and that the compiled `DEBUG`
|
||||
state of the bundles in it is the one that was asked for. Both arguments are
|
||||
required and neither has a default: the expected mode is stated by the caller
|
||||
rather than read from `AUTISTMASK_DEBUG`, and the file list comes from the
|
||||
build's receipt rather than from `dist/` (see
|
||||
[Build Receipts](#build-receipts)). Run automatically at the end of
|
||||
`make build` and `make build-debug`; fails loudly rather than passing whenever
|
||||
it cannot determine something. Not part of `make check`, which does not depend
|
||||
on build artifacts existing.
|
||||
- `script/discard-dist-on-failure COMMAND [ARG...]` — run one step of the
|
||||
**release** build and, if it fails, remove `dist/` before returning that
|
||||
step's exit status, saying on stderr that it did and why. Every step of
|
||||
`make build` runs through it; `make build-debug` runs none of them through it.
|
||||
A step that succeeds removes nothing, and a removal that cannot be completed
|
||||
is reported as loudly as one that was
|
||||
- `script/test-verify-build` — exercise every failure mode of
|
||||
`script/verify-build` against a fixture tree in a temp dir, asserting the exit
|
||||
status and the message of each, and read the `make build` and
|
||||
status and the message of each, assert the state of `dist/` on disk after a
|
||||
failing and a succeeding release build step, and read the `make build` and
|
||||
`make build-debug` recipes back out of `make -n` to check that they pass the
|
||||
mode as an argument on a scrubbed environment. Part of `make check`; it reads
|
||||
no build artifacts and writes nothing under `dist/`. The cases that depend on
|
||||
file permissions cannot mean anything for a process that is not subject to
|
||||
them, so the harness proves its runner against a mode-000 file before counting
|
||||
them, dropping to an unprivileged user when run as root; if it cannot, it
|
||||
skips those cases and says so in a banner rather than passing them.
|
||||
mode as an argument on a scrubbed environment and wrap only the release path.
|
||||
Part of `make check`; it reads no build artifacts and writes nothing under
|
||||
`dist/`. The cases that depend on file permissions cannot mean anything for a
|
||||
process that is not subject to them, so the harness proves its runner against
|
||||
a mode-000 file before counting them, dropping to an unprivileged user when
|
||||
run as root; if it cannot, it skips those cases and says so in a banner rather
|
||||
than passing them.
|
||||
- `script/docker` — build the Docker image tagged via `script/projectname`
|
||||
- `script/cibuild` — CI entrypoint: plain `docker build .`
|
||||
- `script/precommit` — run by the git pre-commit hook; runs `script/check`
|
||||
@@ -176,9 +193,11 @@ The Makefile shims to those. It also carries a few targets that have no
|
||||
silently rewritten. Use `make setup` for a fresh clone.
|
||||
- `make hooks` — shims to `script/install-precommit`
|
||||
- `make build` — build the extension into `dist/chrome/` and `dist/firefox/`,
|
||||
then verify the result against the build's receipt as a release build
|
||||
then verify the result against the build's receipt as a release build. A
|
||||
failure at any step removes `dist/`
|
||||
- `make build-debug` — the same build with `AUTISTMASK_DEBUG=1`, verified as a
|
||||
debug build (see [Debug Builds](#debug-builds))
|
||||
debug build, and keeping its `dist/` on failure (see
|
||||
[Debug Builds](#debug-builds))
|
||||
- `make clean` — remove `dist/`
|
||||
- `make dev` — build in watch mode
|
||||
|
||||
@@ -689,6 +708,51 @@ Both are click-copyable. Truncating to 4 decimals in summary views is acceptable
|
||||
for scannability, but the detail view must never discard precision — it is the
|
||||
one place the user can always use to verify exact details.
|
||||
|
||||
**Specific Exception — nonzero floor on the approval screens:** A nonzero amount
|
||||
must never render as zero. Truncating to 4 decimals does exactly that to an
|
||||
amount below 0.0001 — 1 base unit of an 18-decimal token, 500 base units of an
|
||||
8-decimal one — and on the dApp approval screen and the wait/success/error
|
||||
screens that carry its amount forward, a real transfer or allowance then reads
|
||||
as "nothing is being moved". A swap's `Min. received` is the sharper case: a
|
||||
slippage floor shown as `0.0000` states that the swap may return nothing.
|
||||
|
||||
On those screens, when the truncated string would contain no digit from 1 to 9
|
||||
and the value does, the amount is extended to its first significant digit
|
||||
instead: `0.000000000000000001 DAI`, not `0.0000 DAI`. The test is on the whole
|
||||
truncated string, integer part included, so `1.00005` still shows as `1.0000` —
|
||||
the exception only fires where the entire displayed figure would read as zero. A
|
||||
genuine zero still renders `0.0000`, and truncation stays truncation: `0.99999`
|
||||
shows as `0.9999`, never rounded up.
|
||||
|
||||
The rule and its exception live in `src/shared/amountDisplay.js` as
|
||||
`truncateAmount()` and `truncateAmountNeverZero()`. Everything the approval and
|
||||
confirmation screens display goes through the floored one — the ERC-20 amount,
|
||||
the ETH value and max fee (`src/popup/views/approval.js`), and the swap's
|
||||
`Amount` and `Min. received` lines (`src/shared/uniswap.js`). The history and
|
||||
balance lists (`src/shared/transactions.js`) use the unfloored one: the
|
||||
transaction detail view is the authoritative record and already shows exact
|
||||
precision. The 4-decimal rule is unchanged everywhere else, including for
|
||||
amounts at or above the floor on the approval screens.
|
||||
|
||||
The floor applies only where the token's scale is known. Where it is not, the
|
||||
approval screen states base units instead of a quantity — see Unknown token
|
||||
scale below — and no truncation happens at all.
|
||||
|
||||
**Specific Exception — unknown token scale:** Calldata carries base units and no
|
||||
scale, so every amount on the dApp approval screen needs the token's `decimals`.
|
||||
It is resolved from the bundled token list, then from the tokens the user
|
||||
tracks, then from what the block explorer reported for the contract
|
||||
(`resolveTokenDecimals()` in `src/shared/approvalAmount.js`). Where none of them
|
||||
answers, the amount is not formatted: the line reads
|
||||
`5000000000 base units (decimals unknown)`. A guessed scale is not an
|
||||
approximation but a different number — 1,000 units of a 6-decimal token
|
||||
formatted at 18 decimals reads `0.000000001` — on the screen whose only job is
|
||||
to state what is being authorized. Both amount paths of that screen take this
|
||||
rule: the ERC-20 `transfer`/`approve` line (`src/popup/views/approval.js`) and
|
||||
the swap's `Amount` and `Min. received` lines (`src/shared/uniswap.js`). An
|
||||
unbounded allowance or permit needs no scale to describe and is still shown as
|
||||
`Unlimited`.
|
||||
|
||||
#### Partial USD totals
|
||||
|
||||
Prices are fetched for the top 25 tokens only, so an address can hold assets the
|
||||
|
||||
82
TODO.md
82
TODO.md
@@ -26,7 +26,8 @@ milestone is in flight on `next`; its `next` -> `main` PR is
|
||||
[#190](https://git.eeqj.de/sneak/AutistMask/pulls/190). `make check` verified
|
||||
green on `next` at `e9fa8be` on 2026-08-10, and `make build` produces
|
||||
`dist/chrome/` and `dist/firefox/`, verified against the build's own receipt to
|
||||
be exactly what that build emitted with `DEBUG` compiled off.
|
||||
hold exactly the regular files and symlinks that build emitted, with `DEBUG`
|
||||
compiled off.
|
||||
|
||||
The backlog lives on the
|
||||
[Gitea tracker](https://git.eeqj.de/sneak/AutistMask/issues), which is
|
||||
@@ -44,6 +45,85 @@ but the review is broader than any of them.
|
||||
|
||||
# Completed Steps
|
||||
|
||||
- 2026-08-23: The swap approval screen no longer guesses 18 decimals for a token
|
||||
outside the bundled list
|
||||
([#340](https://git.eeqj.de/sneak/AutistMask/issues/340)). `tokenInfo()` in
|
||||
`src/shared/uniswap.js` returned `decimals: 18` for any such token — the same
|
||||
assumption [#306](https://git.eeqj.de/sneak/AutistMask/issues/306) removed
|
||||
from the ERC-20 amount line — so a 1,000-unit swap of a 6-decimal token was
|
||||
stated as `0.000000001`, and every newly listed token reached it. The swap's
|
||||
`Amount` and `Min. received` lines now resolve the scale through
|
||||
`resolveTokenDecimals()`, the same bundled-list-then-tracked-then-explorer
|
||||
order the ERC-20 line uses, and where nothing knows it they render
|
||||
`unknownDecimalsAmount()` — base units with the scale stated — instead of a
|
||||
number. No new data source and no network call: the scale comes only from what
|
||||
the wallet already holds. An unbounded permit is still shown as `Unlimited`.
|
||||
`README.md` records the rule as a Display Consistency exception.
|
||||
- 2026-08-23: A failed release build no longer leaves a loadable debug bundle in
|
||||
`dist/` ([#333](https://git.eeqj.de/sneak/AutistMask/issues/333)). With
|
||||
`AUTISTMASK_DEBUG=1` exported, `make build` compiled a debug bundle and failed
|
||||
on it in `script/verify-build` — but the bundle stayed on disk, loadable, with
|
||||
every wallet it creates using the publicly committed test recovery phrase.
|
||||
Every step of `make build` now runs through `script/discard-dist-on-failure`,
|
||||
which removes `dist/` when a step fails and says on stderr that it did and
|
||||
why; a removal it cannot complete is reported just as loudly.
|
||||
`make build-debug` is deliberately not wrapped: its output is not mistakable
|
||||
for a release build and is the evidence of the failure.
|
||||
`script/test-verify-build` asserts the state of `dist/` on disk after a
|
||||
failing and a succeeding step, not just the exit status, and reads `make -n`
|
||||
to check the wrapper is on the release path and only there.
|
||||
- 2026-08-23: `README.md` and `script/verify-build`'s own comments now state the
|
||||
emitted-tree guarantee at the width the code actually enforces
|
||||
([#331](https://git.eeqj.de/sneak/AutistMask/issues/331)). The tree walk is
|
||||
`-type f -o -type l`, so the guarantee covers regular files and symlinks under
|
||||
`dist/`; fifos, sockets, device nodes and empty directories are not checked,
|
||||
because a build emits none of them, none can carry a shippable payload, and
|
||||
`grep` on a fifo would hang rather than fail. The exclusion is deliberate and
|
||||
unchanged — the README said "nothing under `dist/` that the build did not
|
||||
write", which was broader than that. Documentation only; no executable line
|
||||
changed.
|
||||
- 2026-08-23: An amount below the 4-decimal display floor no longer reads as
|
||||
zero on the approval screens
|
||||
([#322](https://git.eeqj.de/sneak/AutistMask/issues/322)). With the token's
|
||||
true scale resolved, the 4-decimal truncation still printed a small amount as
|
||||
`0.0000` — 1 base unit of an 18-decimal token, 500 of an 8-decimal one — so a
|
||||
real transfer, allowance or swap was stated as nothing on the one screen whose
|
||||
job is to say what is being authorized, and a swap's `Min. received` claimed
|
||||
the user might receive nothing. Three copies of that truncation existed; they
|
||||
now share `src/shared/amountDisplay.js`. Everything the approval and
|
||||
confirmation screens render (`src/popup/views/approval.js`,
|
||||
`src/shared/uniswap.js`) extends to the first significant digit when the
|
||||
truncated figure would otherwise read as zero, keeping the amount in token
|
||||
units rather than switching to base units mid-line. The history and balance
|
||||
lists (`src/shared/transactions.js`) keep the unfloored rule, which is out of
|
||||
scope by the issue's definition of done. `README.md`'s Display Consistency
|
||||
section records the exception.
|
||||
- 2026-08-20: A second extension page can no longer silently delete a wallet
|
||||
([#304](https://git.eeqj.de/sneak/AutistMask/issues/304)). `saveState()` wrote
|
||||
the entire state blob, and every extension page — the toolbar popup, a dApp
|
||||
approval window, `backgroundRefresh()` — holds its own in-memory `state`,
|
||||
loaded once, with `showView()` saving on every navigation; a second page that
|
||||
saved after a first had written something new overwrote it, no attacker or
|
||||
unusual input required. `saveState()` is now a read-modify-write: it re-reads
|
||||
storage, diffs the persisted fields against a deep-cloned `baseline` snapshot
|
||||
taken at the last `loadState()`/`saveState()` on that page, and writes only
|
||||
the fields that actually changed — everything else is carried forward from
|
||||
storage in its loaded-and-normalized shape (`normalizePersisted()`, shared
|
||||
with `loadState()`), so a legacy or malformed record a load has always
|
||||
self-healed in memory keeps getting written back even on a save that touched
|
||||
something else entirely. `showView()` fires `saveState()` on every navigation
|
||||
without awaiting it, so two saves from the same page can be in flight at once;
|
||||
a FIFO queue serializes them rather than letting a slow one finish after a
|
||||
later one and re-derive a stale answer. Deliberately not done: the live
|
||||
`state` of a field this page does not own is not rehydrated from what another
|
||||
page wrote, only the persisted record is — adopting a concurrently-written
|
||||
value into `state` reintroduced the same clobber one page later, caught by
|
||||
`tests/txStatus.test.js` red. Two writers of the same field still resolve
|
||||
last-writer-wins, documented at the merge point. `tests/stateMerge.test.js`
|
||||
covers the two-page save and the approval-window reproduction from the issue —
|
||||
add a wallet in one page, force a save from a second page loaded before it,
|
||||
both wallets survive — each demonstrated failing against the unfixed full-blob
|
||||
write.
|
||||
- 2026-08-20: A forgotten password no longer wedges the wallet
|
||||
([#312](https://git.eeqj.de/sneak/AutistMask/issues/312)). Deleting a wallet
|
||||
was password-gated and importing its recovery phrase again was refused as a
|
||||
|
||||
78
script/discard-dist-on-failure
Executable file
78
script/discard-dist-on-failure
Executable file
@@ -0,0 +1,78 @@
|
||||
#!/bin/sh
|
||||
# script/discard-dist-on-failure: run one step of the RELEASE build, and if that
|
||||
# step fails, remove dist/ before returning its exit status. Our own extension
|
||||
# to scripts-to-rule-them-all, wrapped around every step of make build.
|
||||
#
|
||||
# Why: with AUTISTMASK_DEBUG=1 exported in the calling shell, make build
|
||||
# compiles a debug bundle and then fails on it in script/verify-build — but the
|
||||
# bundle is already written. It is loadable, and every wallet it creates gets
|
||||
# the publicly committed test recovery phrase from src/shared/constants.js. A
|
||||
# failed release build that leaves that behind is a smaller version of the trap
|
||||
# the verifier exists to close, and "the failure was loud" only works on an
|
||||
# operator who does not load dist/chrome/ anyway. Removing the artifact does not
|
||||
# depend on that.
|
||||
#
|
||||
# Two things this deliberately does not do. It does not wrap make build-debug: a
|
||||
# debug build that failed is not a mistakable artifact, and its output is the
|
||||
# evidence of what went wrong. And it never removes anything on a step that
|
||||
# SUCCEEDS, including the final check-censored --require-dist pass.
|
||||
#
|
||||
# The removal is never silent: it says dist/ is gone and why, on stderr, above
|
||||
# the build's own failure.
|
||||
set -eu
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||
DIST="$ROOT/dist"
|
||||
|
||||
usage() {
|
||||
echo "usage: discard-dist-on-failure COMMAND [ARG...]" >&2
|
||||
}
|
||||
|
||||
# Remove dist/, and say so. A removal that could not be completed is reported as
|
||||
# loudly as one that was: the artifact is still on disk, and reporting nothing
|
||||
# would leave the operator believing it is not.
|
||||
discard_dist() {
|
||||
if [ ! -e "$DIST" ] && [ ! -h "$DIST" ]; then
|
||||
echo "discard-dist-on-failure: the release build failed. There was no" \
|
||||
"dist/ to remove." >&2
|
||||
return 0
|
||||
fi
|
||||
|
||||
rm -rf "$DIST" || true
|
||||
|
||||
if [ -e "$DIST" ] || [ -h "$DIST" ]; then
|
||||
echo "discard-dist-on-failure: the release build failed and dist/" \
|
||||
"COULD NOT BE REMOVED, so it is still on disk. Do not load it:" \
|
||||
"a release build that failed may hold a complete debug bundle," \
|
||||
"whose wallets all use the publicly committed test recovery" \
|
||||
"phrase. Remove it by hand (make clean)." >&2
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "discard-dist-on-failure: the release build failed, so dist/ WAS" \
|
||||
"REMOVED and no longer exists. A release build that fails has often" \
|
||||
"already emitted a complete, loadable debug bundle — every wallet it" \
|
||||
"creates gets the publicly committed test recovery phrase — so the" \
|
||||
"failed build is not left behind to be loaded. Fix the failure and" \
|
||||
"re-run make build, or run make build-debug if a debug build is what" \
|
||||
"was wanted; that target keeps its output." >&2
|
||||
}
|
||||
|
||||
main() {
|
||||
[ "$#" -ge 1 ] || {
|
||||
usage
|
||||
echo "discard-dist-on-failure: no command given, so no build step ran" \
|
||||
"and nothing was removed." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
_status=0
|
||||
"$@" || _status=$?
|
||||
|
||||
[ "$_status" -ne 0 ] || return 0
|
||||
|
||||
discard_dist
|
||||
exit "$_status"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/bin/sh
|
||||
# script/test-verify-build: exercise every failure mode of
|
||||
# script/verify-build. Our own extension to scripts-to-rule-them-all, run
|
||||
# from script/check so make check covers it.
|
||||
# script/verify-build, and what make build does with dist/ after one of them
|
||||
# (script/discard-dist-on-failure). Our own extension to
|
||||
# scripts-to-rule-them-all, run from script/check so make check covers it.
|
||||
#
|
||||
# Why this exists: verify-build is the build-integrity guard, and four separate
|
||||
# reviews of it each found a fresh vacuous pass — the grep exit-2 conflation,
|
||||
@@ -31,6 +32,7 @@ set -eu
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||
VERIFY_BUILD="$ROOT/script/verify-build"
|
||||
DISCARD_DIST="$ROOT/script/discard-dist-on-failure"
|
||||
|
||||
MARKER_ON="autistmask-build-debug=on"
|
||||
MARKER_OFF="autistmask-build-debug=off"
|
||||
@@ -150,6 +152,7 @@ build_fixture() {
|
||||
|
||||
mkdir -p "$FIXTURE/script"
|
||||
ln -s "$VERIFY_BUILD" "$FIXTURE/script/verify-build"
|
||||
ln -s "$DISCARD_DIST" "$FIXTURE/script/discard-dist-on-failure"
|
||||
|
||||
mkdir -p "$FIXTURE/dist/chrome/src/popup" \
|
||||
"$FIXTURE/dist/chrome/src/content" \
|
||||
@@ -513,12 +516,125 @@ c_debug_build() {
|
||||
write_receipt
|
||||
}
|
||||
|
||||
c_no_dist() { rm -rf dist; }
|
||||
|
||||
# --- dist discard -----------------------------------------------------------
|
||||
#
|
||||
# make build wraps every step of the release path in
|
||||
# script/discard-dist-on-failure, so a release build that fails removes dist/:
|
||||
# with AUTISTMASK_DEBUG=1 exported it has already emitted a complete, loadable
|
||||
# debug bundle whose every wallet uses the publicly committed test recovery
|
||||
# phrase, and a loud failure alone does not stop someone loading dist/chrome/
|
||||
# anyway. make build-debug is deliberately not wrapped.
|
||||
#
|
||||
# Both directions are asserted against the state of dist/ ON DISK after the run,
|
||||
# not against the exit status: a case reading only the status would keep passing
|
||||
# if the removal quietly stopped happening, which is the flip this exists to
|
||||
# catch. The wrapper runs against the fixture — its ROOT is the fixture, via the
|
||||
# symlink in the fixture's script/ — with trivial commands standing in for the
|
||||
# build steps, because what is under test is what happens after a step says no,
|
||||
# not the step.
|
||||
|
||||
# discard_case <name> <setup> <status> <gone|kept> <want> <unwanted> [cmd...]
|
||||
discard_case() {
|
||||
_dc_name="$1"
|
||||
_dc_setup="$2"
|
||||
_dc_want_status="$3"
|
||||
_dc_want_dist="$4"
|
||||
_dc_want="$5"
|
||||
_dc_unwanted="$6"
|
||||
shift 6
|
||||
|
||||
build_fixture
|
||||
if ! (cd "$FIXTURE" && "$_dc_setup") >/dev/null 2>&1; then
|
||||
FAILED=$((FAILED + 1))
|
||||
echo " FAIL: $_dc_name"
|
||||
echo " the case's own setup failed, so nothing was tested."
|
||||
return 0
|
||||
fi
|
||||
|
||||
_dc_status=0
|
||||
_dc_out="$(cd "$FIXTURE" &&
|
||||
"$FIXTURE/script/discard-dist-on-failure" "$@" 2>&1)" || _dc_status=$?
|
||||
|
||||
_ok=yes
|
||||
_why=""
|
||||
|
||||
if [ "$_dc_status" -ne "$_dc_want_status" ]; then
|
||||
_ok=no
|
||||
_why="exit status $_dc_status, wanted $_dc_want_status"
|
||||
fi
|
||||
|
||||
# The assertion this case exists for: what is on disk now.
|
||||
if [ -e "$FIXTURE/dist" ] || [ -h "$FIXTURE/dist" ]; then
|
||||
_dc_dist=kept
|
||||
else
|
||||
_dc_dist=gone
|
||||
fi
|
||||
if [ "$_dc_dist" != "$_dc_want_dist" ]; then
|
||||
_ok=no
|
||||
_why="${_why:+$_why; }dist/ is $_dc_dist after the run, wanted"
|
||||
_why="$_why $_dc_want_dist"
|
||||
elif [ "$_dc_want_dist" = kept ] &&
|
||||
[ ! -f "$FIXTURE/dist/chrome/src/popup/index.js" ]; then
|
||||
# Kept has to mean intact: a dist/ emptied out is not one left alone.
|
||||
_ok=no
|
||||
_why="${_why:+$_why; }dist/ survived but its emitted bundle did not"
|
||||
fi
|
||||
|
||||
_dc_check_message "$_dc_want" want
|
||||
_dc_check_message "$_dc_unwanted" unwanted
|
||||
|
||||
if [ "$_ok" = yes ]; then
|
||||
PASSED=$((PASSED + 1))
|
||||
echo " ok: $_dc_name"
|
||||
return 0
|
||||
fi
|
||||
|
||||
FAILED=$((FAILED + 1))
|
||||
echo " FAIL: $_dc_name"
|
||||
echo " $_why"
|
||||
echo " --- discard-dist-on-failure output ---"
|
||||
printf '%s\n' "$_dc_out" | sed 's/^/ /'
|
||||
echo " --- end output ---"
|
||||
}
|
||||
|
||||
# Require ($2 = want) or forbid ($2 = unwanted) a substring in the wrapper's
|
||||
# output, updating _ok and _why. An empty substring asserts nothing. Same grep
|
||||
# discipline as everywhere else here: 0 and 1 are answers, anything else means
|
||||
# the message was never checked.
|
||||
_dc_check_message() {
|
||||
[ -n "$1" ] || return 0
|
||||
|
||||
_dcm_g=0
|
||||
printf '%s\n' "$_dc_out" | grep -q -F -e "$1" || _dcm_g=$?
|
||||
case "$_dcm_g" in
|
||||
0)
|
||||
[ "$2" = unwanted ] || return 0
|
||||
_ok=no
|
||||
_why="${_why:+$_why; }message contained: $1"
|
||||
;;
|
||||
1)
|
||||
[ "$2" = want ] || return 0
|
||||
_ok=no
|
||||
_why="${_why:+$_why; }message did not contain: $1"
|
||||
;;
|
||||
*)
|
||||
_ok=no
|
||||
_why="${_why:+$_why; }grep exited $_dcm_g matching the message, so the
|
||||
message was never checked"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# --- Makefile wiring --------------------------------------------------------
|
||||
|
||||
# The verifier cases above prove what verify-build does when it is told what to
|
||||
# expect. This proves the Makefile tells it — with the mode as an argument, on
|
||||
# a scrubbed environment, and identically whether or not AUTISTMASK_DEBUG is
|
||||
# exported in the shell that ran make. Read off `make -n`, so no build runs.
|
||||
# expect, and the discard cases prove what the wrapper does with dist/. This
|
||||
# proves the Makefile wires both up — the mode as an argument, on a scrubbed
|
||||
# environment, identically whether or not AUTISTMASK_DEBUG is exported in the
|
||||
# shell that ran make, and the wrapper on the release path only. Read off
|
||||
# `make -n`, so no build runs.
|
||||
check_makefile_wiring() {
|
||||
if ! command -v make >/dev/null 2>&1; then
|
||||
SKIPPED=$((SKIPPED + 1))
|
||||
@@ -537,6 +653,34 @@ check_makefile_wiring() {
|
||||
build-debug "verify-build --expect debug"
|
||||
_wiring_case "make build-debug scrubs AUTISTMASK_DEBUG for the verifier" \
|
||||
build-debug "env -u AUTISTMASK_DEBUG"
|
||||
|
||||
# The release path runs its steps through the wrapper, including the final
|
||||
# check-censored pass; the debug path runs none of them through it, which is
|
||||
# what keeps a failed debug build's dist/ on disk.
|
||||
_wiring_case "make build wraps its steps in discard-dist-on-failure" \
|
||||
build "script/discard-dist-on-failure"
|
||||
_wiring_case "make build wraps check-censored --require-dist too" \
|
||||
build "script/discard-dist-on-failure script/check-censored"
|
||||
_wiring_case_absent "make build-debug never discards its dist/" \
|
||||
build-debug "discard-dist-on-failure"
|
||||
}
|
||||
|
||||
# Run `make -n TARGET` with AUTISTMASK_DEBUG=1 exported, into _wc_out. Returns
|
||||
# non-zero, having already reported the failure, when make itself failed: a
|
||||
# recipe that could not be printed was never checked.
|
||||
_wiring_make_n() {
|
||||
AUTISTMASK_DEBUG=1
|
||||
export AUTISTMASK_DEBUG
|
||||
_wc_status=0
|
||||
_wc_out="$(cd "$ROOT" && make -n "$_wc_target" 2>&1)" || _wc_status=$?
|
||||
unset AUTISTMASK_DEBUG
|
||||
|
||||
[ "$_wc_status" -ne 0 ] || return 0
|
||||
|
||||
FAILED=$((FAILED + 1))
|
||||
echo " FAIL: $_wc_name"
|
||||
echo " make -n $_wc_target exited $_wc_status"
|
||||
return 1
|
||||
}
|
||||
|
||||
_wiring_case() {
|
||||
@@ -544,18 +688,7 @@ _wiring_case() {
|
||||
_wc_target="$2"
|
||||
_wc_want="$3"
|
||||
|
||||
AUTISTMASK_DEBUG=1
|
||||
export AUTISTMASK_DEBUG
|
||||
_wc_status=0
|
||||
_wc_out="$(cd "$ROOT" && make -n "$_wc_target" 2>&1)" || _wc_status=$?
|
||||
unset AUTISTMASK_DEBUG
|
||||
|
||||
if [ "$_wc_status" -ne 0 ]; then
|
||||
FAILED=$((FAILED + 1))
|
||||
echo " FAIL: $_wc_name"
|
||||
echo " make -n $_wc_target exited $_wc_status"
|
||||
return 0
|
||||
fi
|
||||
_wiring_make_n || return 0
|
||||
|
||||
_wc_g=0
|
||||
printf '%s\n' "$_wc_out" | grep -q -F -e "$_wc_want" || _wc_g=$?
|
||||
@@ -577,6 +710,34 @@ _wiring_case() {
|
||||
esac
|
||||
}
|
||||
|
||||
# The inverse: the recipe must NOT run something.
|
||||
_wiring_case_absent() {
|
||||
_wc_name="$1"
|
||||
_wc_target="$2"
|
||||
_wc_want="$3"
|
||||
|
||||
_wiring_make_n || return 0
|
||||
|
||||
_wc_g=0
|
||||
printf '%s\n' "$_wc_out" | grep -q -F -e "$_wc_want" || _wc_g=$?
|
||||
case "$_wc_g" in
|
||||
1)
|
||||
PASSED=$((PASSED + 1))
|
||||
echo " ok: $_wc_name"
|
||||
;;
|
||||
0)
|
||||
FAILED=$((FAILED + 1))
|
||||
echo " FAIL: $_wc_name"
|
||||
echo " make -n $_wc_target runs: $_wc_want"
|
||||
;;
|
||||
*)
|
||||
FAILED=$((FAILED + 1))
|
||||
echo " FAIL: $_wc_name"
|
||||
echo " grep exited $_wc_g, so the recipe was never checked"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
run_cases() {
|
||||
check_case "control: untouched dist passes" \
|
||||
no release 0 "2 bundle(s) $MARKER_OFF" c_control
|
||||
@@ -712,6 +873,18 @@ run_cases() {
|
||||
no release 1 "carries a debug marker but the build did not" \
|
||||
c_marker_on_plain_file
|
||||
|
||||
discard_case "a failed release build step removes dist/" \
|
||||
c_control 3 gone "dist/ WAS REMOVED" "" sh -c 'exit 3'
|
||||
|
||||
discard_case "a successful release build step leaves dist/ alone" \
|
||||
c_control 0 kept "" "REMOVED" true
|
||||
|
||||
discard_case "a failed release build step with no dist/ says there was none" \
|
||||
c_no_dist 3 gone "There was no dist/ to remove" "" sh -c 'exit 3'
|
||||
|
||||
discard_case "the wrapper given no command removes nothing" \
|
||||
c_control 1 kept "no command given" ""
|
||||
|
||||
check_makefile_wiring
|
||||
}
|
||||
|
||||
@@ -740,6 +913,10 @@ main() {
|
||||
echo "test-verify-build: $VERIFY_BUILD is missing or not executable" >&2
|
||||
exit 1
|
||||
}
|
||||
[ -x "$DISCARD_DIST" ] || {
|
||||
echo "test-verify-build: $DISCARD_DIST is missing or not executable" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
echo "Testing script/verify-build failure modes..."
|
||||
pick_sha256_tool
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
#!/bin/sh
|
||||
# script/verify-build: assert that dist/ holds exactly what the build that just
|
||||
# ran emitted, and that the compiled DEBUG state of that output is the one the
|
||||
# caller asked for. Our own extension to scripts-to-rule-them-all, run at the
|
||||
# end of make build / make build-debug.
|
||||
# script/verify-build: assert that the regular files and symlinks under dist/
|
||||
# are exactly what the build that just ran emitted (other file types are out of
|
||||
# scope; see "What that does and does not establish" below), and that the
|
||||
# compiled DEBUG state of that output is the one the caller asked for. Our own
|
||||
# extension to scripts-to-rule-them-all, run at the end of make build /
|
||||
# make build-debug.
|
||||
#
|
||||
# Why the DEBUG half exists: DEBUG makes the publicly committed test recovery
|
||||
# phrase the output of wallet creation, so a release artifact built with it live
|
||||
@@ -29,12 +31,16 @@
|
||||
# path fresh per invocation, outside the repo, and deletes it afterwards.
|
||||
#
|
||||
# What that does and does not establish. It establishes that dist/ is byte for
|
||||
# byte the output of the build.js run that just finished, with nothing added,
|
||||
# nothing missing and nothing altered in between, and that the audited bundles
|
||||
# in it compiled to the requested mode. It does NOT establish that the source
|
||||
# tree or build.js were honest, and it says nothing at all to someone handed a
|
||||
# dist/ from elsewhere: without the receipt from its own build they have no
|
||||
# input to this check. That is signing, and it is not this control.
|
||||
# byte the output of the build.js run that just finished, with no regular file
|
||||
# or symlink added, missing or altered in between, and that the audited bundles
|
||||
# in it compiled to the requested mode. Regular files and symlinks are the whole
|
||||
# of what the tree walk covers; fifos, sockets, device nodes and empty
|
||||
# directories under dist/ are not checked, because a build emits none of them,
|
||||
# none can carry a shippable payload, and grep on a fifo would hang rather than
|
||||
# fail. It does NOT establish that the source tree or build.js were honest, and
|
||||
# it says nothing at all to someone handed a dist/ from elsewhere: without the
|
||||
# receipt from its own build they have no input to this check. That is signing,
|
||||
# and it is not this control.
|
||||
#
|
||||
# It fails rather than passes whenever it cannot determine something. Minified
|
||||
# output is not a stable contract, so "matched neither marker" is not evidence
|
||||
@@ -392,8 +398,10 @@ check_receipt_entries() {
|
||||
# its own command line, so a linked dist/ collapses this walk to one entry
|
||||
# and cross-checks nothing.
|
||||
#
|
||||
# Types other than regular files and symlinks are left out on purpose: a build
|
||||
# emits none of them, and grep on a fifo would hang rather than fail.
|
||||
# Types other than regular files and symlinks — fifos, sockets, device nodes and
|
||||
# empty directories — are left out on purpose, and the guarantee is bounded to
|
||||
# what is walked: a build emits none of them, none can carry a shippable
|
||||
# payload, and grep on a fifo would hang rather than fail.
|
||||
check_dist_tree() {
|
||||
LISTING="$(mktemp "${TMPDIR:-/tmp}/verify-build-dist.XXXXXX")" ||
|
||||
fail "could not create a temporary file for the dist/ listing, so the
|
||||
|
||||
@@ -25,6 +25,12 @@ const {
|
||||
resolveTokenDecimals,
|
||||
unknownDecimalsAmount,
|
||||
} = require("../../shared/approvalAmount");
|
||||
// Four decimals, with the nonzero floor these screens hold: every amount this
|
||||
// view renders — the ERC-20 line, the ETH value, the max fee — and every one
|
||||
// it carries forward to the wait/success/error screens goes through it.
|
||||
const {
|
||||
truncateAmountNeverZero: formatTxValue,
|
||||
} = require("../../shared/amountDisplay");
|
||||
const { decryptWithPassword } = require("../../shared/vault");
|
||||
const { getSignerForAddress } = require("../../shared/wallet");
|
||||
const { walletDefect } = require("../../shared/walletDefects");
|
||||
@@ -40,13 +46,6 @@ function approvalAddressHtml(address) {
|
||||
return renderAddressHtml(address, { title });
|
||||
}
|
||||
|
||||
function formatTxValue(val) {
|
||||
const parts = val.split(".");
|
||||
if (parts.length === 1) return val + ".0000";
|
||||
const dec = (parts[1] + "0000").slice(0, 4);
|
||||
return parts[0] + "." + dec;
|
||||
}
|
||||
|
||||
// The amount line for a decoded ERC-20 call. With a known scale it is the
|
||||
// token quantity; with `decimals` null it is the base-unit integer with the
|
||||
// unknown scale stated, because formatting it with an assumed scale is what
|
||||
@@ -74,6 +73,14 @@ function tokenLabel(address) {
|
||||
function decodeCalldata(data, toAddress) {
|
||||
if (!data || data === "0x" || data.length < 10) return null;
|
||||
|
||||
// Where a token's scale is looked for, for every decoder below: the ERC-20
|
||||
// amount line and the swap's Amount and Min. received lines resolve it the
|
||||
// same way, and refuse to format the same way when it is nowhere.
|
||||
const decimalsSources = {
|
||||
trackedTokens: state.trackedTokens,
|
||||
wallets: state.wallets,
|
||||
};
|
||||
|
||||
// Try ERC-20 (approve / transfer)
|
||||
try {
|
||||
const parsed = erc20Iface.parseTransaction({ data });
|
||||
@@ -85,10 +92,10 @@ function decodeCalldata(data, toAddress) {
|
||||
// the wrong number, and for a token with fewer decimals than the
|
||||
// guess it is the wrong number in the direction that reads as
|
||||
// zero. See tokenAmountText().
|
||||
const tokenDecimals = resolveTokenDecimals(toAddress, {
|
||||
trackedTokens: state.trackedTokens,
|
||||
wallets: state.wallets,
|
||||
});
|
||||
const tokenDecimals = resolveTokenDecimals(
|
||||
toAddress,
|
||||
decimalsSources,
|
||||
);
|
||||
const contractLabel = tokenSymbol
|
||||
? tokenSymbol + " (" + toAddress + ")"
|
||||
: toAddress;
|
||||
@@ -168,7 +175,7 @@ function decodeCalldata(data, toAddress) {
|
||||
}
|
||||
|
||||
// Try Uniswap Universal Router
|
||||
const routerResult = uniswap.decode(data, toAddress);
|
||||
const routerResult = uniswap.decode(data, toAddress, decimalsSources);
|
||||
if (routerResult) return routerResult;
|
||||
|
||||
return null;
|
||||
|
||||
46
src/shared/amountDisplay.js
Normal file
46
src/shared/amountDisplay.js
Normal file
@@ -0,0 +1,46 @@
|
||||
// The 4-decimal amount rule from README.md's Display Consistency section, and
|
||||
// the one exception to it, in one place. Three call sites had grown their own
|
||||
// copy of the truncation — the history and balance lists
|
||||
// (`src/shared/transactions.js`), the approval screen's ERC-20 amount line
|
||||
// (`src/popup/views/approval.js`) and its Uniswap swap detail lines
|
||||
// (`src/shared/uniswap.js`) — and a fix applied to one of them left the other
|
||||
// two showing a different number for the same value.
|
||||
//
|
||||
// The two functions below are the two policies, not two implementations of
|
||||
// one: summary lists truncate, and the screens that state what is being
|
||||
// authorized truncate with a floor. Keeping them adjacent is the point, so a
|
||||
// change to the rule cannot reach one screen and miss another.
|
||||
|
||||
// Truncate to exactly four decimal places. Truncation, never rounding: an
|
||||
// amount must never be displayed as larger than it is, so 0.99999 stays
|
||||
// 0.9999.
|
||||
function truncateAmount(val) {
|
||||
const parts = val.split(".");
|
||||
if (parts.length === 1) return val + ".0000";
|
||||
return parts[0] + "." + (parts[1] + "0000").slice(0, 4);
|
||||
}
|
||||
|
||||
// The same rule, plus the invariant the approval and confirmation screens
|
||||
// hold: a nonzero amount never renders as zero. Truncating to four decimals
|
||||
// does exactly that to an amount below 0.0001 — one base unit of an 18-decimal
|
||||
// token, 500 of an 8-decimal one — and a real transfer or allowance then reads
|
||||
// as "nothing is being moved" on the screen whose whole job is to say what is
|
||||
// being authorized.
|
||||
//
|
||||
// When the truncated string carries no significant digit and the value does,
|
||||
// the amount is extended to its first significant digit instead. It stays in
|
||||
// token units, the same unit as the symbol printed beside it. A genuine zero
|
||||
// still renders 0.0000, and anything at or above the floor is untouched.
|
||||
function truncateAmountNeverZero(val) {
|
||||
const truncated = truncateAmount(val);
|
||||
// Tests the whole truncated string, integer part included: 1.00005 has a
|
||||
// significant digit already and stays 1.0000.
|
||||
if (/[1-9]/.test(truncated)) return truncated;
|
||||
const parts = val.split(".");
|
||||
if (parts.length === 1) return truncated;
|
||||
const sig = parts[1].search(/[1-9]/);
|
||||
if (sig === -1) return truncated;
|
||||
return parts[0] + "." + parts[1].slice(0, sig + 1);
|
||||
}
|
||||
|
||||
module.exports = { truncateAmount, truncateAmountNeverZero };
|
||||
@@ -14,6 +14,10 @@
|
||||
// them answers, unknownDecimalsAmount() renders the base-unit integer with the
|
||||
// unknown scale stated, and no formatUnits() call is reached at all.
|
||||
//
|
||||
// The Uniswap decoder's Amount and Min. received lines land on this same
|
||||
// screen and use these same two functions, so there is one way of resolving a
|
||||
// scale and one way of saying there is none.
|
||||
//
|
||||
// This is the display counterpart to transferAmount.js, which takes the same
|
||||
// stance on the wallet's own send path: an amount whose scale is unknown or
|
||||
// disputed is refused rather than guessed at.
|
||||
|
||||
@@ -6,6 +6,7 @@ const { networkById } = require("./networks");
|
||||
const { RESTORABLE_VIEWS } = require("../popup/restorableViews");
|
||||
|
||||
const { storageGet, storageSet } = require("./browserApi");
|
||||
const { log } = require("./log");
|
||||
|
||||
const DEFAULT_STATE = {
|
||||
hasWallet: false,
|
||||
@@ -88,135 +89,529 @@ function currentNetwork() {
|
||||
return networkById(state.networkId);
|
||||
}
|
||||
|
||||
async function saveState() {
|
||||
const persisted = {
|
||||
hasWallet: state.hasWallet,
|
||||
wallets: state.wallets,
|
||||
trackedTokens: state.trackedTokens,
|
||||
networkId: state.networkId,
|
||||
rpcUrl: state.rpcUrl,
|
||||
blockscoutUrl: state.blockscoutUrl,
|
||||
networkEndpoints: state.networkEndpoints,
|
||||
lastBalanceRefresh: state.lastBalanceRefresh,
|
||||
activeAddress: state.activeAddress,
|
||||
allowedSites: state.allowedSites,
|
||||
deniedSites: state.deniedSites,
|
||||
rememberSiteChoice: state.rememberSiteChoice,
|
||||
showZeroBalanceTokens: state.showZeroBalanceTokens,
|
||||
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||
hideFraudContracts: state.hideFraudContracts,
|
||||
hideDustTransactions: state.hideDustTransactions,
|
||||
dustThresholdGwei: state.dustThresholdGwei,
|
||||
utcTimestamps: state.utcTimestamps,
|
||||
fraudContracts: state.fraudContracts,
|
||||
tokenHolderCache: state.tokenHolderCache,
|
||||
theme: state.theme,
|
||||
debugMode: state.debugMode,
|
||||
currentView: state.currentView,
|
||||
selectedWallet: state.selectedWallet,
|
||||
selectedAddress: state.selectedAddress,
|
||||
selectedToken: state.selectedToken,
|
||||
viewData: state.viewData,
|
||||
viewStack: state.viewStack,
|
||||
};
|
||||
await storageSet({ autistmask: persisted });
|
||||
// Every field written to and read from the single "autistmask" storage key.
|
||||
// hasWallet is deliberately excluded from the diffing/merge logic below —
|
||||
// like loadState() does, it is always derived from `wallets`, never carried
|
||||
// as an independent value.
|
||||
const PERSISTED_FIELDS = Object.keys(DEFAULT_STATE)
|
||||
.filter((key) => key !== "hasWallet")
|
||||
.concat([
|
||||
"currentView",
|
||||
"selectedWallet",
|
||||
"selectedAddress",
|
||||
"selectedToken",
|
||||
"viewData",
|
||||
"viewStack",
|
||||
]);
|
||||
|
||||
// Turn a raw stored (or missing) record into the full, defaulted shape
|
||||
// loadState() used to assign directly onto `state`. Pulled out as a pure
|
||||
// function so saveState() can apply it too: the fields THIS page did not
|
||||
// change still have to come from storage in their loaded-and-normalized
|
||||
// form, not as the raw bytes another page (or an old release) left there —
|
||||
// otherwise a legacy shape a load has always self-healed in memory (a
|
||||
// missing networkEndpoints map, an out-of-range flag) is dropped right back
|
||||
// into storage unfixed every time the page that DID normalize it saves
|
||||
// something unrelated, because that field's value never "changed" for that
|
||||
// page to notice.
|
||||
function normalizePersisted(saved) {
|
||||
saved = saved || {};
|
||||
const out = {};
|
||||
out.wallets = saved.wallets || [];
|
||||
// Derived, never trusted verbatim off storage — see loadState().
|
||||
out.hasWallet = out.wallets.length > 0;
|
||||
out.trackedTokens = saved.trackedTokens || [];
|
||||
out.networkId = saved.networkId || DEFAULT_STATE.networkId;
|
||||
out.rpcUrl = saved.rpcUrl || DEFAULT_STATE.rpcUrl;
|
||||
out.blockscoutUrl = saved.blockscoutUrl || DEFAULT_STATE.blockscoutUrl;
|
||||
// An actual object is required, not merely a truthy non-array: the code
|
||||
// below and onChainSwitch() index and ASSIGN INTO this value, and
|
||||
// assigning a property to a string or a number is a silent no-op in
|
||||
// sloppy mode. Copied rather than referenced, nested pairs included, so
|
||||
// normalizing never mutates the object a caller handed in.
|
||||
const rawEndpoints =
|
||||
typeof saved.networkEndpoints === "object" &&
|
||||
saved.networkEndpoints !== null &&
|
||||
!Array.isArray(saved.networkEndpoints)
|
||||
? saved.networkEndpoints
|
||||
: {};
|
||||
out.networkEndpoints = {};
|
||||
for (const netId of Object.keys(rawEndpoints)) {
|
||||
out.networkEndpoints[netId] = { ...rawEndpoints[netId] };
|
||||
}
|
||||
// A profile written before this map existed carries exactly one pair of
|
||||
// endpoints, belonging to whatever network it was last on. Adopt it as
|
||||
// that network's remembered pair, so a custom endpoint set on the old
|
||||
// build is not lost by the first switch away and back.
|
||||
if (!out.networkEndpoints[out.networkId]) {
|
||||
out.networkEndpoints[out.networkId] = {
|
||||
rpcUrl: out.rpcUrl,
|
||||
blockscoutUrl: out.blockscoutUrl,
|
||||
};
|
||||
}
|
||||
out.lastBalanceRefresh = saved.lastBalanceRefresh || 0;
|
||||
out.activeAddress = saved.activeAddress || null;
|
||||
out.allowedSites =
|
||||
saved.allowedSites && !Array.isArray(saved.allowedSites)
|
||||
? saved.allowedSites
|
||||
: {};
|
||||
out.deniedSites =
|
||||
saved.deniedSites && !Array.isArray(saved.deniedSites)
|
||||
? saved.deniedSites
|
||||
: {};
|
||||
out.rememberSiteChoice =
|
||||
saved.rememberSiteChoice !== undefined
|
||||
? saved.rememberSiteChoice
|
||||
: true;
|
||||
out.showZeroBalanceTokens =
|
||||
saved.showZeroBalanceTokens !== undefined
|
||||
? saved.showZeroBalanceTokens
|
||||
: true;
|
||||
// A profile written before this setting existed has no key for it. It
|
||||
// is a safety filter, so absent must load as on, not as undefined.
|
||||
out.hideSpoofedSymbols =
|
||||
saved.hideSpoofedSymbols !== undefined
|
||||
? saved.hideSpoofedSymbols
|
||||
: true;
|
||||
out.hideLowHolderTokens =
|
||||
saved.hideLowHolderTokens !== undefined
|
||||
? saved.hideLowHolderTokens
|
||||
: true;
|
||||
out.hideFraudContracts =
|
||||
saved.hideFraudContracts !== undefined
|
||||
? saved.hideFraudContracts
|
||||
: true;
|
||||
out.hideDustTransactions =
|
||||
saved.hideDustTransactions !== undefined
|
||||
? saved.hideDustTransactions
|
||||
: true;
|
||||
out.dustThresholdGwei =
|
||||
saved.dustThresholdGwei !== undefined
|
||||
? saved.dustThresholdGwei
|
||||
: 100000;
|
||||
out.utcTimestamps =
|
||||
saved.utcTimestamps !== undefined ? saved.utcTimestamps : false;
|
||||
out.fraudContracts = saved.fraudContracts || [];
|
||||
out.tokenHolderCache = saved.tokenHolderCache || {};
|
||||
out.theme = saved.theme || "system";
|
||||
out.debugMode = saved.debugMode !== undefined ? saved.debugMode : false;
|
||||
out.currentView = saved.currentView || null;
|
||||
out.selectedWallet =
|
||||
saved.selectedWallet !== undefined ? saved.selectedWallet : null;
|
||||
out.selectedAddress =
|
||||
saved.selectedAddress !== undefined ? saved.selectedAddress : null;
|
||||
out.selectedToken = saved.selectedToken || null;
|
||||
out.viewData = saved.viewData || {};
|
||||
out.viewStack = restorableStack(saved.viewStack, out.currentView);
|
||||
return out;
|
||||
}
|
||||
|
||||
// The persisted fields as they stood at the end of this page's last
|
||||
// loadState() or saveState(). saveState() diffs the live state against this
|
||||
// to find only the fields THIS page actually changed.
|
||||
//
|
||||
// Deep-cloned, not a reference: callers mutate persisted objects and arrays
|
||||
// in place (state.wallets.push(...)), and a reference baseline would mutate
|
||||
// right along with `state`, so the diff would always come out empty.
|
||||
let baseline = null;
|
||||
|
||||
function snapshotPersisted() {
|
||||
const out = {};
|
||||
for (const key of PERSISTED_FIELDS) out[key] = state[key];
|
||||
return out;
|
||||
}
|
||||
|
||||
function deepEqual(a, b) {
|
||||
if (a === b) return true;
|
||||
if (typeof a !== "object" || typeof b !== "object") return false;
|
||||
if (a === null || b === null) return false;
|
||||
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
||||
const aKeys = Object.keys(a);
|
||||
const bKeys = Object.keys(b);
|
||||
if (aKeys.length !== bKeys.length) return false;
|
||||
for (const key of aKeys) {
|
||||
if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
|
||||
if (!deepEqual(a[key], b[key])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stable identity for a wallet, independent of its position in the array
|
||||
// (which shifts under a concurrent add/delete elsewhere) and independent of
|
||||
// its mutable fields (name is user-editable; addresses gains/loses entries
|
||||
// via scanning and deleteAddress.js). An "hd"/"xprv" wallet's xpub never
|
||||
// changes for its lifetime and is already enforced unique
|
||||
// (findWalletByXpub() in addWallet.js). A "key" wallet has no xpub, exactly
|
||||
// one address for its whole lifetime (nothing ever adds to or removes from
|
||||
// a key wallet's address list), and that address is already enforced
|
||||
// unique (findWalletByAddress()) — so it stands in for identity there.
|
||||
// Neither invariant is enforced by this function or by
|
||||
// mergeListByIdentity() below — they hold only because every wallet-
|
||||
// creation path in addWallet.js happens to populate one or the other before
|
||||
// the wallet ever reaches state.wallets, and because canRemoveAddress() in
|
||||
// walletDelete.js never lets a wallet's address list go to zero. A wallet
|
||||
// with neither (an empty/legacy/corrupt record) falls back to the same
|
||||
// "addr:" identity as every other such record, which is a genuine
|
||||
// collision, not a proxy for one — see the collision handling in
|
||||
// mergeListByIdentity().
|
||||
function walletIdentity(wallet) {
|
||||
if (wallet.xpub) return "xpub:" + wallet.xpub;
|
||||
const first = wallet.addresses && wallet.addresses[0];
|
||||
return "addr:" + (first ? String(first.address).toLowerCase() : "");
|
||||
}
|
||||
|
||||
// Stable identity for an address within one wallet's address list. An
|
||||
// address is unique within its wallet and, once derived or imported, never
|
||||
// changes — only whether it is present.
|
||||
function addressIdentity(addr) {
|
||||
return String(addr.address).toLowerCase();
|
||||
}
|
||||
|
||||
// Merge one array of identity-bearing objects (wallets, or the addresses
|
||||
// inside one wallet) by identity rather than by array index — an index
|
||||
// shifts under a concurrent insert/delete elsewhere, which would merge the
|
||||
// wrong pair of objects entirely.
|
||||
//
|
||||
// `theirs` (fresh storage) sets the membership baseline and the order:
|
||||
// - An item this page never had baseline knowledge of, but that is in
|
||||
// `theirs`, was added by someone else — kept as-is.
|
||||
// - An item `base` had and `ours` no longer has was deleted by THIS page
|
||||
// — dropped even though `theirs` still has it (this page's own delete
|
||||
// must win over a background save that only touched leaf fields).
|
||||
// - An item present in both `ours` and `theirs` is merged leaf-by-leaf via
|
||||
// `mergeItem`, so a leaf this page changed (e.g. a renamed wallet) lands
|
||||
// on top of `theirs`' otherwise-current copy (e.g. a refreshed balance).
|
||||
// Anything left in `ours` that `base` never had and `theirs` does not have
|
||||
// yet is this page's own new addition — appended.
|
||||
//
|
||||
// `identityOf` is not guaranteed collision-free (walletIdentity() falls
|
||||
// back to one shared "addr:" value for any wallet with neither an xpub nor
|
||||
// a populated first address). Two records that collide under it must never
|
||||
// silently collapse into one — that is exactly how this function used to
|
||||
// drop a wallet, encryptedSecret included, with no error and no log. Two
|
||||
// defenses:
|
||||
// - `ours` is indexed into GROUPS, not a single item per identity, so two
|
||||
// colliding live items on this page can't overwrite each other in the
|
||||
// index before the merge below even runs.
|
||||
// - A matched pair with no shared `base` entry (neither page ever agreed
|
||||
// on this identity) is only merged leaf-by-leaf when the two sides are
|
||||
// already equal. If they differ, that is not "the same record edited
|
||||
// twice", it is two different records that happen to share an identity
|
||||
// — both are kept, unmerged, rather than guessing which one is real.
|
||||
function mergeListByIdentity(base, ours, theirs, identityOf, mergeItem) {
|
||||
base = base || [];
|
||||
ours = ours || [];
|
||||
theirs = theirs || [];
|
||||
const baseIndex = new Map(base.map((item) => [identityOf(item), item]));
|
||||
const oursIndex = new Map();
|
||||
for (const item of ours) {
|
||||
const id = identityOf(item);
|
||||
if (!oursIndex.has(id)) oursIndex.set(id, []);
|
||||
oursIndex.get(id).push(item);
|
||||
}
|
||||
|
||||
const result = [];
|
||||
const seen = new Set();
|
||||
|
||||
for (const theirItem of theirs) {
|
||||
const id = identityOf(theirItem);
|
||||
seen.add(id);
|
||||
const oursGroup = oursIndex.get(id);
|
||||
if (baseIndex.has(id) && !oursGroup) continue;
|
||||
if (oursGroup) {
|
||||
const baseItem = baseIndex.get(id);
|
||||
if (!baseItem && !deepEqual(oursGroup[0], theirItem)) {
|
||||
log.errorf(
|
||||
"state: identity collision merging",
|
||||
JSON.stringify(id),
|
||||
"- keeping both records instead of dropping one",
|
||||
);
|
||||
result.push(theirItem, ...oursGroup);
|
||||
} else {
|
||||
result.push(mergeItem(baseItem, oursGroup[0], theirItem));
|
||||
for (let i = 1; i < oursGroup.length; i++) {
|
||||
result.push(oursGroup[i]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result.push(theirItem);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of ours) {
|
||||
const id = identityOf(item);
|
||||
if (seen.has(id)) continue;
|
||||
if (!baseIndex.has(id)) result.push(item);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Merge one wallet's scalar/leaf fields (name, encryptedSecret, nextIndex,
|
||||
// ...) against base, then recurse into its address list by identity. `base`
|
||||
// is null when this page created the wallet itself and no other page has
|
||||
// (yet) produced a same-identity record — nothing to merge in that case,
|
||||
// this page's own copy wins outright. mergeListByIdentity() only ever calls
|
||||
// this with `!base` when `ours` and `theirs` are already equal (a genuine
|
||||
// collision between two DIFFERENT same-identity records is caught and kept
|
||||
// as two separate entries before this function is reached), so returning
|
||||
// `ours` here can't discard a different wallet's data.
|
||||
function mergeWallet(base, ours, theirs) {
|
||||
if (!base) return ours;
|
||||
const merged = { ...theirs };
|
||||
for (const key of Object.keys(ours)) {
|
||||
if (key === "addresses") continue;
|
||||
if (!deepEqual(ours[key], base[key])) merged[key] = ours[key];
|
||||
}
|
||||
merged.addresses = mergeListByIdentity(
|
||||
base.addresses,
|
||||
ours.addresses,
|
||||
theirs.addresses,
|
||||
addressIdentity,
|
||||
mergeAddress,
|
||||
);
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Merge one address's leaf fields (balance, ensName, tokenBalances, ...).
|
||||
// tokenBalances is itself an array, but only backgroundRefresh() ever
|
||||
// writes it and always wholesale (refreshBalances() in
|
||||
// src/shared/balances.js), so there is no membership to reconcile within
|
||||
// it — it is a leaf like balance or ensName, not a list with its own
|
||||
// identity.
|
||||
function mergeAddress(base, ours, theirs) {
|
||||
if (!base) return ours;
|
||||
const merged = { ...theirs };
|
||||
for (const key of Object.keys(ours)) {
|
||||
if (!deepEqual(ours[key], base[key])) merged[key] = ours[key];
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Merge a plain object keyed by string (allowedSites/deniedSites: address ->
|
||||
// hostname list; networkEndpoints: networkId -> {rpcUrl, blockscoutUrl}) the
|
||||
// same way mergeListByIdentity() merges an array — by key, not by whole-
|
||||
// object diff — so a key one page added or removed applies independently of
|
||||
// a key another page edited. Unlike an array's identity function, an object
|
||||
// key can't collide with a different logical entry (Object.keys() is
|
||||
// already deduplicated), so this needs no collision floor of its own.
|
||||
function mergeMapByKey(base, ours, theirs, mergeLeaf) {
|
||||
base = base || {};
|
||||
ours = ours || {};
|
||||
theirs = theirs || {};
|
||||
const result = {};
|
||||
const seen = new Set();
|
||||
|
||||
for (const key of Object.keys(theirs)) {
|
||||
seen.add(key);
|
||||
const inBase = Object.prototype.hasOwnProperty.call(base, key);
|
||||
const inOurs = Object.prototype.hasOwnProperty.call(ours, key);
|
||||
if (inBase && !inOurs) continue; // this page deleted the whole entry
|
||||
if (inOurs) {
|
||||
result[key] = mergeLeaf(base[key], ours[key], theirs[key]);
|
||||
} else {
|
||||
result[key] = theirs[key];
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of Object.keys(ours)) {
|
||||
if (seen.has(key)) continue;
|
||||
if (!Object.prototype.hasOwnProperty.call(base, key)) {
|
||||
result[key] = ours[key];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// allowedSites/deniedSites: { [address]: [hostname, ...] }. The hostname
|
||||
// list is itself membership, not a leaf — src/background/index.js pushes a
|
||||
// newly approved/denied hostname onto it in place, and the Settings "revoke"
|
||||
// button (src/popup/views/settings.js) filters a hostname out of it in
|
||||
// place, from a different page. Merge it the same way wallets are merged:
|
||||
// identity is the hostname itself, so a merged pair is always equal and
|
||||
// mergeItem is a no-op pick.
|
||||
function mergeHostnameList(base, ours, theirs) {
|
||||
return mergeListByIdentity(
|
||||
base,
|
||||
ours,
|
||||
theirs,
|
||||
(hostname) => hostname,
|
||||
(b, o, t) => t,
|
||||
);
|
||||
}
|
||||
|
||||
function mergeSiteMap(base, ours, theirs) {
|
||||
return mergeMapByKey(base, ours, theirs, mergeHostnameList);
|
||||
}
|
||||
|
||||
// networkEndpoints: { [networkId]: {rpcUrl, blockscoutUrl} }. onChainSwitch()
|
||||
// (src/shared/chainSwitch.js) writes state.networkEndpoints[networkId] in
|
||||
// place before saving. No code path ever removes a key from this map, so the
|
||||
// membership collision that matters for allowedSites/wallets (an add on one
|
||||
// page racing a delete on another) can't happen here — but two pages
|
||||
// switching to two different networks concurrently still race a whole-field
|
||||
// diff the same way, so it gets the same per-key merge for the leaf edit
|
||||
// case (e.g. Settings saving a custom RPC URL for the active network).
|
||||
function mergeEndpointEntry(base, ours, theirs) {
|
||||
if (!base) return ours;
|
||||
const merged = { ...theirs };
|
||||
for (const key of Object.keys(ours)) {
|
||||
if (!deepEqual(ours[key], base[key])) merged[key] = ours[key];
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
function mergeNetworkEndpoints(base, ours, theirs) {
|
||||
return mergeMapByKey(base, ours, theirs, mergeEndpointEntry);
|
||||
}
|
||||
|
||||
// Read-modify-write, merged per field, rather than one full-blob write.
|
||||
//
|
||||
// Every extension page (the toolbar popup, a dApp approval window, the
|
||||
// background's backgroundRefresh()) holds its own in-memory `state`, loaded
|
||||
// once, and showView() saves on every navigation. A full-blob write here
|
||||
// clobbers whatever a second page had written since — including, in the
|
||||
// worst case, an entire wallet and its encrypted secret with no attacker
|
||||
// and no unusual input (see the issue this fixes).
|
||||
//
|
||||
// Only the fields this page actually changed — those that differ from
|
||||
// `baseline`, captured at the last loadState()/saveState() on this page —
|
||||
// are written; every other field is carried forward from whatever is in
|
||||
// storage right now, which may already be a value another page wrote.
|
||||
//
|
||||
// `wallets` is merged structurally (mergeListByIdentity(), by wallet
|
||||
// identity and then by address identity within each wallet), not as one
|
||||
// whole field: backgroundRefresh() mutates wallets IN PLACE (addr.balance /
|
||||
// ensName / tokenBalances, via refreshBalances()), so a whole-field diff
|
||||
// would mark all of `wallets` "changed" the moment any balance moved and
|
||||
// write back background's own copy — loaded before its multi-second network
|
||||
// round trip — clobbering a wallet another page added, or resurrecting one
|
||||
// another page deleted, in that window. Merging by identity lets
|
||||
// background's leaf changes and another page's membership changes
|
||||
// (add/delete a wallet or an address) apply independently instead of
|
||||
// colliding as the same field.
|
||||
//
|
||||
// `allowedSites` and `deniedSites` get the same treatment (mergeSiteMap(),
|
||||
// by address key and then by hostname within each address's list), for the
|
||||
// identical reason: src/background/index.js pushes a newly
|
||||
// approved/denied hostname onto them in place, and the Settings "revoke"
|
||||
// button (src/popup/views/settings.js) filters one out in place, from a
|
||||
// different page. A whole-field diff here doesn't just lose data, it is a
|
||||
// security defect — a stale page's save can resurrect a just-revoked site
|
||||
// permission, or silently wipe a permission just granted elsewhere.
|
||||
//
|
||||
// `networkEndpoints` gets the same treatment too (mergeNetworkEndpoints(),
|
||||
// by network id), since onChainSwitch() writes into it in place; the value
|
||||
// per key is a small leaf object with no membership of its own; see the
|
||||
// comment at mergeEndpointEntry() for why the collision this closes is
|
||||
// milder than the other two.
|
||||
//
|
||||
// Every other persisted field stays a whole-field diff:
|
||||
// `trackedTokens`/`fraudContracts`/`viewStack` are arrays of scalars with no
|
||||
// per-element identity to merge by; `tokenHolderCache` is a map shaped like
|
||||
// the ones above, but nothing in src/ ever writes an entry into it — it is
|
||||
// only ever reset wholesale to `{}` (onChainSwitch()) — so there is no
|
||||
// in-place mutation for a whole-field diff to collide with; `viewData` is
|
||||
// this page's own UI scratch space, not data another page has any reason to
|
||||
// share membership of.
|
||||
//
|
||||
// This does not make two pages that both change the SAME leaf concurrently
|
||||
// safe: last write wins on that one leaf, same as before. What it removes
|
||||
// is the cross-field (and now cross-membership-vs-leaf) clobber — a page
|
||||
// that only navigated, or only refreshed a balance, overwriting a wallet or
|
||||
// address list it never touched the membership of.
|
||||
//
|
||||
// This page's own live `state` is deliberately NOT rehydrated from a field
|
||||
// another page changed — only the record written to storage is merged.
|
||||
// showView() fires saveState() on every navigation without awaiting it,
|
||||
// which is what makes the queue above necessary in the first place, and a
|
||||
// save that is slow to come back has no way to tell whether the field it
|
||||
// is about to hand back is still the current answer or has since been
|
||||
// overtaken by something this very page did in the meantime; writing it
|
||||
// into `state` regardless reintroduced exactly the clobber this function
|
||||
// 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
|
||||
// does not own goes on being whatever its last loadState() saw, same as
|
||||
// before this fix; only the persisted record is guaranteed current.
|
||||
async function saveStateOnce() {
|
||||
const current = snapshotPersisted();
|
||||
const result = await storageGet("autistmask");
|
||||
// Normalized, not raw: a field this page did not change still has to
|
||||
// come from storage in its loaded (self-healed) shape. See
|
||||
// normalizePersisted() above.
|
||||
const fresh = normalizePersisted(result.autistmask);
|
||||
|
||||
const merged = { ...fresh };
|
||||
for (const key of PERSISTED_FIELDS) {
|
||||
if (key === "wallets") {
|
||||
merged.wallets = mergeListByIdentity(
|
||||
baseline ? baseline.wallets : [],
|
||||
current.wallets,
|
||||
fresh.wallets,
|
||||
walletIdentity,
|
||||
mergeWallet,
|
||||
);
|
||||
} else if (key === "allowedSites" || key === "deniedSites") {
|
||||
merged[key] = mergeSiteMap(
|
||||
baseline ? baseline[key] : {},
|
||||
current[key],
|
||||
fresh[key],
|
||||
);
|
||||
} else if (key === "networkEndpoints") {
|
||||
merged.networkEndpoints = mergeNetworkEndpoints(
|
||||
baseline ? baseline.networkEndpoints : {},
|
||||
current.networkEndpoints,
|
||||
fresh.networkEndpoints,
|
||||
);
|
||||
} else if (
|
||||
baseline === null ||
|
||||
!deepEqual(current[key], baseline[key])
|
||||
) {
|
||||
merged[key] = current[key];
|
||||
}
|
||||
}
|
||||
merged.hasWallet = Boolean(merged.wallets && merged.wallets.length > 0);
|
||||
|
||||
await storageSet({ autistmask: merged });
|
||||
|
||||
// Derived from this page's own wallets, never adopted off the wire —
|
||||
// see loadState(). Everything else this page did not change is left
|
||||
// exactly as it stood; see the note above.
|
||||
state.hasWallet = state.wallets.length > 0;
|
||||
|
||||
baseline = structuredClone(snapshotPersisted());
|
||||
}
|
||||
|
||||
// showView() calls saveState() on every navigation without awaiting it, so
|
||||
// two saves from the SAME page can be in flight at once — e.g. a screen
|
||||
// shown, then immediately replaced before the first save's storageGet()
|
||||
// round trip has come back. Left concurrent, the first save's turn would
|
||||
// finish after the second's live-state mutation and then re-hydrate `state`
|
||||
// from what IT read, stomping the second, later change back to a stale
|
||||
// value — the same clobber this function exists to prevent, just between
|
||||
// two saves on one page instead of two pages. Queuing makes every save's
|
||||
// snapshot-diff-write-rehydrate run start to finish before the next one
|
||||
// begins, so each one only ever sees the true live state at its turn.
|
||||
let saveQueue = Promise.resolve();
|
||||
|
||||
function saveState() {
|
||||
const turn = saveQueue.then(saveStateOnce);
|
||||
// The queue must advance even when a save rejects, or every save after
|
||||
// it queues behind a promise that never settles.
|
||||
saveQueue = turn.catch(() => {});
|
||||
return turn;
|
||||
}
|
||||
|
||||
async function loadState() {
|
||||
const result = await storageGet("autistmask");
|
||||
if (result.autistmask) {
|
||||
const saved = result.autistmask;
|
||||
state.wallets = saved.wallets || [];
|
||||
// Derived, never read from storage: a profile persisted with the flag
|
||||
// out of step with the wallet list would otherwise stay broken on
|
||||
// every load. Nothing depends on the two disagreeing.
|
||||
state.hasWallet = state.wallets.length > 0;
|
||||
state.trackedTokens = saved.trackedTokens || [];
|
||||
state.networkId = saved.networkId || DEFAULT_STATE.networkId;
|
||||
state.rpcUrl = saved.rpcUrl || DEFAULT_STATE.rpcUrl;
|
||||
state.blockscoutUrl =
|
||||
saved.blockscoutUrl || DEFAULT_STATE.blockscoutUrl;
|
||||
// An actual object is required, not merely a truthy non-array: the
|
||||
// code below and onChainSwitch() index and ASSIGN INTO this value,
|
||||
// and assigning a property to a string or a number is a silent no-op
|
||||
// in sloppy mode. A stored primitive would therefore be re-persisted
|
||||
// unchanged forever, and every switch would fall back to the network
|
||||
// default — the endpoint loss this map exists to prevent, with no
|
||||
// self-healing. The allowedSites/deniedSites guards below are only
|
||||
// read from, which is why they can be looser.
|
||||
state.networkEndpoints =
|
||||
typeof saved.networkEndpoints === "object" &&
|
||||
saved.networkEndpoints !== null &&
|
||||
!Array.isArray(saved.networkEndpoints)
|
||||
? saved.networkEndpoints
|
||||
: {};
|
||||
// A profile written before this map existed carries exactly one pair
|
||||
// of endpoints, belonging to whatever network it was last on. Adopt
|
||||
// it as that network's remembered pair, so a custom endpoint set on
|
||||
// the old build is not lost by the first switch away and back.
|
||||
if (!state.networkEndpoints[state.networkId]) {
|
||||
state.networkEndpoints[state.networkId] = {
|
||||
rpcUrl: state.rpcUrl,
|
||||
blockscoutUrl: state.blockscoutUrl,
|
||||
};
|
||||
}
|
||||
state.lastBalanceRefresh = saved.lastBalanceRefresh || 0;
|
||||
state.activeAddress = saved.activeAddress || null;
|
||||
state.allowedSites =
|
||||
saved.allowedSites && !Array.isArray(saved.allowedSites)
|
||||
? saved.allowedSites
|
||||
: {};
|
||||
state.deniedSites =
|
||||
saved.deniedSites && !Array.isArray(saved.deniedSites)
|
||||
? saved.deniedSites
|
||||
: {};
|
||||
state.rememberSiteChoice =
|
||||
saved.rememberSiteChoice !== undefined
|
||||
? saved.rememberSiteChoice
|
||||
: true;
|
||||
state.showZeroBalanceTokens =
|
||||
saved.showZeroBalanceTokens !== undefined
|
||||
? saved.showZeroBalanceTokens
|
||||
: true;
|
||||
// A profile written before this setting existed has no key for it.
|
||||
// It is a safety filter, so absent must load as on, not as undefined.
|
||||
state.hideSpoofedSymbols =
|
||||
saved.hideSpoofedSymbols !== undefined
|
||||
? saved.hideSpoofedSymbols
|
||||
: true;
|
||||
state.hideLowHolderTokens =
|
||||
saved.hideLowHolderTokens !== undefined
|
||||
? saved.hideLowHolderTokens
|
||||
: true;
|
||||
state.hideFraudContracts =
|
||||
saved.hideFraudContracts !== undefined
|
||||
? saved.hideFraudContracts
|
||||
: true;
|
||||
state.hideDustTransactions =
|
||||
saved.hideDustTransactions !== undefined
|
||||
? saved.hideDustTransactions
|
||||
: true;
|
||||
state.dustThresholdGwei =
|
||||
saved.dustThresholdGwei !== undefined
|
||||
? saved.dustThresholdGwei
|
||||
: 100000;
|
||||
state.utcTimestamps =
|
||||
saved.utcTimestamps !== undefined ? saved.utcTimestamps : false;
|
||||
state.fraudContracts = saved.fraudContracts || [];
|
||||
state.tokenHolderCache = saved.tokenHolderCache || {};
|
||||
state.theme = saved.theme || "system";
|
||||
state.debugMode =
|
||||
saved.debugMode !== undefined ? saved.debugMode : false;
|
||||
state.currentView = saved.currentView || null;
|
||||
state.selectedWallet =
|
||||
saved.selectedWallet !== undefined ? saved.selectedWallet : null;
|
||||
state.selectedAddress =
|
||||
saved.selectedAddress !== undefined ? saved.selectedAddress : null;
|
||||
state.selectedToken = saved.selectedToken || null;
|
||||
state.viewData = saved.viewData || {};
|
||||
state.viewStack = restorableStack(saved.viewStack, state.currentView);
|
||||
Object.assign(state, normalizePersisted(result.autistmask));
|
||||
}
|
||||
// The point of comparison every saveState() on this page diffs against,
|
||||
// whether storage had a profile or was empty. See PERSISTED_FIELDS above
|
||||
// saveState() for why a reference here would be wrong.
|
||||
baseline = structuredClone(snapshotPersisted());
|
||||
}
|
||||
|
||||
function currentAddress() {
|
||||
|
||||
@@ -11,6 +11,10 @@ const { log, debugFetch } = require("./log");
|
||||
const { TOKEN_BY_ADDRESS } = require("./tokenList");
|
||||
const { parseHoldersCount, isLowHolderCount } = require("./holders");
|
||||
const { isSpoofedSymbol } = require("./symbolSpoof");
|
||||
// The plain 4-decimal rule. The history and balance lists deliberately keep
|
||||
// truncation without the approval screens' nonzero floor: the transaction
|
||||
// detail view is the authoritative record and already shows exact precision.
|
||||
const { truncateAmount: formatTxValue } = require("./amountDisplay");
|
||||
|
||||
// Ethereum addresses are case-insensitive: EIP-55 mixed case is a checksum
|
||||
// over the address, not part of its identity. Every address comparison in
|
||||
@@ -20,13 +24,6 @@ function normalizeAddress(addr) {
|
||||
return (addr || "").toLowerCase();
|
||||
}
|
||||
|
||||
function formatTxValue(val) {
|
||||
const parts = val.split(".");
|
||||
if (parts.length === 1) return val + ".0000";
|
||||
const dec = (parts[1] + "0000").slice(0, 4);
|
||||
return parts[0] + "." + dec;
|
||||
}
|
||||
|
||||
function parseTx(tx, addrLower) {
|
||||
const from = tx.from?.hash || "";
|
||||
const to = tx.to?.hash || "";
|
||||
|
||||
@@ -3,6 +3,11 @@
|
||||
|
||||
const { Interface, AbiCoder, getBytes, formatUnits } = require("ethers");
|
||||
const { TOKEN_BY_ADDRESS } = require("./tokenList");
|
||||
const { truncateAmountNeverZero } = require("./amountDisplay");
|
||||
const {
|
||||
resolveTokenDecimals,
|
||||
unknownDecimalsAmount,
|
||||
} = require("./approvalAmount");
|
||||
|
||||
const coder = AbiCoder.defaultAbiCoder();
|
||||
|
||||
@@ -34,20 +39,46 @@ const COMMAND_NAMES = {
|
||||
0x21: "Execute Sub-Plan",
|
||||
};
|
||||
|
||||
// The swap's Amount and Min. received lines land on the same approval screen,
|
||||
// and Amount is carried to the wait/success/error screens as the ERC-20 line
|
||||
// is, so they take the same nonzero floor: a swap of an amount below 0.0001 is
|
||||
// not "0.0000", and a slippage floor of one base unit does not read as "you may
|
||||
// receive nothing".
|
||||
function formatAmount(raw, decimals) {
|
||||
const parts = formatUnits(raw, decimals).split(".");
|
||||
if (parts.length === 1) return parts[0] + ".0000";
|
||||
const dec = (parts[1] + "0000").slice(0, 4);
|
||||
return parts[0] + "." + dec;
|
||||
return truncateAmountNeverZero(formatUnits(raw, decimals));
|
||||
}
|
||||
|
||||
function tokenInfo(address) {
|
||||
// `decimals` is null when nothing knows this token's scale. It is not
|
||||
// defaulted to 18: the swap lines land on the same approval screen as the
|
||||
// ERC-20 line, and a scale guessed there is what showed a 1,000 USDT swap as
|
||||
// 0.000000000001. `sources` is { trackedTokens, wallets }, shaped as they are
|
||||
// on `state`; resolveTokenDecimals() reads the bundled list, then those.
|
||||
function tokenInfo(address, sources) {
|
||||
if (!address || address === "0x0000000000000000000000000000000000000000") {
|
||||
return { symbol: "ETH", decimals: 18, address: null };
|
||||
}
|
||||
const t = TOKEN_BY_ADDRESS.get(address.toLowerCase());
|
||||
if (t) return { symbol: t.symbol, decimals: t.decimals, address };
|
||||
return { symbol: null, decimals: 18, address };
|
||||
return {
|
||||
symbol: t ? t.symbol : null,
|
||||
decimals: resolveTokenDecimals(address, sources),
|
||||
address,
|
||||
};
|
||||
}
|
||||
|
||||
// A swap amount line. With a scale it is the token quantity; with none it is
|
||||
// the base-unit integer with the unknown scale stated, the same refusal the
|
||||
// ERC-20 amount line makes, so the screen has one way of saying it. `display`
|
||||
// is the line on the screen, `raw` is what the status screens carry.
|
||||
function amountText(raw, info) {
|
||||
if (info.decimals === null) {
|
||||
const unknown = unknownDecimalsAmount(raw);
|
||||
return { raw: unknown, display: unknown };
|
||||
}
|
||||
const formatted = formatAmount(raw, info.decimals);
|
||||
return {
|
||||
raw: formatted,
|
||||
display: formatted + (info.symbol ? " " + info.symbol : ""),
|
||||
};
|
||||
}
|
||||
|
||||
// Decode PERMIT2_PERMIT (command 0x0a) input bytes.
|
||||
@@ -320,7 +351,7 @@ function decodeV4Swap(input) {
|
||||
// Try to decode a Universal Router execute() call.
|
||||
// Returns { name, description, details } matching the format used by
|
||||
// the approval UI, or null if the calldata is not a recognised execute().
|
||||
function decode(data, toAddress) {
|
||||
function decode(data, toAddress, sources) {
|
||||
try {
|
||||
const parsed = ROUTER_IFACE.parseTransaction({ data });
|
||||
if (!parsed) return null;
|
||||
@@ -413,10 +444,10 @@ function decode(data, toAddress) {
|
||||
}
|
||||
|
||||
// Resolve token info
|
||||
const inInfo = tokenInfo(inputToken);
|
||||
const inInfo = tokenInfo(inputToken, sources);
|
||||
const outInfo = hasUnwrapWeth
|
||||
? { symbol: "ETH", decimals: 18, address: null }
|
||||
: tokenInfo(outputToken);
|
||||
: tokenInfo(outputToken, sources);
|
||||
|
||||
const inSymbol = inInfo.symbol;
|
||||
const outSymbol = outInfo.symbol;
|
||||
@@ -453,16 +484,15 @@ function decode(data, toAddress) {
|
||||
"0xffffffffffffffffffffffffffffffffffffffff",
|
||||
);
|
||||
const isUnlimited = inputAmount >= maxUint160;
|
||||
const amountRaw = isUnlimited
|
||||
? "Unlimited"
|
||||
: formatAmount(inputAmount, inInfo.decimals);
|
||||
const amountStr = isUnlimited
|
||||
? "Unlimited"
|
||||
: amountRaw + (inSymbol ? " " + inSymbol : "");
|
||||
// An unbounded permit needs no scale to describe, so it is still
|
||||
// named rather than refused.
|
||||
const amount = isUnlimited
|
||||
? { raw: "Unlimited", display: "Unlimited" }
|
||||
: amountText(inputAmount, inInfo);
|
||||
details.push({
|
||||
label: "Amount",
|
||||
value: amountStr,
|
||||
rawValue: amountRaw,
|
||||
value: amount.display,
|
||||
rawValue: amount.raw,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -483,10 +513,10 @@ function decode(data, toAddress) {
|
||||
}
|
||||
|
||||
if (minOutput !== null && minOutput !== undefined) {
|
||||
const minStr =
|
||||
formatAmount(minOutput, outInfo.decimals) +
|
||||
(outSymbol ? " " + outSymbol : "");
|
||||
details.push({ label: "Min. received", value: minStr });
|
||||
details.push({
|
||||
label: "Min. received",
|
||||
value: amountText(minOutput, outInfo).display,
|
||||
});
|
||||
}
|
||||
|
||||
details.push({ label: "Steps", value: commandNames.join(" \u2192 ") });
|
||||
|
||||
190
tests/approvalDisplayFloor.test.js
Normal file
190
tests/approvalDisplayFloor.test.js
Normal file
@@ -0,0 +1,190 @@
|
||||
// The floor of the approval screen's amount line.
|
||||
//
|
||||
// Amounts are truncated to four decimal places for scannability (README.md,
|
||||
// Display Consistency). With the token's true scale resolved, that truncation
|
||||
// can still take a real amount below the floor and print it as `0.0000`: one
|
||||
// base unit of an 18-decimal token, or a few hundred of an 8-decimal one. On
|
||||
// the one screen whose job is to state what is being authorized, a nonzero
|
||||
// transfer or allowance then reads as nothing.
|
||||
//
|
||||
// The invariant asserted here is narrow: a nonzero amount never renders as
|
||||
// zero. The four-decimal rule itself is unchanged, and the string the
|
||||
// confirmation screens carry as `txInfo.amount` is the same one, so it is
|
||||
// asserted on `rawValue` alongside the displayed line.
|
||||
//
|
||||
// Both amount paths of that screen are covered: the ERC-20 line decoded by
|
||||
// `src/popup/views/approval.js`, and the swap's `Amount` and `Min. received`
|
||||
// lines decoded by `src/shared/uniswap.js`.
|
||||
|
||||
globalThis.chrome = {
|
||||
storage: { local: { get: async () => ({}), set: async () => {} } },
|
||||
};
|
||||
|
||||
const { AbiCoder, Interface } = require("ethers");
|
||||
const { ERC20_ABI } = require("../src/shared/constants");
|
||||
const { state } = require("../src/shared/state");
|
||||
const { decodeCalldata } = require("../src/popup/views/approval");
|
||||
const uniswap = require("../src/shared/uniswap");
|
||||
const {
|
||||
truncateAmount,
|
||||
truncateAmountNeverZero,
|
||||
} = require("../src/shared/amountDisplay");
|
||||
|
||||
const iface = new Interface(ERC20_ABI);
|
||||
|
||||
// Bundled tokens, so the scale and the symbol both come from the list.
|
||||
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; // 6 decimals
|
||||
const WBT = "0x925206b8a707096Ed26ae47C84747fE0bb734F59"; // 8 decimals
|
||||
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F"; // 18 decimals
|
||||
// Outside the list, so the scale comes from what the user tracks and the line
|
||||
// carries no symbol.
|
||||
const NOVEL = "0xE2E0000000000000000000000000000000000E2e";
|
||||
|
||||
const RECIPIENT = "0xC0FfEE0000000000000000000000000000c0fFEe";
|
||||
const SPENDER = "0x1111111111111111111111111111111111111111";
|
||||
|
||||
// The Uniswap swap lines land on this same approval screen.
|
||||
const ROUTER = "0x66a9893cc07d91d95644aedd05d03f95e1dba8af";
|
||||
const USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7"; // 6 decimals
|
||||
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; // 18 decimals
|
||||
|
||||
const coder = AbiCoder.defaultAbiCoder();
|
||||
const routerIface = new Interface([
|
||||
"function execute(bytes commands, bytes[] inputs, uint256 deadline)",
|
||||
]);
|
||||
|
||||
// A V2_SWAP_EXACT_IN (command 0x08) execute() call: `amountIn` of USDT for at
|
||||
// least `amountOutMin` of WETH.
|
||||
function swapData(amountIn, amountOutMin) {
|
||||
const input = coder.encode(
|
||||
["address", "uint256", "uint256", "address[]", "bool"],
|
||||
[RECIPIENT, amountIn, amountOutMin, [USDT, WETH], true],
|
||||
);
|
||||
return routerIface.encodeFunctionData("execute", [
|
||||
"0x08",
|
||||
[input],
|
||||
9999999999n,
|
||||
]);
|
||||
}
|
||||
|
||||
function swapDetail(amountIn, amountOutMin, label) {
|
||||
const decoded = uniswap.decode(swapData(amountIn, amountOutMin), ROUTER);
|
||||
return decoded.details.find((d) => d.label === label);
|
||||
}
|
||||
|
||||
function transferData(amount) {
|
||||
return iface.encodeFunctionData("transfer", [RECIPIENT, amount]);
|
||||
}
|
||||
|
||||
function approveData(amount) {
|
||||
return iface.encodeFunctionData("approve", [SPENDER, amount]);
|
||||
}
|
||||
|
||||
// The Amount detail as the approval screen renders it: `value` is the line on
|
||||
// the screen, `rawValue` is what is carried to the wait/success/error screens.
|
||||
function amount(data, token) {
|
||||
const decoded = decodeCalldata(data, token);
|
||||
return decoded.details.find((d) => d.label === "Amount");
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.trackedTokens = [];
|
||||
state.wallets = [];
|
||||
});
|
||||
|
||||
describe("a nonzero amount never renders as zero", () => {
|
||||
test("500 base units of a 6-decimal token", () => {
|
||||
const detail = amount(transferData(500n), USDC);
|
||||
expect(detail.value).toBe("0.0005 USDC");
|
||||
expect(detail.rawValue).toBe("0.0005");
|
||||
});
|
||||
|
||||
test("1 base unit of an 18-decimal token", () => {
|
||||
const detail = amount(transferData(1n), DAI);
|
||||
expect(detail.value).toBe("0.000000000000000001 DAI");
|
||||
expect(detail.rawValue).toBe("0.000000000000000001");
|
||||
});
|
||||
|
||||
test("500 base units of an 8-decimal token", () => {
|
||||
expect(amount(transferData(500n), WBT).rawValue).toBe("0.000005");
|
||||
});
|
||||
|
||||
test("an allowance below the floor is not rendered as zero either", () => {
|
||||
expect(amount(approveData(1n), DAI).value).toBe(
|
||||
"0.000000000000000001 DAI",
|
||||
);
|
||||
});
|
||||
|
||||
// The floor holds at any scale, not only the three above: for every
|
||||
// decimals a token can declare, one base unit has to show a digit.
|
||||
test("one base unit shows a significant digit at every scale", () => {
|
||||
for (let decimals = 0; decimals <= 30; decimals++) {
|
||||
state.trackedTokens = [{ address: NOVEL, decimals }];
|
||||
expect(amount(transferData(1n), NOVEL).rawValue).toMatch(/[1-9]/);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// The swap decoder formats its own amounts, so the same floor has to hold on
|
||||
// the swap lines of the same screen. `Min. received` is the sharper of the
|
||||
// two: the slippage floor rendered as `0.0000` states that the swap may return
|
||||
// nothing.
|
||||
describe("a swap's amounts never render as zero either", () => {
|
||||
test("a swap input below the floor keeps a significant digit", () => {
|
||||
// 50 base units of a 6-decimal token is 0.00005.
|
||||
const detail = swapDetail(50n, 10n ** 15n, "Amount");
|
||||
expect(detail.value).toBe("0.00005 USDT");
|
||||
expect(detail.rawValue).toBe("0.00005");
|
||||
});
|
||||
|
||||
test("a min-received below the floor keeps a significant digit", () => {
|
||||
// 1 wei of an 18-decimal token.
|
||||
expect(swapDetail(10n ** 6n, 1n, "Min. received").value).toBe(
|
||||
"0.000000000000000001 WETH",
|
||||
);
|
||||
});
|
||||
|
||||
test("swap amounts at or above the floor are still truncated", () => {
|
||||
expect(swapDetail(1000000n, 10n ** 15n, "Amount").rawValue).toBe(
|
||||
"1.0000",
|
||||
);
|
||||
expect(
|
||||
swapDetail(1000000n, 999999999999999999n, "Min. received").value,
|
||||
).toBe("0.9999 WETH");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the four-decimal rule is otherwise unchanged", () => {
|
||||
test("a whole amount keeps exactly four decimals", () => {
|
||||
expect(amount(transferData(5000000000n), USDC).rawValue).toBe(
|
||||
"5000.0000",
|
||||
);
|
||||
});
|
||||
|
||||
test("precision beyond four decimals is still truncated", () => {
|
||||
expect(amount(transferData(1234567890123456789n), DAI).rawValue).toBe(
|
||||
"1.2345",
|
||||
);
|
||||
});
|
||||
|
||||
test("an amount at the floor is not extended", () => {
|
||||
expect(amount(transferData(100000000000000n), DAI).rawValue).toBe(
|
||||
"0.0001",
|
||||
);
|
||||
});
|
||||
|
||||
test("a genuine zero still renders as zero", () => {
|
||||
expect(amount(transferData(0n), DAI).rawValue).toBe("0.0000");
|
||||
});
|
||||
|
||||
// The three truncators now share one module. The floor is a policy of the
|
||||
// approval and confirmation screens only: the history and balance lists
|
||||
// keep plain truncation, because the transaction detail view is the
|
||||
// authoritative record and already shows exact precision.
|
||||
test("the list rule stays unfloored", () => {
|
||||
expect(truncateAmount("0.000000000000000001")).toBe("0.0000");
|
||||
expect(truncateAmountNeverZero("0.000000000000000001")).toBe(
|
||||
"0.000000000000000001",
|
||||
);
|
||||
});
|
||||
});
|
||||
443
tests/stateMerge.test.js
Normal file
443
tests/stateMerge.test.js
Normal file
@@ -0,0 +1,443 @@
|
||||
// saveState() used to write the entire state blob every time
|
||||
// (src/shared/state.js). Every extension page — the toolbar popup, a dApp
|
||||
// approval window opened by the background, backgroundRefresh() in
|
||||
// src/background/index.js — holds its own in-memory `state`, loaded once,
|
||||
// and src/popup/views/helpers.js showView() saves on EVERY navigation. So
|
||||
// any second page that saved after a first page had written something new
|
||||
// overwrote it, with no attacker and no unusual input: a whole wallet, name,
|
||||
// addresses and encrypted secret included, silently gone
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/304).
|
||||
//
|
||||
// Both cases below drive the real state.js module through two independent
|
||||
// module registries sharing one storage backend, the way two real extension
|
||||
// pages share one chrome.storage.local. The storage stub structured-clones
|
||||
// on both get and set — a stub that hands back the object it was given
|
||||
// aliases the caller's own mutation and would make this entire defect class
|
||||
// invisible (see https://git.eeqj.de/sneak/AutistMask/issues/324).
|
||||
|
||||
function makeStorage() {
|
||||
let store = {};
|
||||
return {
|
||||
get: async (keys) => {
|
||||
const wanted =
|
||||
keys === undefined || keys === null
|
||||
? Object.keys(store)
|
||||
: [].concat(keys);
|
||||
const out = {};
|
||||
for (const key of wanted) {
|
||||
if (key in store) out[key] = structuredClone(store[key]);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
set: async (items) => {
|
||||
for (const [key, value] of Object.entries(items)) {
|
||||
store[key] = structuredClone(value);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// One extension page: a fresh module registry over the shared storage.
|
||||
// state.js resolves the storage API at require time, so the stub has to be
|
||||
// installed before the module is loaded, and `state` is a module-level
|
||||
// singleton, so each page needs its own registry to hold its own copy.
|
||||
function loadPage(storage) {
|
||||
jest.resetModules();
|
||||
globalThis.chrome = { storage: { local: storage } };
|
||||
return {
|
||||
state: require("../src/shared/state"),
|
||||
helpers: require("../src/popup/views/helpers"),
|
||||
};
|
||||
}
|
||||
|
||||
function wallet(name, secret, address) {
|
||||
return {
|
||||
type: "hd",
|
||||
name,
|
||||
xpub: "xpub-" + name,
|
||||
encryptedSecret: secret,
|
||||
nextIndex: 1,
|
||||
addresses: [{ address, balance: "0", tokenBalances: [] }],
|
||||
};
|
||||
}
|
||||
|
||||
const W1 = wallet(
|
||||
"Wallet 1",
|
||||
"secret-one",
|
||||
"0x66133E8ea0f5D1d612D2502a968757D1048c214a",
|
||||
);
|
||||
const W2 = wallet(
|
||||
"Wallet 2",
|
||||
"secret-two",
|
||||
"0xdAC17F958D2ee523a2206206994597C13D831ec7",
|
||||
);
|
||||
|
||||
// Minimal DOM: showView() toggles view elements, clears the flash line and
|
||||
// creates/removes the debug banner. Nothing here is asserted; it only has to
|
||||
// answer without throwing, the way the popup's own index.html would.
|
||||
function makeElement(id) {
|
||||
const classes = new Set();
|
||||
return {
|
||||
id,
|
||||
textContent: "",
|
||||
style: {},
|
||||
classList: {
|
||||
add: (...n) => n.forEach((c) => classes.add(c)),
|
||||
remove: (...n) => n.forEach((c) => classes.delete(c)),
|
||||
toggle: (c, force) => {
|
||||
const on = force === undefined ? !classes.has(c) : force;
|
||||
if (on) classes.add(c);
|
||||
else classes.delete(c);
|
||||
return on;
|
||||
},
|
||||
},
|
||||
remove: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
function makeDocument() {
|
||||
const els = new Map();
|
||||
return {
|
||||
getElementById(id) {
|
||||
if (id === "debug-banner") return null;
|
||||
if (!els.has(id)) els.set(id, makeElement(id));
|
||||
return els.get(id);
|
||||
},
|
||||
createElement: () => makeElement("created"),
|
||||
body: { prepend: () => {} },
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete globalThis.chrome;
|
||||
delete globalThis.document;
|
||||
});
|
||||
|
||||
describe("a save from a page that never saw a wallet another page added", () => {
|
||||
// The first DoD case on the issue: add a wallet in one page, then force
|
||||
// a save from a second page loaded before that wallet existed. Both
|
||||
// wallets must survive.
|
||||
test("both wallets are in storage afterwards", async () => {
|
||||
const storage = makeStorage();
|
||||
await storage.set({ autistmask: { wallets: [W1] } });
|
||||
|
||||
// Loaded while storage held only Wallet 1, and never reloads —
|
||||
// the approval window in the reproduction, or a second popup that
|
||||
// has been open for a while.
|
||||
const stale = loadPage(storage);
|
||||
await stale.state.loadState();
|
||||
expect(stale.state.state.wallets).toHaveLength(1);
|
||||
|
||||
// A second page, loaded after, adds a wallet — the exact sequence
|
||||
// src/popup/views/addWallet.js uses.
|
||||
const fresh = loadPage(storage);
|
||||
await fresh.state.loadState();
|
||||
fresh.state.state.wallets.push(W2);
|
||||
fresh.state.state.hasWallet = true;
|
||||
await fresh.state.saveState();
|
||||
|
||||
expect(
|
||||
(await storage.get("autistmask")).autistmask.wallets,
|
||||
).toHaveLength(2);
|
||||
|
||||
// The stale page saves something that has nothing to do with
|
||||
// wallets — exactly what showView() does on every navigation, and
|
||||
// what backgroundRefresh() does after a balance poll.
|
||||
stale.state.state.currentView = "settings";
|
||||
await stale.state.saveState();
|
||||
|
||||
const persisted = (await storage.get("autistmask")).autistmask;
|
||||
expect(persisted.wallets.map((w) => w.name)).toEqual([
|
||||
"Wallet 1",
|
||||
"Wallet 2",
|
||||
]);
|
||||
expect(persisted.wallets.map((w) => w.encryptedSecret)).toEqual([
|
||||
"secret-one",
|
||||
"secret-two",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the approval-window reproduction", () => {
|
||||
// approval window open, add a wallet in the popup, confirm the approval
|
||||
// — the exact sequence from the issue. The approval window and the
|
||||
// popup are the same popup code with a different starting view, so
|
||||
// showView() is the real save path in both: src/popup/views/approval.js
|
||||
// showTxApproval() calls showView("approve-tx") when the window opens,
|
||||
// and a successful confirm calls
|
||||
// src/popup/views/txStatus.js showWait() -> startWait(), which calls
|
||||
// showView("wait-tx") — the save that clobbered the second wallet in
|
||||
// the reproduction on the issue.
|
||||
test("the wallet added in the popup survives confirming the approval", async () => {
|
||||
globalThis.document = makeDocument();
|
||||
|
||||
const storage = makeStorage();
|
||||
await storage.set({ autistmask: { wallets: [W1] } });
|
||||
|
||||
// The background opens the approval window on the approve-tx
|
||||
// screen; nothing else has happened yet.
|
||||
const approvalWindow = loadPage(storage);
|
||||
await approvalWindow.state.loadState();
|
||||
approvalWindow.helpers.showView("approve-tx");
|
||||
// showView() does not await its own saveState(); an extra save
|
||||
// joins the same queue and only resolves once that one has too,
|
||||
// which is the black-box way to know it landed.
|
||||
await approvalWindow.state.saveState();
|
||||
|
||||
// The user adds a wallet in the popup — a separate page, loaded
|
||||
// after the approval window.
|
||||
const popup = loadPage(storage);
|
||||
await popup.state.loadState();
|
||||
popup.state.state.wallets.push(W2);
|
||||
popup.state.state.hasWallet = true;
|
||||
await popup.state.saveState();
|
||||
expect(
|
||||
(await storage.get("autistmask")).autistmask.wallets,
|
||||
).toHaveLength(2);
|
||||
|
||||
// The user confirms the approval. The approval window navigates
|
||||
// approve-tx -> wait-tx, saving again from state it loaded before
|
||||
// Wallet 2 ever existed.
|
||||
approvalWindow.helpers.showView("wait-tx");
|
||||
await approvalWindow.state.saveState();
|
||||
|
||||
const persisted = (await storage.get("autistmask")).autistmask;
|
||||
expect(persisted.wallets.map((w) => w.name)).toEqual([
|
||||
"Wallet 1",
|
||||
"Wallet 2",
|
||||
]);
|
||||
expect(persisted.wallets.map((w) => w.encryptedSecret)).toEqual([
|
||||
"secret-one",
|
||||
"secret-two",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// backgroundRefresh() (src/background/index.js) loads state, spends seconds
|
||||
// on network I/O in refreshBalances() (src/shared/balances.js) mutating
|
||||
// addr.balance/ensName/tokenBalances IN PLACE on the wallets it already
|
||||
// knew about, then saves. Precondition 2 on the issue: that refresh window
|
||||
// overlapping a membership change (add or delete) on another page must not
|
||||
// clobber or resurrect a wallet — a whole-field diff on `wallets` failed
|
||||
// this, because "background changed a balance" and "another page changed
|
||||
// membership" collided as the same field.
|
||||
describe("background refresh racing a wallet added on another page", () => {
|
||||
test("the wallet added elsewhere survives background's stale balance save", async () => {
|
||||
const storage = makeStorage();
|
||||
await storage.set({ autistmask: { wallets: [W1] } });
|
||||
|
||||
// "background": loads first, and its save is the one that lands
|
||||
// last, modeling the multi-second network round trip in between.
|
||||
const background = loadPage(storage);
|
||||
await background.state.loadState();
|
||||
background.state.state.wallets[0].addresses[0].balance = "1.2345";
|
||||
|
||||
// A second page, loaded after, adds a wallet while background's
|
||||
// refresh is still in flight.
|
||||
const popup = loadPage(storage);
|
||||
await popup.state.loadState();
|
||||
popup.state.state.wallets.push(W2);
|
||||
popup.state.state.hasWallet = true;
|
||||
await popup.state.saveState();
|
||||
expect(
|
||||
(await storage.get("autistmask")).autistmask.wallets,
|
||||
).toHaveLength(2);
|
||||
|
||||
// background's save lands last, carrying only its balance update.
|
||||
await background.state.saveState();
|
||||
|
||||
const persisted = (await storage.get("autistmask")).autistmask;
|
||||
expect(persisted.wallets.map((w) => w.name)).toEqual([
|
||||
"Wallet 1",
|
||||
"Wallet 2",
|
||||
]);
|
||||
expect(persisted.wallets.map((w) => w.encryptedSecret)).toEqual([
|
||||
"secret-one",
|
||||
"secret-two",
|
||||
]);
|
||||
// The balance update itself must not be lost either — this is a
|
||||
// merge, not deletion-always-wins.
|
||||
expect(persisted.wallets[0].addresses[0].balance).toBe("1.2345");
|
||||
});
|
||||
});
|
||||
|
||||
describe("background refresh racing a wallet deleted on another page", () => {
|
||||
test("the wallet deleted elsewhere stays deleted after background's stale balance save", async () => {
|
||||
const storage = makeStorage();
|
||||
await storage.set({ autistmask: { wallets: [W1, W2] } });
|
||||
|
||||
const background = loadPage(storage);
|
||||
await background.state.loadState();
|
||||
background.state.state.wallets[0].addresses[0].balance = "1.2345";
|
||||
|
||||
// A second page deletes Wallet 2 while background's refresh is in
|
||||
// flight — the same splice deleteWallet.js's removeWalletFromState()
|
||||
// does.
|
||||
const popup = loadPage(storage);
|
||||
await popup.state.loadState();
|
||||
popup.state.state.wallets.splice(1, 1);
|
||||
popup.state.state.hasWallet = popup.state.state.wallets.length > 0;
|
||||
await popup.state.saveState();
|
||||
expect(
|
||||
(await storage.get("autistmask")).autistmask.wallets,
|
||||
).toHaveLength(1);
|
||||
|
||||
await background.state.saveState();
|
||||
|
||||
const persisted = (await storage.get("autistmask")).autistmask;
|
||||
expect(persisted.wallets.map((w) => w.name)).toEqual(["Wallet 1"]);
|
||||
expect(persisted.wallets[0].addresses[0].balance).toBe("1.2345");
|
||||
});
|
||||
});
|
||||
|
||||
// allowedSites/deniedSites: { [address]: [hostname, ...] }. Mutated in place
|
||||
// from two different contexts — src/background/index.js:592-599 pushes a
|
||||
// newly approved hostname onto state.allowedSites[activeAddress], and the
|
||||
// Settings "revoke" button (src/popup/views/settings.js:55-68) filters a
|
||||
// hostname out of state[key][addr] in place, deleting the address key
|
||||
// entirely once its list is empty — the exact membership-vs-whole-field
|
||||
// pattern that made the whole-field `wallets` diff unsafe, on a
|
||||
// security-relevant field: a stale whole-field save here can resurrect a
|
||||
// revoked permission or wipe a freshly granted one.
|
||||
const ADDR1 = "0x66133E8ea0f5D1d612D2502a968757D1048c214a";
|
||||
const ADDR2 = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
|
||||
|
||||
function approveSite(pageState, address, hostname) {
|
||||
if (!pageState.allowedSites[address]) {
|
||||
pageState.allowedSites[address] = [];
|
||||
}
|
||||
if (!pageState.allowedSites[address].includes(hostname)) {
|
||||
pageState.allowedSites[address].push(hostname);
|
||||
}
|
||||
}
|
||||
|
||||
function revokeSite(pageState, hostname) {
|
||||
for (const addr of Object.keys(pageState.allowedSites)) {
|
||||
pageState.allowedSites[addr] = pageState.allowedSites[addr].filter(
|
||||
(h) => h !== hostname,
|
||||
);
|
||||
if (pageState.allowedSites[addr].length === 0) {
|
||||
delete pageState.allowedSites[addr];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("a dApp approval racing a stale Settings page's later save", () => {
|
||||
test("the fresh approval survives Settings revoking an unrelated site", async () => {
|
||||
const storage = makeStorage();
|
||||
await storage.set({
|
||||
autistmask: {
|
||||
wallets: [W1],
|
||||
allowedSites: { [ADDR2]: ["other.example"] },
|
||||
},
|
||||
});
|
||||
|
||||
// Settings loads first, and its save lands last — before either has
|
||||
// any idea a dApp approval happened elsewhere in between.
|
||||
const settings = loadPage(storage);
|
||||
await settings.state.loadState();
|
||||
|
||||
// A dApp approval window, opened later, approves a new site for a
|
||||
// different address and saves — the real sequence at
|
||||
// src/background/index.js:592-599.
|
||||
const approval = loadPage(storage);
|
||||
await approval.state.loadState();
|
||||
approveSite(approval.state.state, ADDR1, "dapp.example");
|
||||
await approval.state.saveState();
|
||||
expect(
|
||||
(await storage.get("autistmask")).autistmask.allowedSites[ADDR1],
|
||||
).toEqual(["dapp.example"]);
|
||||
|
||||
// Settings revokes its own, unrelated site — the real sequence at
|
||||
// src/popup/views/settings.js:55-68 — and saves from state loaded
|
||||
// before the dApp approval ever happened.
|
||||
revokeSite(settings.state.state, "other.example");
|
||||
await settings.state.saveState();
|
||||
|
||||
const persisted = (await storage.get("autistmask")).autistmask;
|
||||
expect(persisted.allowedSites[ADDR1]).toEqual(["dapp.example"]);
|
||||
expect(persisted.allowedSites[ADDR2]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a revoked site permission against a stale page's later save", () => {
|
||||
test("the revocation holds even when the stale page approves something else", async () => {
|
||||
const storage = makeStorage();
|
||||
await storage.set({
|
||||
autistmask: {
|
||||
wallets: [W1],
|
||||
allowedSites: { [ADDR1]: ["evil.example"] },
|
||||
},
|
||||
});
|
||||
|
||||
// A stale page loads while the permission still stands.
|
||||
const stale = loadPage(storage);
|
||||
await stale.state.loadState();
|
||||
|
||||
// Settings revokes it — src/popup/views/settings.js:55-68 — from a
|
||||
// second page.
|
||||
const settings = loadPage(storage);
|
||||
await settings.state.loadState();
|
||||
revokeSite(settings.state.state, "evil.example");
|
||||
await settings.state.saveState();
|
||||
expect(
|
||||
(await storage.get("autistmask")).autistmask.allowedSites[ADDR1],
|
||||
).toBeUndefined();
|
||||
|
||||
// The stale page, unaware of the revoke, approves an unrelated site
|
||||
// for a different address and saves — src/background/index.js:592-599.
|
||||
approveSite(stale.state.state, ADDR2, "good.example");
|
||||
await stale.state.saveState();
|
||||
|
||||
const persisted = (await storage.get("autistmask")).autistmask;
|
||||
expect(persisted.allowedSites[ADDR2]).toEqual(["good.example"]);
|
||||
expect(persisted.allowedSites[ADDR1]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// mergeListByIdentity()'s identity function is not guaranteed collision-free
|
||||
// — walletIdentity() falls back to one shared "addr:" value for any wallet
|
||||
// with neither an xpub nor a populated first address (a legacy or corrupt
|
||||
// record). Two such records created independently on two different pages
|
||||
// must not silently collapse into one, dropping the loser's
|
||||
// encryptedSecret with no error and no log.
|
||||
function legacyWallet(name, secret) {
|
||||
return {
|
||||
type: "legacy",
|
||||
name,
|
||||
encryptedSecret: secret,
|
||||
nextIndex: 0,
|
||||
addresses: [],
|
||||
};
|
||||
}
|
||||
|
||||
describe("two wallets independently created with a colliding identity", () => {
|
||||
test("both survive, encryptedSecret included, instead of one silently replacing the other", async () => {
|
||||
const storage = makeStorage();
|
||||
await storage.set({ autistmask: { wallets: [W1] } });
|
||||
|
||||
// Both pages load before either has created their malformed wallet,
|
||||
// so neither has baseline knowledge of the other's.
|
||||
const pageA = loadPage(storage);
|
||||
await pageA.state.loadState();
|
||||
const pageB = loadPage(storage);
|
||||
await pageB.state.loadState();
|
||||
|
||||
pageA.state.state.wallets.push(legacyWallet("Legacy A", "secret-a"));
|
||||
pageA.state.state.hasWallet = true;
|
||||
await pageA.state.saveState();
|
||||
expect(
|
||||
(await storage.get("autistmask")).autistmask.wallets,
|
||||
).toHaveLength(2);
|
||||
|
||||
pageB.state.state.wallets.push(legacyWallet("Legacy B", "secret-b"));
|
||||
pageB.state.state.hasWallet = true;
|
||||
await pageB.state.saveState();
|
||||
|
||||
const persisted = (await storage.get("autistmask")).autistmask;
|
||||
const secrets = persisted.wallets.map((w) => w.encryptedSecret);
|
||||
expect(secrets).toContain("secret-one");
|
||||
expect(secrets).toContain("secret-a");
|
||||
expect(secrets).toContain("secret-b");
|
||||
});
|
||||
});
|
||||
176
tests/uniswapUnknownDecimals.test.js
Normal file
176
tests/uniswapUnknownDecimals.test.js
Normal file
@@ -0,0 +1,176 @@
|
||||
// The scale the swap lines of the dApp approval screen are displayed with.
|
||||
//
|
||||
// Issue #340: `tokenInfo()` in `src/shared/uniswap.js` returned `decimals: 18`
|
||||
// for any token absent from the bundled list — the same guess
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/306 removed from the ERC-20
|
||||
// amount line, still live on the swap path. A 1,000-token swap of a 6-decimal
|
||||
// token then rendered as `0.000000001` on the one screen whose job is to state
|
||||
// what is being authorized, and every newly listed token reaches it.
|
||||
//
|
||||
// What is asserted here is the rule #306 established: resolve the real scale
|
||||
// wherever the wallet already has it, and where nothing has it refuse to
|
||||
// format — base units with the scale stated, never a quantity.
|
||||
|
||||
globalThis.chrome = {
|
||||
storage: { local: { get: async () => ({}), set: async () => {} } },
|
||||
};
|
||||
|
||||
const { AbiCoder, Interface } = require("ethers");
|
||||
const { state } = require("../src/shared/state");
|
||||
const { unknownDecimalsAmount } = require("../src/shared/approvalAmount");
|
||||
const { decodeCalldata } = require("../src/popup/views/approval");
|
||||
|
||||
const ROUTER = "0x66a9893cc07d91d95644aedd05d03f95e1dba8af";
|
||||
const RECIPIENT = "0xC0FfEE0000000000000000000000000000c0fFEe";
|
||||
// Outside the bundled list, as every newly listed token is.
|
||||
const NOVEL = "0xE2E0000000000000000000000000000000000E2e";
|
||||
// Also outside it, standing in for the swap's output side.
|
||||
const NOVEL_OUT = "0xd0d0000000000000000000000000000000000d0d";
|
||||
// In the bundled list, at 18 decimals.
|
||||
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
|
||||
|
||||
// 1,000.00 of a 6-decimal token — the amount from the issue, which the 18
|
||||
// guess rendered as 0.000000001.
|
||||
const THOUSAND_AT_SIX = 1000000000n;
|
||||
// 0.5 WETH out, so the Min. received line has a real number of its own.
|
||||
const HALF_WETH = 500000000000000000n;
|
||||
|
||||
const coder = AbiCoder.defaultAbiCoder();
|
||||
const routerIface = new Interface([
|
||||
"function execute(bytes commands, bytes[] inputs, uint256 deadline)",
|
||||
]);
|
||||
|
||||
// A V2_SWAP_EXACT_IN (command 0x08) execute() call: `amountIn` of `tokenIn`
|
||||
// for at least `amountOutMin` of `tokenOut`.
|
||||
function swapData(tokenIn, amountIn, tokenOut, amountOutMin) {
|
||||
const input = coder.encode(
|
||||
["address", "uint256", "uint256", "address[]", "bool"],
|
||||
[RECIPIENT, amountIn, amountOutMin, [tokenIn, tokenOut], true],
|
||||
);
|
||||
return routerIface.encodeFunctionData("execute", [
|
||||
"0x08",
|
||||
[input],
|
||||
9999999999n,
|
||||
]);
|
||||
}
|
||||
|
||||
// A wallet holding `token` with the decimals the block explorer reported,
|
||||
// shaped as balances.js writes it onto state.
|
||||
function walletsHolding(token, decimals) {
|
||||
return [
|
||||
{
|
||||
name: "Wallet 1",
|
||||
addresses: [
|
||||
{
|
||||
address: "0x" + "a".repeat(40),
|
||||
balance: "1.0",
|
||||
tokenBalances: [
|
||||
{
|
||||
address: token,
|
||||
symbol: "NOVEL",
|
||||
decimals,
|
||||
balance: "1000.0",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// The swap detail line as the approval screen renders it. It goes through
|
||||
// decodeCalldata() rather than uniswap.decode() directly, because the scale
|
||||
// sources the screen supplies are part of what is under test.
|
||||
function swapDetail(data, label) {
|
||||
const decoded = decodeCalldata(data, ROUTER);
|
||||
return decoded.details.find((d) => d.label === label);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.trackedTokens = [];
|
||||
state.wallets = [];
|
||||
});
|
||||
|
||||
describe("a swap of a token outside the bundled list", () => {
|
||||
const data = () => swapData(NOVEL, THOUSAND_AT_SIX, WETH, HALF_WETH);
|
||||
|
||||
test("shows the true quantity when the user tracks the token", () => {
|
||||
state.trackedTokens = [
|
||||
{ address: NOVEL, symbol: "NOVEL", decimals: 6 },
|
||||
];
|
||||
expect(swapDetail(data(), "Amount").value).toBe("1000.0000");
|
||||
});
|
||||
|
||||
test("shows the true quantity from the explorer's decimals", () => {
|
||||
state.wallets = walletsHolding(NOVEL, "6");
|
||||
expect(swapDetail(data(), "Amount").value).toBe("1000.0000");
|
||||
});
|
||||
|
||||
test("refuses to format when nothing knows the scale", () => {
|
||||
const detail = swapDetail(data(), "Amount");
|
||||
expect(detail.value).toBe("1000000000 base units (decimals unknown)");
|
||||
expect(detail.value).toBe(unknownDecimalsAmount(THOUSAND_AT_SIX));
|
||||
// The defect: an 18-decimal guess renders this swap as 0.000000001, a
|
||||
// quantity, and a wrong one.
|
||||
expect(detail.value).not.toMatch(/^0\./);
|
||||
expect(detail.value).not.toMatch(/[0-9]\.[0-9]/);
|
||||
});
|
||||
|
||||
test("the amount carried to the status screens is the same refusal", () => {
|
||||
expect(swapDetail(data(), "Amount").rawValue).toBe(
|
||||
"1000000000 base units (decimals unknown)",
|
||||
);
|
||||
});
|
||||
|
||||
test("a bundled token on the other side still formats", () => {
|
||||
expect(swapDetail(data(), "Min. received").value).toBe("0.5000 WETH");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the Min. received line takes the same rule", () => {
|
||||
test("refuses to format an output token of unknown scale", () => {
|
||||
const data = swapData(WETH, HALF_WETH, NOVEL_OUT, THOUSAND_AT_SIX);
|
||||
const detail = swapDetail(data, "Min. received");
|
||||
expect(detail.value).toBe("1000000000 base units (decimals unknown)");
|
||||
expect(detail.value).not.toMatch(/[0-9]\.[0-9]/);
|
||||
});
|
||||
|
||||
test("shows the true quantity when the user tracks the output token", () => {
|
||||
state.trackedTokens = [
|
||||
{ address: NOVEL_OUT, symbol: "NOVEL", decimals: 6 },
|
||||
];
|
||||
const data = swapData(WETH, HALF_WETH, NOVEL_OUT, THOUSAND_AT_SIX);
|
||||
expect(swapDetail(data, "Min. received").value).toBe("1000.0000");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the permit amount takes the same rule", () => {
|
||||
// PERMIT2_PERMIT (command 0x0a): the input token and amount come from the
|
||||
// permit rather than from a swap step.
|
||||
function permitData(token, amount) {
|
||||
const input = coder.encode(
|
||||
[
|
||||
"tuple(tuple(address,uint160,uint48,uint48),address,uint256)",
|
||||
"bytes",
|
||||
],
|
||||
[[[token, amount, 0, 0], ROUTER, 9999999999], "0x1234"],
|
||||
);
|
||||
return routerIface.encodeFunctionData("execute", [
|
||||
"0x0a",
|
||||
[input],
|
||||
9999999999n,
|
||||
]);
|
||||
}
|
||||
|
||||
test("refuses to format a permit on a token of unknown scale", () => {
|
||||
const detail = swapDetail(permitData(NOVEL, THOUSAND_AT_SIX), "Amount");
|
||||
expect(detail.value).toBe("1000000000 base units (decimals unknown)");
|
||||
});
|
||||
|
||||
test("an unbounded permit is still named, with or without a scale", () => {
|
||||
const maxUint160 = (1n << 160n) - 1n;
|
||||
expect(swapDetail(permitData(NOVEL, maxUint160), "Amount").value).toBe(
|
||||
"Unlimited",
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user