Compare commits
8
Commits
09e6454545
..
next
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45aead6340 | ||
|
|
e517219038 | ||
|
|
a3da448f0d | ||
|
|
93c34e1a2a | ||
|
|
4472746b89 | ||
|
|
4109c4d44a | ||
|
|
7b9821b06f | ||
|
|
070ad82338 |
@@ -502,9 +502,10 @@ papered over:
|
||||
opens while libsodium is still loading, is not driven.
|
||||
- Approval windows open at 1280x720 whatever size the extension asks for. The
|
||||
site-connection prompt and the transaction approval are checked for sideways
|
||||
scrolling at 396x600 by sizing the page itself, which leaves out the window's
|
||||
frame and the page widening its window, so whether an approval screen fits its
|
||||
window is checked in the Firefox suite only.
|
||||
scrolling at 396x600 by sizing the page itself for that measurement only, and
|
||||
the rest of each test runs at 1280x720. That leaves out the window's frame and
|
||||
the page widening its window, so whether an approval screen fits its window is
|
||||
checked in the Firefox suite only.
|
||||
|
||||
Any test that drives a failure path on purpose declares the `console.error` it
|
||||
is about to provoke, via `errors.expect()`. That is not a mute: the declaration
|
||||
@@ -1128,13 +1129,15 @@ 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`). The token permission warning on the signature
|
||||
screen takes the same rule for its amounts. An unbounded allowance or permit
|
||||
needs no scale to describe and is still shown as `Unlimited`. A source's answer
|
||||
counts only if it is a whole number from 0 to 80: `decimals()` returns a
|
||||
`uint8`, but `formatUnits()` cannot format more than 80 decimal places, so a
|
||||
token that reports 81 to 255 is shown as one whose scale nothing knows.
|
||||
(`src/popup/views/approval.js`) and the swap's `Amount`, `Min. received`,
|
||||
`Moved from the sender` and `Permit2 allowance` lines and the `Paid to` line of
|
||||
a move into the router (`src/shared/uniswap.js`). The token permission warning
|
||||
on the signature screen takes the same rule for its amounts. An unbounded
|
||||
allowance or permit needs no scale to describe and is still shown as
|
||||
`Unlimited`. A source's answer counts only if it is a whole number from 0 to 80:
|
||||
`decimals()` returns a `uint8`, but `formatUnits()` cannot format more than 80
|
||||
decimal places, so a token that reports 81 to 255 is shown as one whose scale
|
||||
nothing knows.
|
||||
|
||||
The rule holds only if nothing invents a scale UPSTREAM of it. Those three
|
||||
sources are read as authoritative, so a value written into one of them cannot be
|
||||
@@ -1252,9 +1255,31 @@ Decoding). So a step whose USDT-for-USDC swap action could not be read, with a
|
||||
A V4 step with no swap action sets only the sides its `SETTLE`, `SETTLE_ALL`,
|
||||
`TAKE` or `TAKE_ALL` names.
|
||||
|
||||
An `UNWRAP_WETH` step makes `Token Out` ETH only when the output side is WETH,
|
||||
on mainnet or Sepolia, or when no step set the output side; a WETH
|
||||
`Min. received` figure then reads in ETH. Otherwise `Token Out` and
|
||||
An `UNWRAP_WETH` step makes `Token Out` ETH only when no step set the output
|
||||
side, or when the output side is WETH, on mainnet or Sepolia, that the step that
|
||||
set it paid to the router and that the router still holds when the `UNWRAP_WETH`
|
||||
runs (Transaction Decoding below gives what the router holds). The router
|
||||
unwraps only the WETH it holds, so WETH that step paid to the user, or to anyone
|
||||
else, stays WETH: a swap that pays the router WETH, then a swap that pays the
|
||||
user WETH, then an unwrap, shows WETH with the second swap's minimum. The
|
||||
minimum reads in ETH only when that step paid all its WETH to the router and
|
||||
every step between it and the `UNWRAP_WETH` is one the decoder read of these: a
|
||||
`PERMIT2_PERMIT`, a `BALANCE_CHECK_ERC20`, or a `SWEEP`, `TRANSFER`,
|
||||
`PAY_PORTION` or `PAY_PORTION_FULL_PRECISION` of a token other than WETH, but
|
||||
not of ETH to a WETH contract, which pays the router WETH. None of these can
|
||||
take WETH out of the router or pay anyone WETH; the decoder treats every other
|
||||
step as one that may. Otherwise the swap shows ETH with no minimum, as it does
|
||||
after a V4 step that `TAKE`s some of its WETH to the user and the rest to the
|
||||
router, or that pays the router WETH beside a payout the decoder cannot read,
|
||||
and with a WETH interface fee paid by `PAY_PORTION` before the `UNWRAP_WETH`:
|
||||
the decoder does not count how much of that step's minimum reaches the
|
||||
`UNWRAP_WETH`, nor read the `UNWRAP_WETH`'s own minimum. When an `UNWRAP_WETH`
|
||||
of that WETH pays the router, or its recipient cannot be read, the router may
|
||||
hold the ETH, and a later step may pay it out as WETH, as a `WRAP_ETH` of it to
|
||||
the user does: after any later step but those listed, the swap shows WETH with
|
||||
no minimum. Once the swap shows no minimum, or shows WETH this way, no later
|
||||
step, a later `UNWRAP_WETH` included, brings back the minimum or ETH; only a
|
||||
later step that sets the output side sets it anew. Otherwise `Token Out` and
|
||||
`Min. received` keep the output side's own token and figure, whether the swap
|
||||
was paid in ETH or in a token: a V2 exact-out swap that buys USDC and then
|
||||
unwraps the WETH it did not spend shows USDC. The token permission warning on
|
||||
@@ -1378,6 +1403,19 @@ carries a `schemaVersion` — `STATE_SCHEMA_VERSION` in
|
||||
`saveState()` and the background's `updateState()` both do, so whichever context
|
||||
wrote last, the record says which build's shape it is in.
|
||||
|
||||
Each write reads the record, changes it and writes it back, holding a lock from
|
||||
the read to the write: the browser's own (`navigator.locks`), taken through
|
||||
`withLock()` in `src/shared/browserApi.js`. Every page of the extension and its
|
||||
background share it, except a page in a Firefox private window, which Firefox
|
||||
gives locks of its own (see https://git.eeqj.de/sneak/AutistMask/issues/646).
|
||||
The popup's `saveState()`, the background's `updateState()` and the
|
||||
StateRecovery reset all take it, so among the pages and the background that
|
||||
share it, no write lands between another write's read and its write, where it
|
||||
would be lost. Chrome has it from version 69, older than any Chrome that runs a
|
||||
Manifest V3 extension, in pages and in the service worker; Firefox from version
|
||||
96, older than the 115 `manifest/firefox.json` declares. Where it is missing, a
|
||||
write fails rather than going ahead without it.
|
||||
|
||||
Version 1 is the shape that shipped before versions existed, so a stored record
|
||||
with no `schemaVersion` is version 1 rather than a defect: it loads normally and
|
||||
is migrated in place by being stamped on the first write. An upgrade never shows
|
||||
@@ -1988,7 +2026,11 @@ view would leave a wallet one click from deletion.
|
||||
- Type: transaction classification — one of: Native ETH Transfer, ERC-20
|
||||
Token Transfer, Swap, Token Approval, Contract Call, Contract Creation. A
|
||||
transfer with a token contract is an ERC-20 Token Transfer whatever symbol
|
||||
the token reports.
|
||||
the token reports. A call named `execute` or `multicall` is a Swap, here
|
||||
and on its history row, only when it was sent to one of the Universal
|
||||
Router addresses Uniswap publishes for the network it was sent on (see
|
||||
Transaction Decoding); sent to any other contract, its history row shows
|
||||
the method name and this line reads Contract Call.
|
||||
- Status: "Success" or "Failed"
|
||||
- From: blockie + color dot + full address (tap to copy) + etherscan link;
|
||||
ENS name if available
|
||||
@@ -2052,8 +2094,11 @@ view would leave a wallet one click from deletion.
|
||||
none, and the tokens tracked on that network, and sends `chainChanged`
|
||||
with the new chain id to every open tab. A token is tracked only on the
|
||||
network it was added on, because a contract address names a token on one
|
||||
network only. Choosing the network already active changes nothing and
|
||||
sends nothing
|
||||
network only. Switching also clears every address's balances. A balance
|
||||
refresh, by the popup or the background, stores what it fetched only if
|
||||
the stored network is still the one it fetched on when it returns, so the
|
||||
previous network's balances never reach the new one. Choosing the network
|
||||
already active changes nothing and sends nothing
|
||||
- Ethereum RPC: endpoint URL input + "Save" button (validated against
|
||||
`eth_chainId` before being saved)
|
||||
- Blockscout API: endpoint URL input + "Save" button (validated against
|
||||
@@ -2382,10 +2427,11 @@ view would leave a wallet one click from deletion.
|
||||
transaction"
|
||||
- Decoded action (if calldata is recognized): action name, token details,
|
||||
amounts, what each swap step spends that the `Amount` line does not give,
|
||||
what each `PERMIT2_TRANSFER_FROM` moves and where to, steps, deadline, and
|
||||
unless a swap pays only the From address, a `Paid to` line for each other
|
||||
address it pays, or saying that a token stays in the router or who it pays
|
||||
is unknown (see Transaction Decoding)
|
||||
what each `PERMIT2_TRANSFER_FROM` moves and where to, what each
|
||||
`PERMIT2_PERMIT` whose amount is not the `Amount` figure lets its spender
|
||||
take, steps, deadline, and unless a swap pays only the From address, a
|
||||
`Paid to` line for each other address it pays, or saying that a token
|
||||
stays in the router or who it pays is unknown (see Transaction Decoding)
|
||||
- From: color dot + full address + etherscan link
|
||||
- Contract: color dot + full address + etherscan link, token symbol label if
|
||||
known; for a contract creation, the same sentence as on WaitTx
|
||||
@@ -3174,34 +3220,42 @@ Currently supported:
|
||||
added to the total while both are quantities: a V3 exact-in of 600 USDT and a
|
||||
V2 exact-in of 400 USDT, both paid by the user, read `1000.0000 USDT`. When
|
||||
the decoder does not know a take's amount, the total is not known and there is
|
||||
no `Amount` line. `Token In` is the token of the last `PERMIT2_PERMIT` the
|
||||
decoder reads, when there is one. Its amount, `Unlimited` included, stands as
|
||||
the `Amount` figure in place of the total only in the plain shape of Uniswap's
|
||||
own routes: it is the only `PERMIT2_PERMIT`, its spender is the router, the
|
||||
router may not let it fail, no step before it takes its token or a token the
|
||||
decoder does not know, and the decoder reads every step after it in full.
|
||||
Permit2 then lets the router take no more of the token than that amount, so
|
||||
the permit covers every take of it. A step the decoder does not read in full
|
||||
may raise what Permit2 lets the router take, as a `PERMIT2_PERMIT_BATCH` can:
|
||||
a command the decoder does not read (listed at the end of this section), a
|
||||
step whose input it cannot read, in whole or in part, and a step it fails on.
|
||||
In any other case the line gives the total, as with no permit. When the step
|
||||
that sets the input side spends a token other than the permit's, or one the
|
||||
decoder does not know, its amount gets lines of its own and the total has no
|
||||
figure to start from: unless the permit's amount stands there is no `Amount`
|
||||
line, and each take of the permit's token gets lines of its own. Each take the
|
||||
total does not count gives three lines after the `Amount` line (after
|
||||
`Token In` when there is none): one of a token other than `Token In`; one of
|
||||
`Token In` after an amount that is not a quantity (a V4 open delta,
|
||||
`ALREADY_PAID`, which keep their wording on the `Amount` line, or no stated
|
||||
amount, as of a V4 exact-out step); and one whose amount the decoder does not
|
||||
know. When the step that sets the input side states no amount and there is no
|
||||
`Amount` line, that step gets them too whenever another take's lines give a
|
||||
figure, so that figure cannot read as all that leaves. They come in step
|
||||
order, the step that sets the input side first when it has them:
|
||||
`Moved from the sender`, its amount, worded as the `Amount` line words one, or
|
||||
`Unknown (could not be decoded)` when the decoder does not know it;
|
||||
`Token moved`, giving the token's address as the `Token In` line does; and
|
||||
no `Amount` line. A `PERMIT2_PERMIT` names `Token In` only when its amount,
|
||||
`Unlimited` included, stands as the `Amount` figure in place of the total,
|
||||
which it does only in the plain shape of Uniswap's own routes: it comes before
|
||||
the step that sets the input side, it is the only `PERMIT2_PERMIT` in the
|
||||
transaction, its spender is the router, the router may not let it fail, no
|
||||
step before it takes its token or a token the decoder does not know, and the
|
||||
decoder reads every step after it in full. Permit2 then lets the router take
|
||||
no more of the token than that amount, so the permit covers every take of it.
|
||||
A step the decoder does not read in full may raise what Permit2 lets the
|
||||
router take, as a `PERMIT2_PERMIT_BATCH` can: a command the decoder does not
|
||||
read (listed at the end of this section), a step whose input it cannot read,
|
||||
in whole or in part, and a step it fails on. Every other `PERMIT2_PERMIT`,
|
||||
before the step that sets the input side or after it, leaves `Token In` and
|
||||
the `Amount` line as they read with no permit: a permit of 5,000 DAI to
|
||||
another address and then a V3 exact-in of 600 USDT read `Swap USDT → USDC`
|
||||
with `Amount 600.0000 USDT`, and so do that exact-in and then a permit of
|
||||
5,000 DAI to the router. When a permit's amount stands and the step that sets
|
||||
the input side spends a token other than the permit's, or one the decoder does
|
||||
not know, that step's amount gets lines of its own, unless it states no amount
|
||||
and the user pays it none of its input token. Each take the total does not
|
||||
count gives three lines after the `Amount` line (after `Token In` when there
|
||||
is none): one of a token other than `Token In`; one of `Token In` after an
|
||||
amount that is not a quantity (a V4 open delta, `ALREADY_PAID`, which keep
|
||||
their wording on the `Amount` line, or no stated amount, as of a V4 exact-out
|
||||
step); and one whose amount the decoder does not know. When the step that sets
|
||||
the input side states no amount, the user pays it some of its input token, and
|
||||
there is no `Amount` line, that step gets them too whenever another take's
|
||||
lines give a figure, or a `PERMIT2_TRANSFER_FROM` of its token gives one, on
|
||||
the lines below or, into the router, on its `Paid to` line, so that figure
|
||||
cannot read as all that leaves. When it states no amount and the user pays it
|
||||
none of its input token, as when the router pays it, that step takes none of
|
||||
that token from the user's wallet and never gets them, with a permit or
|
||||
without. They come in step order, the step that sets the input side first when
|
||||
it has them: `Moved from the sender`, its amount, worded as the `Amount` line
|
||||
words one, or `Unknown (could not be decoded)` when the decoder does not know
|
||||
it; `Token moved`, giving the token's address as the `Token In` line does; and
|
||||
`Moved to`, which reads `The swap step that spends it`. A token the decoder
|
||||
does not know gives the `Moved from the sender` line alone. A step may also
|
||||
take from the user's wallet what the decoder did not read: a V4 step whose
|
||||
@@ -3222,11 +3276,19 @@ Currently supported:
|
||||
on every router but `UniversalRouterV1`, and otherwise gives the address. A
|
||||
move into the router needs none of them, because its `Paid to` line and
|
||||
`Token moved into the router` line already give the amount, the token and
|
||||
where it goes, and so its amount is shown once. These lines change neither the
|
||||
`Paid to` lines nor the minimum's label. A step goes unread when its recipient
|
||||
does not decode as an address, when it is a V3 swap step whose path is shorter
|
||||
than one token address or has bytes after its last hop, or when it is a
|
||||
command the decoder does not read: every command other than `PERMIT2_PERMIT`,
|
||||
where it goes, and so its amount is shown once. Every `PERMIT2_PERMIT` whose
|
||||
amount does not stand as the `Amount` figure, before the step that sets the
|
||||
input side or after it, gives three lines, in step order, after those for each
|
||||
`PERMIT2_TRANSFER_FROM`: `Permit2 allowance`, its amount, for example
|
||||
`5000.0000 DAI`, or `Unlimited` for Permit2's maximum; `Allowance token`,
|
||||
giving the token's address as the `Token In` line does; and
|
||||
`Allowance spender`, the address it lets take the token. Only a permit whose
|
||||
amount stands gives none: the `Amount` line gives its amount, `Token In` its
|
||||
token, and its spender is the router. These lines change neither the `Paid to`
|
||||
lines nor the minimum's label. A step goes unread when its recipient does not
|
||||
decode as an address, when it is a V3 swap step whose path is shorter than one
|
||||
token address or has bytes after its last hop, or when it is a command the
|
||||
decoder does not read: every command other than `PERMIT2_PERMIT`,
|
||||
`PERMIT2_TRANSFER_FROM`, `V2_SWAP_EXACT_IN`, `V2_SWAP_EXACT_OUT`,
|
||||
`V3_SWAP_EXACT_IN`, `V3_SWAP_EXACT_OUT`, `V4_SWAP`, `SWEEP`, `TRANSFER`,
|
||||
`PAY_PORTION`, `PAY_PORTION_FULL_PRECISION`, `ACROSS_V4_DEPOSIT_V3`,
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
"fmt": "prettier --write .",
|
||||
"fmt-check": "prettier --check ."
|
||||
},
|
||||
"jest": {
|
||||
"setupFiles": [
|
||||
"<rootDir>/tests/support/navigatorLocks.js"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
"@tailwindcss/cli": "4.3.1",
|
||||
|
||||
@@ -1379,6 +1379,13 @@ const RECENT_BALANCE_REFRESH_MS = Math.floor(BALANCE_REFRESH_PERIOD_MS / 2);
|
||||
// balances that came back — by address, onto whatever storage holds NOW.
|
||||
// Applying by address rather than writing the array back is what keeps a
|
||||
// wallet or address added, renamed or deleted during the round trip.
|
||||
//
|
||||
// Nothing is applied when the network stored NOW is not the one the refresh
|
||||
// ran on. A network switch during the round trip cleared every address's
|
||||
// balances (applyChainSwitchFields()), and the previous network's must not come
|
||||
// back over them (https://git.eeqj.de/sneak/AutistMask/issues/577).
|
||||
// lastBalanceRefresh is left as the switch set it, so the next tick refreshes
|
||||
// the new network.
|
||||
async function backgroundRefresh() {
|
||||
const s = await getState();
|
||||
const now = Date.now();
|
||||
@@ -1402,6 +1409,7 @@ async function backgroundRefresh() {
|
||||
}
|
||||
|
||||
await updateState((fresh) => {
|
||||
if (fresh.networkId !== s.networkId) return;
|
||||
for (const wallet of fresh.wallets) {
|
||||
for (const addr of wallet.addresses || []) {
|
||||
const got = refreshed.get(String(addr.address).toLowerCase());
|
||||
|
||||
+19
-26
@@ -16,17 +16,20 @@
|
||||
// across any number of awaits and no concurrent work can
|
||||
// move it.
|
||||
// updateState(fn) read fresh, apply fn to that fresh record, write it
|
||||
// back — all inside a queue, so two background writes
|
||||
// never interleave, and the read is one storage round trip
|
||||
// ahead of the write rather than a page lifetime ahead of
|
||||
// it (which is what made the popup's saveState() need a
|
||||
// back — all holding the lock every write of the stored
|
||||
// record takes, so no other write lands in between, by
|
||||
// the background or by any page except a page in a
|
||||
// Firefox private window (README, "Stored state and its
|
||||
// version"). The read is one storage round trip ahead of
|
||||
// the write rather than a page lifetime ahead of it
|
||||
// (which is what made the popup's saveState() need a
|
||||
// per-field merge against a baseline at all).
|
||||
//
|
||||
// A handler that must both read and write therefore does its network work
|
||||
// against a snapshot it owns, and applies the RESULT inside updateState().
|
||||
// It never publishes an object other in-flight work is holding.
|
||||
|
||||
const { storageGet, storageSet } = require("../shared/browserApi");
|
||||
const { storageGet, storageSet, withLock } = require("../shared/browserApi");
|
||||
const { normalizePersisted } = require("../shared/persistedState");
|
||||
const {
|
||||
STATE_SCHEMA_VERSION,
|
||||
@@ -51,11 +54,6 @@ async function getState() {
|
||||
return normalizePersisted(result.autistmask);
|
||||
}
|
||||
|
||||
// Serializes the read-modify-write turns below. Two of them interleaved would
|
||||
// each read before the other wrote, and the second write would carry the first
|
||||
// one's fields back to their pre-turn values.
|
||||
let updateQueue = Promise.resolve();
|
||||
|
||||
async function updateStateOnce(mutate) {
|
||||
const s = await getState();
|
||||
await mutate(s);
|
||||
@@ -70,27 +68,22 @@ async function updateStateOnce(mutate) {
|
||||
|
||||
// Apply `mutate` to a record read fresh from storage and write the result
|
||||
// back. `mutate` receives a detached, normalized profile and mutates it in
|
||||
// place; it may be async, but it must not do anything slow — the window
|
||||
// between the read and the write is the window in which another context's
|
||||
// write is lost, and keeping it to one storage round trip is what makes a
|
||||
// whole-record write safe here. Concretely: the write is the WHOLE record, so
|
||||
// a popup write that lands inside that window is reverted, in every field, by
|
||||
// the record this turn read before it. That is accepted because the window is
|
||||
// one round trip long and the popup is not writing while the worker is;
|
||||
// widening it is what would make it a real hazard.
|
||||
// place; it may be async, but it must not do anything slow. The write is the
|
||||
// WHOLE record, which is safe only because the lock (withLock() in
|
||||
// src/shared/browserApi.js) is held from the read to the write: two
|
||||
// background turns, or a turn and a page's save, never interleave
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/641). Every page's save waits
|
||||
// while it is held, except a page in a Firefox private window, which Firefox
|
||||
// gives locks of its own (README, "Stored state and its version").
|
||||
//
|
||||
// `mutate` must also not call updateState() itself, directly or through
|
||||
// anything it awaits: the queue is strictly serial, so the inner turn waits on
|
||||
// the outer one, which is waiting on the inner one. That deadlocks the whole
|
||||
// background, not just the caller. Mutate the record you were handed.
|
||||
// anything it awaits: the inner turn waits for the lock the outer one holds,
|
||||
// and the outer one is waiting on the inner one. That deadlocks every write of
|
||||
// the stored record, not just the caller. Mutate the record you were handed.
|
||||
//
|
||||
// Resolves with the record that was written.
|
||||
function updateState(mutate) {
|
||||
const turn = updateQueue.then(() => updateStateOnce(mutate));
|
||||
// The queue must advance even when a turn rejects, or every update after
|
||||
// it queues behind a promise that never settles.
|
||||
updateQueue = turn.catch(() => {});
|
||||
return turn;
|
||||
return withLock("autistmask", () => updateStateOnce(mutate));
|
||||
}
|
||||
|
||||
module.exports = { getState, updateState };
|
||||
|
||||
+36
-5
@@ -68,23 +68,54 @@ let refreshInFlight = false;
|
||||
// the recovery screen: there is no profile left to refresh.
|
||||
let refreshTimer = null;
|
||||
|
||||
// The refresh writes into a copy of the wallets. Inside the save, under the
|
||||
// lock, its results are copied onto the address records in `state` only if the
|
||||
// network it ran on is still the active one, on this page and in the stored
|
||||
// record; the background's switch, after the user approves a site's request,
|
||||
// changes only the stored record. A switch while the refresh ran cleared every
|
||||
// address's balances (applyChainSwitchFields() in
|
||||
// src/shared/chainSwitchFields.js), and the previous network's must not come
|
||||
// back over them (https://git.eeqj.de/sneak/AutistMask/issues/577). A dropped
|
||||
// refresh is not recorded as done. Results are copied by address, so an address
|
||||
// added or removed meanwhile is left as it is.
|
||||
async function doRefreshAndRender() {
|
||||
if (refreshInFlight) return;
|
||||
refreshInFlight = true;
|
||||
try {
|
||||
const networkId = state.networkId;
|
||||
const wallets = structuredClone(state.wallets);
|
||||
await Promise.all([
|
||||
refreshPrices(),
|
||||
refreshBalances(
|
||||
state.wallets,
|
||||
wallets,
|
||||
state.rpcUrl,
|
||||
state.blockscoutUrl,
|
||||
state.trackedTokens,
|
||||
state.networkId,
|
||||
networkId,
|
||||
pageClosed.signal,
|
||||
),
|
||||
]);
|
||||
state.lastBalanceRefresh = Date.now();
|
||||
await saveState();
|
||||
const refreshed = new Map();
|
||||
for (const wallet of wallets) {
|
||||
for (const addr of wallet.addresses) {
|
||||
refreshed.set(addr.address, addr);
|
||||
}
|
||||
}
|
||||
await saveState((stored) => {
|
||||
if (state.networkId !== networkId) return false;
|
||||
if (stored.networkId !== networkId) return false;
|
||||
for (const wallet of state.wallets) {
|
||||
for (const addr of wallet.addresses) {
|
||||
const got = refreshed.get(addr.address);
|
||||
if (!got) continue;
|
||||
for (const key of ["balance", "ensName", "tokenBalances"]) {
|
||||
if (got[key] !== undefined) addr[key] = got[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
state.lastBalanceRefresh = Date.now();
|
||||
return true;
|
||||
});
|
||||
renderWalletList();
|
||||
} catch (e) {
|
||||
// Every call site fires this and walks away — the boot below, the ten
|
||||
@@ -220,7 +251,7 @@ async function widenApprovalWindow() {
|
||||
async function init() {
|
||||
// First, before anything can save: showView() saves on every navigation
|
||||
// without awaiting, so a save that fails from here on has somewhere to be
|
||||
// reported rather than being swallowed by the save queue
|
||||
// reported rather than reaching only the console
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/362). Registered ahead of
|
||||
// the approval-window branch below too, since that window saves as well.
|
||||
//
|
||||
|
||||
@@ -24,7 +24,11 @@
|
||||
// than written again locally so that tests/popupElementIds.test.js sees these
|
||||
// lookups and holds every id below against the markup.
|
||||
const { $, VIEWS } = require("./helpers");
|
||||
const { storageGet, storageRemove } = require("../../shared/browserApi");
|
||||
const {
|
||||
storageGet,
|
||||
storageRemove,
|
||||
withLock,
|
||||
} = require("../../shared/browserApi");
|
||||
const { log } = require("../../shared/log");
|
||||
|
||||
// Typed in full before anything is erased, in the same spirit as the wallet
|
||||
@@ -137,7 +141,11 @@ async function resetProfile() {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await storageRemove("autistmask");
|
||||
// Under the lock every write of the stored record takes, so the erase
|
||||
// cannot land between another write's read and its write and be undone.
|
||||
// A page in a Firefox private window is the exception: Firefox gives
|
||||
// it locks of its own (README, "Stored state and its version").
|
||||
await withLock("autistmask", () => storageRemove("autistmask"));
|
||||
} catch (e) {
|
||||
log.errorf("state recovery: reset failed:", e);
|
||||
setFlash("The saved data could not be erased. Nothing was changed.");
|
||||
|
||||
@@ -31,6 +31,11 @@
|
||||
// Everything is resolved on use rather than captured at module load. The MV3
|
||||
// service worker is torn down and re-evaluated repeatedly, and the unit
|
||||
// suite installs its stubs on `global.chrome` around a require().
|
||||
//
|
||||
// The module also holds withLock(), a wrapper around the browser's
|
||||
// `navigator.locks`, which is in neither namespace. It sits beside
|
||||
// storageGet() and storageSet() because every write of the stored record
|
||||
// takes it.
|
||||
|
||||
// The extension API namespace, preferring `browser.*` where it exists.
|
||||
//
|
||||
@@ -219,6 +224,33 @@ function storageRemove(keys) {
|
||||
return Promise.resolve(storage.remove(keys));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` while holding the browser's lock called `name`
|
||||
* (`navigator.locks`), and settle as `fn` settles. Every page of the extension
|
||||
* and its background share these locks, except a page in a Firefox private
|
||||
* window (README, "Stored state and its version"), so while one of them holds
|
||||
* `name` another asking for it waits, in the order they asked. The lock is let
|
||||
* go when `fn` settles, whether it resolved or rejected.
|
||||
*
|
||||
* Every write of the stored record holds the lock named after its key,
|
||||
* "autistmask", from its read to its write: saveState() in
|
||||
* src/shared/state.js, updateState() in src/background/state.js, and the
|
||||
* reset in src/popup/views/stateRecovery.js.
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {function(): Promise<*>} fn
|
||||
* @returns {Promise<*>} what `fn` resolved with.
|
||||
* @throws rejects, without running `fn`, where `navigator.locks` is absent.
|
||||
*/
|
||||
function withLock(name, fn) {
|
||||
if (typeof navigator === "undefined" || !navigator.locks) {
|
||||
return Promise.reject(
|
||||
new Error("navigator.locks is not available in this context"),
|
||||
);
|
||||
}
|
||||
return navigator.locks.request(name, () => fn());
|
||||
}
|
||||
|
||||
// `storage.session`, the browser's session storage: what is kept there lasts
|
||||
// until the browser closes. It survives the background worker being stopped
|
||||
// and started again, which module-level variables do not (README, Background
|
||||
@@ -373,4 +405,5 @@ module.exports = {
|
||||
windowsGetLastFocused,
|
||||
windowsRemove,
|
||||
windowsUpdate,
|
||||
withLock,
|
||||
};
|
||||
|
||||
+36
-34
@@ -35,7 +35,7 @@ const {
|
||||
migrationNeeded,
|
||||
} = require("./stateSchema");
|
||||
|
||||
const { storageGet, storageSet } = require("./browserApi");
|
||||
const { storageGet, storageSet, withLock } = require("./browserApi");
|
||||
const { log } = require("./log");
|
||||
|
||||
// The live record the proxy below guards. Everything inside this module reads
|
||||
@@ -458,8 +458,8 @@ function mergeNetworkEndpoints(base, ours, theirs) {
|
||||
// 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
|
||||
// which is why saves from one page wait for each other (see saveState()), 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
|
||||
@@ -467,11 +467,7 @@ function mergeNetworkEndpoints(base, ours, theirs) {
|
||||
// (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() {
|
||||
// A copy, so what this save compares and writes is the page's state as it
|
||||
// stood when the save began. A change made while it waits on storage is
|
||||
// left for the next save, which compares against this copy.
|
||||
const current = structuredClone(snapshotPersisted());
|
||||
async function saveStateOnce(beforeWrite) {
|
||||
const result = await storageGet("autistmask");
|
||||
// The record in storage right now is about to be merged into and written
|
||||
// back, so it is validated exactly like a load validates it. Without this,
|
||||
@@ -485,6 +481,12 @@ async function saveStateOnce() {
|
||||
// come from storage in its loaded (self-healed) shape. See
|
||||
// normalizePersisted() in persistedState.js.
|
||||
const fresh = normalizePersisted(result.autistmask);
|
||||
if (beforeWrite && beforeWrite(fresh) === false) return;
|
||||
|
||||
// A copy, so what this save compares and writes is the page's state as it
|
||||
// stood once the stored record was read. A change made while it waits on
|
||||
// the write is left for the next save, which compares against this copy.
|
||||
const current = structuredClone(snapshotPersisted());
|
||||
|
||||
const merged = { ...fresh };
|
||||
for (const key of PERSISTED_FIELDS) {
|
||||
@@ -529,35 +531,21 @@ async function saveStateOnce() {
|
||||
rawState.hasWallet = rawState.wallets.length > 0;
|
||||
|
||||
// What this save compared and wrote, not the page's state now: a change
|
||||
// made during the save must still differ from the baseline, or the save
|
||||
// queued after it finds nothing to store
|
||||
// made during the save must still differ from the baseline, or the next
|
||||
// save finds nothing to store
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/448).
|
||||
baseline = current;
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
// Where a failed save is REPORTED, set once by the context that has a screen
|
||||
// to say it on (src/popup/index.js).
|
||||
//
|
||||
// A save that fails must not fail silently. showView() fires saveState() on
|
||||
// every navigation without awaiting it, and the queue below has to attach a
|
||||
// rejection handler to keep advancing — so a failing save was swallowed
|
||||
// entirely: no throw, no message, nothing on screen. The wallet kept running
|
||||
// against storage that was rejecting every write, which is the data-loss half
|
||||
// of https://git.eeqj.de/sneak/AutistMask/issues/362. The awaited callers were
|
||||
// no better off: `await saveState()` inside an unguarded event handler surfaces
|
||||
// in the console and nowhere the user looks.
|
||||
// every navigation without awaiting it, and `await saveState()` inside an
|
||||
// unguarded event handler is no better: either way, without this, a failure
|
||||
// would reach only the console, where the user never looks, and the wallet
|
||||
// would keep running against storage that rejects every write. That is the
|
||||
// data-loss half of https://git.eeqj.de/sneak/AutistMask/issues/362.
|
||||
//
|
||||
// This is the "tell the user" half; the other half is the floor in
|
||||
// normalizePersisted(), which stops the malformed-record cause from arising in
|
||||
@@ -583,11 +571,25 @@ function reportSaveFailure(err) {
|
||||
}
|
||||
}
|
||||
|
||||
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(() => {});
|
||||
// Each save runs start to finish holding the lock every write of the stored
|
||||
// record takes (withLock() in src/shared/browserApi.js), so no write by
|
||||
// another page or the background lands between its read and its write and is
|
||||
// lost (https://git.eeqj.de/sneak/AutistMask/issues/641). A page in a Firefox
|
||||
// private window is the exception: Firefox gives it locks of its own (README,
|
||||
// "Stored state and its version").
|
||||
//
|
||||
// The same lock orders this page's own saves. showView() calls saveState() on
|
||||
// every navigation without awaiting it, so two saves from one page can be
|
||||
// asked for at once; they take the lock in the order they were asked, and each
|
||||
// compares the page's state, as it stands once the stored record has been read
|
||||
// and `beforeWrite` has run, against the baseline the save before it left.
|
||||
//
|
||||
// `beforeWrite`, when given, is called inside the lock with the stored record
|
||||
// as just read, before this page's state is compared against it. It may change
|
||||
// `state`, and this save writes that change. When it returns false, nothing is
|
||||
// written; any other return lets the save go ahead.
|
||||
function saveState(beforeWrite) {
|
||||
const turn = withLock("autistmask", () => saveStateOnce(beforeWrite));
|
||||
// Every failed save is reported, whether or not the caller awaited this
|
||||
// one. The returned promise still rejects, so a caller that DOES await
|
||||
// keeps its own error handling.
|
||||
|
||||
@@ -20,6 +20,7 @@ const { toDecimals } = require("./transferAmount");
|
||||
// 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");
|
||||
const { routerRelease } = require("./uniswap");
|
||||
|
||||
// Ethereum addresses are case-insensitive: EIP-55 mixed case is a checksum
|
||||
// over the address, not part of its identity. Every address comparison in
|
||||
@@ -51,7 +52,6 @@ function parseTx(tx, addrLower, chainId) {
|
||||
}
|
||||
// Map known DEX methods to "Swap" for cleaner display
|
||||
const SWAP_METHODS = new Set([
|
||||
"execute",
|
||||
"swap",
|
||||
"swapExactTokensForTokens",
|
||||
"swapTokensForExactTokens",
|
||||
@@ -59,9 +59,16 @@ function parseTx(tx, addrLower, chainId) {
|
||||
"swapTokensForExactETH",
|
||||
"swapExactTokensForETH",
|
||||
"swapETHForExactTokens",
|
||||
"multicall",
|
||||
]);
|
||||
const label = SWAP_METHODS.has(method)
|
||||
// Multisigs, smart accounts and many other contracts also have an
|
||||
// `execute` or `multicall` method, so either is a swap only when sent
|
||||
// to a Universal Router on this transaction's network: the same
|
||||
// addresses the approval screen decodes a swap for.
|
||||
const isSwap =
|
||||
SWAP_METHODS.has(method) ||
|
||||
((method === "execute" || method === "multicall") &&
|
||||
routerRelease(to, chainId) !== null);
|
||||
const label = isSwap
|
||||
? "Swap"
|
||||
: method.charAt(0).toUpperCase() + method.slice(1);
|
||||
direction = "contract";
|
||||
|
||||
+238
-59
@@ -494,8 +494,9 @@ function amountText(raw, info) {
|
||||
};
|
||||
}
|
||||
|
||||
// The line giving a moved token under `label`, in the shape of the Token In
|
||||
// line, so the screens show it as they show that one. ETH has no address.
|
||||
// The line giving a moved token, or the token of a permit, under `label`, in
|
||||
// the shape of the Token In line, so the screens show it as they show that
|
||||
// one. ETH has no address.
|
||||
function tokenMovedLine(label, token, sources) {
|
||||
const info = tokenInfo(token, sources);
|
||||
if (!present(info.address)) {
|
||||
@@ -596,12 +597,14 @@ function decodeV2SwapExactOut(input) {
|
||||
// token(20) ...), or null when it is not one token followed by whole hops of
|
||||
// a fee and a token (40 hex digits, then 46 per hop). The router reads only
|
||||
// whole hops and ignores any bytes after the last one, so the last 20 bytes
|
||||
// of such a path are not the token it reads there.
|
||||
// of such a path are not the token it reads there. Both are checksummed, as
|
||||
// the ABI decoder gives every other address, so a token reads the same on
|
||||
// every line.
|
||||
function decodeV3Path(pathHex) {
|
||||
const hex = pathHex.startsWith("0x") ? pathHex.slice(2) : pathHex;
|
||||
if (hex.length < 40 || (hex.length - 40) % 46 !== 0) return null;
|
||||
const first = "0x" + hex.slice(0, 40);
|
||||
const last = "0x" + hex.slice(-40);
|
||||
const first = getAddress("0x" + hex.slice(0, 40));
|
||||
const last = getAddress("0x" + hex.slice(-40));
|
||||
return { first, last };
|
||||
}
|
||||
|
||||
@@ -1204,9 +1207,18 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
let inputToken = null;
|
||||
let inputAmount = null;
|
||||
let inputEstablished = false;
|
||||
// The last PERMIT2_PERMIT this decoder read, or null (see
|
||||
// permitStands after the loop).
|
||||
// Whether the user pays the V4 step that set the input side any of
|
||||
// its input currency (see decodeV4Swap()). Only a V4 step can set the
|
||||
// input side with no amount, the one case in which this is read.
|
||||
let inputPaidByUser = false;
|
||||
// The last PERMIT2_PERMIT this decoder read before a step set the
|
||||
// input side, or null (see permitStands after the loop).
|
||||
let permit = null;
|
||||
// Every PERMIT2_PERMIT this decoder read, before a step set the input
|
||||
// side or after, in step order, as { token, amount, spender, step }.
|
||||
// Each whose amount is not the Amount figure gets lines of its own
|
||||
// (see after the PERMIT2_TRANSFER_FROM lines).
|
||||
const permits = [];
|
||||
// The index of each step this decoder did not read in full: a
|
||||
// command it does not read, a step whose input it cannot read, in
|
||||
// whole or in part, and one it fails on (see permitStands).
|
||||
@@ -1215,6 +1227,31 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
let minOutput = null;
|
||||
let outputEstablished = false;
|
||||
let hasUnwrapWeth = false;
|
||||
// Set when an UNWRAP_WETH pays out, as ETH, the output side's WETH,
|
||||
// which the router holds; cleared whenever the output side is set
|
||||
// again, or a later step may pay that ETH out as WETH (see after the
|
||||
// loop). `unwrapIntoRouterStep` is the index of the first such
|
||||
// UNWRAP_WETH that may have paid the ETH to the router, which then
|
||||
// holds it: its recipient is the router or cannot be read. A later
|
||||
// UNWRAP_WETH does not replace it. It is null when there is none, and
|
||||
// is cleared with `outputUnwrapped` when the output side is set again.
|
||||
let outputUnwrapped = false;
|
||||
let unwrapIntoRouterStep = null;
|
||||
// The index of the step that set the output side.
|
||||
let outputStep = -1;
|
||||
// The index of the last step this decoder treats as one that may take
|
||||
// WETH out of the router or pay anyone WETH: any step but one it read
|
||||
// that is a PERMIT2_PERMIT, a BALANCE_CHECK_ERC20, or a SWEEP,
|
||||
// TRANSFER, PAY_PORTION or PAY_PORTION_FULL_PRECISION of a token
|
||||
// other than WETH, and not of ETH to a WETH contract, which pays the
|
||||
// router WETH (see keepsRouterWeth in the loop). None of those can.
|
||||
let lastWethStep = -1;
|
||||
// Where the step that set the output side paid its output: the
|
||||
// recipient of a swap step, as written, or of each TAKE, TAKE_ALL and
|
||||
// TAKE_PORTION of it in a V4 step, a TAKE_ALL as paid to the sender,
|
||||
// with null for a payout of that step this decoder did not read. A
|
||||
// BALANCE_CHECK_ERC20 pays nobody.
|
||||
let outputRecipients = [];
|
||||
let hasV2OrV3ExactOut = false;
|
||||
let swapUndecoded = false;
|
||||
let hasSubPlan = false;
|
||||
@@ -1239,8 +1276,9 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
// when no earlier hop set it. A half the establishing hop did not
|
||||
// state stays null and the line says so, rather than being filled in
|
||||
// from a different hop. A PERMIT2_PERMIT sets no side here: after the
|
||||
// loop, the last one read names Token In, and the Amount line is
|
||||
// formed there, in one place (see permitStands).
|
||||
// loop, one whose amount stands as the Amount figure names Token In,
|
||||
// and the Amount line is formed there, in one place (see
|
||||
// permitStands).
|
||||
const setInput = (token, amount) => {
|
||||
inputToken = present(token) ? token : null;
|
||||
inputAmount = present(amount) ? amount : null;
|
||||
@@ -1251,11 +1289,15 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
if (!present(token) && !present(amount)) return;
|
||||
setInput(token, amount);
|
||||
};
|
||||
const setOutput = (token, amount) => {
|
||||
const setOutput = (step, token, amount, recipients) => {
|
||||
if (!present(token) && !present(amount)) return;
|
||||
outputToken = present(token) ? token : null;
|
||||
minOutput = present(amount) ? amount : null;
|
||||
outputEstablished = true;
|
||||
outputUnwrapped = false;
|
||||
unwrapIntoRouterStep = null;
|
||||
outputRecipients = recipients;
|
||||
outputStep = step;
|
||||
};
|
||||
|
||||
// What the steps take from the sender beyond the amount of the step
|
||||
@@ -1389,6 +1431,14 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
v2PairFor(chainId, next.path[0], next.path[1]).toLowerCase()
|
||||
);
|
||||
};
|
||||
// Whether a SWEEP, TRANSFER, PAY_PORTION or PAY_PORTION_FULL_PRECISION
|
||||
// of `token` to `recipient` pays anyone WETH (see lastWethStep): it
|
||||
// does when `token` is WETH, and when it pays ETH to a WETH contract,
|
||||
// which pays the router WETH for it.
|
||||
const paysWeth = (token, recipient) =>
|
||||
WETH_ADDRESSES.includes(token.toLowerCase()) ||
|
||||
(token === "0x0000000000000000000000000000000000000000" &&
|
||||
WETH_ADDRESSES.includes(recipient.toLowerCase()));
|
||||
|
||||
for (let i = 0; i < commandsBytes.length; i++) {
|
||||
const cmdId = commandsBytes[i] & commandTypeMask;
|
||||
@@ -1405,6 +1455,9 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
? COMMAND_NAMES[command]
|
||||
: "Command 0x" + cmdId.toString(16).padStart(2, "0"),
|
||||
);
|
||||
// Set by a branch below that reads a step that cannot take WETH
|
||||
// out of the router or pay anyone WETH (see lastWethStep).
|
||||
let keepsRouterWeth = false;
|
||||
|
||||
try {
|
||||
if (command === "EXECUTE_SUB_PLAN") {
|
||||
@@ -1421,23 +1474,33 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
} else if (command === "PERMIT2_PERMIT") {
|
||||
const p = decodePermit2(inputs[i]);
|
||||
if (p) {
|
||||
permits.push({ ...p, step: i });
|
||||
keepsRouterWeth = true;
|
||||
} else {
|
||||
stepsUnread.push(i);
|
||||
}
|
||||
// Only a permit whose amount stands as the Amount figure
|
||||
// names Token In (see permitStands). Every other permit,
|
||||
// before the step that sets the input side or after it,
|
||||
// leaves Token In and Amount as they read with no permit
|
||||
// and gets lines of its own. One after a step set the input
|
||||
// side never stands, so only one before it is kept here.
|
||||
if (p && !inputEstablished) {
|
||||
// Whether a step before it took its token, or may
|
||||
// have: the step that set the input side or one in
|
||||
// `userPaid`, when its token is the permit's or not
|
||||
// known.
|
||||
// have: one in `userPaid`, when its token is the
|
||||
// permit's or not known. No step has set the input
|
||||
// side yet.
|
||||
const mayBeItsToken = (token) =>
|
||||
!present(token) || sameAddress(token, p.token);
|
||||
const tookBefore =
|
||||
(inputEstablished && mayBeItsToken(inputToken)) ||
|
||||
userPaid.some((t) => mayBeItsToken(t.token));
|
||||
const tookBefore = userPaid.some((t) =>
|
||||
mayBeItsToken(t.token),
|
||||
);
|
||||
permit = {
|
||||
...p,
|
||||
step: i,
|
||||
allowedToFail,
|
||||
beforeEveryTake: !tookBefore,
|
||||
};
|
||||
} else {
|
||||
stepsUnread.push(i);
|
||||
}
|
||||
} else if (command === "PERMIT2_TRANSFER_FROM") {
|
||||
const p = decodePermit2TransferFrom(inputs[i]);
|
||||
@@ -1491,6 +1554,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
// what the user receives: it sets no side, and the
|
||||
// step says so.
|
||||
commandNames[i] += " (of another address)";
|
||||
keepsRouterWeth = true;
|
||||
} else {
|
||||
// The router passes this check whenever the owner
|
||||
// holds at least minBalance, so a zero one guarantees
|
||||
@@ -1501,8 +1565,9 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
// does. It pays nobody.
|
||||
const minBalance = allowedToFail ? 0n : b.minBalance;
|
||||
if (!(minBalance === 0n && present(minOutput))) {
|
||||
setOutput(b.token, minBalance);
|
||||
setOutput(i, b.token, minBalance, []);
|
||||
}
|
||||
keepsRouterWeth = true;
|
||||
}
|
||||
} else if (command === "V3_SWAP_EXACT_IN") {
|
||||
const s = decodeV3SwapExactIn(inputs[i]);
|
||||
@@ -1515,7 +1580,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
// Always update output: in multi-step swaps (V3 → V4),
|
||||
// the last swap step determines the final output token
|
||||
// and minimum received amount.
|
||||
setOutput(s.tokenOut, s.amountOutMin);
|
||||
setOutput(i, s.tokenOut, s.amountOutMin, [s.recipient]);
|
||||
if (!s.payerIsUser) {
|
||||
spendFromRouter(s.tokenIn, s.amountIn);
|
||||
}
|
||||
@@ -1535,7 +1600,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
} else if (s.payerIsUser) {
|
||||
addUserPaid(s.tokenIn, s.amountIn);
|
||||
}
|
||||
setOutput(s.tokenOut, s.amountOutMin);
|
||||
setOutput(i, s.tokenOut, s.amountOutMin, [s.recipient]);
|
||||
if (!s.payerIsUser) {
|
||||
spendFromRouter(s.tokenIn, s.amountIn);
|
||||
}
|
||||
@@ -1566,7 +1631,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
} else if (s.payerIsUser) {
|
||||
addUserPaid(s.tokenIn, s.amountInMax);
|
||||
}
|
||||
setOutput(s.tokenOut, s.amountOut);
|
||||
setOutput(i, s.tokenOut, s.amountOut, [s.recipient]);
|
||||
if (!isHop(i, s.tokenOut, s.recipient)) {
|
||||
addPayee(s.recipient, s.tokenOut);
|
||||
}
|
||||
@@ -1588,6 +1653,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
if (!isRouter(s.recipient)) {
|
||||
heldByRouter.delete(s.token.toLowerCase());
|
||||
}
|
||||
keepsRouterWeth = !paysWeth(s.token, s.recipient);
|
||||
} else {
|
||||
payeeUnread = true;
|
||||
stepsUnread.push(i);
|
||||
@@ -1625,6 +1691,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
) {
|
||||
heldByRouter.delete(t.token.toLowerCase());
|
||||
}
|
||||
keepsRouterWeth = !paysWeth(t.token, t.recipient);
|
||||
} else {
|
||||
payeeUnread = true;
|
||||
stepsUnread.push(i);
|
||||
@@ -1724,6 +1791,14 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
(p) => p.currency === v4.tokenIn,
|
||||
);
|
||||
const amountIn = paidIn ? paidIn.amount : v4?.amountIn;
|
||||
// Where the step pays its output, if it sets the output
|
||||
// side (see outputRecipients).
|
||||
const takeRecipients = v4
|
||||
? v4.takes
|
||||
.filter((t) => t.currency === v4.tokenOut)
|
||||
.map((t) => t.recipient)
|
||||
.concat(v4.recipientUnread ? [null] : [])
|
||||
: [];
|
||||
if (v4 && v4.hasSwapAction) {
|
||||
// A step with a swap action always sets the output
|
||||
// side, as the last swap step wins, and sets the
|
||||
@@ -1740,13 +1815,22 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
outputToken = v4.tokenOut;
|
||||
minOutput = v4.amountOutMin;
|
||||
outputEstablished = true;
|
||||
outputUnwrapped = false;
|
||||
unwrapIntoRouterStep = null;
|
||||
outputRecipients = takeRecipients;
|
||||
outputStep = i;
|
||||
} else if (v4) {
|
||||
// A step with no swap action sets only the sides its
|
||||
// SETTLE, SETTLE_ALL, TAKE or TAKE_ALL names:
|
||||
// setInputOnce() and setOutput() leave alone a side
|
||||
// whose two halves are both unstated.
|
||||
setInputOnce(v4.tokenIn, amountIn);
|
||||
setOutput(v4.tokenOut, v4.amountOutMin);
|
||||
setOutput(
|
||||
i,
|
||||
v4.tokenOut,
|
||||
v4.amountOutMin,
|
||||
takeRecipients,
|
||||
);
|
||||
}
|
||||
// Every V4 step, with a swap action or without, takes
|
||||
// from the sender what the user pays it (an amount an
|
||||
@@ -1756,6 +1840,7 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
// this decoder could not read may take anything: the
|
||||
// router still runs it.
|
||||
const setInputHere = inputEstablished && !inputSetBefore;
|
||||
if (setInputHere) inputPaidByUser = paidIn !== undefined;
|
||||
if (v4) {
|
||||
for (const p of v4.paidByUser) {
|
||||
if (setInputHere && p === paidIn) continue;
|
||||
@@ -1767,7 +1852,43 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
}
|
||||
} else if (command === "UNWRAP_WETH") {
|
||||
hasUnwrapWeth = true;
|
||||
// The router unwraps all the WETH it holds, even when the
|
||||
// recipient cannot be read. The output side's WETH is
|
||||
// among it when the step that set the output side paid it
|
||||
// to the router and the router still holds WETH. WETH
|
||||
// that step paid to the user, or to anyone else, stays
|
||||
// WETH. When that step also paid some of its output
|
||||
// elsewhere or made a payout this decoder did not read,
|
||||
// or this decoder treats a step between the two as one
|
||||
// that may take WETH out of the router or pay anyone WETH
|
||||
// (see lastWethStep), the WETH unwrapped may be only part
|
||||
// of the output side's, or none of it.
|
||||
// This decoder does not count how much of that step's
|
||||
// minimum then reaches the UNWRAP_WETH, nor read the
|
||||
// UNWRAP_WETH's own minimum, so the output side keeps no
|
||||
// figure.
|
||||
const u = decodeUnwrapWeth(inputs[i]);
|
||||
const toRouter = (r) => present(r) && isRouter(r);
|
||||
if (
|
||||
present(outputToken) &&
|
||||
WETH_ADDRESSES.includes(outputToken.toLowerCase()) &&
|
||||
heldByRouter.has(outputToken.toLowerCase()) &&
|
||||
outputRecipients.some(toRouter)
|
||||
) {
|
||||
outputUnwrapped = true;
|
||||
if (
|
||||
unwrapIntoRouterStep === null &&
|
||||
(u === null || isRouter(u.recipient))
|
||||
) {
|
||||
unwrapIntoRouterStep = i;
|
||||
}
|
||||
if (
|
||||
!outputRecipients.every(toRouter) ||
|
||||
lastWethStep > outputStep
|
||||
) {
|
||||
minOutput = null;
|
||||
}
|
||||
}
|
||||
if (u) {
|
||||
addPayee(u.recipient);
|
||||
// It pays out all the router's WETH, as ETH. Into the
|
||||
@@ -1804,6 +1925,26 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
if (allowedToFail) {
|
||||
commandNames[i] += " (allowed to fail)";
|
||||
}
|
||||
if (!keepsRouterWeth) {
|
||||
lastWethStep = i;
|
||||
}
|
||||
}
|
||||
|
||||
// After an UNWRAP_WETH that may have paid the output side's WETH to
|
||||
// the router as ETH, a later step may pay that ETH out as WETH, as a
|
||||
// WRAP_ETH of it to the user does. This decoder treats every later
|
||||
// step but those lastWethStep names as one that may, and does not
|
||||
// count how much of that ETH each pays out: after one, the output
|
||||
// side reads as WETH with no figure. Neither this nor the loss of the
|
||||
// figure in the UNWRAP_WETH branch is undone by any later step, a
|
||||
// later UNWRAP_WETH included, but one that sets the output side again.
|
||||
if (
|
||||
outputUnwrapped &&
|
||||
unwrapIntoRouterStep !== null &&
|
||||
lastWethStep > unwrapIntoRouterStep
|
||||
) {
|
||||
outputUnwrapped = false;
|
||||
minOutput = null;
|
||||
}
|
||||
|
||||
// The Amount line, and the lines for what the steps take beyond it.
|
||||
@@ -1816,18 +1957,21 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
// lines of its own. One whose amount is not known also leaves the
|
||||
// total unknown, with no figure.
|
||||
//
|
||||
// The last PERMIT2_PERMIT read names Token In. Its amount stands as
|
||||
// the Amount figure in place of the total only in the plain shape of
|
||||
// Uniswap's own routes: it is the only PERMIT2_PERMIT, its spender is
|
||||
// the router, the router may not let it fail, no step before it took
|
||||
// its token or one not known, and this decoder read every step after
|
||||
// it in full (see stepsUnread). Permit2 then lets the router take no
|
||||
// more of the token than that amount, so the permit covers every take
|
||||
// of it. A later step this decoder did not read may raise what Permit2
|
||||
// lets the router take, as a PERMIT2_PERMIT_BATCH can. A step that
|
||||
// may take from the sender what this decoder did not read leaves no
|
||||
// figure, permit or not (see spentUnread()), and an EXECUTE_SUB_PLAN
|
||||
// step leaves both sides unknown (below).
|
||||
// A PERMIT2_PERMIT names Token In only when its amount stands as the
|
||||
// Amount figure in place of the total, which it does only in the
|
||||
// plain shape of Uniswap's own routes: it comes before the step that
|
||||
// set the input side, it is the only PERMIT2_PERMIT in the
|
||||
// transaction, its spender is the router, the router may not let it
|
||||
// fail, no step before it took its token or one not known, and this
|
||||
// decoder read every step after it in full (see stepsUnread). Permit2
|
||||
// then lets the router take no more of the token than that amount, so
|
||||
// the permit covers every take of it. A later step this decoder did
|
||||
// not read may raise what Permit2 lets the router take, as a
|
||||
// PERMIT2_PERMIT_BATCH can. Every other PERMIT2_PERMIT leaves Token In
|
||||
// and the Amount line as they read with no permit, and gets lines of
|
||||
// its own below. A step that may take from the sender what this decoder
|
||||
// did not read leaves no figure, permit or not (see spentUnread()),
|
||||
// and an EXECUTE_SUB_PLAN step leaves both sides unknown (below).
|
||||
const stepCommands = Array.from(
|
||||
commandsBytes,
|
||||
(b) => commands[b & commandTypeMask],
|
||||
@@ -1844,20 +1988,27 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
// (see spentUnread()), or a token it does not know.
|
||||
const spentFromSender = [];
|
||||
let total = null;
|
||||
// Whether the step that set the input side counts as a take from the
|
||||
// sender, which may get lines of its own. The amount it stated counts
|
||||
// whoever pays it. Stating none, it counts only when the user pays it
|
||||
// some of its input token: paid from the router, it takes nothing
|
||||
// from the sender.
|
||||
const hasFirstTake =
|
||||
inputEstablished && (present(inputAmount) || inputPaidByUser);
|
||||
// The take of the step that set the input side, when the total
|
||||
// starts from it and it stated no amount (see below), or null.
|
||||
let firstTakeUnstated = null;
|
||||
if (permit === null || sameAddress(inputToken, permit.token)) {
|
||||
if (!permitStands || sameAddress(inputToken, permit.token)) {
|
||||
total = inputAmount;
|
||||
if (inputEstablished && !present(inputAmount)) {
|
||||
if (hasFirstTake && !present(inputAmount)) {
|
||||
firstTakeUnstated = { token: inputToken, amount: null };
|
||||
}
|
||||
} else if (inputEstablished) {
|
||||
} else if (hasFirstTake) {
|
||||
// The step that set the input side spent a token other than the
|
||||
// permit's, or one not known, so the total starts with no figure.
|
||||
// permit's, or one not known, so its amount gets lines of its own.
|
||||
spentFromSender.push({ token: inputToken, amount: inputAmount });
|
||||
}
|
||||
if (permit !== null) inputToken = permit.token;
|
||||
if (permitStands) inputToken = permit.token;
|
||||
for (const t of userPaid) {
|
||||
const ofTokenIn = sameAddress(t.token, inputToken);
|
||||
if (ofTokenIn && permitStands) continue;
|
||||
@@ -1873,46 +2024,48 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
if (ofTokenIn && !present(t.amount)) total = null;
|
||||
}
|
||||
inputAmount = permitStands ? permit.amount : total;
|
||||
// With no Amount figure, a later take's own figure could read as all
|
||||
// that leaves, so the step that set the input side, when it stated
|
||||
// no amount, then gets lines of its own too, first, saying its amount
|
||||
// is not known.
|
||||
// With no Amount figure, a later take's own figure, or that of a
|
||||
// PERMIT2_TRANSFER_FROM of the same token, into the router or not,
|
||||
// could read as all that leaves, so the step that set the input side,
|
||||
// when the user pays it and it stated no amount, then gets lines of
|
||||
// its own too, first, saying its amount is not known.
|
||||
if (
|
||||
!present(inputAmount) &&
|
||||
firstTakeUnstated !== null &&
|
||||
spentFromSender.some((s) => present(s.amount))
|
||||
(spentFromSender.some((s) => present(s.amount)) ||
|
||||
[...movedFromSender, ...movedIntoRouter].some((m) =>
|
||||
sameAddress(m.token, firstTakeUnstated.token),
|
||||
))
|
||||
) {
|
||||
spentFromSender.unshift(firstTakeUnstated);
|
||||
}
|
||||
|
||||
// The commands of an EXECUTE_SUB_PLAN step may spend the user's tokens
|
||||
// or pay the user, before or after any other step, and a permit among
|
||||
// them would name Token In. What the other steps state is
|
||||
// then not the whole swap, so both sides are set unknown, with no
|
||||
// figure, wherever the step stands.
|
||||
// or pay the user, before or after any other step. What the other
|
||||
// steps state is then not the whole swap, so both sides are set
|
||||
// unknown, with no figure, wherever the step stands.
|
||||
if (hasSubPlan) {
|
||||
inputToken = null;
|
||||
inputAmount = null;
|
||||
outputToken = null;
|
||||
minOutput = null;
|
||||
outputEstablished = true;
|
||||
outputUnwrapped = false;
|
||||
}
|
||||
|
||||
// Resolve token info. A null token on either side means no step named
|
||||
// a currency for it, a V4 step with a swap action left it unknown, or
|
||||
// an EXECUTE_SUB_PLAN step did; tokenInfo() refuses rather than calling
|
||||
// it ETH. UNWRAP_WETH turns WETH into ETH, so it makes the output ETH
|
||||
// when the output side is WETH, or when no step set the output side. A
|
||||
// V4 step with a swap action, or an EXECUTE_SUB_PLAN step, did set it,
|
||||
// even when it set it unknown. Any other output keeps its own token
|
||||
// and figure: a swap that buys USDC and then unwraps the WETH it did
|
||||
// not spend receives USDC.
|
||||
const outputIsWeth =
|
||||
present(outputToken) &&
|
||||
WETH_ADDRESSES.includes(outputToken.toLowerCase());
|
||||
// when it unwraps the output side's WETH (`outputUnwrapped`), or when
|
||||
// no step set the output side. A V4 step with a swap action, or
|
||||
// an EXECUTE_SUB_PLAN step, did set it, even when it set it unknown.
|
||||
// Any other output keeps its own token and figure: a swap that pays
|
||||
// its WETH to the user and then unwraps receives WETH, and one that
|
||||
// buys USDC and then unwraps the WETH it did not spend receives USDC.
|
||||
const inInfo = tokenInfo(inputToken, sources);
|
||||
const outInfo =
|
||||
hasUnwrapWeth && (outputIsWeth || !outputEstablished)
|
||||
outputUnwrapped || (hasUnwrapWeth && !outputEstablished)
|
||||
? { symbol: "ETH", decimals: 18, address: null }
|
||||
: tokenInfo(outputToken, sources);
|
||||
|
||||
@@ -2048,6 +2201,32 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
);
|
||||
}
|
||||
|
||||
// What each PERMIT2_PERMIT lets its spender take: its amount, its
|
||||
// token and the spender, an address on a line of its own. Permit2's
|
||||
// maximum is unbounded. Only a permit whose amount stands as the
|
||||
// Amount figure (see permitStands) gets none: that line already gives
|
||||
// its amount and Token In its token, and its spender is the router.
|
||||
// Every other permit, one after the step that set the input side
|
||||
// included, gets these lines, so nothing it lets anyone take goes
|
||||
// unstated.
|
||||
for (const p of permits) {
|
||||
if (permitStands && p.step === permit.step) continue;
|
||||
details.push({
|
||||
label: "Permit2 allowance",
|
||||
value:
|
||||
p.amount >= MAX_UINT160
|
||||
? "Unlimited"
|
||||
: amountText(p.amount, tokenInfo(p.token, sources))
|
||||
.display,
|
||||
});
|
||||
details.push(tokenMovedLine("Allowance token", p.token, sources));
|
||||
details.push({
|
||||
label: "Allowance spender",
|
||||
value: p.spender,
|
||||
address: p.spender,
|
||||
});
|
||||
}
|
||||
|
||||
// Keyed on the address, not the symbol: a token absent from the
|
||||
// bundled list has no symbol, and gating the line on one dropped it
|
||||
// entirely, leaving a Min. received figure with nothing saying what is
|
||||
@@ -2177,4 +2356,4 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { decode };
|
||||
module.exports = { decode, routerRelease };
|
||||
|
||||
@@ -19,7 +19,10 @@
|
||||
// that followed persisted the pre-refresh values — while still stamping
|
||||
// lastBalanceRefresh, suppressing the redo.
|
||||
//
|
||||
// Both use the real persistence path over a cloning storage stub. Nothing here
|
||||
// A network switch landing inside a balance refresh's round trip is covered at
|
||||
// the end (https://git.eeqj.de/sneak/AutistMask/issues/577).
|
||||
//
|
||||
// All use the real persistence path over a cloning storage stub. Nothing here
|
||||
// asserts the absence of a loadState() call; each asserts the OUTCOME, so it
|
||||
// holds against any implementation that gets the outcome right.
|
||||
|
||||
@@ -395,3 +398,48 @@ describe("a balance refresh under another handler's state read", () => {
|
||||
expect(after.wallets[0].addresses[0].balance).toBe(REFRESHED_BALANCE);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a balance refresh under a network switch", () => {
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/577. The switch clears every
|
||||
// address's balances, and a refresh that started on the previous network
|
||||
// must not write that network's back over them when it returns. The same
|
||||
// refresh in the popup is in tests/balanceRefreshNetworkSwitch.test.js.
|
||||
test("a refresh that returns after a switch writes nothing, and the next one runs on the new network", async () => {
|
||||
const roundTrip = deferred();
|
||||
const reachedNetwork = deferred();
|
||||
const ranOn = [];
|
||||
|
||||
const bg = loadWorker("sepolia", {
|
||||
refreshBalances: async (wallets, rpcUrl, explorer, tokens, id) => {
|
||||
ranOn.push(id);
|
||||
reachedNetwork.resolve();
|
||||
await roundTrip.promise;
|
||||
wallets[0].addresses[0].balance = REFRESHED_BALANCE;
|
||||
},
|
||||
});
|
||||
|
||||
const refresh = bg.fireBalanceAlarm();
|
||||
await reachedNetwork.promise;
|
||||
|
||||
// The user switches to Ethereum Mainnet in Settings while the round
|
||||
// trip is out.
|
||||
const during = bg.persisted();
|
||||
applyChainSwitchFields(during, MAINNET.id);
|
||||
global.chrome.storage.write("autistmask", during);
|
||||
|
||||
roundTrip.resolve();
|
||||
await refresh;
|
||||
|
||||
const after = bg.persisted();
|
||||
expect(after.networkId).toBe("mainnet");
|
||||
expect(after.wallets[0].addresses[0].balance).toBe("0");
|
||||
expect(after.lastBalanceRefresh).toBe(0);
|
||||
|
||||
await bg.fireBalanceAlarm();
|
||||
|
||||
expect(ranOn).toEqual(["sepolia", "mainnet"]);
|
||||
expect(bg.persisted().wallets[0].addresses[0].balance).toBe(
|
||||
REFRESHED_BALANCE,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
// A balance refresh the popup started on one network, and that returns after
|
||||
// the network was switched to another, writes nothing: the switch cleared every
|
||||
// address's balances, and the previous network's must not come back over them
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/577). The switch is made either
|
||||
// by the user in this popup's Settings, or by the background after the user
|
||||
// approved a site's request, which changes only the stored record. Driven
|
||||
// through the real popup over a stored profile on Ethereum Mainnet. The same
|
||||
// refresh in the background is in tests/backgroundStateIsolation.test.js.
|
||||
|
||||
const {
|
||||
bootPopup,
|
||||
cleanupPopup,
|
||||
unversionedValidProfile,
|
||||
TOKEN_ADDRESS,
|
||||
} = require("./support/popupBoot");
|
||||
const { applyChainSwitchFields } = require("../src/shared/chainSwitchFields");
|
||||
|
||||
afterEach(() => {
|
||||
cleanupPopup();
|
||||
});
|
||||
|
||||
// Starts the ten-second refresh and holds it open. The balance stand-in writes
|
||||
// Ethereum Mainnet's balances in place, on the records handed in, as the real
|
||||
// refreshBalances() does, once the returned function is called. Resolves with
|
||||
// that function and the refresh still running.
|
||||
async function holdRefresh(page) {
|
||||
const { refreshBalances } = require("../src/shared/balances");
|
||||
let answer;
|
||||
refreshBalances.mockImplementationOnce(async (wallets) => {
|
||||
await new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
});
|
||||
wallets[0].addresses[0].balance = "7.0";
|
||||
wallets[0].addresses[0].tokenBalances = [
|
||||
{
|
||||
address: TOKEN_ADDRESS,
|
||||
name: "Test Token",
|
||||
symbol: "TST",
|
||||
decimals: 18,
|
||||
balance: "5.0",
|
||||
holders: null,
|
||||
},
|
||||
];
|
||||
});
|
||||
const ticking = page.tick();
|
||||
await page.settle();
|
||||
return {
|
||||
finish: async () => {
|
||||
answer();
|
||||
await ticking;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Picks `networkId` in the Settings network selector, as the user does.
|
||||
async function chooseNetwork(page, networkId) {
|
||||
const select = page.node("settings-network");
|
||||
select.value = networkId;
|
||||
for (const fn of select.listeners.change) await fn();
|
||||
await page.settle();
|
||||
}
|
||||
|
||||
// The stored record holds none of Ethereum Mainnet's balances, and no refresh
|
||||
// recorded as done.
|
||||
function expectNothingStored(page) {
|
||||
const stored = page.storage.read("autistmask");
|
||||
expect(stored.networkId).toBe("sepolia");
|
||||
expect(stored.wallets[0].addresses[0].balance).toBe("0");
|
||||
expect(stored.wallets[0].addresses[0].tokenBalances).toEqual([]);
|
||||
expect(stored.lastBalanceRefresh).toBe(0);
|
||||
}
|
||||
|
||||
test("a refresh that returns after a switch in Settings writes nothing, and the next one runs on the new network", async () => {
|
||||
const page = await bootPopup(unversionedValidProfile());
|
||||
expect(page.pageErrors).toEqual([]);
|
||||
const { refreshBalances } = require("../src/shared/balances");
|
||||
const { state } = require("../src/shared/state");
|
||||
|
||||
const refresh = await holdRefresh(page);
|
||||
await page.click("btn-settings");
|
||||
await chooseNetwork(page, "sepolia");
|
||||
await refresh.finish();
|
||||
|
||||
expect(state.wallets[0].addresses[0].balance).toBe("0");
|
||||
expect(state.wallets[0].addresses[0].tokenBalances).toEqual([]);
|
||||
expectNothingStored(page);
|
||||
|
||||
await page.click("btn-settings-back");
|
||||
expect(page.visibleViews()).toEqual(["main"]);
|
||||
expect(page.text("total-value")).toBe("0.0000 SepoliaETH");
|
||||
|
||||
await page.tick();
|
||||
|
||||
expect(refreshBalances.mock.lastCall[4]).toBe("sepolia");
|
||||
expect(page.storage.read("autistmask").lastBalanceRefresh).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
// The stored record still holds Ethereum Mainnet while the refresh's save reads
|
||||
// it, so only this page's own network shows the switch.
|
||||
test("a refresh whose save is reading the stored record when the user switches in Settings writes nothing", async () => {
|
||||
const page = await bootPopup(unversionedValidProfile());
|
||||
expect(page.pageErrors).toEqual([]);
|
||||
const { state } = require("../src/shared/state");
|
||||
|
||||
const refresh = await holdRefresh(page);
|
||||
await page.click("btn-settings");
|
||||
|
||||
// The next read of the stored record, the refresh's save's, is held.
|
||||
const get = page.storage.local.get;
|
||||
const read = get.getMockImplementation();
|
||||
let releaseRead;
|
||||
get.mockImplementationOnce(async (key) => {
|
||||
await new Promise((resolve) => {
|
||||
releaseRead = resolve;
|
||||
});
|
||||
return read(key);
|
||||
});
|
||||
const finishing = refresh.finish();
|
||||
await page.settle();
|
||||
|
||||
// The user picks Sepolia meanwhile; the switch's own save waits for the
|
||||
// refresh's save to let the lock go.
|
||||
const select = page.node("settings-network");
|
||||
select.value = "sepolia";
|
||||
const switching = Promise.all(select.listeners.change.map((fn) => fn()));
|
||||
await page.settle();
|
||||
|
||||
releaseRead();
|
||||
await finishing;
|
||||
await switching;
|
||||
await page.settle();
|
||||
|
||||
expect(state.networkId).toBe("sepolia");
|
||||
expect(state.wallets[0].addresses[0].balance).toBe("0");
|
||||
expect(state.wallets[0].addresses[0].tokenBalances).toEqual([]);
|
||||
expectNothingStored(page);
|
||||
});
|
||||
|
||||
test("a refresh that returns after the background switched the network writes nothing", async () => {
|
||||
const page = await bootPopup(unversionedValidProfile());
|
||||
expect(page.pageErrors).toEqual([]);
|
||||
const { saveState } = require("../src/shared/state");
|
||||
|
||||
const refresh = await holdRefresh(page);
|
||||
// The background writes the switch to Sepolia, as its updateState() does
|
||||
// once the user approves a site's request. This page is not told.
|
||||
const record = page.storage.read("autistmask");
|
||||
applyChainSwitchFields(record, "sepolia");
|
||||
page.storage.write("autistmask", record);
|
||||
await refresh.finish();
|
||||
|
||||
expectNothingStored(page);
|
||||
|
||||
// Nor does a later save by this page, such as every navigation makes.
|
||||
await saveState();
|
||||
|
||||
expectNothingStored(page);
|
||||
});
|
||||
@@ -158,7 +158,7 @@ global.document = {
|
||||
body: { prepend() {}, appendChild() {} },
|
||||
addEventListener() {},
|
||||
};
|
||||
global.navigator = { clipboard: { writeText() {} } };
|
||||
global.navigator.clipboard = { writeText() {} };
|
||||
|
||||
const {
|
||||
Interface,
|
||||
|
||||
@@ -189,7 +189,7 @@ global.document = {
|
||||
body: { prepend() {}, appendChild() {} },
|
||||
addEventListener() {},
|
||||
};
|
||||
global.navigator = { clipboard: { writeText() {} } };
|
||||
global.navigator.clipboard = { writeText() {} };
|
||||
|
||||
const {
|
||||
BaseWallet,
|
||||
|
||||
+13
-3
@@ -367,11 +367,14 @@ async function leaveTransactionDetail(page) {
|
||||
await openAddressDetail(page);
|
||||
}
|
||||
|
||||
// Back out to Home from wherever the previous test finished.
|
||||
// Back out to Home from wherever the previous test finished, and wait for the
|
||||
// save that navigation makes, so a test reading the stored stack next reads
|
||||
// the one Home left.
|
||||
async function goHome(page) {
|
||||
await leaveTransactionDetail(page);
|
||||
await page.click("#btn-address-back");
|
||||
await visible(page, "#view-main");
|
||||
await waitForPersisted(page, "currentView", "main", "back on Home");
|
||||
}
|
||||
|
||||
// One field of the popup's state as it was actually persisted, read out of
|
||||
@@ -5035,10 +5038,17 @@ function addressRowReport(page) {
|
||||
// Measured at the popup's 396x600 (POPUP_VIEWPORT). Every page in this
|
||||
// context, approval windows included, is otherwise 1280x720 whatever size
|
||||
// the extension asks for, and a page that wide never scrolls sideways. The
|
||||
// page keeps the new size afterwards.
|
||||
// page is then put back to the size it had, so the size a later step runs at
|
||||
// does not depend on whether this one ran.
|
||||
async function assertAddressesFit(page, where) {
|
||||
const sizeBefore = page.viewportSize();
|
||||
await page.setViewportSize(POPUP_VIEWPORT);
|
||||
const report = await addressRowReport(page);
|
||||
let report;
|
||||
try {
|
||||
report = await addressRowReport(page);
|
||||
} finally {
|
||||
await page.setViewportSize(sizeBefore);
|
||||
}
|
||||
assert(
|
||||
report.rows.length > 0,
|
||||
where + ": no address rows were rendered, so nothing was measured",
|
||||
|
||||
@@ -151,7 +151,7 @@ global.document = {
|
||||
body: { prepend() {}, appendChild() {} },
|
||||
addEventListener() {},
|
||||
};
|
||||
global.navigator = { clipboard: { writeText() {} } };
|
||||
global.navigator.clipboard = { writeText() {} };
|
||||
|
||||
const { state } = require("../src/shared/state");
|
||||
const { NETWORKS } = require("../src/shared/networks");
|
||||
|
||||
@@ -364,7 +364,7 @@ describe("a save that fails", () => {
|
||||
return storage;
|
||||
}
|
||||
|
||||
test("is reported, not swallowed by the save queue", async () => {
|
||||
test("is reported when the caller does not await it", async () => {
|
||||
const storage = failingStorage(unversionedValidProfile());
|
||||
const { state, loadState, saveState, onSaveFailure } =
|
||||
loadStateModule(storage);
|
||||
|
||||
@@ -97,7 +97,7 @@ global.document = {
|
||||
body: { prepend() {}, appendChild() {} },
|
||||
addEventListener() {},
|
||||
};
|
||||
global.navigator = { clipboard: { writeText() {} } };
|
||||
global.navigator.clipboard = { writeText() {} };
|
||||
|
||||
const { state } = require("../src/shared/state");
|
||||
const send = require("../src/popup/views/send");
|
||||
|
||||
@@ -151,7 +151,7 @@ global.document = {
|
||||
body: { prepend() {}, appendChild() {} },
|
||||
addEventListener() {},
|
||||
};
|
||||
global.navigator = { clipboard: { writeText() {} } };
|
||||
global.navigator.clipboard = { writeText() {} };
|
||||
|
||||
const { refreshBalances } = require("../src/shared/balances");
|
||||
const { state } = require("../src/shared/state");
|
||||
|
||||
@@ -146,7 +146,7 @@ global.document = {
|
||||
body: { prepend() {}, appendChild() {} },
|
||||
addEventListener() {},
|
||||
};
|
||||
global.navigator = { clipboard: { writeText() {} } };
|
||||
global.navigator.clipboard = { writeText() {} };
|
||||
|
||||
const { Transaction, Wallet, formatEther } = require("ethers");
|
||||
const { refreshBalances } = require("../src/shared/balances");
|
||||
|
||||
@@ -160,7 +160,7 @@ describe("the approval-window reproduction", () => {
|
||||
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,
|
||||
// waits for the lock behind that one and so resolves only after it,
|
||||
// which is the black-box way to know it landed.
|
||||
await approvalWindow.state.saveState();
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// A popup save reads the stored record, merges this page's changes into it
|
||||
// and writes it back. The background's write of a network the user approved
|
||||
// used to be able to land between that read and that write, and the popup's
|
||||
// write then put the old network back
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/641). Every write of the record
|
||||
// now holds a lock from its read to its write.
|
||||
//
|
||||
// The popup and the background run here as the real modules over one shared
|
||||
// storage stub, and share the lock the way the background and a page outside
|
||||
// a Firefox private window share the browser's
|
||||
// (tests/support/navigatorLocks.js).
|
||||
|
||||
const { makeStorageStub } = require("./support/storageStub");
|
||||
|
||||
function loadContexts(storage) {
|
||||
jest.resetModules();
|
||||
globalThis.chrome = { storage: { local: storage.local } };
|
||||
return {
|
||||
popup: require("../src/shared/state"),
|
||||
background: require("../src/background/state"),
|
||||
applyChainSwitchFields: require("../src/shared/chainSwitchFields")
|
||||
.applyChainSwitchFields,
|
||||
};
|
||||
}
|
||||
|
||||
// Lets every pending promise callback run, and then some.
|
||||
function nextMacrotask() {
|
||||
return new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete globalThis.chrome;
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
test("a network the background switches to during a popup save stays stored", async () => {
|
||||
const storage = makeStorageStub({ autistmask: { networkId: "sepolia" } });
|
||||
const { popup, background, applyChainSwitchFields } = loadContexts(storage);
|
||||
await popup.loadState();
|
||||
|
||||
// The popup navigates, so its save has a change of its own to write.
|
||||
popup.state.currentView = "settings";
|
||||
|
||||
// The popup's save has read the record and is about to write it back when
|
||||
// the user's approval of a site's switch to mainnet reaches the
|
||||
// background. Without the lock the background's whole update runs before
|
||||
// the next macrotask; with it, the update waits for the popup's write.
|
||||
let backgroundSwitch;
|
||||
const realSet = storage.local.set.getMockImplementation();
|
||||
storage.local.set.mockImplementationOnce(async (items) => {
|
||||
backgroundSwitch = background.updateState((fresh) =>
|
||||
applyChainSwitchFields(fresh, "mainnet"),
|
||||
);
|
||||
await nextMacrotask();
|
||||
return realSet(items);
|
||||
});
|
||||
|
||||
await popup.saveState();
|
||||
await backgroundSwitch;
|
||||
|
||||
const stored = storage.read("autistmask");
|
||||
expect(stored.networkId).toBe("mainnet");
|
||||
expect(stored.currentView).toBe("settings");
|
||||
});
|
||||
|
||||
test("after a save that failed, the next save still keeps a network the background switches to during it", async () => {
|
||||
jest.spyOn(console, "error").mockImplementation(() => {});
|
||||
const storage = makeStorageStub({ autistmask: { networkId: "sepolia" } });
|
||||
const { popup, background, applyChainSwitchFields } = loadContexts(storage);
|
||||
await popup.loadState();
|
||||
popup.state.currentView = "settings";
|
||||
|
||||
// The first save's write is refused, so it gives the lock back having
|
||||
// failed.
|
||||
storage.local.set.mockRejectedValueOnce(new Error("quota exceeded"));
|
||||
await expect(popup.saveState()).rejects.toThrow("quota exceeded");
|
||||
|
||||
// The next save is between its read and its write when the background
|
||||
// switches to mainnet, as in the test above.
|
||||
let backgroundSwitch;
|
||||
const realSet = storage.local.set.getMockImplementation();
|
||||
storage.local.set.mockImplementationOnce(async (items) => {
|
||||
backgroundSwitch = background.updateState((fresh) =>
|
||||
applyChainSwitchFields(fresh, "mainnet"),
|
||||
);
|
||||
await nextMacrotask();
|
||||
return realSet(items);
|
||||
});
|
||||
|
||||
await popup.saveState();
|
||||
await backgroundSwitch;
|
||||
|
||||
const stored = storage.read("autistmask");
|
||||
expect(stored.networkId).toBe("mainnet");
|
||||
expect(stored.currentView).toBe("settings");
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
// `navigator.locks` for the unit tests, which run on node, where there is none.
|
||||
//
|
||||
// One lock per name: granted in the order it was asked for, and let go when
|
||||
// the callback settles, whether it resolved or rejected. That is what the
|
||||
// browser's own does for the one call the extension makes,
|
||||
// `navigator.locks.request(name, callback)`. Every module a test file loads
|
||||
// shares it, as the extension's background and its pages share the browser's,
|
||||
// except a page in a Firefox private window (README, "Stored state and its
|
||||
// version").
|
||||
//
|
||||
// Run before each test file by `setupFiles` in package.json.
|
||||
|
||||
// For each name, a promise that settles once the last request for it has
|
||||
// let the lock go.
|
||||
const released = new Map();
|
||||
|
||||
function request(name, callback) {
|
||||
const previous = released.get(name) || Promise.resolve();
|
||||
const result = previous.then(() => callback({ name, mode: "exclusive" }));
|
||||
released.set(
|
||||
name,
|
||||
result.catch(() => {}),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
globalThis.navigator = { locks: { request } };
|
||||
+380
-26
@@ -1,4 +1,4 @@
|
||||
const { AbiCoder, Interface, solidityPacked } = require("ethers");
|
||||
const { AbiCoder, Interface, getAddress, solidityPacked } = require("ethers");
|
||||
const uniswap = require("../src/shared/uniswap");
|
||||
|
||||
// A Universal Router on Ethereum Mainnet, chain id 0x1: UniversalRouterV2,
|
||||
@@ -696,12 +696,8 @@ describe("uniswap decoder", () => {
|
||||
USER_ADDR,
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(detail(result, "Token In").address).toBe(
|
||||
USDT_ADDR.toLowerCase(),
|
||||
);
|
||||
expect(detail(result, "Token Out").address).toBe(
|
||||
WETH_ADDR.toLowerCase(),
|
||||
);
|
||||
expect(detail(result, "Token In").address).toBe(USDT_ADDR);
|
||||
expect(detail(result, "Token Out").address).toBe(WETH_ADDR);
|
||||
|
||||
const amount = detail(result, "Amount");
|
||||
expect(amount.value).toBe("Up to 2000.0000 USDT");
|
||||
@@ -735,9 +731,7 @@ describe("uniswap decoder", () => {
|
||||
expect(result.name).toBe("Swap ETH → USDC");
|
||||
expect(detail(result, "Amount").value).toBe("Up to 0.5000 ETH");
|
||||
expect(detail(result, "Moved from the sender")).toBeUndefined();
|
||||
expect(detail(result, "Token Out").address).toBe(
|
||||
USDC_ADDR.toLowerCase(),
|
||||
);
|
||||
expect(detail(result, "Token Out").address).toBe(USDC_ADDR);
|
||||
expect(detail(result, "Paid to")).toBeUndefined();
|
||||
expect(detail(result, "Min. received").value).toBe("1500.0000 USDC");
|
||||
});
|
||||
@@ -875,7 +869,7 @@ describe("uniswap decoder", () => {
|
||||
const data = buildExecute(
|
||||
solidityPacked(["uint8", "uint8"], [0x08, 0x0c]),
|
||||
[
|
||||
encodeV2SwapExactIn(USER_ADDR, 1000000n, 500000000000000n, [
|
||||
encodeV2SwapExactIn(ROUTER_ADDR, 1000000n, 500000000000000n, [
|
||||
USDC_ADDR,
|
||||
SEPOLIA_WETH_ADDR,
|
||||
]),
|
||||
@@ -958,7 +952,7 @@ describe("uniswap decoder", () => {
|
||||
const data = buildExecute(
|
||||
solidityPacked(["uint8", "uint8"], [0x08, 0x0c]),
|
||||
[
|
||||
encodeV2SwapExactIn(USER_ADDR, 1000000n, 500000000000000n, [
|
||||
encodeV2SwapExactIn(ROUTER_ADDR, 1000000n, 500000000000000n, [
|
||||
USDT_ADDR,
|
||||
WETH_ADDR,
|
||||
]),
|
||||
@@ -1406,6 +1400,14 @@ describe("uniswap decoder", () => {
|
||||
return lines.slice(from + 1, to);
|
||||
}
|
||||
|
||||
// The lines of a PERMIT2_PERMIT whose amount does not stand as the
|
||||
// Amount figure, of `amount` of `token` for `spender`.
|
||||
const permitLines = (amount, token, symbol, spender) => [
|
||||
["Permit2 allowance", amount],
|
||||
["Allowance token", symbol + " (" + token + ")"],
|
||||
["Allowance spender", getAddress(spender)],
|
||||
];
|
||||
|
||||
// execute() of these command bytes and inputs, decoded as sent by
|
||||
// the user.
|
||||
function decodeSteps(commands, inputs) {
|
||||
@@ -1711,6 +1713,7 @@ describe("uniswap decoder", () => {
|
||||
kind: "a V4 step swapping 400 USDT with a SETTLE of 5,000 USDT by the user, the rest taken to another address,",
|
||||
commands: [0x10],
|
||||
inputs: [V4_SETTLE_5000],
|
||||
permit: [],
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT of 1 USDT that the router may let fail, then that V4 step,",
|
||||
@@ -1719,6 +1722,12 @@ describe("uniswap decoder", () => {
|
||||
encodePermit2(USDT_ADDR, 1000000n, ROUTER_ADDR),
|
||||
V4_SETTLE_5000,
|
||||
],
|
||||
permit: permitLines(
|
||||
"1.0000 USDT",
|
||||
USDT_ADDR,
|
||||
"USDT",
|
||||
ROUTER_ADDR,
|
||||
),
|
||||
},
|
||||
// The unread SWEEP keeps the permit's amount from standing.
|
||||
{
|
||||
@@ -1735,11 +1744,18 @@ describe("uniswap decoder", () => {
|
||||
1,
|
||||
),
|
||||
],
|
||||
permit: permitLines(
|
||||
"5000.0000 USDT",
|
||||
USDT_ADDR,
|
||||
"USDT",
|
||||
ROUTER_ADDR,
|
||||
),
|
||||
},
|
||||
])("$kind shows the 5,000 USDT", ({ commands, inputs }) => {
|
||||
])("$kind shows the 5,000 USDT", ({ commands, inputs, permit }) => {
|
||||
const result = decodeSteps(commands, inputs);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Amount", "5000.0000 USDT"],
|
||||
...permit,
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -2023,19 +2039,24 @@ describe("uniswap decoder", () => {
|
||||
});
|
||||
|
||||
// Out of that shape the permit caps nothing the Amount line can rely
|
||||
// on, so the line gives the total the steps take, as with no permit.
|
||||
// on, so the line gives the total the steps take, as with no permit,
|
||||
// and each permit gets lines of its own.
|
||||
const ONE_USDT_PERMIT = (spender) =>
|
||||
encodePermit2(USDT_ADDR, 1000000n, spender);
|
||||
const ONE_USDT_LINES = (spender) =>
|
||||
permitLines("1.0000 USDT", USDT_ADDR, "USDT", spender);
|
||||
test.each([
|
||||
{
|
||||
kind: "to another spender",
|
||||
commands: [0x0a],
|
||||
permits: [ONE_USDT_PERMIT(OTHER_ADDR)],
|
||||
lines: ONE_USDT_LINES(OTHER_ADDR),
|
||||
},
|
||||
{
|
||||
kind: "that the router lets fail",
|
||||
commands: [0x8a],
|
||||
permits: [ONE_USDT_PERMIT(ROUTER_ADDR)],
|
||||
lines: ONE_USDT_LINES(ROUTER_ADDR),
|
||||
},
|
||||
{
|
||||
kind: "followed by a second one",
|
||||
@@ -2044,10 +2065,14 @@ describe("uniswap decoder", () => {
|
||||
ONE_USDT_PERMIT(ROUTER_ADDR),
|
||||
ONE_USDT_PERMIT(ROUTER_ADDR),
|
||||
],
|
||||
lines: [
|
||||
...ONE_USDT_LINES(ROUTER_ADDR),
|
||||
...ONE_USDT_LINES(ROUTER_ADDR),
|
||||
],
|
||||
},
|
||||
])(
|
||||
"a split after a PERMIT2_PERMIT $kind shows the total the steps take",
|
||||
({ commands, permits }) => {
|
||||
({ commands, permits, lines }) => {
|
||||
const result = decodeSteps(
|
||||
[...commands, 0x00, 0x08],
|
||||
[
|
||||
@@ -2061,10 +2086,20 @@ describe("uniswap decoder", () => {
|
||||
);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Amount", "1000.0000 USDT"],
|
||||
...lines,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
// The lines of a PERMIT2_PERMIT of 600 USDT to the router whose
|
||||
// amount does not stand.
|
||||
const USDT_600_LINES = permitLines(
|
||||
"600.0000 USDT",
|
||||
USDT_ADDR,
|
||||
"USDT",
|
||||
ROUTER_ADDR,
|
||||
);
|
||||
|
||||
// A PERMIT2_PERMIT_BATCH, which this decoder does not read, may raise
|
||||
// what the router may take of the permit's token again.
|
||||
test("a split after a PERMIT2_PERMIT and a PERMIT2_PERMIT_BATCH shows the total the steps take", () => {
|
||||
@@ -2096,6 +2131,7 @@ describe("uniswap decoder", () => {
|
||||
);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Amount", "10000.0000 USDT"],
|
||||
...USDT_600_LINES,
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -2141,6 +2177,7 @@ describe("uniswap decoder", () => {
|
||||
);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Amount", "10000.0000 USDT"],
|
||||
...USDT_600_LINES,
|
||||
]);
|
||||
},
|
||||
);
|
||||
@@ -2168,8 +2205,9 @@ describe("uniswap decoder", () => {
|
||||
];
|
||||
// What a V3_SWAP_EXACT_OUT takes, at most its amountInMax, counts
|
||||
// as a V2_SWAP_EXACT_OUT's does, and the Amount line is a maximum.
|
||||
// The permit of 10,000 USDT stands; the one of 600 USDT does not,
|
||||
// because the step before it took its token.
|
||||
// The permit of 10,000 USDT stands. The one of 600 USDT comes after
|
||||
// the step that set the input side, so it does not stand and gets
|
||||
// lines of its own.
|
||||
test.each([
|
||||
{
|
||||
kind: "a V3 exact-in of 600 USDT, then a V3_SWAP_EXACT_OUT of at most 400 USDT",
|
||||
@@ -2201,17 +2239,185 @@ describe("uniswap decoder", () => {
|
||||
V3_600,
|
||||
],
|
||||
amount: "Up to 10000.0000 USDT",
|
||||
permit: USDT_600_LINES,
|
||||
},
|
||||
])(
|
||||
"$kind, all paid by the user, shows the total as a maximum",
|
||||
({ commands, inputs, amount }) => {
|
||||
({ commands, inputs, amount, permit = [] }) => {
|
||||
const result = decodeSteps(commands, inputs);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Amount", amount],
|
||||
...permit,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/370 — a PERMIT2_PERMIT
|
||||
// after the step that set the input side named Token In in place of
|
||||
// that step's token, and its amount could stand as the Amount figure.
|
||||
// Only a permit whose amount stands as the Amount figure names Token
|
||||
// In now. Every other, before the swap steps or after them, leaves
|
||||
// Token In and Amount as they read with no permit and gets lines of
|
||||
// its own.
|
||||
describe("a PERMIT2_PERMIT whose amount does not stand as the Amount figure", () => {
|
||||
const DAI_5000 = 5000000000000000000000n;
|
||||
const USDT_5000 = 5000000000n;
|
||||
const MAX_UINT160 = 2n ** 160n - 1n;
|
||||
|
||||
test.each([
|
||||
{
|
||||
kind: "a V3 exact-in of 600 USDT, then a PERMIT2_PERMIT of 5,000 DAI to the router,",
|
||||
commands: [0x00, 0x0a],
|
||||
inputs: [
|
||||
V3_600,
|
||||
encodePermit2(DAI_ADDR, DAI_5000, ROUTER_ADDR),
|
||||
],
|
||||
lines: permitLines(
|
||||
"5000.0000 DAI",
|
||||
DAI_ADDR,
|
||||
"DAI",
|
||||
ROUTER_ADDR,
|
||||
),
|
||||
},
|
||||
{
|
||||
kind: "a V3 exact-in of 600 USDT, then a PERMIT2_PERMIT of unlimited DAI to another spender,",
|
||||
commands: [0x00, 0x0a],
|
||||
inputs: [
|
||||
V3_600,
|
||||
encodePermit2(DAI_ADDR, MAX_UINT160, OTHER_ADDR),
|
||||
],
|
||||
lines: permitLines(
|
||||
"Unlimited",
|
||||
DAI_ADDR,
|
||||
"DAI",
|
||||
OTHER_ADDR,
|
||||
),
|
||||
},
|
||||
{
|
||||
kind: "a V3 exact-in of 600 USDT, then a PERMIT2_PERMIT of 600 USDT, the swap's own token, to the router,",
|
||||
commands: [0x00, 0x0a],
|
||||
inputs: [
|
||||
V3_600,
|
||||
encodePermit2(USDT_ADDR, USDT_600, ROUTER_ADDR),
|
||||
],
|
||||
lines: USDT_600_LINES,
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT of 5,000 USDT to another spender, then a V3 exact-in of 600 USDT,",
|
||||
commands: [0x0a, 0x00],
|
||||
inputs: [
|
||||
encodePermit2(USDT_ADDR, USDT_5000, OTHER_ADDR),
|
||||
V3_600,
|
||||
],
|
||||
lines: permitLines(
|
||||
"5000.0000 USDT",
|
||||
USDT_ADDR,
|
||||
"USDT",
|
||||
OTHER_ADDR,
|
||||
),
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT of 5,000 USDT to the router that the router may let fail, then a V3 exact-in of 600 USDT,",
|
||||
commands: [0x8a, 0x00],
|
||||
inputs: [
|
||||
encodePermit2(USDT_ADDR, USDT_5000, ROUTER_ADDR),
|
||||
V3_600,
|
||||
],
|
||||
lines: permitLines(
|
||||
"5000.0000 USDT",
|
||||
USDT_ADDR,
|
||||
"USDT",
|
||||
ROUTER_ADDR,
|
||||
),
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT of 5,000 DAI to another spender, then a V3 exact-in of 600 USDT,",
|
||||
commands: [0x0a, 0x00],
|
||||
inputs: [
|
||||
encodePermit2(DAI_ADDR, DAI_5000, OTHER_ADDR),
|
||||
V3_600,
|
||||
],
|
||||
lines: permitLines(
|
||||
"5000.0000 DAI",
|
||||
DAI_ADDR,
|
||||
"DAI",
|
||||
OTHER_ADDR,
|
||||
),
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT of 5,000 DAI to the router, a V3 exact-in of 600 USDT, then a PERMIT2_PERMIT of 600 USDT to the router,",
|
||||
commands: [0x0a, 0x00, 0x0a],
|
||||
inputs: [
|
||||
encodePermit2(DAI_ADDR, DAI_5000, ROUTER_ADDR),
|
||||
V3_600,
|
||||
encodePermit2(USDT_ADDR, USDT_600, ROUTER_ADDR),
|
||||
],
|
||||
lines: [
|
||||
...permitLines(
|
||||
"5000.0000 DAI",
|
||||
DAI_ADDR,
|
||||
"DAI",
|
||||
ROUTER_ADDR,
|
||||
),
|
||||
...USDT_600_LINES,
|
||||
],
|
||||
},
|
||||
])(
|
||||
"$kind shows the swap's 600 USDT and each permit's own lines",
|
||||
({ commands, inputs, lines }) => {
|
||||
const result = decodeSteps(commands, inputs);
|
||||
expect(result.name).toBe("Swap USDT → USDC");
|
||||
// The swap step names Token In, its address checksummed,
|
||||
// as on a permit's Allowance token line.
|
||||
expect(detail(result, "Token In").value).toBe(
|
||||
"USDT (" + USDT_ADDR + ")",
|
||||
);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Amount", "600.0000 USDT"],
|
||||
...lines,
|
||||
]);
|
||||
expect(detail(result, "Amount").rawValue).toBe("600.0000");
|
||||
},
|
||||
);
|
||||
|
||||
// With two permits neither amount stands, so the Amount line
|
||||
// gives the total the steps take of USDT, the 400 DAI the last
|
||||
// step takes gets lines of its own, and so does each permit.
|
||||
test("a PERMIT2_PERMIT of USDT, a V3 exact-in of 600 USDT, a PERMIT2_PERMIT of DAI and a V2 exact-in of 400 DAI shows both tokens' amounts and each permit's own lines", () => {
|
||||
const result = decodeSteps(
|
||||
[0x0a, 0x00, 0x0a, 0x08],
|
||||
[
|
||||
encodePermit2(USDT_ADDR, USDT_5000, ROUTER_ADDR),
|
||||
V3_600,
|
||||
encodePermit2(DAI_ADDR, DAI_400, ROUTER_ADDR),
|
||||
encodeV2SwapExactIn(USER_ADDR, DAI_400, 390000000n, [
|
||||
DAI_ADDR,
|
||||
USDC_ADDR,
|
||||
]),
|
||||
],
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → USDC");
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Amount", "600.0000 USDT"],
|
||||
["Moved from the sender", "400.0000 DAI"],
|
||||
["Token moved", "DAI (" + DAI_ADDR + ")"],
|
||||
["Moved to", "The swap step that spends it"],
|
||||
...permitLines(
|
||||
"5000.0000 USDT",
|
||||
USDT_ADDR,
|
||||
"USDT",
|
||||
ROUTER_ADDR,
|
||||
),
|
||||
...permitLines(
|
||||
"400.0000 DAI",
|
||||
DAI_ADDR,
|
||||
"DAI",
|
||||
ROUTER_ADDR,
|
||||
),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// A V3_SWAP_EXACT_OUT whose path is shorter than one token cannot be
|
||||
// read. It may pay any address and take from the sender, so it
|
||||
// leaves no Amount figure.
|
||||
@@ -2257,7 +2463,7 @@ describe("uniswap decoder", () => {
|
||||
// A V3 exact-out of 1,500 USDC for at most 0.5 WETH spends WETH, not
|
||||
// SPK. After it, a PERMIT2_PERMIT of 1 WETH and a V3 exact-in of 0.5
|
||||
// WETH: the permit's amount does not stand, because the step before
|
||||
// it also takes WETH.
|
||||
// it also takes WETH, so the permit gets lines of its own.
|
||||
test("a V3_SWAP_EXACT_OUT whose path has bytes after its last hop, then a PERMIT2_PERMIT and a V3 exact-in, shows no Amount figure", () => {
|
||||
const path = pathEndingIn([USDC_ADDR, WETH_ADDR], SPK_ADDR);
|
||||
const result = decodeSteps(
|
||||
@@ -2273,6 +2479,7 @@ describe("uniswap decoder", () => {
|
||||
);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Moved from the sender", UNDECODED],
|
||||
...permitLines("1.0000 WETH", WETH_ADDR, "WETH", ROUTER_ADDR),
|
||||
]);
|
||||
expect(detail(result, "Paid to").value).toBe(UNDECODED);
|
||||
});
|
||||
@@ -2318,6 +2525,24 @@ describe("uniswap decoder", () => {
|
||||
encodeV4TakeAll(WETH_ADDR, 0n),
|
||||
],
|
||||
);
|
||||
// The same step with its SETTLE of OPEN_DELTA paid from the router.
|
||||
const V4_EXACT_OUT_600_FROM_ROUTER = encodeV4Swap(
|
||||
new Uint8Array([
|
||||
V4_SWAP_EXACT_OUT_SINGLE_ID,
|
||||
V4_SETTLE_ID,
|
||||
V4_TAKE_ALL_ID,
|
||||
]),
|
||||
[
|
||||
encodeV4ExactOutSingle(
|
||||
USDT_ADDR,
|
||||
WETH_ADDR,
|
||||
ONE_WETH,
|
||||
USDT_600,
|
||||
),
|
||||
settle(USDT_ADDR, 0n, false),
|
||||
encodeV4TakeAll(WETH_ADDR, 0n),
|
||||
],
|
||||
);
|
||||
test.each([
|
||||
{
|
||||
kind: "a V4 exact-out step with a SETTLE of OPEN_DELTA by the user",
|
||||
@@ -2325,6 +2550,13 @@ describe("uniswap decoder", () => {
|
||||
first: V4_EXACT_OUT_600,
|
||||
lines: [...UNKNOWN_USDT, ...UP_TO_400_USDT],
|
||||
},
|
||||
// Paid from the router, the step takes nothing from the wallet.
|
||||
{
|
||||
kind: "a V4 exact-out step with a SETTLE of OPEN_DELTA from the router",
|
||||
commands: [0x10, 0x09],
|
||||
first: V4_EXACT_OUT_600_FROM_ROUTER,
|
||||
lines: UP_TO_400_USDT,
|
||||
},
|
||||
// Settled by the user, the step's amount would be what that
|
||||
// SETTLE pays, which the decoder cannot state here.
|
||||
{
|
||||
@@ -2370,6 +2602,36 @@ describe("uniswap decoder", () => {
|
||||
},
|
||||
);
|
||||
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/634 — after a
|
||||
// PERMIT2_PERMIT of another token, the V4 exact-out step paid from
|
||||
// the router still takes nothing from the wallet, so it gets no lines
|
||||
// of its own. On next it got lines saying its amount is not known.
|
||||
const ONE_DAI_PERMIT = encodePermit2(DAI_ADDR, 10n ** 18n, ROUTER_ADDR);
|
||||
test.each([
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT of 1 DAI, then a V4 exact-out step of at most 600 USDT paid from the router",
|
||||
commands: [0x0a, 0x10],
|
||||
inputs: [ONE_DAI_PERMIT, V4_EXACT_OUT_600_FROM_ROUTER],
|
||||
lines: [["Amount", "1.0000 DAI"]],
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT of 1 DAI, a V4 exact-out step of at most 600 USDT paid from the router, then a V2 exact-out of at most 400 USDT the user pays for",
|
||||
commands: [0x0a, 0x10, 0x09],
|
||||
inputs: [
|
||||
ONE_DAI_PERMIT,
|
||||
V4_EXACT_OUT_600_FROM_ROUTER,
|
||||
V2_EXACT_OUT_400,
|
||||
],
|
||||
lines: [["Amount", "Up to 1.0000 DAI"], ...UP_TO_400_USDT],
|
||||
},
|
||||
])(
|
||||
"$kind, gives the V4 step no lines of its own",
|
||||
({ commands, inputs, lines }) => {
|
||||
const result = decodeSteps(commands, inputs);
|
||||
expect(linesBetweenTokens(result)).toEqual(lines);
|
||||
},
|
||||
);
|
||||
|
||||
// The V4 exact-out route above the other way round, where the later
|
||||
// take's unknown amount leaves no figure at all, and other ways the
|
||||
// step that sets the input side states no amount.
|
||||
@@ -2388,7 +2650,11 @@ describe("uniswap decoder", () => {
|
||||
V4_EXACT_OUT_600,
|
||||
V2_EXACT_OUT_400,
|
||||
],
|
||||
lines: [...UNKNOWN_USDT, ...UP_TO_400_USDT],
|
||||
lines: [
|
||||
...UNKNOWN_USDT,
|
||||
...UP_TO_400_USDT,
|
||||
...ONE_USDT_LINES(OTHER_ADDR),
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "a V4 step whose swap action cannot be read, with a SETTLE of WETH by the user, then a V2 exact-out of at most 400 USDT",
|
||||
@@ -2423,6 +2689,98 @@ describe("uniswap decoder", () => {
|
||||
},
|
||||
);
|
||||
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/634 — a
|
||||
// PERMIT2_TRANSFER_FROM of the token the V4 exact-out step spends,
|
||||
// before or after it, shows its own figure, so the step's amount is
|
||||
// shown as not known beside it, and the 400 USDT cannot read as all
|
||||
// that leaves. On next only the 400 USDT was shown. Into the router,
|
||||
// the 400 USDT is on its Paid to line.
|
||||
const transfer = (token, recipient, amount) =>
|
||||
coder.encode(
|
||||
["address", "address", "uint160"],
|
||||
[token, recipient, amount],
|
||||
);
|
||||
const MOVED_400_USDT = [
|
||||
["Moved from the sender", "400.0000 USDT"],
|
||||
["Token moved", "USDT (" + USDT_ADDR + ")"],
|
||||
["Moved to", OTHER_ADDR],
|
||||
];
|
||||
test.each([
|
||||
{
|
||||
kind: "a V4 exact-out step of at most 600 USDT, then a PERMIT2_TRANSFER_FROM of 400 USDT to another address",
|
||||
commands: [0x10, 0x02],
|
||||
inputs: [
|
||||
V4_EXACT_OUT_600,
|
||||
transfer(USDT_ADDR, OTHER_ADDR, USDT_400),
|
||||
],
|
||||
lines: [...UNKNOWN_USDT, ...MOVED_400_USDT],
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_TRANSFER_FROM of 400 USDT to another address, then a V4 exact-out step of at most 600 USDT",
|
||||
commands: [0x02, 0x10],
|
||||
inputs: [
|
||||
transfer(USDT_ADDR, OTHER_ADDR, USDT_400),
|
||||
V4_EXACT_OUT_600,
|
||||
],
|
||||
lines: [...UNKNOWN_USDT, ...MOVED_400_USDT],
|
||||
},
|
||||
{
|
||||
kind: "a V4 exact-out step of at most 600 USDT, then a PERMIT2_TRANSFER_FROM of 400 USDT into the router",
|
||||
commands: [0x10, 0x02],
|
||||
inputs: [
|
||||
V4_EXACT_OUT_600,
|
||||
transfer(USDT_ADDR, ROUTER_ADDR, USDT_400),
|
||||
],
|
||||
lines: UNKNOWN_USDT,
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_TRANSFER_FROM of 400 USDT into the router, then a V4 exact-out step of at most 600 USDT",
|
||||
commands: [0x02, 0x10],
|
||||
inputs: [
|
||||
transfer(USDT_ADDR, ROUTER_ADDR, USDT_400),
|
||||
V4_EXACT_OUT_600,
|
||||
],
|
||||
lines: UNKNOWN_USDT,
|
||||
},
|
||||
])(
|
||||
"$kind, paid by the user, shows that the step's amount is not known",
|
||||
({ commands, inputs, lines }) => {
|
||||
const result = decodeSteps(commands, inputs);
|
||||
expect(linesBetweenTokens(result)).toEqual(lines);
|
||||
},
|
||||
);
|
||||
|
||||
// Paid from the router, the V4 exact-out step takes nothing from the
|
||||
// wallet, so the moves give all that leaves.
|
||||
test("a PERMIT2_TRANSFER_FROM of 400 USDT into the router, one of 10 USDT to another address, then a V4 exact-out step paid from the router, shows only the moves", () => {
|
||||
const result = decodeSteps(
|
||||
[0x02, 0x02, 0x10],
|
||||
[
|
||||
transfer(USDT_ADDR, ROUTER_ADDR, USDT_400),
|
||||
transfer(USDT_ADDR, OTHER_ADDR, 10000000n),
|
||||
V4_EXACT_OUT_600_FROM_ROUTER,
|
||||
],
|
||||
);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Moved from the sender", "10.0000 USDT"],
|
||||
["Token moved", "USDT (" + USDT_ADDR + ")"],
|
||||
["Moved to", OTHER_ADDR],
|
||||
]);
|
||||
});
|
||||
|
||||
// A move of another token says nothing of how much USDT leaves.
|
||||
test("a V4 exact-out step of at most 600 USDT, then a PERMIT2_TRANSFER_FROM of 400 DAI, shows only the DAI moved", () => {
|
||||
const result = decodeSteps(
|
||||
[0x10, 0x02],
|
||||
[V4_EXACT_OUT_600, transfer(DAI_ADDR, OTHER_ADDR, DAI_400)],
|
||||
);
|
||||
expect(linesBetweenTokens(result)).toEqual([
|
||||
["Moved from the sender", "400.0000 DAI"],
|
||||
["Token moved", "DAI (" + DAI_ADDR + ")"],
|
||||
["Moved to", OTHER_ADDR],
|
||||
]);
|
||||
});
|
||||
|
||||
// A V2 exact-out step makes every amount the swap steps spend a maximum,
|
||||
// the total included.
|
||||
test("a split with a V2 exact-out step the user pays for shows the total as a maximum", () => {
|
||||
@@ -2922,9 +3280,7 @@ describe("uniswap decoder", () => {
|
||||
);
|
||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||
expect(result.name).toBe("Uniswap Swap");
|
||||
expect(detail(result, "Token In").address).toBe(
|
||||
USDT_ADDR.toLowerCase(),
|
||||
);
|
||||
expect(detail(result, "Token In").address).toBe(USDT_ADDR);
|
||||
expect(detail(result, "Amount").value).toBe("1000.0000 USDT");
|
||||
expect(detail(result, "Token Out").value).toBe(
|
||||
"Unknown (not named in the calldata)",
|
||||
@@ -2982,9 +3338,7 @@ describe("uniswap decoder", () => {
|
||||
"Unknown (not named in the calldata)",
|
||||
);
|
||||
expect(detail(result, "Amount")).toBeUndefined();
|
||||
expect(detail(result, "Token Out").address).toBe(
|
||||
USDT_ADDR.toLowerCase(),
|
||||
);
|
||||
expect(detail(result, "Token Out").address).toBe(USDT_ADDR);
|
||||
expect(detail(result, "Min. received").value).toBe("990.0000 USDT");
|
||||
});
|
||||
|
||||
|
||||
+561
-18
@@ -7,9 +7,12 @@
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/592), the address whose
|
||||
// balance a BALANCE_CHECK_ERC20 checks
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/600), any token a swap
|
||||
// leaves in the router (https://git.eeqj.de/sneak/AutistMask/issues/606), and
|
||||
// leaves in the router (https://git.eeqj.de/sneak/AutistMask/issues/606),
|
||||
// what each PERMIT2_TRANSFER_FROM moves
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/611).
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/611), and when an
|
||||
// UNWRAP_WETH makes the output ETH
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/607 and
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/642).
|
||||
//
|
||||
// Every swap command, SWEEP, WRAP_ETH, UNWRAP_WETH, TRANSFER, PAY_PORTION,
|
||||
// PAY_PORTION_FULL_PRECISION, PERMIT2_TRANSFER_FROM, ACROSS_V4_DEPOSIT_V3 and
|
||||
@@ -268,18 +271,28 @@ const SWAP_USDT_FOR_ETH = [
|
||||
[[[ZERO, USDT, 500, 10, ZERO], false, USDT_2000, ONE_WETH, "0x"]],
|
||||
),
|
||||
];
|
||||
const SWAP_USDT_FOR_WETH = [
|
||||
0x06, // SWAP_EXACT_IN_SINGLE
|
||||
coder.encode(
|
||||
[
|
||||
"tuple(tuple(address,address,uint24,int24,address),bool,uint128,uint128,bytes)",
|
||||
],
|
||||
[[[USDT, WETH, 500, 10, ZERO], true, USDT_2000, ONE_WETH, "0x"]],
|
||||
),
|
||||
];
|
||||
// SWAP_EXACT_IN_SINGLE with no parameters, which cannot be read.
|
||||
const UNREADABLE_SWAP = [0x06, "0x"];
|
||||
const SETTLE_USDT = [
|
||||
0x0b,
|
||||
coder.encode(["address", "uint256", "bool"], [USDT, 0n, true]),
|
||||
];
|
||||
function take(currency, recipient) {
|
||||
// A TAKE of `amount`, by default zero: the open delta, all the step owes.
|
||||
function take(currency, recipient, amount = 0n) {
|
||||
return [
|
||||
0x0e,
|
||||
coder.encode(
|
||||
["address", "address", "uint256"],
|
||||
[currency, recipient, 0n],
|
||||
[currency, recipient, amount],
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -531,7 +544,7 @@ describe("an output left in the router is not received", () => {
|
||||
{
|
||||
kind: "an UNWRAP_WETH to the user, then the swap",
|
||||
data: execute(unwrapWeth(MSG_SENDER), toRouter),
|
||||
min: "1.0000 ETH",
|
||||
min: "1.0000 WETH",
|
||||
},
|
||||
{
|
||||
kind: "the swap, then a WRAP_ETH of zero to the user",
|
||||
@@ -568,6 +581,530 @@ describe("an output left in the router is not received", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/607: an UNWRAP_WETH pays out,
|
||||
// as ETH, the WETH the router holds when it runs. Token Out read ETH whenever
|
||||
// the output side was WETH, so a swap that paid its WETH to the user before
|
||||
// the UNWRAP_WETH read as ETH, though the user receives WETH.
|
||||
describe("an UNWRAP_WETH makes the output ETH only when the router holds it", () => {
|
||||
test("a swap paying its WETH to the user, then an UNWRAP_WETH, reads as WETH", () => {
|
||||
const result = decode(
|
||||
execute(swapToWeth(MSG_SENDER), unwrapWeth(MSG_SENDER)),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(labels(result)).toEqual(PAID_TO_USER);
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 WETH");
|
||||
});
|
||||
|
||||
test("a swap paying its WETH to the router, then an UNWRAP_WETH to the user, reads as ETH", () => {
|
||||
const result = decode(
|
||||
execute(swapToWeth(ADDRESS_THIS), unwrapWeth(MSG_SENDER)),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(labels(result)).toEqual(PAID_TO_USER);
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 ETH");
|
||||
});
|
||||
|
||||
// The SWEEP pays the user all the WETH the router holds, so the
|
||||
// UNWRAP_WETH finds none of it.
|
||||
test("a swap paying its WETH to the router, then a SWEEP of it to the user, then an UNWRAP_WETH, reads as WETH", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
sweep(WETH, MSG_SENDER),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 WETH");
|
||||
});
|
||||
|
||||
// The user receives the first step's WETH as WETH and the second's as
|
||||
// ETH. The second step sets the output side and pays its WETH to the
|
||||
// router, so the output reads as ETH with the second step's minimum.
|
||||
test("two swaps, the second paying its WETH to the router, then an UNWRAP_WETH, reads as ETH", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(MSG_SENDER),
|
||||
v2Swap(0x08, ADDRESS_THIS, USDC_1990, ONE_WETH / 2n, [
|
||||
USDC,
|
||||
WETH,
|
||||
]),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(detail(result, "Min. received").value).toBe("0.5000 ETH");
|
||||
});
|
||||
|
||||
// The same two swaps the other way round. The user receives the first
|
||||
// step's WETH as ETH and the second's as WETH. The second step sets the
|
||||
// output side and pays its WETH to the user, so the output reads as WETH
|
||||
// with the second step's minimum, though the router holds the first's.
|
||||
test("two swaps, the second paying its WETH to the user, then an UNWRAP_WETH, reads as WETH", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
v2Swap(0x08, ADDRESS_THIS, USDC_1990, ONE_WETH / 2n, [
|
||||
USDC,
|
||||
WETH,
|
||||
]),
|
||||
swapToWeth(MSG_SENDER),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDC → WETH");
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 WETH");
|
||||
});
|
||||
|
||||
// One V4 step buys at least 1 WETH and TAKEs 0.6 WETH to the user and the
|
||||
// rest to the router. The user receives 0.6 WETH and the rest as ETH.
|
||||
// Neither minimum is shown: the decoder does not count how much of the
|
||||
// step's minimum reaches the router, nor read the UNWRAP_WETH's own.
|
||||
test("one V4 step paying part of its WETH to the user and the rest to the router, then an UNWRAP_WETH, reads as ETH with no minimum", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
v4Swap(
|
||||
SWAP_USDT_FOR_WETH,
|
||||
SETTLE_USDT,
|
||||
take(WETH, MSG_SENDER, (ONE_WETH * 6n) / 10n),
|
||||
take(WETH, ADDRESS_THIS),
|
||||
),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(labels(result)).toEqual([
|
||||
"Protocol",
|
||||
"Token In",
|
||||
"Amount",
|
||||
"Token Out",
|
||||
"Steps",
|
||||
"Deadline",
|
||||
]);
|
||||
});
|
||||
|
||||
// A TAKE the decoder cannot read may pay part of the WETH to the user.
|
||||
test("one V4 step paying WETH to the router beside a TAKE that cannot be read, then an UNWRAP_WETH, reads as ETH with no minimum", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
v4Swap(
|
||||
SWAP_USDT_FOR_WETH,
|
||||
SETTLE_USDT,
|
||||
withDirtyWord(take(WETH, MSG_SENDER), 1),
|
||||
take(WETH, ADDRESS_THIS),
|
||||
),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(detail(result, "Min. received")).toBeUndefined();
|
||||
expect(detail(result, "Min. paid out")).toBeUndefined();
|
||||
});
|
||||
|
||||
// A step after the UNWRAP_WETH that sets the output side sets it anew.
|
||||
test("a swap paying WETH to the user after an UNWRAP_WETH of an earlier swap's WETH reads as WETH", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
v2Swap(0x08, MSG_SENDER, USDC_1990, ONE_WETH / 2n, [
|
||||
USDC,
|
||||
WETH,
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(detail(result, "Min. received").value).toBe("0.5000 WETH");
|
||||
});
|
||||
|
||||
// The EXECUTE_SUB_PLAN's own steps, which the decoder does not read, buy
|
||||
// the user USDC as well, so Token Out is not named.
|
||||
test("a swap paying its WETH to the router, then an UNWRAP_WETH, then an EXECUTE_SUB_PLAN, names no Token Out", () => {
|
||||
const subPlan = [
|
||||
0x21,
|
||||
coder.encode(
|
||||
["bytes", "bytes[]"],
|
||||
[
|
||||
"0x00",
|
||||
[
|
||||
v3SwapExactIn(
|
||||
MSG_SENDER,
|
||||
USDT_2000,
|
||||
USDC_1990,
|
||||
USDT,
|
||||
USDC,
|
||||
)[1],
|
||||
],
|
||||
],
|
||||
),
|
||||
];
|
||||
const result = decode(
|
||||
execute(swapToWeth(ADDRESS_THIS), unwrapWeth(MSG_SENDER), subPlan),
|
||||
);
|
||||
expect(result.name).toBe("Uniswap Swap");
|
||||
expect(detail(result, "Token Out").value).toBe(UNDECODED);
|
||||
expect(detail(result, "Min. received")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/642: a step between the swap and
|
||||
// the UNWRAP_WETH may take WETH out of the router or pay it WETH, and a step
|
||||
// after an UNWRAP_WETH into the router may pay its ETH out as WETH, yet each
|
||||
// route read as ETH with the swap's minimum. A step the decoder read that is a
|
||||
// PERMIT2_PERMIT, a BALANCE_CHECK_ERC20, or a SWEEP, TRANSFER, PAY_PORTION or
|
||||
// PAY_PORTION_FULL_PRECISION of a token other than WETH, and not of ETH to a
|
||||
// WETH contract, cannot take WETH out of the router or pay anyone WETH; the
|
||||
// decoder treats every other step as one that may.
|
||||
describe("what reaches the UNWRAP_WETH of the swap's WETH", () => {
|
||||
const NO_MINIMUM_TO_USER = PAID_TO_USER.filter(
|
||||
(l) => l !== "Min. received",
|
||||
);
|
||||
const NO_MINIMUM_ELSEWHERE = PAID_ELSEWHERE.filter(
|
||||
(l) => l !== "Min. paid out",
|
||||
);
|
||||
|
||||
test.each([
|
||||
{
|
||||
kind: "a TRANSFER of 0.0025 WETH",
|
||||
step: transfer(0x05, WETH, OTHER, ONE_WETH / 400n),
|
||||
},
|
||||
{
|
||||
kind: "a PAY_PORTION of 25 bips",
|
||||
step: transfer(0x06, WETH, OTHER, 25n),
|
||||
},
|
||||
{
|
||||
kind: "a PAY_PORTION_FULL_PRECISION of 1e15",
|
||||
step: transfer(0x07, WETH, OTHER, 10n ** 15n),
|
||||
},
|
||||
])(
|
||||
"$kind to another address between them reads as ETH with no minimum",
|
||||
({ step }) => {
|
||||
const result = decode(
|
||||
execute(swapToWeth(ADDRESS_THIS), step, unwrapWeth(MSG_SENDER)),
|
||||
USER,
|
||||
ROUTER_V2_1_2,
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(labels(result)).toEqual(NO_MINIMUM_ELSEWHERE);
|
||||
expect(paidTo(result)).toEqual([OTHER]);
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
{
|
||||
kind: "a SWEEP whose recipient cannot be read",
|
||||
step: withDirtyWord(sweep(WETH, OTHER), 1),
|
||||
},
|
||||
{
|
||||
kind: "a V4 SETTLE of 0.5 WETH from the router",
|
||||
step: v4Swap([
|
||||
0x0b,
|
||||
coder.encode(
|
||||
["address", "uint256", "bool"],
|
||||
[WETH, ONE_WETH / 2n, false],
|
||||
),
|
||||
]),
|
||||
},
|
||||
{
|
||||
kind: "a bridge deposit of 0.5 WETH",
|
||||
step: acrossDeposit(USER, USER, WETH, ONE_WETH / 2n),
|
||||
},
|
||||
{
|
||||
kind: "a PERMIT2_TRANSFER_FROM of 0.5 WETH into the router",
|
||||
step: permit2TransferFrom(WETH, ADDRESS_THIS, ONE_WETH / 2n),
|
||||
},
|
||||
])("$kind between them reads as ETH with no minimum", ({ step }) => {
|
||||
const result = decode(
|
||||
execute(swapToWeth(ADDRESS_THIS), step, unwrapWeth(MSG_SENDER)),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(detail(result, "Min. received")).toBeUndefined();
|
||||
expect(detail(result, "Min. paid out")).toBeUndefined();
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
kind: "a PERMIT2_PERMIT between them",
|
||||
steps: [permit2Permit(USDT, USDT_2000), unwrapWeth(MSG_SENDER)],
|
||||
},
|
||||
{
|
||||
kind: "a BALANCE_CHECK_ERC20 of another address between them",
|
||||
steps: [balanceCheck(USDC, 1n, OTHER), unwrapWeth(MSG_SENDER)],
|
||||
},
|
||||
{
|
||||
kind: "a BALANCE_CHECK_ERC20 of the sender with a zero minimum between them",
|
||||
steps: [balanceCheck(USDC, 0n), unwrapWeth(MSG_SENDER)],
|
||||
},
|
||||
{
|
||||
kind: "a SWEEP of USDC between them",
|
||||
steps: [sweep(USDC, MSG_SENDER), unwrapWeth(MSG_SENDER)],
|
||||
},
|
||||
{
|
||||
kind: "an UNWRAP_WETH into the router, then a SWEEP of its ETH,",
|
||||
steps: [unwrapWeth(ADDRESS_THIS), sweep(ZERO, MSG_SENDER)],
|
||||
},
|
||||
])("$kind reads as ETH with the swap's minimum", ({ steps }) => {
|
||||
const result = decode(execute(swapToWeth(ADDRESS_THIS), ...steps));
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 ETH");
|
||||
});
|
||||
|
||||
test("a V4 step that TAKEs its WETH to the router, then an UNWRAP_WETH to the user, reads as ETH with the swap's minimum", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
v4Swap(
|
||||
SWAP_USDT_FOR_WETH,
|
||||
SETTLE_USDT,
|
||||
take(WETH, ADDRESS_THIS),
|
||||
),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 ETH");
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
kind: "a TRANSFER of 100 USDC",
|
||||
step: transfer(0x05, USDC, OTHER, 100000000n),
|
||||
},
|
||||
{
|
||||
kind: "a PAY_PORTION of 25 bips of USDC",
|
||||
step: transfer(0x06, USDC, OTHER, 25n),
|
||||
},
|
||||
{
|
||||
kind: "a PAY_PORTION_FULL_PRECISION of 1e15 of USDC",
|
||||
step: transfer(0x07, USDC, OTHER, 10n ** 15n),
|
||||
},
|
||||
])(
|
||||
"$kind to another address between them reads as ETH with the swap's minimum",
|
||||
({ step }) => {
|
||||
const result = decode(
|
||||
execute(swapToWeth(ADDRESS_THIS), step, unwrapWeth(MSG_SENDER)),
|
||||
USER,
|
||||
ROUTER_V2_1_2,
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(paidTo(result)).toEqual([OTHER]);
|
||||
expect(detail(result, "Min. paid out").value).toBe("1.0000 ETH");
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
{
|
||||
kind: "a TRANSFER of 0.0025 ETH",
|
||||
step: transfer(0x05, ZERO, OTHER, ONE_WETH / 400n),
|
||||
},
|
||||
{
|
||||
kind: "a PAY_PORTION of 25 bips of its ETH",
|
||||
step: transfer(0x06, ZERO, OTHER, 25n),
|
||||
},
|
||||
{
|
||||
kind: "a PAY_PORTION_FULL_PRECISION of 1e15 of its ETH",
|
||||
step: transfer(0x07, ZERO, OTHER, 10n ** 15n),
|
||||
},
|
||||
])(
|
||||
"an UNWRAP_WETH into the router, then $kind to another address, then a SWEEP of its ETH to the user, reads as ETH with the swap's minimum",
|
||||
({ step }) => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
unwrapWeth(ADDRESS_THIS),
|
||||
step,
|
||||
sweep(ZERO, MSG_SENDER),
|
||||
),
|
||||
USER,
|
||||
ROUTER_V2_1_2,
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(paidTo(result)).toEqual([OTHER]);
|
||||
expect(detail(result, "Min. paid out").value).toBe("1.0000 ETH");
|
||||
},
|
||||
);
|
||||
|
||||
// The SWEEP pays the user the swap's WETH, so the UNWRAP_WETH unwraps the
|
||||
// WRAP_ETH's.
|
||||
test("a SWEEP of the swap's WETH to the user, then a WRAP_ETH into the router, reads as ETH with no minimum", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
sweep(WETH, MSG_SENDER),
|
||||
wrapEth(ADDRESS_THIS, ONE_WETH),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(labels(result)).toEqual(NO_MINIMUM_TO_USER);
|
||||
});
|
||||
|
||||
test("an UNWRAP_WETH into the router, then a WRAP_ETH of all its ETH to the user, reads as WETH with no minimum", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
unwrapWeth(ADDRESS_THIS),
|
||||
wrapEth(MSG_SENDER, CONTRACT_BALANCE),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(labels(result)).toEqual(NO_MINIMUM_TO_USER);
|
||||
});
|
||||
|
||||
// The router reads the recipient from the last 20 bytes of its word,
|
||||
// here address(2), the router itself.
|
||||
test("an UNWRAP_WETH whose recipient cannot be read, then a WRAP_ETH of all the router's ETH to the user, reads as WETH with no minimum", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
withDirtyWord(unwrapWeth(ADDRESS_THIS), 0),
|
||||
wrapEth(MSG_SENDER, CONTRACT_BALANCE),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(detail(result, "Min. received")).toBeUndefined();
|
||||
expect(detail(result, "Min. paid out")).toBeUndefined();
|
||||
});
|
||||
|
||||
// The first UNWRAP_WETH may pay the router the swap's output as ETH, and
|
||||
// the WRAP_ETH to the user pays all of it out as WETH, so the last
|
||||
// UNWRAP_WETH finds none of it.
|
||||
test.each([
|
||||
{
|
||||
kind: "an UNWRAP_WETH whose recipient cannot be read, then a WRAP_ETH of all the router's ETH to the user",
|
||||
steps: [
|
||||
withDirtyWord(unwrapWeth(ADDRESS_THIS), 0),
|
||||
wrapEth(MSG_SENDER, CONTRACT_BALANCE),
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "an UNWRAP_WETH into the router, a WRAP_ETH of all its ETH to the user, then a WRAP_ETH of all its ETH into the router",
|
||||
steps: [
|
||||
unwrapWeth(ADDRESS_THIS),
|
||||
wrapEth(MSG_SENDER, CONTRACT_BALANCE),
|
||||
wrapEth(ADDRESS_THIS, CONTRACT_BALANCE),
|
||||
],
|
||||
},
|
||||
])(
|
||||
"$kind, then an UNWRAP_WETH to the user, reads as WETH with no minimum",
|
||||
({ steps }) => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
...steps,
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(detail(result, "Min. received")).toBeUndefined();
|
||||
expect(detail(result, "Min. paid out")).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
// A SWEEP of WETH pays out WETH, and ETH paid to a WETH contract pays the
|
||||
// router WETH for it. The decoder treats each as a step that may pay out
|
||||
// as WETH the swap's output, which the router holds as ETH.
|
||||
test.each([
|
||||
{
|
||||
kind: "a SWEEP of WETH to the user",
|
||||
step: sweep(WETH, MSG_SENDER),
|
||||
},
|
||||
{
|
||||
kind: "a SWEEP of its ETH to the WETH contract",
|
||||
step: sweep(ZERO, WETH),
|
||||
},
|
||||
{
|
||||
kind: "a TRANSFER of 0.5 ETH to the WETH contract",
|
||||
step: transfer(0x05, ZERO, WETH, ONE_WETH / 2n),
|
||||
},
|
||||
{
|
||||
kind: "a PAY_PORTION of all its ETH to the WETH contract",
|
||||
step: transfer(0x06, ZERO, WETH, 10000n),
|
||||
},
|
||||
])(
|
||||
"an UNWRAP_WETH into the router, then $kind, reads as WETH with no minimum",
|
||||
({ step }) => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
unwrapWeth(ADDRESS_THIS),
|
||||
step,
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(detail(result, "Min. received")).toBeUndefined();
|
||||
expect(detail(result, "Min. paid out")).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
// The user receives 0.5 WETH and the rest of the swap's output as ETH.
|
||||
test("an UNWRAP_WETH into the router, then a WRAP_ETH of 0.5 ETH to the user, reads as WETH with no minimum", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
unwrapWeth(ADDRESS_THIS),
|
||||
wrapEth(MSG_SENDER, ONE_WETH / 2n),
|
||||
sweep(ZERO, MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → WETH");
|
||||
expect(labels(result)).toEqual(NO_MINIMUM_TO_USER);
|
||||
});
|
||||
|
||||
// The UNWRAP_WETH pays the user the swap's WETH as ETH; the WRAP_ETH wraps
|
||||
// the ETH an earlier V4 step paid the router.
|
||||
test("an UNWRAP_WETH to the user, then a WRAP_ETH of all the router's ETH to the user, reads as ETH", () => {
|
||||
const result = decode(
|
||||
execute(
|
||||
v4Swap(
|
||||
SWAP_USDT_FOR_ETH,
|
||||
SETTLE_USDT,
|
||||
take(ZERO, ADDRESS_THIS),
|
||||
),
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
wrapEth(MSG_SENDER, CONTRACT_BALANCE),
|
||||
),
|
||||
);
|
||||
expect(detail(result, "Token Out").value).toBe("ETH");
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 ETH");
|
||||
});
|
||||
|
||||
// The first swap is for at least 0.5 WETH and the second for at least
|
||||
// 1 WETH. The second sets the output side again, so the first
|
||||
// UNWRAP_WETH into the router no longer bears on it.
|
||||
test.each([
|
||||
{ kind: "a V3 swap step", step: swapToWeth(ADDRESS_THIS) },
|
||||
{
|
||||
kind: "a V4 step that TAKEs its WETH to the router",
|
||||
step: v4Swap(
|
||||
SWAP_USDT_FOR_WETH,
|
||||
SETTLE_USDT,
|
||||
take(WETH, ADDRESS_THIS),
|
||||
),
|
||||
},
|
||||
])(
|
||||
"a swap paying WETH to the router, an UNWRAP_WETH into the router, a SWEEP of its ETH to the user, then $kind and an UNWRAP_WETH to the user, reads as ETH with the second swap's minimum",
|
||||
({ step }) => {
|
||||
const result = decode(
|
||||
execute(
|
||||
v3SwapExactIn(
|
||||
ADDRESS_THIS,
|
||||
USDT_2000,
|
||||
ONE_WETH / 2n,
|
||||
USDT,
|
||||
WETH,
|
||||
),
|
||||
unwrapWeth(ADDRESS_THIS),
|
||||
sweep(ZERO, MSG_SENDER),
|
||||
step,
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
);
|
||||
expect(result.name).toBe("Swap USDT → ETH");
|
||||
expect(detail(result, "Min. received").value).toBe("1.0000 ETH");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// https://git.eeqj.de/sneak/AutistMask/issues/606: any token a step pays the
|
||||
// router stays there unless a later step pays out or spends all of it, not
|
||||
// only the swap's output. A V4 SETTLE can take more of the user's tokens than
|
||||
@@ -1534,15 +2071,6 @@ describe("a payout of part of the router's output", () => {
|
||||
),
|
||||
min: "1.0000 WETH",
|
||||
},
|
||||
{
|
||||
kind: "PAY_PORTION of 25 bips, then UNWRAP_WETH",
|
||||
data: execute(
|
||||
swapToWeth(ADDRESS_THIS),
|
||||
transfer(0x06, WETH, OTHER, 25n),
|
||||
unwrapWeth(MSG_SENDER),
|
||||
),
|
||||
min: "1.0000 ETH",
|
||||
},
|
||||
{
|
||||
kind: "V4 TAKE_PORTION of 25 bips, then TAKE_ALL",
|
||||
data: execute(
|
||||
@@ -2281,7 +2809,7 @@ describe("the allow-revert flag", () => {
|
||||
mark: " (allowed to fail)",
|
||||
},
|
||||
])(
|
||||
"on $router, a PERMIT2_PERMIT with the flag is listed as 'Permit2 Permit$mark', and the swap reads as without the flag",
|
||||
"on $router, a PERMIT2_PERMIT with the flag is listed as 'Permit2 Permit$mark', and the swap's lines read as without the flag",
|
||||
({ address, mark }) => {
|
||||
const steps = [
|
||||
permit2Permit(USDT, USDT_2000),
|
||||
@@ -2296,9 +2824,24 @@ describe("the allow-revert flag", () => {
|
||||
expect(detail(withFlag, "Steps").value).toBe(
|
||||
"Permit2 Permit" + mark + " → V3 Swap (Exact In)",
|
||||
);
|
||||
const withoutSteps = (r) =>
|
||||
r.details.filter((d) => d.label !== "Steps");
|
||||
expect(withoutSteps(withFlag)).toEqual(withoutSteps(plain));
|
||||
// The permit names the router at ROUTER as its spender, so its
|
||||
// amount stands as the Amount figure only there, and only without
|
||||
// the flag. With the flag it stands on no router and gets lines
|
||||
// of its own, and the swap step names Token In: the same token,
|
||||
// its address written the same way.
|
||||
const permitLines = [
|
||||
"Permit2 allowance",
|
||||
"Allowance token",
|
||||
"Allowance spender",
|
||||
];
|
||||
const swapLines = (r) =>
|
||||
r.details.filter(
|
||||
(d) => !["Steps", ...permitLines].includes(d.label),
|
||||
);
|
||||
expect(swapLines(withFlag)).toEqual(swapLines(plain));
|
||||
expect(
|
||||
labels(withFlag).filter((l) => permitLines.includes(l)),
|
||||
).toEqual(permitLines);
|
||||
expect(detail(withFlag, "Min. received").value).toBe("1.0000 WETH");
|
||||
},
|
||||
);
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
// only when the transaction is sent to a Universal Router deployment on the
|
||||
// network it is for; anywhere else it is left to the raw data.
|
||||
//
|
||||
// The transaction history labelled any call named `execute` or `multicall` a
|
||||
// Swap, whatever address it went to
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/580). It now does so only for
|
||||
// such a call sent to a Universal Router deployment on the network the
|
||||
// transaction is on; any other is labelled by its method name.
|
||||
//
|
||||
// The transaction detail screen and the approval screen are driven against a
|
||||
// minimal DOM stub in the shape tests/tokenTransferDetail.test.js uses, the
|
||||
// approval screen opened the way tests/swapStatusAmount.test.js opens it.
|
||||
@@ -33,6 +39,7 @@ globalThis.chrome = {
|
||||
};
|
||||
|
||||
const { state } = require("../src/shared/state");
|
||||
const { fetchRecentTransactions } = require("../src/shared/transactions");
|
||||
const approval = require("../src/popup/views/approval");
|
||||
const { decodeCalldata } = approval;
|
||||
const transactionDetail = require("../src/popup/views/transactionDetail");
|
||||
@@ -47,6 +54,8 @@ const SEPOLIA_ROUTER = "0x3a9d48ab9751398bbfa63ad67599bb04e4bdf98b";
|
||||
const ROUTER_ON_BOTH = "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD";
|
||||
// The address with no code from the issue.
|
||||
const ORDINARY = "0x0b0050Da68435b3EcBC236c40F16dB2070bCD79A";
|
||||
// A contract that is not a router, such as a multisig.
|
||||
const OTHER_CONTRACT = "0x5afe000000000000000000000000000000005afe";
|
||||
|
||||
const RECIPIENT = "0xC0FfEE0000000000000000000000000000c0fFEe";
|
||||
const SEPOLIA_WETH = "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14";
|
||||
@@ -129,8 +138,13 @@ describe("execute() calldata on the approval screen's decoder", () => {
|
||||
// The transaction the explorer reports: SWAP_DATA, sent to `mockSentTo`.
|
||||
const TX_HASH = "0x" + "5".repeat(64);
|
||||
let mockSentTo = null;
|
||||
// The transactions the explorer reports for RECIPIENT's history.
|
||||
let mockHistory = [];
|
||||
|
||||
function mockExplorerAnswer(url) {
|
||||
if (url.endsWith("/addresses/" + RECIPIENT + "/transactions")) {
|
||||
return { items: mockHistory };
|
||||
}
|
||||
if (url.endsWith("/transactions/" + TX_HASH)) {
|
||||
return {
|
||||
to: { hash: mockSentTo },
|
||||
@@ -187,10 +201,9 @@ function node(id) {
|
||||
}
|
||||
|
||||
// Open the transaction detail screen with `activeNetworkId` active, for the
|
||||
// Sepolia transaction the explorer reports sent to `sentTo`, and wait for its
|
||||
// decoded details.
|
||||
async function showDetailSentTo(sentTo, activeNetworkId) {
|
||||
mockSentTo = sentTo;
|
||||
// history row `row`, and wait for its decoded details.
|
||||
async function showDetail(row, activeNetworkId) {
|
||||
mockSentTo = row.to;
|
||||
globalThis.document = makeDocument();
|
||||
globalThis.window = { location: { search: "" } };
|
||||
state.networkId = activeNetworkId;
|
||||
@@ -198,22 +211,32 @@ async function showDetailSentTo(sentTo, activeNetworkId) {
|
||||
state.viewData = {};
|
||||
state.viewStack = [];
|
||||
state.currentView = null;
|
||||
transactionDetail.show({
|
||||
hash: TX_HASH,
|
||||
from: RECIPIENT,
|
||||
to: sentTo,
|
||||
value: "",
|
||||
symbol: "SepoliaETH",
|
||||
timestamp: 1790000000,
|
||||
isError: false,
|
||||
direction: "contract",
|
||||
directionLabel: "Swap",
|
||||
method: "execute",
|
||||
chainId: SEPOLIA,
|
||||
});
|
||||
transactionDetail.show(row);
|
||||
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
|
||||
// Open the transaction detail screen with `activeNetworkId` active, for the
|
||||
// Sepolia transaction the explorer reports sent to `sentTo`, and wait for its
|
||||
// decoded details.
|
||||
async function showDetailSentTo(sentTo, activeNetworkId) {
|
||||
await showDetail(
|
||||
{
|
||||
hash: TX_HASH,
|
||||
from: RECIPIENT,
|
||||
to: sentTo,
|
||||
value: "",
|
||||
symbol: "SepoliaETH",
|
||||
timestamp: 1790000000,
|
||||
isError: false,
|
||||
direction: "contract",
|
||||
directionLabel: "Swap",
|
||||
method: "execute",
|
||||
chainId: SEPOLIA,
|
||||
},
|
||||
activeNetworkId,
|
||||
);
|
||||
}
|
||||
|
||||
describe("execute() calldata on the transaction detail screen", () => {
|
||||
test("sent to a router on the active network, it is a swap", async () => {
|
||||
await showDetailSentTo(SEPOLIA_ROUTER, "sepolia");
|
||||
@@ -245,6 +268,58 @@ describe("execute() calldata on the transaction detail screen", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// The history row made from the explorer's answer for RECIPIENT's `method`
|
||||
// call sent to the contract `sentTo` on the network with `chainId`. The
|
||||
// explorer gives the address in checksummed form.
|
||||
async function historyRow(method, sentTo, chainId) {
|
||||
mockHistory = [
|
||||
{
|
||||
hash: TX_HASH,
|
||||
block_number: 7000000,
|
||||
timestamp: "2026-09-01T00:00:00Z",
|
||||
from: { hash: RECIPIENT },
|
||||
to: { hash: getAddress(sentTo), is_contract: true },
|
||||
value: "0",
|
||||
method,
|
||||
status: "ok",
|
||||
},
|
||||
];
|
||||
const rows = await fetchRecentTransactions(
|
||||
RECIPIENT,
|
||||
"https://explorer.example/api/v2",
|
||||
chainId,
|
||||
);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
// The history row's label and TransactionDetail's Type line, for a Sepolia
|
||||
// transaction. The active network does not decide either.
|
||||
describe.each([
|
||||
["execute", "Execute"],
|
||||
["multicall", "Multicall"],
|
||||
])("a %s() call in the history", (method, methodLabel) => {
|
||||
test("sent to a router on its network, it is a Swap", async () => {
|
||||
const row = await historyRow(method, SEPOLIA_ROUTER, SEPOLIA);
|
||||
expect(row.directionLabel).toBe("Swap");
|
||||
await showDetail(row, "mainnet");
|
||||
expect(node("tx-detail-type").textContent).toBe("Swap");
|
||||
});
|
||||
|
||||
test("sent to another contract, it is labelled by its method name", async () => {
|
||||
const row = await historyRow(method, OTHER_CONTRACT, SEPOLIA);
|
||||
expect(row.directionLabel).toBe(methodLabel);
|
||||
await showDetail(row, "sepolia");
|
||||
expect(node("tx-detail-type").textContent).toBe("Contract Call");
|
||||
});
|
||||
|
||||
test("sent to a router of the other network only, it is labelled by its method name", async () => {
|
||||
const row = await historyRow(method, MAINNET_ROUTER, SEPOLIA);
|
||||
expect(row.directionLabel).toBe(methodLabel);
|
||||
await showDetail(row, "mainnet");
|
||||
expect(node("tx-detail-type").textContent).toBe("Contract Call");
|
||||
});
|
||||
});
|
||||
|
||||
// Open the approval screen with Ethereum Mainnet active, for a site's Sepolia
|
||||
// transaction that sends SWAP_DATA to `sentTo`.
|
||||
async function showApprovalSentTo(sentTo) {
|
||||
|
||||
@@ -120,7 +120,7 @@ global.document = {
|
||||
body: { prepend() {}, appendChild() {} },
|
||||
addEventListener() {},
|
||||
};
|
||||
global.navigator = { clipboard: { writeText() {} } };
|
||||
global.navigator.clipboard = { writeText() {} };
|
||||
|
||||
const { AbiCoder, parseUnits } = require("ethers");
|
||||
const { fetchTokenBalances } = require("../src/shared/balances");
|
||||
|
||||
Reference in New Issue
Block a user