Compare commits
2
Commits
ab86707a77
...
05f2eea033
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05f2eea033 | ||
|
|
5e4b8ff3b0 |
@@ -1144,8 +1144,9 @@ fetched, without that cross-address check, and shows the row's figure.
|
|||||||
|
|
||||||
**Decoded amount lines on the transaction approval screen:** the `Amount` line
|
**Decoded amount lines on the transaction approval screen:** the `Amount` line
|
||||||
of a decoded ERC-20 call, and the `Amount` and `Min. received` lines of a
|
of a decoded ERC-20 call, and the `Amount` and `Min. received` lines of a
|
||||||
decoded swap (see TxApproval below), do not always read as a number. They can
|
decoded swap (see TxApproval below; `Min. received` reads `Min. paid out` unless
|
||||||
read:
|
only the user is paid, see Transaction Decoding), do not always read as a
|
||||||
|
number. They can read:
|
||||||
|
|
||||||
- A formatted quantity, e.g. `17.1900 USDT`, when the token's scale is known:
|
- A formatted quantity, e.g. `17.1900 USDT`, when the token's scale is known:
|
||||||
truncated to four decimals, with the floor and the zero cases described above.
|
truncated to four decimals, with the floor and the zero cases described above.
|
||||||
@@ -1743,37 +1744,46 @@ view would leave a wallet one click from deletion.
|
|||||||
arrives, as the balance minus the reserve, and the transaction is signed
|
arrives, as the balance minus the reserve, and the transaction is signed
|
||||||
with that estimate's fee fields, so a fee fetched again at signing cannot
|
with that estimate's fee fields, so a fee fetched again at signing cannot
|
||||||
exceed what the amount leaves behind. The address keeps whatever part of
|
exceed what the amount leaves behind. The address keeps whatever part of
|
||||||
the reserve the transaction does not use. If the balance no longer covers
|
the reserve the transaction does not use. If the balance could not be read
|
||||||
the fee, the amount is left as it was and the amount-plus-fee error below
|
or no longer covers the fee, the amount is left as it was and one of the
|
||||||
blocks the send
|
errors below blocks the send
|
||||||
- Your balance: value + symbol (USD in parentheses), or `unknown (SYMBOL)`
|
- Your balance: the From address's balance on the network its transaction
|
||||||
for a token whose scale is unknown
|
was reviewed on, read from that network's RPC endpoint each time the
|
||||||
|
screen is shown, so a screen the popup reopens onto states and checks that
|
||||||
|
network's balance as it is then, whichever network is active. "Loading..."
|
||||||
|
until the read returns, then value + symbol (USD in parentheses), or
|
||||||
|
`unknown (SYMBOL)` for a token whose scale is unknown or when the read
|
||||||
|
failed. The amount check uses the same balances: the ETH balance, and for
|
||||||
|
a token transfer the token balance as well
|
||||||
- Network fee: "Estimating..." then two lines, or "Unable to estimate",
|
- Network fee: "Estimating..." then two lines, or "Unable to estimate",
|
||||||
fetched async. The first line is what the transfer is expected to cost,
|
fetched async once the balance is read. The first line is what the
|
||||||
`gasLimit * gasPrice` (USD in parentheses); the second is the
|
transfer is expected to cost, `gasLimit * gasPrice` (USD in parentheses);
|
||||||
`gasLimit * maxFeePerGas` reserve the node requires, which is what the
|
the second is the `gasLimit * maxFeePerGas` reserve the node requires,
|
||||||
balance check gates on. The second line is omitted on a network with no
|
which is what the balance check gates on. The second line is omitted on a
|
||||||
type-2 pricing, where the two are the same number, but its space is
|
network with no type-2 pricing, where the two are the same number, but its
|
||||||
reserved either way
|
space is reserved either way
|
||||||
- Warnings: inline warnings from the local checks (scam address, self-send)
|
- Warnings: inline warnings from the local checks (scam address, self-send)
|
||||||
plus four reserved warning boxes made visible by the async checks —
|
plus four reserved warning boxes made visible by the async checks —
|
||||||
recipient that has never sent a transaction and holds no ETH, recipient is
|
recipient that has never sent a transaction and holds no ETH, recipient is
|
||||||
a contract, burn address, and an Etherscan phishing/scam label. An address
|
a contract, burn address, and an Etherscan phishing/scam label. An address
|
||||||
that has received ETH but never sent a transaction still holds that ETH,
|
that has received ETH but never sent a transaction still holds that ETH,
|
||||||
so it gets no warning
|
so it gets no warning
|
||||||
- Errors (insufficient balance), plus three reserved error boxes — the
|
- Errors (an invalid amount), plus five reserved error boxes, so the balance
|
||||||
amount plus the fee exceeds the balance (ETH transfers), not enough ETH to
|
and the fee arriving later move nothing — the amount exceeds the balance
|
||||||
pay the fee for the transfer (ERC-20 transfers), and the fee could not be
|
(for a token whose scale is unknown it says the token's balance is
|
||||||
estimated. The first two are mutually exclusive per transfer type, so only
|
unknown), the balance could not be read (it asks the user to go back and
|
||||||
the applicable one holds space. The last names its cause: for a token
|
try again), the amount plus the fee exceeds the balance (ETH transfers),
|
||||||
whose scale is unknown the fee can never be estimated, and it says the
|
not enough ETH to pay the fee for the transfer (ERC-20 transfers), and the
|
||||||
wallet does not know how many decimal places the token uses and that the
|
fee could not be estimated. The third and fourth are mutually exclusive
|
||||||
transaction cannot be sent; for any other failure it asks the user to go
|
per transfer type, so only the applicable one holds space. The last names
|
||||||
back and try again
|
its cause: for a token whose scale is unknown the fee can never be
|
||||||
|
estimated, and it says the wallet does not know how many decimal places
|
||||||
|
the token uses and that the transaction cannot be sent; for any other
|
||||||
|
failure it asks the user to go back and try again
|
||||||
- Password: an inline field on this screen, not a modal, with its own error
|
- Password: an inline field on this screen, not a modal, with its own error
|
||||||
line
|
line
|
||||||
- "Sign & Send" button (disabled if errors, and while the network fee
|
- "Sign & Send" button (disabled if errors, while the balance is being read,
|
||||||
estimate is pending or unavailable)
|
and while the network fee estimate is pending or unavailable)
|
||||||
- **Transitions**:
|
- **Transitions**:
|
||||||
- "Sign & Send" (correct password) → broadcast tx → **WaitTx**
|
- "Sign & Send" (correct password) → broadcast tx → **WaitTx**
|
||||||
- "Sign & Send" (correct password) → broadcast fails → **ErrorTx**
|
- "Sign & Send" (correct password) → broadcast fails → **ErrorTx**
|
||||||
@@ -1795,9 +1805,9 @@ view would leave a wallet one click from deletion.
|
|||||||
whichever network is active: its amounts are in that network's native
|
whichever network is active: its amounts are in that network's native
|
||||||
currency, its USD values are that network's, so a testnet transaction
|
currency, its USD values are that network's, so a testnet transaction
|
||||||
shows none, its From, To and token contract links open that network's
|
shows none, its From, To and token contract links open that network's
|
||||||
explorer, the fee estimate and the contract and never-sent recipient
|
explorer, the balance read, the fee estimate and the contract and
|
||||||
checks ask that network's RPC endpoint, and the Etherscan label check asks
|
never-sent recipient checks ask that network's RPC endpoint, and the
|
||||||
that network's explorer
|
Etherscan label check asks that network's explorer
|
||||||
- "Sign & Send" (wrong password) → "Wrong password." on the password error
|
- "Sign & Send" (wrong password) → "Wrong password." on the password error
|
||||||
line, no screen change
|
line, no screen change
|
||||||
- "Sign & Send" signs as the From address above, not as whichever address is
|
- "Sign & Send" signs as the From address above, not as whichever address is
|
||||||
@@ -2279,7 +2289,9 @@ view would leave a wallet one click from deletion.
|
|||||||
- Site origin (bold, scheme and port included) + "wants to send a
|
- Site origin (bold, scheme and port included) + "wants to send a
|
||||||
transaction"
|
transaction"
|
||||||
- Decoded action (if calldata is recognized): action name, token details,
|
- Decoded action (if calldata is recognized): action name, token details,
|
||||||
amounts, steps, deadline (see Transaction Decoding)
|
amounts, steps, deadline, and unless a swap pays only the From address, a
|
||||||
|
`Paid to` line for each other address it pays, or saying that its output
|
||||||
|
stays in the router or who it pays is unknown (see Transaction Decoding)
|
||||||
- From: color dot + full address + etherscan link
|
- From: color dot + full address + etherscan link
|
||||||
- Contract: color dot + full address + etherscan link, token symbol label if
|
- Contract: color dot + full address + etherscan link, token symbol label if
|
||||||
known; for a contract creation, the same sentence as on WaitTx
|
known; for a contract creation, the same sentence as on WaitTx
|
||||||
@@ -2914,7 +2926,34 @@ Currently supported:
|
|||||||
listed as `Execute Sub-Plan (its steps are not shown)`, and whatever the other
|
listed as `Execute Sub-Plan (its steps are not shown)`, and whatever the other
|
||||||
steps state, the summary names no swap direction, `Token In` and `Token Out`
|
steps state, the summary names no swap direction, `Token In` and `Token Out`
|
||||||
read `Unknown (could not be decoded)`, and there is no `Amount` or
|
read `Unknown (could not be decoded)`, and there is no `Amount` or
|
||||||
`Min. received` line.
|
`Min. received` line. Each swap step, `SWEEP`, `WRAP_ETH`, `UNWRAP_WETH` and
|
||||||
|
V4 `TAKE` names the address it pays, and `TAKE_ALL` pays the transaction's
|
||||||
|
sender. The router reads `address(1)` as the transaction's sender, and
|
||||||
|
`address(2)` as the router itself, which holds what it is paid until a later
|
||||||
|
step pays it out; a payment to the router, as `address(2)` or by its own
|
||||||
|
address, is not counted as paid out. When a swap step or `TAKE` pays the
|
||||||
|
router the swap's output token, the output stays in the router unless a later
|
||||||
|
`SWEEP` of that token, or a later `UNWRAP_WETH` when it is WETH, pays it out.
|
||||||
|
A swap step paying an address that the very next step spends, as a V2 exact-in
|
||||||
|
of the same token whose `amountIn` is `ALREADY_PAID` (zero) or
|
||||||
|
`CONTRACT_BALANCE`, is a hop, not a payout: Uniswap's mixed routes pay the
|
||||||
|
next V2 pair directly, and the router enforces that swap's own minimum. Every
|
||||||
|
other payment counts, in whichever step and of whatever token. The minimum
|
||||||
|
reads `Min. received` only when some step pays the transaction's sender (the
|
||||||
|
From address on TxApproval, the sender the explorer reports on
|
||||||
|
TransactionDetail), no step pays any other address, no step that may pay an
|
||||||
|
address went unread, and the output does not stay in the router. Otherwise it
|
||||||
|
reads `Min. paid out`, a `Paid to` line after `Token Out` names each other
|
||||||
|
address paid, one reads
|
||||||
|
`The router, where it stays (no later step pays it out)` when the output stays
|
||||||
|
in the router, and one more reads `Unknown (could not be decoded)` when such a
|
||||||
|
step went unread, or `Unknown (not named in the calldata)` when no step pays
|
||||||
|
anyone. A step goes unread when its recipient does not decode as an address,
|
||||||
|
or when it is a command or V4 action the decoder does not read: every command
|
||||||
|
other than `PERMIT2_PERMIT`, `V2_SWAP_EXACT_IN`, `V2_SWAP_EXACT_OUT`,
|
||||||
|
`V3_SWAP_EXACT_IN`, `V4_SWAP`, `SWEEP`, `WRAP_ETH`, `UNWRAP_WETH` and
|
||||||
|
`BALANCE_CHECK_ERC20` (`V3_SWAP_EXACT_OUT`, `TRANSFER`, `PAY_PORTION` and
|
||||||
|
`EXECUTE_SUB_PLAN` among them), and V4 `TAKE_PORTION`.
|
||||||
|
|
||||||
### Non-Goals Forever
|
### Non-Goals Forever
|
||||||
|
|
||||||
|
|||||||
@@ -664,6 +664,20 @@
|
|||||||
id="confirm-errors"
|
id="confirm-errors"
|
||||||
class="mb-2 border border-border border-dashed p-2 invisible min-h-[1.25rem]"
|
class="mb-2 border border-border border-dashed p-2 invisible min-h-[1.25rem]"
|
||||||
></div>
|
></div>
|
||||||
|
<!-- Its sentence names the token, or why the token's balance
|
||||||
|
is unknown, so show() in confirmTx.js sets it. -->
|
||||||
|
<div
|
||||||
|
id="confirm-balance-error"
|
||||||
|
class="mb-2 border border-border border-dashed p-2 text-xs invisible"
|
||||||
|
></div>
|
||||||
|
<div
|
||||||
|
id="confirm-balance-read-error"
|
||||||
|
class="mb-2 border border-border border-dashed p-2 text-xs invisible"
|
||||||
|
>
|
||||||
|
Your balance could not be read from the network, so this
|
||||||
|
transaction cannot be checked against it. Please go back and
|
||||||
|
try again.
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
id="confirm-amount-fee-error"
|
id="confirm-amount-fee-error"
|
||||||
class="mb-2 border border-border border-dashed p-2 text-xs invisible"
|
class="mb-2 border border-border border-dashed p-2 text-xs invisible"
|
||||||
|
|||||||
@@ -79,10 +79,10 @@ function tokenAmountText(rawAmount, decimals, symbol) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to decode calldata sent to `toAddress` on the network with chain id
|
// Try to decode calldata sent from `fromAddress` to `toAddress` on the network
|
||||||
// `chainId`, using known ABIs.
|
// with chain id `chainId`, using known ABIs.
|
||||||
// Returns { name, description, details } or null.
|
// Returns { name, description, details } or null.
|
||||||
function decodeCalldata(data, toAddress, chainId) {
|
function decodeCalldata(data, toAddress, chainId, fromAddress) {
|
||||||
if (!data || data === "0x" || data.length < 10) return null;
|
if (!data || data === "0x" || data.length < 10) return null;
|
||||||
|
|
||||||
// Where a token's scale is looked for, for every decoder below: the ERC-20
|
// Where a token's scale is looked for, for every decoder below: the ERC-20
|
||||||
@@ -191,6 +191,7 @@ function decodeCalldata(data, toAddress, chainId) {
|
|||||||
toAddress,
|
toAddress,
|
||||||
chainId,
|
chainId,
|
||||||
decimalsSources,
|
decimalsSources,
|
||||||
|
fromAddress,
|
||||||
);
|
);
|
||||||
if (routerResult) return routerResult;
|
if (routerResult) return routerResult;
|
||||||
|
|
||||||
@@ -277,11 +278,12 @@ function showTxApproval(details) {
|
|||||||
|
|
||||||
// If this is an ERC-20 call, try to extract the real recipient and amount.
|
// If this is an ERC-20 call, try to extract the real recipient and amount.
|
||||||
// Decoded for the network the transaction is for, which the Network line
|
// Decoded for the network the transaction is for, which the Network line
|
||||||
// names.
|
// names, and the address the From line names.
|
||||||
const decoded = decodeCalldata(
|
const decoded = decodeCalldata(
|
||||||
approvedTx.data,
|
approvedTx.data,
|
||||||
toAddr || "",
|
toAddr || "",
|
||||||
approvedTx.chainId,
|
approvedTx.chainId,
|
||||||
|
details.approvedFrom,
|
||||||
);
|
);
|
||||||
if (decoded && decoded.details) {
|
if (decoded && decoded.details) {
|
||||||
// The asset the status summary is counted in: an ERC-20 call's Token
|
// The asset the status summary is counted in: an ERC-20 call's Token
|
||||||
|
|||||||
+135
-87
@@ -2,7 +2,13 @@
|
|||||||
// Shows transaction details, warnings, errors. On Sign & Send,
|
// Shows transaction details, warnings, errors. On Sign & Send,
|
||||||
// reads inline password, decrypts secret, signs and broadcasts.
|
// reads inline password, decrypts secret, signs and broadcasts.
|
||||||
|
|
||||||
const { parseEther, parseUnits, formatEther, Contract } = require("ethers");
|
const {
|
||||||
|
parseEther,
|
||||||
|
parseUnits,
|
||||||
|
formatEther,
|
||||||
|
formatUnits,
|
||||||
|
Contract,
|
||||||
|
} = require("ethers");
|
||||||
const {
|
const {
|
||||||
$,
|
$,
|
||||||
showError,
|
showError,
|
||||||
@@ -35,11 +41,12 @@ const {
|
|||||||
const { ERC20_ABI, isBurnAddress } = require("../../shared/constants");
|
const { ERC20_ABI, isBurnAddress } = require("../../shared/constants");
|
||||||
const {
|
const {
|
||||||
displayedDecimals,
|
displayedDecimals,
|
||||||
|
toDecimals,
|
||||||
transferAmountUnits,
|
transferAmountUnits,
|
||||||
} = require("../../shared/transferAmount");
|
} = require("../../shared/transferAmount");
|
||||||
const { assertWithinCeilings } = require("../../shared/approvalVerify");
|
const { assertWithinCeilings } = require("../../shared/approvalVerify");
|
||||||
// The balance lines, the fee reserve and the insufficient-balance messages go
|
// The balance line and the fee reserve go through it, as the approval screen's
|
||||||
// through it, as the approval screen's amounts do.
|
// amounts do.
|
||||||
const { truncateAmountNeverZero } = require("../../shared/amountDisplay");
|
const { truncateAmountNeverZero } = require("../../shared/amountDisplay");
|
||||||
const {
|
const {
|
||||||
CODES,
|
CODES,
|
||||||
@@ -63,6 +70,13 @@ let feeWei = null;
|
|||||||
// amount was derived from. Null for any other send, which ethers prices from
|
// amount was derived from. Null for any other send, which ethers prices from
|
||||||
// the node at signing time.
|
// the node at signing time.
|
||||||
let maxSendFees = null;
|
let maxSendFees = null;
|
||||||
|
// The From address's balances on the network this screen is drawn for, read
|
||||||
|
// from that network's node by readBalances() each time the screen is shown,
|
||||||
|
// so a screen the popup reopens onto states them as they are then, not as
|
||||||
|
// Send knew them. Null until the read returns; then `eth` and `token` are
|
||||||
|
// decimal strings, `token` null for an ETH send or a token whose scale is
|
||||||
|
// unknown, and both null if the read failed.
|
||||||
|
let balances = null;
|
||||||
|
|
||||||
function restore() {
|
function restore() {
|
||||||
const d = state.viewData;
|
const d = state.viewData;
|
||||||
@@ -101,18 +115,48 @@ function renderAmount(txInfo) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The balance line, with its USD value: "Loading..." until readBalances()
|
||||||
|
// returns, then the balance it read.
|
||||||
|
function renderBalance(txInfo) {
|
||||||
|
const isErc20 = txInfo.token !== "ETH";
|
||||||
|
const rawSymbol = isErc20
|
||||||
|
? txInfo.tokenSymbol || "?"
|
||||||
|
: nativeCurrencyByChainId(txInfo.chainId);
|
||||||
|
const symbol = displaySymbol(rawSymbol);
|
||||||
|
if (balances === null) {
|
||||||
|
$("confirm-balance").textContent = "Loading...";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// A null balance is one nobody established, for a token whose scale is
|
||||||
|
// unknown or after a read that failed, and is stated as unknown, never as
|
||||||
|
// zero (https://git.eeqj.de/sneak/AutistMask/issues/349).
|
||||||
|
const bal = isErc20 ? balances.token : balances.eth;
|
||||||
|
if (bal === null) {
|
||||||
|
$("confirm-balance").textContent = "unknown (" + symbol + ")";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const price = getPrice(isErc20 ? rawSymbol : "ETH", txInfo.chainId);
|
||||||
|
const balUsd = price ? parseFloat(bal) * price : null;
|
||||||
|
$("confirm-balance").textContent = valueWithUsd(
|
||||||
|
truncateAmountNeverZero(bal) + " " + symbol,
|
||||||
|
balUsd,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function show(txInfo) {
|
function show(txInfo) {
|
||||||
pendingTx = txInfo;
|
pendingTx = txInfo;
|
||||||
feeStatus = FEE_PENDING;
|
feeStatus = FEE_PENDING;
|
||||||
feeWei = null;
|
feeWei = null;
|
||||||
maxSendFees = null;
|
maxSendFees = null;
|
||||||
|
balances = null;
|
||||||
// The network this screen is drawn for, and the only one it sends on: the
|
// The network this screen is drawn for, and the only one it sends on: the
|
||||||
// one active when Send handed the transaction over. Drawn again from the
|
// one active when Send handed the transaction over. Drawn again from the
|
||||||
// saved transaction, as when the popup reopens onto this screen, it keeps
|
// saved transaction, as when the popup reopens onto this screen, it keeps
|
||||||
// that network, so Sign & Send refuses once Settings has switched to
|
// that network, so Sign & Send refuses once Settings has switched to
|
||||||
// another. Everything this screen shows is that network's: native
|
// another. Everything this screen shows is that network's: native
|
||||||
// currency, USD values, explorer links, and the node and explorer its
|
// currency, USD values, explorer links, the balance, and the node and
|
||||||
// checks ask. The wait, success and error screens label amounts by it.
|
// explorer its checks ask. The wait, success and error screens label
|
||||||
|
// amounts by it.
|
||||||
if (!txInfo.chainId) txInfo.chainId = currentNetwork().chainId;
|
if (!txInfo.chainId) txInfo.chainId = currentNetwork().chainId;
|
||||||
|
|
||||||
const isErc20 = txInfo.token !== "ETH";
|
const isErc20 = txInfo.token !== "ETH";
|
||||||
@@ -165,33 +209,7 @@ function show(txInfo) {
|
|||||||
$("confirm-to-ens").classList.add("hidden");
|
$("confirm-to-ens").classList.add("hidden");
|
||||||
|
|
||||||
renderAmount(txInfo);
|
renderAmount(txInfo);
|
||||||
|
renderBalance(txInfo);
|
||||||
// Balance (with inline USD)
|
|
||||||
const ethPrice = getPrice("ETH", txInfo.chainId);
|
|
||||||
const tokenPrice = getPrice(rawSymbol, txInfo.chainId);
|
|
||||||
if (isErc20) {
|
|
||||||
// null is a balance whose scale nothing knows, not a balance of zero
|
|
||||||
// (https://git.eeqj.de/sneak/AutistMask/issues/349). The send is
|
|
||||||
// refused at encode time for the same missing scale; what this line
|
|
||||||
// must not do is state a quantity nobody established.
|
|
||||||
const bal = txInfo.tokenBalance;
|
|
||||||
const balUsd =
|
|
||||||
tokenPrice && bal != null ? parseFloat(bal) * tokenPrice : null;
|
|
||||||
$("confirm-balance").textContent =
|
|
||||||
bal == null
|
|
||||||
? "unknown (" + symbol + ")"
|
|
||||||
: valueWithUsd(
|
|
||||||
truncateAmountNeverZero(bal) + " " + symbol,
|
|
||||||
balUsd,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
const bal = txInfo.balance || "0";
|
|
||||||
const balUsd = ethPrice ? parseFloat(bal) * ethPrice : null;
|
|
||||||
$("confirm-balance").textContent = valueWithUsd(
|
|
||||||
truncateAmountNeverZero(bal) + " " + symbol,
|
|
||||||
balUsd,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for warnings (synchronous local checks)
|
// Check for warnings (synchronous local checks)
|
||||||
const localWarnings = getLocalWarnings(txInfo.to, {
|
const localWarnings = getLocalWarnings(txInfo.to, {
|
||||||
@@ -257,6 +275,20 @@ function show(txInfo) {
|
|||||||
" cannot be checked against your balance. Please go back and" +
|
" cannot be checked against your balance. Please go back and" +
|
||||||
" try again.";
|
" try again.";
|
||||||
|
|
||||||
|
// So does the message for an amount the balance does not cover. It is
|
||||||
|
// set here, before the first paint, so the balance read returning only
|
||||||
|
// makes it visible and moves nothing, which is why it quotes no balance.
|
||||||
|
// Without the token's scale readBalances() reads no token balance.
|
||||||
|
$("confirm-balance-error").textContent =
|
||||||
|
isErc20 && toDecimals(txInfo.tokenDecimals) === null
|
||||||
|
? "This token's balance is unknown, because nothing this wallet" +
|
||||||
|
" can consult reports how many decimal places it uses, so the" +
|
||||||
|
" amount you are trying to send cannot be checked against it."
|
||||||
|
: "Your " +
|
||||||
|
symbol +
|
||||||
|
" balance does not cover this amount. Please go back and send" +
|
||||||
|
" a smaller amount.";
|
||||||
|
|
||||||
renderValidation(txInfo);
|
renderValidation(txInfo);
|
||||||
|
|
||||||
// Reset password field and error
|
// Reset password field and error
|
||||||
@@ -282,69 +314,78 @@ function show(txInfo) {
|
|||||||
$("confirm-burn-warning").style.visibility = "visible";
|
$("confirm-burn-warning").style.visibility = "visible";
|
||||||
}
|
}
|
||||||
|
|
||||||
estimateGas(txInfo);
|
// The fee is estimated once the balances are read, because a max ETH
|
||||||
|
// send's amount is the ETH balance minus the estimate's reserve.
|
||||||
|
readBalances(txInfo).then(() => estimateGas(txInfo));
|
||||||
checkRecipientHistory(txInfo);
|
checkRecipientHistory(txInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read the From address's balances from the node of the network this
|
||||||
|
// transaction was reviewed for: ETH, and for a token send the token, at the
|
||||||
|
// scale the screen renders the amount with. A token whose scale is unknown has
|
||||||
|
// no balance to read. Never rejects.
|
||||||
|
async function readBalances(txInfo) {
|
||||||
|
let read;
|
||||||
|
try {
|
||||||
|
const provider = reviewedNetworkProvider(txInfo);
|
||||||
|
const decimals = toDecimals(txInfo.tokenDecimals);
|
||||||
|
const readToken = txInfo.token !== "ETH" && decimals !== null;
|
||||||
|
const [ethWei, tokenUnits] = await Promise.all([
|
||||||
|
provider.getBalance(txInfo.from),
|
||||||
|
readToken
|
||||||
|
? new Contract(txInfo.token, ERC20_ABI, provider).balanceOf(
|
||||||
|
txInfo.from,
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
]);
|
||||||
|
read = {
|
||||||
|
eth: formatEther(ethWei),
|
||||||
|
token: readToken ? formatUnits(tokenUnits, decimals) : null,
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
log.errorf("balance read failed:", e.shortMessage || e.message);
|
||||||
|
read = { eth: null, token: null };
|
||||||
|
}
|
||||||
|
// The user may have left this transaction while the read was in flight.
|
||||||
|
if (pendingTx !== txInfo) return;
|
||||||
|
balances = read;
|
||||||
|
renderBalance(txInfo);
|
||||||
|
renderValidation(txInfo);
|
||||||
|
}
|
||||||
|
|
||||||
// Render the balance check for the transaction on screen. Called once during
|
// Render the balance check for the transaction on screen. Called once during
|
||||||
// show() and again when the fee estimate resolves or fails. Every element it
|
// show(), again when the balances are read, and again when the fee estimate
|
||||||
// touches already occupies its space, so re-running it never moves anything.
|
// resolves or fails. Every element it touches already occupies its space, so
|
||||||
|
// re-running it never moves anything.
|
||||||
function renderValidation(txInfo) {
|
function renderValidation(txInfo) {
|
||||||
const isErc20 = txInfo.token !== "ETH";
|
const isErc20 = txInfo.token !== "ETH";
|
||||||
const symbol = isErc20
|
|
||||||
? displaySymbol(txInfo.tokenSymbol || "?")
|
// Null while the balances are being read and after a read that failed.
|
||||||
: nativeCurrencyByChainId(txInfo.chainId);
|
// validateTransfer() takes a missing balance as nothing to spend from, so
|
||||||
|
// sending stays blocked either way, and the only message shown for it is
|
||||||
|
// the one saying the read failed.
|
||||||
|
const ethBalance = balances ? balances.eth : null;
|
||||||
|
const tokenBalance = balances ? balances.token : null;
|
||||||
|
const balanceRead = ethBalance !== null;
|
||||||
|
|
||||||
const { canSend, codes } = validateTransfer({
|
const { canSend, codes } = validateTransfer({
|
||||||
isErc20,
|
isErc20,
|
||||||
amount: txInfo.amount,
|
amount: txInfo.amount,
|
||||||
tokenDecimals: txInfo.tokenDecimals,
|
tokenDecimals: txInfo.tokenDecimals,
|
||||||
ethBalance: txInfo.balance,
|
ethBalance,
|
||||||
tokenBalance: txInfo.tokenBalance,
|
tokenBalance,
|
||||||
feeStatus,
|
feeStatus,
|
||||||
feeWei,
|
feeWei,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Messages carrying the user's own numbers are built here; the fixed
|
// An invalid amount is known before the first paint, so its message is
|
||||||
// sentences live in the reserved elements in index.html, except the
|
// written here. Every message a later result brings has a reserved
|
||||||
// gas and fee-unknown ones, which show() sets.
|
// element, its sentence fixed in index.html or set by show(), and is only
|
||||||
|
// made visible below, so nothing moves when the result arrives.
|
||||||
const messages = [];
|
const messages = [];
|
||||||
if (codes.includes(CODES.AMOUNT_INVALID)) {
|
if (codes.includes(CODES.AMOUNT_INVALID)) {
|
||||||
messages.push("Please enter a valid amount to send.");
|
messages.push("Please enter a valid amount to send.");
|
||||||
}
|
}
|
||||||
if (codes.includes(CODES.INSUFFICIENT_TOKEN)) {
|
|
||||||
messages.push(
|
|
||||||
txInfo.tokenBalance == null
|
|
||||||
? "This token's balance is unknown, because nothing this" +
|
|
||||||
" wallet can consult reports how many decimal places it" +
|
|
||||||
" uses, so the amount you are trying to send cannot be" +
|
|
||||||
" checked against it."
|
|
||||||
: "Insufficient " +
|
|
||||||
symbol +
|
|
||||||
" balance. You have " +
|
|
||||||
truncateAmountNeverZero(txInfo.tokenBalance) +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
" but are trying to send " +
|
|
||||||
txInfo.amount +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
".",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (codes.includes(CODES.INSUFFICIENT_ETH)) {
|
|
||||||
messages.push(
|
|
||||||
"Insufficient balance. You have " +
|
|
||||||
truncateAmountNeverZero(txInfo.balance || "0") +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
" but are trying to send " +
|
|
||||||
txInfo.amount +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
".",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const errorsEl = $("confirm-errors");
|
const errorsEl = $("confirm-errors");
|
||||||
if (messages.length > 0) {
|
if (messages.length > 0) {
|
||||||
@@ -357,13 +398,20 @@ function renderValidation(txInfo) {
|
|||||||
errorsEl.style.visibility = "hidden";
|
errorsEl.style.visibility = "hidden";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setVisible("confirm-balance-read-error", balances !== null && !balanceRead);
|
||||||
|
setVisible(
|
||||||
|
"confirm-balance-error",
|
||||||
|
balanceRead &&
|
||||||
|
(codes.includes(CODES.INSUFFICIENT_TOKEN) ||
|
||||||
|
codes.includes(CODES.INSUFFICIENT_ETH)),
|
||||||
|
);
|
||||||
setVisible(
|
setVisible(
|
||||||
"confirm-amount-fee-error",
|
"confirm-amount-fee-error",
|
||||||
codes.includes(CODES.INSUFFICIENT_ETH_WITH_FEE),
|
balanceRead && codes.includes(CODES.INSUFFICIENT_ETH_WITH_FEE),
|
||||||
);
|
);
|
||||||
setVisible(
|
setVisible(
|
||||||
"confirm-gas-error",
|
"confirm-gas-error",
|
||||||
codes.includes(CODES.INSUFFICIENT_ETH_FOR_FEE),
|
balanceRead && codes.includes(CODES.INSUFFICIENT_ETH_FOR_FEE),
|
||||||
);
|
);
|
||||||
setVisible(
|
setVisible(
|
||||||
"confirm-fee-unknown-error",
|
"confirm-fee-unknown-error",
|
||||||
@@ -472,14 +520,14 @@ async function estimateGas(txInfo) {
|
|||||||
}
|
}
|
||||||
feeStatus = FEE_KNOWN;
|
feeStatus = FEE_KNOWN;
|
||||||
feeWei = gasCostWei;
|
feeWei = gasCostWei;
|
||||||
// A max ETH send is the balance minus this estimate's reserve, not the
|
// A max ETH send is the balance readBalances() read minus this
|
||||||
// Send screen's, and is signed with this estimate's fee fields: fees
|
// estimate's reserve, not the Send screen's, and is signed with this
|
||||||
// fetched again at signing could exceed the reserve it leaves, and the
|
// estimate's fee fields: fees fetched again at signing could exceed
|
||||||
// node would refuse it for want of funds. Where the balance no longer
|
// the reserve it leaves, and the node would refuse it for want of
|
||||||
// covers the fee, the amount is left as it is and the balance check
|
// funds. Where the balance is unknown or no longer covers the fee, the
|
||||||
// below says so.
|
// amount is left as it is and the balance check below says so.
|
||||||
if (txInfo.max && txInfo.token === "ETH") {
|
if (txInfo.max && txInfo.token === "ETH") {
|
||||||
const amount = maxEthAmount(txInfo.balance, gasCostWei);
|
const amount = maxEthAmount(balances?.eth, gasCostWei);
|
||||||
if (amount !== null) {
|
if (amount !== null) {
|
||||||
txInfo.amount = amount;
|
txInfo.amount = amount;
|
||||||
renderAmount(txInfo);
|
renderAmount(txInfo);
|
||||||
@@ -546,8 +594,8 @@ async function populateVerifyAndSend(connectedSigner, tx, fees = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Show a full-sentence send failure in the reserved errors box, the same
|
// Show a full-sentence send failure in the reserved errors box, the same
|
||||||
// element and markup renderValidation() uses for messages carrying the user's
|
// element and markup renderValidation() uses for the invalid-amount message,
|
||||||
// own numbers, so it never moves anything on the screen.
|
// so it never moves anything on the screen.
|
||||||
function showSendError(message) {
|
function showSendError(message) {
|
||||||
const el = $("confirm-errors");
|
const el = $("confirm-errors");
|
||||||
el.innerHTML = `<div class="text-xs">${escapeHtml(message)}</div>`;
|
el.innerHTML = `<div class="text-xs">${escapeHtml(message)}</div>`;
|
||||||
|
|||||||
+9
-16
@@ -164,8 +164,9 @@ function renderSendTokenSelect(addr) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The token balance and scale the Send screen states and hands the
|
// The token balance the Send screen states, and the scale it hands the
|
||||||
// confirmation screen, so the two screens describe the holding the same way.
|
// confirmation screen, which reads the balance itself from the network it is
|
||||||
|
// drawn for.
|
||||||
//
|
//
|
||||||
// The scale is resolved the same way balances.js resolved the scale it
|
// The scale is resolved the same way balances.js resolved the scale it
|
||||||
// DISPLAYED this token's balance at: bundled list, then the user's tracked
|
// DISPLAYED this token's balance at: bundled list, then the user's tracked
|
||||||
@@ -188,13 +189,11 @@ function renderSendTokenSelect(addr) {
|
|||||||
//
|
//
|
||||||
// The two resolutions can therefore differ, and where they do, the stored
|
// The two resolutions can therefore differ, and where they do, the stored
|
||||||
// `balance` is a quantity computed at a scale this screen has just declined to
|
// `balance` is a quantity computed at a scale this screen has just declined to
|
||||||
// stand behind. Stating it would leave validateTransfer() checking the amount
|
// stand behind, so it is withdrawn: unknown scale means unknown balance. It is
|
||||||
// against a number the wallet does not vouch for, so it is withdrawn: unknown
|
// null rather than "0": this screen states it as unknown, as the confirmation
|
||||||
// scale means unknown balance. It is null rather than "0": both screens state
|
// screen does, and Max fills nothing in for it. Only a stored quantity is
|
||||||
// an unknown balance as unknown, and validateTransfer() treats it as no balance
|
// withdrawn: the "0" for a token that has no row at all is an absence of
|
||||||
// to spend from, which is the fail-closed side of an amount nobody can check.
|
// holdings, which is true at every scale.
|
||||||
// Only a stored quantity is withdrawn: the "0" for a token that has no row at
|
|
||||||
// all is an absence of holdings, which is true at every scale.
|
|
||||||
function tokenBalanceAndDecimals(addr, token) {
|
function tokenBalanceAndDecimals(addr, token) {
|
||||||
const tb = (addr.tokenBalances || []).find(
|
const tb = (addr.tokenBalances || []).find(
|
||||||
(t) => t.address.toLowerCase() === token.toLowerCase(),
|
(t) => t.address.toLowerCase() === token.toLowerCase(),
|
||||||
@@ -378,7 +377,6 @@ function init(_ctx) {
|
|||||||
const addr = currentAddress();
|
const addr = currentAddress();
|
||||||
|
|
||||||
let tokenSymbol = null;
|
let tokenSymbol = null;
|
||||||
let tokenBalance = null;
|
|
||||||
let tokenDecimals = null;
|
let tokenDecimals = null;
|
||||||
if (token !== "ETH") {
|
if (token !== "ETH") {
|
||||||
tokenSymbol = resolveSymbol(
|
tokenSymbol = resolveSymbol(
|
||||||
@@ -386,10 +384,7 @@ function init(_ctx) {
|
|||||||
addr.tokenBalances,
|
addr.tokenBalances,
|
||||||
state.trackedTokens,
|
state.trackedTokens,
|
||||||
);
|
);
|
||||||
({ tokenBalance, tokenDecimals } = tokenBalanceAndDecimals(
|
({ tokenDecimals } = tokenBalanceAndDecimals(addr, token));
|
||||||
addr,
|
|
||||||
token,
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The confirmation screen's own amount check, so it is never shown
|
// The confirmation screen's own amount check, so it is never shown
|
||||||
@@ -424,9 +419,7 @@ function init(_ctx) {
|
|||||||
ensName: ensName,
|
ensName: ensName,
|
||||||
amount: amount,
|
amount: amount,
|
||||||
token: token,
|
token: token,
|
||||||
balance: addr.balance,
|
|
||||||
tokenSymbol: tokenSymbol,
|
tokenSymbol: tokenSymbol,
|
||||||
tokenBalance: tokenBalance,
|
|
||||||
tokenDecimals: tokenDecimals,
|
tokenDecimals: tokenDecimals,
|
||||||
max: amountIsMax,
|
max: amountIsMax,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -316,11 +316,13 @@ async function loadFullTxDetails(txHash, chainId) {
|
|||||||
// Decoded against the address the transaction was sent to, as the
|
// Decoded against the address the transaction was sent to, as the
|
||||||
// explorer reports it, not the history entry's `to`: for a token
|
// explorer reports it, not the history entry's `to`: for a token
|
||||||
// transfer that is the transfer's recipient, not the token contract.
|
// transfer that is the transfer's recipient, not the token contract.
|
||||||
// On the active network, the one whose explorer was just asked.
|
// On the active network, the one whose explorer was just asked, and
|
||||||
|
// from the sender it reports.
|
||||||
const decoded = decodeCalldata(
|
const decoded = decodeCalldata(
|
||||||
inputData,
|
inputData,
|
||||||
txData.to?.hash || "",
|
txData.to?.hash || "",
|
||||||
currentNetwork().chainId,
|
currentNetwork().chainId,
|
||||||
|
txData.from?.hash || "",
|
||||||
);
|
);
|
||||||
if (decoded) {
|
if (decoded) {
|
||||||
// Render decoded calldata matching approval view style
|
// Render decoded calldata matching approval view style
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
// encoded with.
|
// encoded with.
|
||||||
//
|
//
|
||||||
// A token amount is a decimal string plus a scale, and the two come from
|
// A token amount is a decimal string plus a scale, and the two come from
|
||||||
// different places. The confirmation screen renders the amount, the balance and
|
// different places. The confirmation screen renders the amount, the symbol and
|
||||||
// the symbol from the block explorer's cached metadata (see
|
// the balance it reads from the node with the block explorer's cached metadata
|
||||||
// fetchTokenBalances() in balances.js); the transfer used to be encoded from
|
// (see fetchTokenBalances() in balances.js); the transfer used to be encoded
|
||||||
// decimals() read off the contract at signing time, and nothing compared the
|
// from decimals() read off the contract at signing time, and nothing compared
|
||||||
// two. A token whose on-chain scale differs from the cached one — an
|
// the two. A token whose on-chain scale differs from the cached one — an
|
||||||
// upgradeable or proxy token, a caller-dependent one, a stale or wrong explorer
|
// upgradeable or proxy token, a caller-dependent one, a stale or wrong explorer
|
||||||
// entry — therefore signed an amount that was never displayed, off by a power
|
// entry — therefore signed an amount that was never displayed, off by a power
|
||||||
// of ten for every decimal place of disagreement.
|
// of ten for every decimal place of disagreement.
|
||||||
|
|||||||
@@ -111,8 +111,8 @@ function isValidAmount(amount, tokenDecimals = null) {
|
|||||||
|
|
||||||
// The most ETH a send can carry: the exact balance minus the fee reserve from
|
// The most ETH a send can carry: the exact balance minus the fee reserve from
|
||||||
// feeReserveWei(), as a decimal string, so validateTransfer() passes it with
|
// feeReserveWei(), as a decimal string, so validateTransfer() passes it with
|
||||||
// exactly that reserve left behind. `ethBalance` is the exact decimal string
|
// exactly that reserve left behind. `ethBalance` is an exact decimal string as
|
||||||
// balances.js stores, never a rounded one. Null when the balance does not
|
// formatEther() writes it, never a rounded one. Null when the balance does not
|
||||||
// leave anything to send once the fee is paid, or when either input is
|
// leave anything to send once the fee is paid, or when either input is
|
||||||
// unusable.
|
// unusable.
|
||||||
function maxEthAmount(ethBalance, feeWei) {
|
function maxEthAmount(ethBalance, feeWei) {
|
||||||
|
|||||||
+231
-34
@@ -101,16 +101,23 @@ function formatAmount(raw, decimals) {
|
|||||||
|
|
||||||
// One wording for either side of the screen: a currency the calldata never
|
// One wording for either side of the screen: a currency the calldata never
|
||||||
// named. It reads as a refusal, the same stance unknownDecimalsAmount() takes
|
// named. It reads as a refusal, the same stance unknownDecimalsAmount() takes
|
||||||
// on a scale — not as a token name, and not as a quantity.
|
// on a scale — not as a token name, and not as a quantity. The Paid to line
|
||||||
|
// uses it too, when no step names anyone paid.
|
||||||
const UNNAMED_CURRENCY = "Unknown (not named in the calldata)";
|
const UNNAMED_CURRENCY = "Unknown (not named in the calldata)";
|
||||||
|
|
||||||
// The same refusal when a V4 swap action could not be read (see
|
// The same refusal when a V4 swap action could not be read (see
|
||||||
// decodeExactly()), or the transaction has an EXECUTE_SUB_PLAN step, whose
|
// decodeExactly()), or the transaction has an EXECUTE_SUB_PLAN step, whose
|
||||||
// commands this decoder does not read. That action names both of its
|
// commands this decoder does not read. That action names both of its
|
||||||
// currencies, and those commands may name one, so saying the calldata did not
|
// currencies, and those commands may name one, so saying the calldata did not
|
||||||
// name it would be false.
|
// name it would be false. The Paid to line uses it too, when a step may pay an
|
||||||
|
// address this decoder did not read.
|
||||||
const UNDECODED_CURRENCY = "Unknown (could not be decoded)";
|
const UNDECODED_CURRENCY = "Unknown (could not be decoded)";
|
||||||
|
|
||||||
|
// The Paid to line when the swap's output is paid to the router and no later
|
||||||
|
// step pays it out of the router.
|
||||||
|
const STAYS_IN_ROUTER =
|
||||||
|
"The router, where it stays (no later step pays it out)";
|
||||||
|
|
||||||
// Explicit presence, never truthiness. Every gate in this file that guards a
|
// Explicit presence, never truthiness. Every gate in this file that guards a
|
||||||
// decoded value goes through here: an address is never falsy once set, but an
|
// decoded value goes through here: an address is never falsy once set, but an
|
||||||
// amount of 0n is, and a gate that cannot tell a genuine zero from an absent
|
// amount of 0n is, and a gate that cannot tell a genuine zero from an absent
|
||||||
@@ -160,6 +167,11 @@ const OPEN_DELTA = Symbol("v4-open-delta");
|
|||||||
// that nothing is swapped.
|
// that nothing is swapped.
|
||||||
const ALREADY_PAID = Symbol("v2-already-paid");
|
const ALREADY_PAID = Symbol("v2-already-paid");
|
||||||
|
|
||||||
|
// The router's whole-balance amount, universal-router
|
||||||
|
// `ActionConstants.CONTRACT_BALANCE`: a V2 exact-in given it as `amountIn`
|
||||||
|
// pays the pair all the router holds of the input token.
|
||||||
|
const CONTRACT_BALANCE = 2n ** 255n;
|
||||||
|
|
||||||
// The amount lines that state a fact instead of a quantity. Same register as
|
// The amount lines that state a fact instead of a quantity. Same register as
|
||||||
// UNNAMED_CURRENCY — a sentence in the value slot, so it cannot be misread as a
|
// UNNAMED_CURRENCY — a sentence in the value slot, so it cannot be misread as a
|
||||||
// number — and deliberately not another phrasing of "not named": these say
|
// number — and deliberately not another phrasing of "not named": these say
|
||||||
@@ -179,6 +191,21 @@ const WETH_ADDRESSES = [
|
|||||||
"0xfff9976782d46cc05630d1f6ebab18b2324d6b14",
|
"0xfff9976782d46cc05630d1f6ebab18b2324d6b14",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Two recipient values the router reads as placeholders, not as addresses:
|
||||||
|
// MSG_SENDER pays the caller of execute(), which is the transaction's sender,
|
||||||
|
// and ADDRESS_THIS pays the router itself, which holds what it is paid until a
|
||||||
|
// later step pays it out. The swap commands, SWEEP, WRAP_ETH and UNWRAP_WETH
|
||||||
|
// map their recipient through the dispatcher's map(), and a V4 TAKE through
|
||||||
|
// V4Router's _mapRecipient(); TAKE_ALL always pays the caller.
|
||||||
|
// - constants: https://github.com/Uniswap/universal-router/blob/cda697da221e24ca143bc4f55023694a2a16796f/contracts/libraries/Constants.sol
|
||||||
|
// - map(), UniversalRouterV1: https://github.com/Uniswap/universal-router/blob/cda697da221e24ca143bc4f55023694a2a16796f/contracts/libraries/Recipient.sol
|
||||||
|
// - map(), UniversalRouterV2: https://github.com/Uniswap/universal-router/blob/3663f6db6e2fe121753cd2d899699c2dc75dca86/contracts/base/Dispatcher.sol
|
||||||
|
// - constants, V4: https://github.com/Uniswap/v4-periphery/blob/444c526b77d804590f0d7bc5a481af5a3277c952/src/libraries/ActionConstants.sol
|
||||||
|
// - _mapRecipient(): https://github.com/Uniswap/v4-periphery/blob/444c526b77d804590f0d7bc5a481af5a3277c952/src/base/BaseActionsRouter.sol
|
||||||
|
// - TAKE, TAKE_ALL and TAKE_PORTION: https://github.com/Uniswap/v4-periphery/blob/444c526b77d804590f0d7bc5a481af5a3277c952/src/V4Router.sol
|
||||||
|
const MSG_SENDER = "0x0000000000000000000000000000000000000001";
|
||||||
|
const ADDRESS_THIS = "0x0000000000000000000000000000000000000002";
|
||||||
|
|
||||||
// `decimals` is null when nothing knows this token's scale. It is not
|
// `decimals` is null when nothing knows this token's scale. It is not
|
||||||
// defaulted to 18: the swap lines land on the same approval screen as the
|
// defaulted to 18: the swap lines land on the same approval screen as the
|
||||||
// ERC-20 line, and a scale guessed there is what showed a 1,000 USDT swap as
|
// ERC-20 line, and a scale guessed there is what showed a 1,000 USDT swap as
|
||||||
@@ -265,6 +292,7 @@ function decodeV2SwapExactIn(input) {
|
|||||||
input,
|
input,
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
|
recipient: d[0],
|
||||||
amountIn: d[1] === 0n ? ALREADY_PAID : d[1],
|
amountIn: d[1] === 0n ? ALREADY_PAID : d[1],
|
||||||
amountOutMin: d[2],
|
amountOutMin: d[2],
|
||||||
tokenIn: d[3][0],
|
tokenIn: d[3][0],
|
||||||
@@ -285,6 +313,7 @@ function decodeV2SwapExactOut(input) {
|
|||||||
input,
|
input,
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
|
recipient: d[0],
|
||||||
amountOut: d[1],
|
amountOut: d[1],
|
||||||
amountInMax: d[2],
|
amountInMax: d[2],
|
||||||
tokenIn: d[3][0],
|
tokenIn: d[3][0],
|
||||||
@@ -316,6 +345,7 @@ function decodeV3SwapExactIn(input) {
|
|||||||
const path = decodeV3Path(d[3]);
|
const path = decodeV3Path(d[3]);
|
||||||
if (!path) return null;
|
if (!path) return null;
|
||||||
return {
|
return {
|
||||||
|
recipient: d[0],
|
||||||
amountIn: d[1],
|
amountIn: d[1],
|
||||||
amountOutMin: d[2],
|
amountOutMin: d[2],
|
||||||
tokenIn: path.tokenIn,
|
tokenIn: path.tokenIn,
|
||||||
@@ -326,12 +356,37 @@ function decodeV3SwapExactIn(input) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode WRAP_ETH (command 0x0b) input bytes.
|
// Decode SWEEP (command 0x04) input bytes. The router pays its whole balance
|
||||||
|
// of `token` to the recipient.
|
||||||
|
// ABI: (address token, address recipient, uint256 amountMin)
|
||||||
|
function decodeSweep(input) {
|
||||||
|
try {
|
||||||
|
const d = coder.decode(["address", "address", "uint256"], input);
|
||||||
|
return { token: d[0], recipient: d[1] };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode WRAP_ETH (command 0x0b) input bytes. The router pays the WETH to the
|
||||||
|
// recipient.
|
||||||
// ABI: (address recipient, uint256 amount)
|
// ABI: (address recipient, uint256 amount)
|
||||||
function decodeWrapEth(input) {
|
function decodeWrapEth(input) {
|
||||||
try {
|
try {
|
||||||
const d = coder.decode(["address", "uint256"], input);
|
const d = coder.decode(["address", "uint256"], input);
|
||||||
return { amount: d[1] };
|
return { recipient: d[0], amount: d[1] };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode UNWRAP_WETH (command 0x0c) input bytes. The router turns its whole
|
||||||
|
// WETH balance into ETH and pays it to the recipient.
|
||||||
|
// ABI: (address recipient, uint256 amountMin)
|
||||||
|
function decodeUnwrapWeth(input) {
|
||||||
|
try {
|
||||||
|
const d = coder.decode(["address", "uint256"], input);
|
||||||
|
return { recipient: d[0] };
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -346,6 +401,7 @@ const V4_SETTLE = 0x0b;
|
|||||||
const V4_SETTLE_ALL = 0x0c;
|
const V4_SETTLE_ALL = 0x0c;
|
||||||
const V4_TAKE = 0x0e;
|
const V4_TAKE = 0x0e;
|
||||||
const V4_TAKE_ALL = 0x0f;
|
const V4_TAKE_ALL = 0x0f;
|
||||||
|
const V4_TAKE_PORTION = 0x10;
|
||||||
|
|
||||||
// A V4 exact-in `amountIn`, read the way V4Router reads it: zero is
|
// A V4 exact-in `amountIn`, read the way V4Router reads it: zero is
|
||||||
// ActionConstants.OPEN_DELTA, not a quantity of zero. See the OPEN_DELTA
|
// ActionConstants.OPEN_DELTA, not a quantity of zero. See the OPEN_DELTA
|
||||||
@@ -500,6 +556,10 @@ function totalAmount(amounts) {
|
|||||||
// these rules leave unknown is set unknown, with no figure. A step with no
|
// these rules leave unknown is set unknown, with no figure. A step with no
|
||||||
// swap action sets only the sides SETTLE, SETTLE_ALL, TAKE and TAKE_ALL
|
// swap action sets only the sides SETTLE, SETTLE_ALL, TAKE and TAKE_ALL
|
||||||
// name.
|
// name.
|
||||||
|
//
|
||||||
|
// `takes` is every TAKE and TAKE_ALL, as the currency it takes and its
|
||||||
|
// recipient as written, MSG_SENDER for a TAKE_ALL. `recipientUnread` is set
|
||||||
|
// when the step has a payout this decoder did not read.
|
||||||
function decodeV4Swap(input) {
|
function decodeV4Swap(input) {
|
||||||
try {
|
try {
|
||||||
const d = coder.decode(["bytes", "bytes[]"], input);
|
const d = coder.decode(["bytes", "bytes[]"], input);
|
||||||
@@ -508,6 +568,8 @@ function decodeV4Swap(input) {
|
|||||||
|
|
||||||
let settleToken = null;
|
let settleToken = null;
|
||||||
let takeToken = null;
|
let takeToken = null;
|
||||||
|
const takes = [];
|
||||||
|
let recipientUnread = false;
|
||||||
// The step's swap actions that could be read, as decodeV4SwapAction()
|
// The step's swap actions that could be read, as decodeV4SwapAction()
|
||||||
// reads them.
|
// reads them.
|
||||||
const swaps = [];
|
const swaps = [];
|
||||||
@@ -537,10 +599,12 @@ function decodeV4Swap(input) {
|
|||||||
params[i],
|
params[i],
|
||||||
);
|
);
|
||||||
takeToken = t[0];
|
takeToken = t[0];
|
||||||
|
takes.push({ currency: t[0], recipient: t[1] });
|
||||||
} else if (actionId === V4_TAKE_ALL) {
|
} else if (actionId === V4_TAKE_ALL) {
|
||||||
// TAKE_ALL: (address currency, uint256 minAmount)
|
// TAKE_ALL: (address currency, uint256 minAmount)
|
||||||
const t = coder.decode(["address", "uint256"], params[i]);
|
const t = coder.decode(["address", "uint256"], params[i]);
|
||||||
takeToken = t[0];
|
takeToken = t[0];
|
||||||
|
takes.push({ currency: t[0], recipient: MSG_SENDER });
|
||||||
} else if (
|
} else if (
|
||||||
actionId === V4_SWAP_EXACT_IN_SINGLE ||
|
actionId === V4_SWAP_EXACT_IN_SINGLE ||
|
||||||
actionId === V4_SWAP_EXACT_IN ||
|
actionId === V4_SWAP_EXACT_IN ||
|
||||||
@@ -552,9 +616,19 @@ function decodeV4Swap(input) {
|
|||||||
} catch {
|
} catch {
|
||||||
swapUndecoded = true;
|
swapUndecoded = true;
|
||||||
}
|
}
|
||||||
|
} else if (actionId === V4_TAKE_PORTION) {
|
||||||
|
// It pays a share of a currency to an address this decoder
|
||||||
|
// does not read
|
||||||
|
// (https://git.eeqj.de/sneak/AutistMask/issues/599).
|
||||||
|
// V4Router reverts on any action not named here.
|
||||||
|
recipientUnread = true;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Skip sub-actions we can't decode
|
// Skip sub-actions we can't decode. A TAKE or TAKE_ALL among
|
||||||
|
// them is a payout this decoder did not read.
|
||||||
|
if (actionId === V4_TAKE || actionId === V4_TAKE_ALL) {
|
||||||
|
recipientUnread = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -565,6 +639,8 @@ function decodeV4Swap(input) {
|
|||||||
tokenOut: takeToken,
|
tokenOut: takeToken,
|
||||||
amountIn: null,
|
amountIn: null,
|
||||||
amountOutMin: null,
|
amountOutMin: null,
|
||||||
|
takes,
|
||||||
|
recipientUnread,
|
||||||
swapUndecoded,
|
swapUndecoded,
|
||||||
hasSwapAction: true,
|
hasSwapAction: true,
|
||||||
};
|
};
|
||||||
@@ -604,6 +680,8 @@ function decodeV4Swap(input) {
|
|||||||
tokenOut,
|
tokenOut,
|
||||||
amountIn,
|
amountIn,
|
||||||
amountOutMin,
|
amountOutMin,
|
||||||
|
takes,
|
||||||
|
recipientUnread,
|
||||||
swapUndecoded,
|
swapUndecoded,
|
||||||
hasSwapAction: swaps.length > 0,
|
hasSwapAction: swaps.length > 0,
|
||||||
};
|
};
|
||||||
@@ -612,14 +690,14 @@ function decodeV4Swap(input) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to decode a Universal Router execute() call sent to `toAddress` on the
|
// Try to decode a Universal Router execute() call sent from `fromAddress`, the
|
||||||
// network with chain id `chainId`.
|
// user, to `toAddress` on the network with chain id `chainId`.
|
||||||
// Returns { name, description, details } matching the format used by
|
// Returns { name, description, details } matching the format used by
|
||||||
// the approval UI, or null if the calldata is not a recognised execute() or
|
// the approval UI, or null if the calldata is not a recognised execute() or
|
||||||
// `toAddress` is not a Universal Router on that network: the same calldata
|
// `toAddress` is not a Universal Router on that network: the same calldata
|
||||||
// sent to any other contract is not a swap through the router, whatever that
|
// sent to any other contract is not a swap through the router, whatever that
|
||||||
// contract does with it.
|
// contract does with it.
|
||||||
function decode(data, toAddress, chainId, sources) {
|
function decode(data, toAddress, chainId, sources, fromAddress) {
|
||||||
const commandTypeMask = routerCommandTypeMask(toAddress, chainId);
|
const commandTypeMask = routerCommandTypeMask(toAddress, chainId);
|
||||||
if (commandTypeMask === null) return null;
|
if (commandTypeMask === null) return null;
|
||||||
try {
|
try {
|
||||||
@@ -678,6 +756,57 @@ function decode(data, toAddress, chainId, sources) {
|
|||||||
outputEstablished = true;
|
outputEstablished = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Who the steps pay, in whichever step and of whatever token.
|
||||||
|
// MSG_SENDER is the sender. The router itself, as ADDRESS_THIS or by
|
||||||
|
// its own address, holds what it is paid until a later step pays it
|
||||||
|
// out.
|
||||||
|
const sender = (fromAddress || "").toLowerCase();
|
||||||
|
let paidToSender = false;
|
||||||
|
// Each other address paid, once.
|
||||||
|
const paidElsewhere = [];
|
||||||
|
// Set when a step may pay an address this decoder did not read.
|
||||||
|
let payeeUnread = false;
|
||||||
|
// The tokens, lowercased, that a swap step or a V4 TAKE paid to the
|
||||||
|
// router and no later SWEEP of that token, or UNWRAP_WETH of WETH,
|
||||||
|
// paid out.
|
||||||
|
const heldByRouter = new Set();
|
||||||
|
const isRouter = (recipient) => {
|
||||||
|
const r = recipient.toLowerCase();
|
||||||
|
return r === ADDRESS_THIS || r === toAddress.toLowerCase();
|
||||||
|
};
|
||||||
|
// A step pays `recipient`. `output` is the token a swap step or a V4
|
||||||
|
// TAKE pays; other steps pass none.
|
||||||
|
const addPayee = (recipient, output) => {
|
||||||
|
const r = recipient.toLowerCase();
|
||||||
|
if (isRouter(recipient)) {
|
||||||
|
if (present(output)) heldByRouter.add(output.toLowerCase());
|
||||||
|
} else if (r === MSG_SENDER || r === sender) {
|
||||||
|
paidToSender = true;
|
||||||
|
} else if (!paidElsewhere.some((a) => a.toLowerCase() === r)) {
|
||||||
|
paidElsewhere.push(recipient);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// A swap step that pays `token` to an address the very next step
|
||||||
|
// spends, as a V2 exact-in of that token whose input is already paid,
|
||||||
|
// is a hop, not a payout: Uniswap's mixed routes pay the next V2 pair
|
||||||
|
// directly, and the router enforces that next swap's own minimum. Its
|
||||||
|
// input is already paid when its amountIn is ALREADY_PAID, or
|
||||||
|
// CONTRACT_BALANCE, which Uniswap's routes send and with which the
|
||||||
|
// router adds only what it holds.
|
||||||
|
const isHop = (i, token) => {
|
||||||
|
if (i + 1 >= commandsBytes.length) return false;
|
||||||
|
if ((commandsBytes[i + 1] & commandTypeMask) !== 0x08) return false;
|
||||||
|
const next = decodeV2SwapExactIn(inputs[i + 1]);
|
||||||
|
return (
|
||||||
|
next !== null &&
|
||||||
|
(next.amountIn === ALREADY_PAID ||
|
||||||
|
next.amountIn === CONTRACT_BALANCE) &&
|
||||||
|
present(token) &&
|
||||||
|
present(next.tokenIn) &&
|
||||||
|
next.tokenIn.toLowerCase() === token.toLowerCase()
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
for (let i = 0; i < commandsBytes.length; i++) {
|
for (let i = 0; i < commandsBytes.length; i++) {
|
||||||
const cmdId = commandsBytes[i] & commandTypeMask;
|
const cmdId = commandsBytes[i] & commandTypeMask;
|
||||||
commandNames.push(
|
commandNames.push(
|
||||||
@@ -690,30 +819,27 @@ function decode(data, toAddress, chainId, sources) {
|
|||||||
// EXECUTE_SUB_PLAN runs a further list of commands held in
|
// EXECUTE_SUB_PLAN runs a further list of commands held in
|
||||||
// its input, which this decoder does not read. The step
|
// its input, which this decoder does not read. The step
|
||||||
// says so, and after this loop neither side is named.
|
// says so, and after this loop neither side is named.
|
||||||
|
// Those commands may pay any address.
|
||||||
hasSubPlan = true;
|
hasSubPlan = true;
|
||||||
commandNames[i] += " (its steps are not shown)";
|
commandNames[i] += " (its steps are not shown)";
|
||||||
}
|
payeeUnread = true;
|
||||||
|
} else if (cmdId === 0x0a) {
|
||||||
if (cmdId === 0x0a) {
|
|
||||||
const p = decodePermit2(inputs[i]);
|
const p = decodePermit2(inputs[i]);
|
||||||
// A permit states both halves itself, so it may replace an
|
// A permit states both halves itself, so it may replace an
|
||||||
// input side an earlier hop established without breaking
|
// input side an earlier hop established without breaking
|
||||||
// the invariant.
|
// the invariant.
|
||||||
if (p) setInput(p.token, p.amount);
|
if (p) setInput(p.token, p.amount);
|
||||||
}
|
} else if (cmdId === 0x0e) {
|
||||||
|
|
||||||
if (cmdId === 0x0e) {
|
|
||||||
const b = decodeBalanceCheck(inputs[i]);
|
const b = decodeBalanceCheck(inputs[i]);
|
||||||
// The router passes this check whenever the owner holds at
|
// The router passes this check whenever the owner holds at
|
||||||
// least minBalance, so a zero one guarantees nothing and
|
// least minBalance, so a zero one guarantees nothing and
|
||||||
// does not replace a minimum an earlier step stated. Any
|
// does not replace a minimum an earlier step stated. Any
|
||||||
// other minBalance sets the output side as a swap does.
|
// other minBalance sets the output side as a swap does.
|
||||||
|
// It pays nobody.
|
||||||
if (b && !(b.minBalance === 0n && present(minOutput))) {
|
if (b && !(b.minBalance === 0n && present(minOutput))) {
|
||||||
setOutput(b.token, b.minBalance);
|
setOutput(b.token, b.minBalance);
|
||||||
}
|
}
|
||||||
}
|
} else if (cmdId === 0x00) {
|
||||||
|
|
||||||
if (cmdId === 0x00) {
|
|
||||||
const s = decodeV3SwapExactIn(inputs[i]);
|
const s = decodeV3SwapExactIn(inputs[i]);
|
||||||
if (s) {
|
if (s) {
|
||||||
setInputOnce(s.tokenIn, s.amountIn);
|
setInputOnce(s.tokenIn, s.amountIn);
|
||||||
@@ -721,39 +847,69 @@ function decode(data, toAddress, chainId, sources) {
|
|||||||
// the last swap step determines the final output token
|
// the last swap step determines the final output token
|
||||||
// and minimum received amount.
|
// and minimum received amount.
|
||||||
setOutput(s.tokenOut, s.amountOutMin);
|
setOutput(s.tokenOut, s.amountOutMin);
|
||||||
|
if (!isHop(i, s.tokenOut)) {
|
||||||
|
addPayee(s.recipient, s.tokenOut);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
payeeUnread = true;
|
||||||
}
|
}
|
||||||
}
|
} else if (cmdId === 0x08) {
|
||||||
|
|
||||||
if (cmdId === 0x08) {
|
|
||||||
const s = decodeV2SwapExactIn(inputs[i]);
|
const s = decodeV2SwapExactIn(inputs[i]);
|
||||||
if (s) {
|
if (s) {
|
||||||
setInputOnce(s.tokenIn, s.amountIn);
|
setInputOnce(s.tokenIn, s.amountIn);
|
||||||
setOutput(s.tokenOut, s.amountOutMin);
|
setOutput(s.tokenOut, s.amountOutMin);
|
||||||
|
if (!isHop(i, s.tokenOut)) {
|
||||||
|
addPayee(s.recipient, s.tokenOut);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
payeeUnread = true;
|
||||||
}
|
}
|
||||||
}
|
} else if (cmdId === 0x09) {
|
||||||
|
|
||||||
if (cmdId === 0x09) {
|
|
||||||
// Buys exactly amountOut and spends at most amountInMax.
|
// Buys exactly amountOut and spends at most amountInMax.
|
||||||
hasV2ExactOut = true;
|
hasV2ExactOut = true;
|
||||||
const s = decodeV2SwapExactOut(inputs[i]);
|
const s = decodeV2SwapExactOut(inputs[i]);
|
||||||
if (s) {
|
if (s) {
|
||||||
setInputOnce(s.tokenIn, s.amountInMax);
|
setInputOnce(s.tokenIn, s.amountInMax);
|
||||||
setOutput(s.tokenOut, s.amountOut);
|
setOutput(s.tokenOut, s.amountOut);
|
||||||
|
if (!isHop(i, s.tokenOut)) {
|
||||||
|
addPayee(s.recipient, s.tokenOut);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
payeeUnread = true;
|
||||||
}
|
}
|
||||||
}
|
} else if (cmdId === 0x04) {
|
||||||
|
const s = decodeSweep(inputs[i]);
|
||||||
if (cmdId === 0x0b) {
|
if (s) {
|
||||||
|
addPayee(s.recipient);
|
||||||
|
if (!isRouter(s.recipient)) {
|
||||||
|
heldByRouter.delete(s.token.toLowerCase());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
payeeUnread = true;
|
||||||
|
}
|
||||||
|
} else if (cmdId === 0x0b) {
|
||||||
const w = decodeWrapEth(inputs[i]);
|
const w = decodeWrapEth(inputs[i]);
|
||||||
if (w) {
|
if (w) {
|
||||||
setInputOnce(
|
setInputOnce(
|
||||||
"0x0000000000000000000000000000000000000000",
|
"0x0000000000000000000000000000000000000000",
|
||||||
w.amount,
|
w.amount,
|
||||||
);
|
);
|
||||||
|
addPayee(w.recipient);
|
||||||
|
} else {
|
||||||
|
payeeUnread = true;
|
||||||
}
|
}
|
||||||
}
|
} else if (cmdId === 0x10) {
|
||||||
|
|
||||||
if (cmdId === 0x10) {
|
|
||||||
const v4 = decodeV4Swap(inputs[i]);
|
const v4 = decodeV4Swap(inputs[i]);
|
||||||
|
if (v4) {
|
||||||
|
for (const t of v4.takes) {
|
||||||
|
if (!isHop(i, t.currency)) {
|
||||||
|
addPayee(t.recipient, t.currency);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!v4 || v4.recipientUnread) {
|
||||||
|
payeeUnread = true;
|
||||||
|
}
|
||||||
if (v4 && v4.swapUndecoded) {
|
if (v4 && v4.swapUndecoded) {
|
||||||
// A swap action of this step went unread, so the step
|
// A swap action of this step went unread, so the step
|
||||||
// is marked.
|
// is marked.
|
||||||
@@ -784,13 +940,29 @@ function decode(data, toAddress, chainId, sources) {
|
|||||||
setInputOnce(v4.tokenIn, v4.amountIn);
|
setInputOnce(v4.tokenIn, v4.amountIn);
|
||||||
setOutput(v4.tokenOut, v4.amountOutMin);
|
setOutput(v4.tokenOut, v4.amountOutMin);
|
||||||
}
|
}
|
||||||
}
|
} else if (cmdId === 0x0c) {
|
||||||
|
|
||||||
if (cmdId === 0x0c) {
|
|
||||||
hasUnwrapWeth = true;
|
hasUnwrapWeth = true;
|
||||||
|
const u = decodeUnwrapWeth(inputs[i]);
|
||||||
|
if (u) {
|
||||||
|
addPayee(u.recipient);
|
||||||
|
if (!isRouter(u.recipient)) {
|
||||||
|
WETH_ADDRESSES.forEach((w) =>
|
||||||
|
heldByRouter.delete(w),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
payeeUnread = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Any other command may pay an address this decoder does
|
||||||
|
// not read: V3_SWAP_EXACT_OUT does, and so do TRANSFER,
|
||||||
|
// PAY_PORTION and the others
|
||||||
|
// https://git.eeqj.de/sneak/AutistMask/issues/599 lists.
|
||||||
|
payeeUnread = true;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Skip commands we can't decode
|
// Skip commands we can't decode. One may pay any address.
|
||||||
|
payeeUnread = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -936,6 +1108,31 @@ function decode(data, toAddress, chainId, sources) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The output is received by the sender only when some step pays the
|
||||||
|
// sender, none pays another address, none may pay an address this
|
||||||
|
// decoder did not read, and the output token is not left in the
|
||||||
|
// router. Otherwise each other address paid is named, and further
|
||||||
|
// lines say when the output stays in the router, a payout could not
|
||||||
|
// be read, or no step names anyone paid.
|
||||||
|
const outputHeld =
|
||||||
|
present(outputToken) && heldByRouter.has(outputToken.toLowerCase());
|
||||||
|
const received =
|
||||||
|
paidToSender &&
|
||||||
|
paidElsewhere.length === 0 &&
|
||||||
|
!payeeUnread &&
|
||||||
|
!outputHeld;
|
||||||
|
for (const address of paidElsewhere) {
|
||||||
|
details.push({ label: "Paid to", value: address, address });
|
||||||
|
}
|
||||||
|
if (outputHeld) {
|
||||||
|
details.push({ label: "Paid to", value: STAYS_IN_ROUTER });
|
||||||
|
}
|
||||||
|
if (payeeUnread) {
|
||||||
|
details.push({ label: "Paid to", value: UNDECODED_CURRENCY });
|
||||||
|
} else if (!paidToSender && paidElsewhere.length === 0 && !outputHeld) {
|
||||||
|
details.push({ label: "Paid to", value: UNNAMED_CURRENCY });
|
||||||
|
}
|
||||||
|
|
||||||
if (present(minOutput)) {
|
if (present(minOutput)) {
|
||||||
// A zero floor is the one case the user most needs stated: the
|
// A zero floor is the one case the user most needs stated: the
|
||||||
// swap guarantees nothing back. It is said in words, in the same
|
// swap guarantees nothing back. It is said in words, in the same
|
||||||
@@ -944,7 +1141,7 @@ function decode(data, toAddress, chainId, sources) {
|
|||||||
// return nothing" — and because it is true at every scale, so it
|
// return nothing" — and because it is true at every scale, so it
|
||||||
// holds even when the output token's decimals are unknown.
|
// holds even when the output token's decimals are unknown.
|
||||||
details.push({
|
details.push({
|
||||||
label: "Min. received",
|
label: received ? "Min. received" : "Min. paid out",
|
||||||
value:
|
value:
|
||||||
minOutput === 0n
|
minOutput === 0n
|
||||||
? NO_MINIMUM
|
? NO_MINIMUM
|
||||||
|
|||||||
@@ -291,7 +291,6 @@ async function confirmSend(from, selected) {
|
|||||||
to: RECIPIENT,
|
to: RECIPIENT,
|
||||||
amount: "0.5",
|
amount: "0.5",
|
||||||
token: "ETH",
|
token: "ETH",
|
||||||
balance: "1.0",
|
|
||||||
});
|
});
|
||||||
await settle();
|
await settle();
|
||||||
node("confirm-tx-password").value = PASSWORD;
|
node("confirm-tx-password").value = PASSWORD;
|
||||||
|
|||||||
@@ -68,10 +68,13 @@ function swapData(amountIn, amountOutMin) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function swapDetail(amountIn, amountOutMin, label) {
|
function swapDetail(amountIn, amountOutMin, label) {
|
||||||
|
// Sent by the address the swap pays, so the output is the user's.
|
||||||
const decoded = uniswap.decode(
|
const decoded = uniswap.decode(
|
||||||
swapData(amountIn, amountOutMin),
|
swapData(amountIn, amountOutMin),
|
||||||
ROUTER,
|
ROUTER,
|
||||||
"0x1",
|
"0x1",
|
||||||
|
{},
|
||||||
|
RECIPIENT,
|
||||||
);
|
);
|
||||||
return decoded.details.find((d) => d.label === label);
|
return decoded.details.find((d) => d.label === label);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,20 +15,37 @@
|
|||||||
// reviewed for, because choosing that network again in Settings and pressing
|
// reviewed for, because choosing that network again in Settings and pressing
|
||||||
// Back only unhides it, and Sign & Send then sends from it.
|
// Back only unhides it, and Sign & Send then sends from it.
|
||||||
//
|
//
|
||||||
|
// Its balance line and balance check are that network's balance, read from
|
||||||
|
// that network's node each time the screen is drawn
|
||||||
|
// (https://git.eeqj.de/sneak/AutistMask/issues/558), not the balance Send
|
||||||
|
// handed over. The fee estimate after the read stays on that network when
|
||||||
|
// the network is switched while the read runs.
|
||||||
|
//
|
||||||
// Driven through the real confirmation screen, signer and chain switch, with
|
// Driven through the real confirmation screen, signer and chain switch, with
|
||||||
// only the node, fetch and the DOM stubbed. The stub node is on the network
|
// only the node, fetch and the DOM stubbed. The stub node is on the network
|
||||||
// its provider was built for, so a broadcast records the network it went to.
|
// its provider was built for, so a broadcast records the network it went to,
|
||||||
|
// and a balance read answers with that network's balance.
|
||||||
|
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
// The questions the stub node was asked for the fee and the recipient checks,
|
// The questions the stub node was asked for the balance, the fee and the
|
||||||
// by method, network name and RPC URL, in order. The signed transactions it
|
// recipient checks, by method, network name and RPC URL, in order. The
|
||||||
// was handed, with its network's chain id and RPC URL. And whether it quotes
|
// balances it reports on each network, by network name: ETH in wei and the
|
||||||
// fees as a network with no type-2 pricing does.
|
// token in its base units. The signed transactions it was handed, with its
|
||||||
const mockNode = { asked: [], broadcast: [], legacyFees: false };
|
// network's chain id and RPC URL. And whether it quotes fees as a network
|
||||||
|
// with no type-2 pricing does.
|
||||||
|
const mockNode = {
|
||||||
|
asked: [],
|
||||||
|
balanceWei: {},
|
||||||
|
tokenUnits: {},
|
||||||
|
broadcast: [],
|
||||||
|
legacyFees: false,
|
||||||
|
};
|
||||||
|
|
||||||
jest.mock("ethers", () => {
|
jest.mock("ethers", () => {
|
||||||
const actual = jest.requireActual("ethers");
|
const actual = jest.requireActual("ethers");
|
||||||
|
// The selector of balanceOf(address).
|
||||||
|
const BALANCE_OF = "0x70a08231";
|
||||||
class StubProvider {
|
class StubProvider {
|
||||||
constructor(url, network) {
|
constructor(url, network) {
|
||||||
this.url = url;
|
this.url = url;
|
||||||
@@ -44,6 +61,22 @@ jest.mock("ethers", () => {
|
|||||||
async getNetwork() {
|
async getNetwork() {
|
||||||
return this.network;
|
return this.network;
|
||||||
}
|
}
|
||||||
|
async getBalance() {
|
||||||
|
this.record("getBalance");
|
||||||
|
return mockNode.balanceWei[this.network.name];
|
||||||
|
}
|
||||||
|
// balanceOf() is the one contract call the screen makes before Sign
|
||||||
|
// & Send.
|
||||||
|
async call(tx) {
|
||||||
|
if (!tx.data.startsWith(BALANCE_OF)) {
|
||||||
|
throw new Error("the stub node answers only balanceOf()");
|
||||||
|
}
|
||||||
|
this.record("balanceOf");
|
||||||
|
return actual.AbiCoder.defaultAbiCoder().encode(
|
||||||
|
["uint256"],
|
||||||
|
[mockNode.tokenUnits[this.network.name]],
|
||||||
|
);
|
||||||
|
}
|
||||||
async getFeeData() {
|
async getFeeData() {
|
||||||
this.record("getFeeData");
|
this.record("getFeeData");
|
||||||
if (mockNode.legacyFees) {
|
if (mockNode.legacyFees) {
|
||||||
@@ -158,7 +191,13 @@ global.document = {
|
|||||||
};
|
};
|
||||||
global.navigator = { clipboard: { writeText() {} } };
|
global.navigator = { clipboard: { writeText() {} } };
|
||||||
|
|
||||||
const { BaseWallet, Transaction, Wallet } = require("ethers");
|
const {
|
||||||
|
BaseWallet,
|
||||||
|
JsonRpcProvider,
|
||||||
|
Transaction,
|
||||||
|
Wallet,
|
||||||
|
parseEther,
|
||||||
|
} = require("ethers");
|
||||||
const { encryptWithPassword } = require("../src/shared/vault");
|
const { encryptWithPassword } = require("../src/shared/vault");
|
||||||
const { state, loadState, saveState } = require("../src/shared/state");
|
const { state, loadState, saveState } = require("../src/shared/state");
|
||||||
const { onChainSwitch } = require("../src/shared/chainSwitch");
|
const { onChainSwitch } = require("../src/shared/chainSwitch");
|
||||||
@@ -198,6 +237,11 @@ beforeAll(async () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
elements.clear();
|
elements.clear();
|
||||||
mockNode.asked = [];
|
mockNode.asked = [];
|
||||||
|
mockNode.balanceWei = {
|
||||||
|
mainnet: parseEther("5"),
|
||||||
|
sepolia: parseEther("5"),
|
||||||
|
};
|
||||||
|
mockNode.tokenUnits = { mainnet: 0n, sepolia: 0n };
|
||||||
mockNode.broadcast = [];
|
mockNode.broadcast = [];
|
||||||
mockNode.legacyFees = false;
|
mockNode.legacyFees = false;
|
||||||
global.fetch.mockClear();
|
global.fetch.mockClear();
|
||||||
@@ -212,7 +256,7 @@ afterEach(() => {
|
|||||||
|
|
||||||
// Show the confirmation screen for 1 of the native token on `networkId`, or
|
// Show the confirmation screen for 1 of the native token on `networkId`, or
|
||||||
// for the transfer `changes` makes of it, as Review on the Send screen does,
|
// for the transfer `changes` makes of it, as Review on the Send screen does,
|
||||||
// with its fee estimate settled.
|
// with its balance read and its fee estimate settled.
|
||||||
async function review(networkId, changes = {}) {
|
async function review(networkId, changes = {}) {
|
||||||
await onChainSwitch(networkId);
|
await onChainSwitch(networkId);
|
||||||
await reviewOnActiveNetwork(changes);
|
await reviewOnActiveNetwork(changes);
|
||||||
@@ -225,7 +269,7 @@ async function reviewOnActiveNetwork(changes = {}) {
|
|||||||
type: "key",
|
type: "key",
|
||||||
name: "Wallet 1",
|
name: "Wallet 1",
|
||||||
encryptedSecret,
|
encryptedSecret,
|
||||||
addresses: [{ address: HOLDER, balance: "5.0" }],
|
addresses: [{ address: HOLDER }],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
state.selectedWallet = 0;
|
state.selectedWallet = 0;
|
||||||
@@ -237,9 +281,7 @@ async function reviewOnActiveNetwork(changes = {}) {
|
|||||||
ensName: null,
|
ensName: null,
|
||||||
amount: "1",
|
amount: "1",
|
||||||
token: "ETH",
|
token: "ETH",
|
||||||
balance: "5.0",
|
|
||||||
tokenSymbol: null,
|
tokenSymbol: null,
|
||||||
tokenBalance: null,
|
|
||||||
tokenDecimals: null,
|
tokenDecimals: null,
|
||||||
max: false,
|
max: false,
|
||||||
...changes,
|
...changes,
|
||||||
@@ -323,12 +365,24 @@ function expectNativeTransferOn(networkId) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// show() estimates the fee and checks the recipient without awaiting either;
|
// show() reads the balance and then estimates the fee, and checks the
|
||||||
// this lets both finish.
|
// recipient, without awaiting any of them; this lets all of them finish.
|
||||||
async function settle() {
|
async function settle() {
|
||||||
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
|
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function errors() {
|
||||||
|
return el("confirm-errors").innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
function shown(id) {
|
||||||
|
return el(id).style.visibility === "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendDisabled() {
|
||||||
|
return el("btn-confirm-send").disabled;
|
||||||
|
}
|
||||||
|
|
||||||
async function signAndSend() {
|
async function signAndSend() {
|
||||||
el("confirm-tx-password").value = PASSWORD;
|
el("confirm-tx-password").value = PASSWORD;
|
||||||
await el("btn-confirm-send").handlers.get("click")();
|
await el("btn-confirm-send").handlers.get("click")();
|
||||||
@@ -359,9 +413,10 @@ test("a transfer reviewed after the active network's RPC endpoint was changed in
|
|||||||
await reviewOnActiveNetwork();
|
await reviewOnActiveNetwork();
|
||||||
|
|
||||||
expect(mockNode.asked).toEqual([
|
expect(mockNode.asked).toEqual([
|
||||||
{ method: "getFeeData", network: "sepolia", url: newNode },
|
{ method: "getBalance", network: "sepolia", url: newNode },
|
||||||
{ method: "getCode", network: "sepolia", url: newNode },
|
{ method: "getCode", network: "sepolia", url: newNode },
|
||||||
{ method: "getTransactionCount", network: "sepolia", url: newNode },
|
{ method: "getTransactionCount", network: "sepolia", url: newNode },
|
||||||
|
{ method: "getFeeData", network: "sepolia", url: newNode },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -411,7 +466,7 @@ describe.each([
|
|||||||
expectNativeTransferOn(reviewedOn);
|
expectNativeTransferOn(reviewedOn);
|
||||||
expect(mockNode.asked).toEqual([
|
expect(mockNode.asked).toEqual([
|
||||||
{
|
{
|
||||||
method: "getFeeData",
|
method: "getBalance",
|
||||||
network: reviewedOn,
|
network: reviewedOn,
|
||||||
url: ownNode(reviewedOn),
|
url: ownNode(reviewedOn),
|
||||||
},
|
},
|
||||||
@@ -425,6 +480,11 @@ describe.each([
|
|||||||
network: reviewedOn,
|
network: reviewedOn,
|
||||||
url: ownNode(reviewedOn),
|
url: ownNode(reviewedOn),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
method: "getFeeData",
|
||||||
|
network: reviewedOn,
|
||||||
|
url: ownNode(reviewedOn),
|
||||||
|
},
|
||||||
]);
|
]);
|
||||||
expect(global.fetch.mock.calls.map(([url]) => url)).toEqual([
|
expect(global.fetch.mock.calls.map(([url]) => url)).toEqual([
|
||||||
explorerUrl + "/address/" + RECIPIENT,
|
explorerUrl + "/address/" + RECIPIENT,
|
||||||
@@ -472,12 +532,106 @@ describe.each([
|
|||||||
await review(reviewedOn, { amount: "10" });
|
await review(reviewedOn, { amount: "10" });
|
||||||
await switchReopenAndGoBack(reviewedOn, switchedTo);
|
await switchReopenAndGoBack(reviewedOn, switchedTo);
|
||||||
|
|
||||||
expect(el("confirm-errors").innerHTML).toContain(
|
expect(shown("confirm-balance-error")).toBe(true);
|
||||||
"Insufficient balance. You have 5.0000 " +
|
expect(el("confirm-balance-error").textContent).toBe(
|
||||||
|
"Your " +
|
||||||
symbol +
|
symbol +
|
||||||
" but are trying to send 10 " +
|
" balance does not cover this amount. Please go back and" +
|
||||||
symbol +
|
" send a smaller amount.",
|
||||||
".",
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("states and checks that network's balance as it is then, which no longer covers the send", async () => {
|
||||||
|
await review(reviewedOn);
|
||||||
|
expect(sendDisabled()).toBe(false);
|
||||||
|
mockNode.balanceWei = {
|
||||||
|
[reviewedOn]: parseEther("0.5"),
|
||||||
|
[switchedTo]: parseEther("5"),
|
||||||
|
};
|
||||||
|
await switchReopenAndGoBack(reviewedOn, switchedTo);
|
||||||
|
|
||||||
|
expect(el("confirm-balance").textContent).toBe(
|
||||||
|
"0.5000 " + symbol + usdOn(reviewedOn, "$1,000.00"),
|
||||||
|
);
|
||||||
|
expect(shown("confirm-balance-error")).toBe(true);
|
||||||
|
expect(sendDisabled()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("states and checks that network's balance as it is then, which now covers the send, and refuses to send it", async () => {
|
||||||
|
mockNode.balanceWei[reviewedOn] = parseEther("0.5");
|
||||||
|
await review(reviewedOn);
|
||||||
|
expect(sendDisabled()).toBe(true);
|
||||||
|
mockNode.balanceWei = {
|
||||||
|
[reviewedOn]: parseEther("5"),
|
||||||
|
[switchedTo]: parseEther("0.5"),
|
||||||
|
};
|
||||||
|
await switchReopenAndGoBack(reviewedOn, switchedTo);
|
||||||
|
|
||||||
|
expect(el("confirm-balance").textContent).toBe(
|
||||||
|
"5.0000 " + symbol + usdOn(reviewedOn, "$10,000.00"),
|
||||||
|
);
|
||||||
|
expect(errors()).toBe("");
|
||||||
|
expect(shown("confirm-balance-error")).toBe(false);
|
||||||
|
expect(shown("confirm-amount-fee-error")).toBe(false);
|
||||||
|
expect(sendDisabled()).toBe(false);
|
||||||
|
|
||||||
|
await signAndSend();
|
||||||
|
|
||||||
|
expect(signTransaction).not.toHaveBeenCalled();
|
||||||
|
expect(mockNode.broadcast).toEqual([]);
|
||||||
|
expect(errors()).toContain(
|
||||||
|
"The active network changed after this transaction was" +
|
||||||
|
" reviewed, so it was not sent.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const tokenSend = {
|
||||||
|
token: TOKEN,
|
||||||
|
tokenSymbol: "TOK",
|
||||||
|
tokenDecimals: 6,
|
||||||
|
};
|
||||||
|
|
||||||
|
test("of a token, states and checks that network's token balance as it is then, which no longer covers the send", async () => {
|
||||||
|
mockNode.tokenUnits[reviewedOn] = 10000000n;
|
||||||
|
await review(reviewedOn, tokenSend);
|
||||||
|
expect(sendDisabled()).toBe(false);
|
||||||
|
mockNode.tokenUnits = {
|
||||||
|
[reviewedOn]: 500000n,
|
||||||
|
[switchedTo]: 10000000n,
|
||||||
|
};
|
||||||
|
await switchReopenAndGoBack(reviewedOn, switchedTo);
|
||||||
|
|
||||||
|
expect(el("confirm-balance").textContent).toBe("0.5000 TOK");
|
||||||
|
expect(shown("confirm-balance-error")).toBe(true);
|
||||||
|
expect(el("confirm-balance-error").textContent).toBe(
|
||||||
|
"Your TOK balance does not cover this amount. Please go back" +
|
||||||
|
" and send a smaller amount.",
|
||||||
|
);
|
||||||
|
expect(sendDisabled()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("of a token, states and checks that network's token balance as it is then, which now covers the send, and refuses to send it", async () => {
|
||||||
|
await review(reviewedOn, tokenSend);
|
||||||
|
expect(sendDisabled()).toBe(true);
|
||||||
|
mockNode.tokenUnits = {
|
||||||
|
[reviewedOn]: 10000000n,
|
||||||
|
[switchedTo]: 0n,
|
||||||
|
};
|
||||||
|
await switchReopenAndGoBack(reviewedOn, switchedTo);
|
||||||
|
|
||||||
|
expect(el("confirm-balance").textContent).toBe("10.0000 TOK");
|
||||||
|
expect(errors()).toBe("");
|
||||||
|
expect(shown("confirm-balance-error")).toBe(false);
|
||||||
|
expect(shown("confirm-gas-error")).toBe(false);
|
||||||
|
expect(sendDisabled()).toBe(false);
|
||||||
|
|
||||||
|
await signAndSend();
|
||||||
|
|
||||||
|
expect(signTransaction).not.toHaveBeenCalled();
|
||||||
|
expect(mockNode.broadcast).toEqual([]);
|
||||||
|
expect(errors()).toContain(
|
||||||
|
"The active network changed after this transaction was" +
|
||||||
|
" reviewed, so it was not sent.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -492,10 +646,10 @@ describe.each([
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("of an ERC-20 token, links the token contract to that network's explorer and prices the token by that network", async () => {
|
test("of an ERC-20 token, links the token contract to that network's explorer and prices the token by that network", async () => {
|
||||||
|
mockNode.tokenUnits[reviewedOn] = 50000000n;
|
||||||
await review(reviewedOn, {
|
await review(reviewedOn, {
|
||||||
token: TOKEN,
|
token: TOKEN,
|
||||||
tokenSymbol: "USDC",
|
tokenSymbol: "USDC",
|
||||||
tokenBalance: "50",
|
|
||||||
tokenDecimals: 6,
|
tokenDecimals: 6,
|
||||||
amount: "10",
|
amount: "10",
|
||||||
});
|
});
|
||||||
@@ -536,3 +690,101 @@ test("the send is refused by a signer on another network's node", async () => {
|
|||||||
expect(signTransaction).not.toHaveBeenCalled();
|
expect(signTransaction).not.toHaveBeenCalled();
|
||||||
expect(mockNode.broadcast).toEqual([]);
|
expect(mockNode.broadcast).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("the balance read", () => {
|
||||||
|
test("leaves the balance line Loading... and Sign & Send disabled until it returns", async () => {
|
||||||
|
let answer;
|
||||||
|
const getBalance = jest
|
||||||
|
.spyOn(JsonRpcProvider.prototype, "getBalance")
|
||||||
|
.mockImplementationOnce(() => new Promise((r) => (answer = r)));
|
||||||
|
try {
|
||||||
|
await review("sepolia");
|
||||||
|
} finally {
|
||||||
|
getBalance.mockRestore();
|
||||||
|
}
|
||||||
|
expect(el("confirm-balance").textContent).toBe("Loading...");
|
||||||
|
expect(el("confirm-fee-amount").textContent).toBe("Estimating...");
|
||||||
|
expect(el("confirm-errors").style.visibility).toBe("hidden");
|
||||||
|
expect(shown("confirm-balance-error")).toBe(false);
|
||||||
|
expect(shown("confirm-balance-read-error")).toBe(false);
|
||||||
|
expect(sendDisabled()).toBe(true);
|
||||||
|
|
||||||
|
answer(parseEther("5"));
|
||||||
|
await settle();
|
||||||
|
expect(el("confirm-balance").textContent).toBe("5.0000 SepoliaETH");
|
||||||
|
expect(sendDisabled()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The Chrome suite measures that nothing moves; this checks the message
|
||||||
|
// is already written, only hidden, before the read returns.
|
||||||
|
test("that finds the amount not covered only makes a message written before it visible", async () => {
|
||||||
|
let answer;
|
||||||
|
const getBalance = jest
|
||||||
|
.spyOn(JsonRpcProvider.prototype, "getBalance")
|
||||||
|
.mockImplementationOnce(() => new Promise((r) => (answer = r)));
|
||||||
|
try {
|
||||||
|
await review("sepolia");
|
||||||
|
} finally {
|
||||||
|
getBalance.mockRestore();
|
||||||
|
}
|
||||||
|
const message =
|
||||||
|
"Your SepoliaETH balance does not cover this amount. Please go" +
|
||||||
|
" back and send a smaller amount.";
|
||||||
|
expect(el("confirm-balance-error").textContent).toBe(message);
|
||||||
|
expect(shown("confirm-balance-error")).toBe(false);
|
||||||
|
|
||||||
|
answer(parseEther("0.5"));
|
||||||
|
await settle();
|
||||||
|
expect(el("confirm-balance-error").textContent).toBe(message);
|
||||||
|
expect(shown("confirm-balance-error")).toBe(true);
|
||||||
|
expect(errors()).toBe("");
|
||||||
|
expect(sendDisabled()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The fee is estimated once the read returns, after the switch, and still
|
||||||
|
// asks the node of the network the screen was drawn for.
|
||||||
|
test("still in flight when Sepolia is chosen in Settings leaves the balance and the fee on mainnet", async () => {
|
||||||
|
let answer;
|
||||||
|
const getBalance = jest
|
||||||
|
.spyOn(JsonRpcProvider.prototype, "getBalance")
|
||||||
|
.mockImplementationOnce(() => new Promise((r) => (answer = r)));
|
||||||
|
try {
|
||||||
|
await review("mainnet");
|
||||||
|
} finally {
|
||||||
|
getBalance.mockRestore();
|
||||||
|
}
|
||||||
|
const feeAskedOn = () =>
|
||||||
|
mockNode.asked
|
||||||
|
.filter((q) => q.method === "getFeeData")
|
||||||
|
.map((q) => q.network);
|
||||||
|
expect(feeAskedOn()).toEqual([]);
|
||||||
|
|
||||||
|
await onChainSwitch("sepolia");
|
||||||
|
answer(parseEther("5"));
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(feeAskedOn()).toEqual(["mainnet"]);
|
||||||
|
expect(el("confirm-balance").textContent).toBe("5.0000 ETH");
|
||||||
|
// 21000 gas at 10 gwei expected, at 20 gwei reserved.
|
||||||
|
expect(el("confirm-fee-amount").textContent).toBe("~0.0002 ETH");
|
||||||
|
expect(el("confirm-fee-reserve").textContent).toBe(
|
||||||
|
"up to 0.0004 ETH reserved",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("that fails states the balance as unknown, not zero, and blocks sending", async () => {
|
||||||
|
const getBalance = jest
|
||||||
|
.spyOn(JsonRpcProvider.prototype, "getBalance")
|
||||||
|
.mockRejectedValueOnce(new Error("the node did not answer"));
|
||||||
|
try {
|
||||||
|
await review("sepolia");
|
||||||
|
} finally {
|
||||||
|
getBalance.mockRestore();
|
||||||
|
}
|
||||||
|
expect(el("confirm-balance").textContent).toBe("unknown (SepoliaETH)");
|
||||||
|
expect(shown("confirm-balance-read-error")).toBe(true);
|
||||||
|
expect(shown("confirm-balance-error")).toBe(false);
|
||||||
|
expect(errors()).toBe("");
|
||||||
|
expect(sendDisabled()).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+23
-9
@@ -244,16 +244,21 @@ function latestBlock() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// keccak("decimals()")[0:4], and the same for symbol() and name().
|
// keccak("decimals()")[0:4], and the same for symbol(), name() and
|
||||||
|
// balanceOf(address).
|
||||||
const SELECTOR_DECIMALS = "0x313ce567";
|
const SELECTOR_DECIMALS = "0x313ce567";
|
||||||
const SELECTOR_SYMBOL = "0x95d89b41";
|
const SELECTOR_SYMBOL = "0x95d89b41";
|
||||||
const SELECTOR_NAME = "0x06fdde03";
|
const SELECTOR_NAME = "0x06fdde03";
|
||||||
|
const SELECTOR_BALANCE_OF = "0x70a08231";
|
||||||
|
|
||||||
// Every eth_call still answers with a zero word except decimals(), symbol()
|
// Every eth_call still answers with a zero word except decimals(), symbol(),
|
||||||
// and name() on the stub token. The wallet reads decimals() back at signing
|
// name() and balanceOf() on the stub token. The wallet reads decimals() back
|
||||||
// time to compare with the scale the confirmation screen rendered (issue
|
// at signing time to compare with the scale the confirmation screen rendered
|
||||||
// #305). Adding the token by its contract address reads all three (issue
|
// (issue #305). Adding the token by its contract address reads the first three
|
||||||
// #295); symbol() and name() answer what the explorer reports for it.
|
// (issue #295); symbol() and name() answer what the explorer reports for it.
|
||||||
|
// The confirmation screen reads balanceOf()
|
||||||
|
// (https://git.eeqj.de/sneak/AutistMask/issues/558), which answers the holding
|
||||||
|
// the explorer reports, or zero when no holding is seeded.
|
||||||
//
|
//
|
||||||
// opts.tokenDecimalsOverride is the lying contract: set it and decimals()
|
// opts.tokenDecimalsOverride is the lying contract: set it and decimals()
|
||||||
// answers something other than the value this same fixture reports through
|
// answers something other than the value this same fixture reports through
|
||||||
@@ -278,6 +283,9 @@ function ethCallResult(req, opts) {
|
|||||||
if (data.startsWith(SELECTOR_NAME)) {
|
if (data.startsWith(SELECTOR_NAME)) {
|
||||||
return abi.encode(["string"], [tokenObject(opts).name]);
|
return abi.encode(["string"], [tokenObject(opts).name]);
|
||||||
}
|
}
|
||||||
|
if (data.startsWith(SELECTOR_BALANCE_OF) && opts.seedTokenBalance) {
|
||||||
|
return word(tokenBalanceItems(opts)[0].value);
|
||||||
|
}
|
||||||
return ZERO_WORD;
|
return ZERO_WORD;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -420,9 +428,10 @@ const HOLD_MAX_MS = 30000;
|
|||||||
|
|
||||||
// Hold a reply open for as long as the test asks: until opts[name] is false.
|
// Hold a reply open for as long as the test asks: until opts[name] is false.
|
||||||
//
|
//
|
||||||
// The switch (holdGasEstimate, holdTransactionCount or holdBlockscout) is read
|
// The switch (holdBalance, holdGasEstimate, holdTransactionCount or
|
||||||
// here rather than captured, so a test flips it on the same options object the
|
// holdBlockscout) is read here rather than captured, so a test flips it on the
|
||||||
// route was registered with — the same pattern as seedTokenTransfer. This is
|
// same options object the route was registered with — the same pattern as
|
||||||
|
// seedTokenTransfer. This is
|
||||||
// the only way to observe a screen while its request is genuinely in flight;
|
// the only way to observe a screen while its request is genuinely in flight;
|
||||||
// sampling the screen and hoping to win a race against the network would
|
// sampling the screen and hoping to win a race against the network would
|
||||||
// assert nothing on a slow machine.
|
// assert nothing on a slow machine.
|
||||||
@@ -557,6 +566,9 @@ async function handleRpc(route, postData, opts, report) {
|
|||||||
report("unstubbed request: POST " + route.request().url());
|
report("unstubbed request: POST " + route.request().url());
|
||||||
return route.abort();
|
return route.abort();
|
||||||
}
|
}
|
||||||
|
if (batch.some((req) => req.method === "eth_getBalance")) {
|
||||||
|
await awaitRelease(opts, "holdBalance", report);
|
||||||
|
}
|
||||||
if (batch.some((req) => req.method === "eth_estimateGas")) {
|
if (batch.some((req) => req.method === "eth_estimateGas")) {
|
||||||
await awaitRelease(opts, "holdGasEstimate", report);
|
await awaitRelease(opts, "holdGasEstimate", report);
|
||||||
}
|
}
|
||||||
@@ -615,6 +627,8 @@ function traceEnabled(raw) {
|
|||||||
* fixture expects.
|
* fixture expects.
|
||||||
* @param {boolean} [opts.failGasEstimate] answer eth_estimateGas with a
|
* @param {boolean} [opts.failGasEstimate] answer eth_estimateGas with a
|
||||||
* node-side refusal.
|
* node-side refusal.
|
||||||
|
* @param {boolean} [opts.holdBalance] hold every batch containing an
|
||||||
|
* eth_getBalance until this is cleared again.
|
||||||
* @param {boolean} [opts.holdGasEstimate] hold every batch containing an
|
* @param {boolean} [opts.holdGasEstimate] hold every batch containing an
|
||||||
* eth_estimateGas until this is cleared again.
|
* eth_estimateGas until this is cleared again.
|
||||||
* @param {boolean} [opts.holdTransactionCount] hold every batch containing an
|
* @param {boolean} [opts.holdTransactionCount] hold every batch containing an
|
||||||
|
|||||||
+92
-35
@@ -2232,7 +2232,7 @@ function feeEth(wei) {
|
|||||||
|
|
||||||
// What the confirmation screen is showing right now, read out of the DOM in
|
// What the confirmation screen is showing right now, read out of the DOM in
|
||||||
// one pass: whether sending is allowed, which reason it is giving, what the
|
// one pass: whether sending is allowed, which reason it is giving, what the
|
||||||
// fee block says, and how tall the whole view is.
|
// fee block says, how tall the whole view is, and where Sign & Send sits in it.
|
||||||
async function confirmState(page) {
|
async function confirmState(page) {
|
||||||
return page.evaluate(() => {
|
return page.evaluate(() => {
|
||||||
const el = (id) => document.getElementById(id);
|
const el = (id) => document.getElementById(id);
|
||||||
@@ -2245,6 +2245,9 @@ async function confirmState(page) {
|
|||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
height: el("view-confirm-tx").getBoundingClientRect().height,
|
height: el("view-confirm-tx").getBoundingClientRect().height,
|
||||||
|
sendTop:
|
||||||
|
el("btn-confirm-send").getBoundingClientRect().top -
|
||||||
|
el("view-confirm-tx").getBoundingClientRect().top,
|
||||||
type: el("confirm-type").textContent.trim(),
|
type: el("confirm-type").textContent.trim(),
|
||||||
balance: el("confirm-balance").textContent.trim(),
|
balance: el("confirm-balance").textContent.trim(),
|
||||||
fee: el("confirm-fee-amount").textContent.trim(),
|
fee: el("confirm-fee-amount").textContent.trim(),
|
||||||
@@ -2253,6 +2256,9 @@ async function confirmState(page) {
|
|||||||
errors: shown("confirm-errors")
|
errors: shown("confirm-errors")
|
||||||
? el("confirm-errors").textContent.trim()
|
? el("confirm-errors").textContent.trim()
|
||||||
: "",
|
: "",
|
||||||
|
balanceError: shown("confirm-balance-error")
|
||||||
|
? el("confirm-balance-error").textContent.trim()
|
||||||
|
: "",
|
||||||
amountFeeError: shown("confirm-amount-fee-error"),
|
amountFeeError: shown("confirm-amount-fee-error"),
|
||||||
gasError: shown("confirm-gas-error"),
|
gasError: shown("confirm-gas-error"),
|
||||||
feeUnknownError: shown("confirm-fee-unknown-error"),
|
feeUnknownError: shown("confirm-fee-unknown-error"),
|
||||||
@@ -2271,6 +2277,16 @@ async function waitForEstimate(page) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function waitForBalance(page) {
|
||||||
|
await page.waitForFunction(
|
||||||
|
() =>
|
||||||
|
document.getElementById("confirm-balance").textContent.trim() !==
|
||||||
|
"Loading...",
|
||||||
|
null,
|
||||||
|
{ timeout: 60000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
async function backToAddress(page) {
|
async function backToAddress(page) {
|
||||||
if (await page.isVisible("#view-confirm-tx")) {
|
if (await page.isVisible("#view-confirm-tx")) {
|
||||||
await page.click("#btn-confirm-back");
|
await page.click("#btn-confirm-back");
|
||||||
@@ -2282,13 +2298,14 @@ async function backToAddress(page) {
|
|||||||
await openAddressDetail(page);
|
await openAddressDetail(page);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Drive the popup to the confirmation screen for one send.
|
// Drive the popup to the confirmation screen for one send, and return as soon
|
||||||
|
// as the screen is shown, its balance read still in flight.
|
||||||
//
|
//
|
||||||
// It waits for the send screen to be showing `balance`, the fixture's balance
|
// It waits for the send screen to be showing `balance`, the fixture's balance
|
||||||
// as that screen displays it, before filling anything in. Waiting for it —
|
// as that screen displays it, before filling anything in. Waiting for it —
|
||||||
// rather than for a refresh to have probably landed — is what keeps every
|
// rather than for a refresh to have probably landed — is what keeps every
|
||||||
// assertion below deterministic after a fixture change.
|
// assertion below deterministic after a fixture change.
|
||||||
async function goToConfirm(page, { token, balance, amount }) {
|
async function openConfirm(page, { token, balance, amount }) {
|
||||||
await backToAddress(page);
|
await backToAddress(page);
|
||||||
await page.click("#btn-send");
|
await page.click("#btn-send");
|
||||||
await visible(page, "#view-send");
|
await visible(page, "#view-send");
|
||||||
@@ -2303,6 +2320,14 @@ async function goToConfirm(page, { token, balance, amount }) {
|
|||||||
await page.fill("#send-amount", amount);
|
await page.fill("#send-amount", amount);
|
||||||
await page.click("#btn-send-review");
|
await page.click("#btn-send-review");
|
||||||
await visible(page, "#view-confirm-tx");
|
await visible(page, "#view-confirm-tx");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same, returning once the screen has read the balance. It reads it
|
||||||
|
// before it estimates the fee, so every state below is read with the balance
|
||||||
|
// in place, the pending fee included.
|
||||||
|
async function goToConfirm(page, send) {
|
||||||
|
await openConfirm(page, send);
|
||||||
|
await waitForBalance(page);
|
||||||
await assertAddressesFit(page, "the confirmation screen");
|
await assertAddressesFit(page, "the confirmation screen");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2378,7 +2403,10 @@ test("ConfirmTx blocks sending while the fee estimate is pending (#238)", async
|
|||||||
"the estimate-failed message is shown for an estimate that is merely pending",
|
"the estimate-failed message is shown for an estimate that is merely pending",
|
||||||
);
|
);
|
||||||
assert(
|
assert(
|
||||||
!st.amountFeeError && !st.gasError && st.errors === "",
|
!st.amountFeeError &&
|
||||||
|
!st.gasError &&
|
||||||
|
st.errors === "" &&
|
||||||
|
st.balanceError === "",
|
||||||
"a balance message is shown before the fee is known",
|
"a balance message is shown before the fee is known",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -2409,6 +2437,7 @@ test("ConfirmTx enables Send once the estimate lands, quoting both numbers (#238
|
|||||||
);
|
);
|
||||||
assert(
|
assert(
|
||||||
st.errors === "" &&
|
st.errors === "" &&
|
||||||
|
st.balanceError === "" &&
|
||||||
!st.amountFeeError &&
|
!st.amountFeeError &&
|
||||||
!st.gasError &&
|
!st.gasError &&
|
||||||
!st.feeUnknownError,
|
!st.feeUnknownError,
|
||||||
@@ -2475,30 +2504,54 @@ test("ConfirmTx gates on the fee RESERVE, not the displayed estimate (#238)", as
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("ConfirmTx refuses a send that exceeds the balance outright (#238)", async (env) => {
|
// The screen is first measured with its balance read held, so the message the
|
||||||
await goToConfirm(env.page, {
|
// read brings must already hold its space when the read returns (#558).
|
||||||
token: "ETH",
|
test("ConfirmTx refuses a send that exceeds the balance outright, and nothing moves when the balance arrives (#238)", async (env) => {
|
||||||
balance: FUNDED_ETH_TEXT + " ETH",
|
env.routeOpts.holdBalance = true;
|
||||||
amount: OVER_BALANCE_AMOUNT,
|
let reading;
|
||||||
});
|
try {
|
||||||
|
await openConfirm(env.page, {
|
||||||
|
token: "ETH",
|
||||||
|
balance: FUNDED_ETH_TEXT + " ETH",
|
||||||
|
amount: OVER_BALANCE_AMOUNT,
|
||||||
|
});
|
||||||
|
reading = await confirmState(env.page);
|
||||||
|
} finally {
|
||||||
|
env.routeOpts.holdBalance = false;
|
||||||
|
}
|
||||||
|
assert(
|
||||||
|
reading.balance === "Loading...",
|
||||||
|
"the balance read was not held: " + JSON.stringify(reading.balance),
|
||||||
|
);
|
||||||
|
await waitForBalance(env.page);
|
||||||
await waitForEstimate(env.page);
|
await waitForEstimate(env.page);
|
||||||
|
|
||||||
const st = await confirmState(env.page);
|
const st = await confirmState(env.page);
|
||||||
const want =
|
|
||||||
"Insufficient balance. You have " +
|
|
||||||
FUNDED_ETH_TEXT +
|
|
||||||
" ETH but are trying to send " +
|
|
||||||
OVER_BALANCE_AMOUNT +
|
|
||||||
" ETH.";
|
|
||||||
assert(
|
assert(
|
||||||
st.errors === want,
|
st.balance === FUNDED_ETH_TEXT + " ETH",
|
||||||
"wrong over-balance message: " + JSON.stringify(st.errors),
|
"the confirmation screen shows the wrong balance: " +
|
||||||
|
JSON.stringify(st.balance),
|
||||||
|
);
|
||||||
|
const want =
|
||||||
|
"Your ETH balance does not cover this amount. Please go back and" +
|
||||||
|
" send a smaller amount.";
|
||||||
|
assert(
|
||||||
|
st.balanceError === want,
|
||||||
|
"wrong over-balance message: " + JSON.stringify(st.balanceError),
|
||||||
);
|
);
|
||||||
assert(st.sendDisabled, "Send is enabled for a send that exceeds balance");
|
assert(st.sendDisabled, "Send is enabled for a send that exceeds balance");
|
||||||
assert(
|
assert(
|
||||||
!st.amountFeeError,
|
!st.amountFeeError,
|
||||||
"the amount-plus-fee message is shown for an amount that alone exceeds the balance",
|
"the amount-plus-fee message is shown for an amount that alone exceeds the balance",
|
||||||
);
|
);
|
||||||
|
assert(
|
||||||
|
st.sendTop === reading.sendTop,
|
||||||
|
"Sign & Send moved when the balance read returned: " +
|
||||||
|
reading.sendTop +
|
||||||
|
"px -> " +
|
||||||
|
st.sendTop +
|
||||||
|
"px",
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("ConfirmTx refuses to send when the fee estimate fails, with its own message (#238)", async (env) => {
|
test("ConfirmTx refuses to send when the fee estimate fails, with its own message (#238)", async (env) => {
|
||||||
@@ -2542,7 +2595,10 @@ test("ConfirmTx refuses to send when the fee estimate fails, with its own messag
|
|||||||
"the estimate-failed message is not shown after a failed estimate",
|
"the estimate-failed message is not shown after a failed estimate",
|
||||||
);
|
);
|
||||||
assert(
|
assert(
|
||||||
!st.amountFeeError && !st.gasError && st.errors === "",
|
!st.amountFeeError &&
|
||||||
|
!st.gasError &&
|
||||||
|
st.errors === "" &&
|
||||||
|
st.balanceError === "",
|
||||||
"a balance message is shown for an estimate that simply failed",
|
"a balance message is shown for an estimate that simply failed",
|
||||||
);
|
);
|
||||||
assert(
|
assert(
|
||||||
@@ -2633,21 +2689,19 @@ test("ConfirmTx refuses an ERC-20 send that exceeds the token balance (#238)", a
|
|||||||
await waitForEstimate(env.page);
|
await waitForEstimate(env.page);
|
||||||
|
|
||||||
const st = await confirmState(env.page);
|
const st = await confirmState(env.page);
|
||||||
const want =
|
|
||||||
"Insufficient " +
|
|
||||||
STUB_TOKEN.symbol +
|
|
||||||
" balance. You have " +
|
|
||||||
TOKEN_BALANCE_TEXT +
|
|
||||||
" " +
|
|
||||||
STUB_TOKEN.symbol +
|
|
||||||
" but are trying to send " +
|
|
||||||
OVER_TOKEN_AMOUNT +
|
|
||||||
" " +
|
|
||||||
STUB_TOKEN.symbol +
|
|
||||||
".";
|
|
||||||
assert(
|
assert(
|
||||||
st.errors === want,
|
st.balance === TOKEN_BALANCE_TEXT + " " + STUB_TOKEN.symbol,
|
||||||
"wrong over-token-balance message: " + JSON.stringify(st.errors),
|
"the confirmation screen shows the wrong token balance: " +
|
||||||
|
JSON.stringify(st.balance),
|
||||||
|
);
|
||||||
|
const want =
|
||||||
|
"Your " +
|
||||||
|
STUB_TOKEN.symbol +
|
||||||
|
" balance does not cover this amount. Please go back and send a" +
|
||||||
|
" smaller amount.";
|
||||||
|
assert(
|
||||||
|
st.balanceError === want,
|
||||||
|
"wrong over-token-balance message: " + JSON.stringify(st.balanceError),
|
||||||
);
|
);
|
||||||
assert(
|
assert(
|
||||||
st.sendDisabled,
|
st.sendDisabled,
|
||||||
@@ -2703,9 +2757,9 @@ test("ConfirmTx gates the ERC-20 fee on the RESERVE, with the ERC-20 message (#2
|
|||||||
"the native-ETH over-budget message is shown on an ERC-20 transfer",
|
"the native-ETH over-budget message is shown on an ERC-20 transfer",
|
||||||
);
|
);
|
||||||
assert(
|
assert(
|
||||||
st.errors === "",
|
st.errors === "" && st.balanceError === "",
|
||||||
"a token-balance message is shown for a transfer the token balance covers: " +
|
"a token-balance message is shown for a transfer the token balance covers: " +
|
||||||
JSON.stringify(st.errors),
|
JSON.stringify(st.errors + st.balanceError),
|
||||||
);
|
);
|
||||||
assert(
|
assert(
|
||||||
st.height === env.erc20PendingHeight,
|
st.height === env.erc20PendingHeight,
|
||||||
@@ -4859,6 +4913,9 @@ async function main() {
|
|||||||
seedTokenBalance: false,
|
seedTokenBalance: false,
|
||||||
ethBalanceWei: null,
|
ethBalanceWei: null,
|
||||||
failGasEstimate: false,
|
failGasEstimate: false,
|
||||||
|
// Whether a JSON-RPC batch asking for a balance is held unanswered:
|
||||||
|
// the confirmation screen's own balance read (#558).
|
||||||
|
holdBalance: false,
|
||||||
holdGasEstimate: false,
|
holdGasEstimate: false,
|
||||||
// Whether a JSON-RPC batch asking for a transaction count is held
|
// Whether a JSON-RPC batch asking for a transaction count is held
|
||||||
// unanswered: the address scan after creating a wallet (#475).
|
// unanswered: the address scan after creating a wallet (#475).
|
||||||
|
|||||||
@@ -17,6 +17,10 @@ jest.mock("ethers", () => {
|
|||||||
async lookupAddress() {
|
async lookupAddress() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
// The 1.5 of the native token the address holds on either network.
|
||||||
|
async getBalance() {
|
||||||
|
return 1500000000000000000n;
|
||||||
|
}
|
||||||
// 10 gwei expected, 20 gwei reserved per gas.
|
// 10 gwei expected, 20 gwei reserved per gas.
|
||||||
async getFeeData() {
|
async getFeeData() {
|
||||||
return { maxFeePerGas: 20000000000n, gasPrice: 10000000000n };
|
return { maxFeePerGas: 20000000000n, gasPrice: 10000000000n };
|
||||||
@@ -339,14 +343,11 @@ describe.each([
|
|||||||
|
|
||||||
test("the insufficient-balance error", async () => {
|
test("the insufficient-balance error", async () => {
|
||||||
await confirmSend("2");
|
await confirmSend("2");
|
||||||
expect(
|
expect(text("confirm-balance-error")).toBe(
|
||||||
global.document.getElementById("confirm-errors").innerHTML,
|
"Your " +
|
||||||
).toContain(
|
|
||||||
"You have 1.5000 " +
|
|
||||||
symbol +
|
symbol +
|
||||||
" but are trying to send 2 " +
|
" balance does not cover this amount. Please go back and send" +
|
||||||
symbol +
|
" a smaller amount.",
|
||||||
".",
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -781,7 +781,6 @@ const WELL_FORMED_DATA = {
|
|||||||
from: ADDRESS,
|
from: ADDRESS,
|
||||||
to: ADDRESS,
|
to: ADDRESS,
|
||||||
amount: "1",
|
amount: "1",
|
||||||
balance: "2",
|
|
||||||
},
|
},
|
||||||
pendingWait: {
|
pendingWait: {
|
||||||
hash: "0x1",
|
hash: "0x1",
|
||||||
|
|||||||
@@ -23,7 +23,10 @@ jest.mock("../src/shared/log", () => ({
|
|||||||
isDebug: () => false,
|
isDebug: () => false,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// What the confirmation screen asks the node for.
|
const { AbiCoder } = require("ethers");
|
||||||
|
|
||||||
|
// What the confirmation screen asks the node for. The address holds the 1 ETH
|
||||||
|
// and 250 TOK the wallet below records.
|
||||||
const mockProvider = {
|
const mockProvider = {
|
||||||
getFeeData: async () => ({
|
getFeeData: async () => ({
|
||||||
maxFeePerGas: 2000000000n,
|
maxFeePerGas: 2000000000n,
|
||||||
@@ -32,7 +35,11 @@ const mockProvider = {
|
|||||||
estimateGas: async () => 21000n,
|
estimateGas: async () => 21000n,
|
||||||
getCode: async () => "0x",
|
getCode: async () => "0x",
|
||||||
getTransactionCount: async () => 1,
|
getTransactionCount: async () => 1,
|
||||||
getBalance: async () => 0n,
|
getBalance: async () => 1000000000000000000n,
|
||||||
|
// The one contract call the screen makes, balanceOf(), answered at the
|
||||||
|
// token's 6 decimal places.
|
||||||
|
call: async () =>
|
||||||
|
AbiCoder.defaultAbiCoder().encode(["uint256"], [250000000n]),
|
||||||
};
|
};
|
||||||
|
|
||||||
jest.mock("../src/shared/balances", () => {
|
jest.mock("../src/shared/balances", () => {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
// What the stub node answers. Each test sets what it needs.
|
// What the stub node answers. Each test sets what it needs.
|
||||||
const mockNode = {
|
const mockNode = {
|
||||||
balanceWei: 0n,
|
balanceWei: 0n,
|
||||||
|
tokenUnits: 0n,
|
||||||
feeData: { maxFeePerGas: 1n, gasPrice: 1n },
|
feeData: { maxFeePerGas: 1n, gasPrice: 1n },
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -30,6 +31,13 @@ jest.mock("ethers", () => {
|
|||||||
async getBalance() {
|
async getBalance() {
|
||||||
return mockNode.balanceWei;
|
return mockNode.balanceWei;
|
||||||
}
|
}
|
||||||
|
// balanceOf(), the one contract call these screens make.
|
||||||
|
async call() {
|
||||||
|
return actual.AbiCoder.defaultAbiCoder().encode(
|
||||||
|
["uint256"],
|
||||||
|
[mockNode.tokenUnits],
|
||||||
|
);
|
||||||
|
}
|
||||||
async lookupAddress() {
|
async lookupAddress() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -195,10 +203,19 @@ function errors() {
|
|||||||
return global.document.getElementById("confirm-errors").innerHTML;
|
return global.document.getElementById("confirm-errors").innerHTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The message for an amount the balance does not cover, while it is shown.
|
||||||
|
function balanceError() {
|
||||||
|
const box = global.document.getElementById("confirm-balance-error");
|
||||||
|
return box.style.visibility === "visible" ? box.textContent : "";
|
||||||
|
}
|
||||||
|
|
||||||
// The ETH balance the node reports and the token rows the explorer reports,
|
// The ETH balance the node reports and the token rows the explorer reports,
|
||||||
// fetched and stored exactly where the popup stores them.
|
// fetched and stored exactly where the popup stores them. The node reports the
|
||||||
|
// token holding the explorer does.
|
||||||
async function refreshWith(balanceWei, tokenItems = []) {
|
async function refreshWith(balanceWei, tokenItems = []) {
|
||||||
mockNode.balanceWei = balanceWei;
|
mockNode.balanceWei = balanceWei;
|
||||||
|
mockNode.tokenUnits =
|
||||||
|
tokenItems.length > 0 ? BigInt(tokenItems[0].value) : 0n;
|
||||||
mockExplorer.items = tokenItems;
|
mockExplorer.items = tokenItems;
|
||||||
state.wallets = [{ name: "Wallet 1", addresses: [{ address: HOLDER }] }];
|
state.wallets = [{ name: "Wallet 1", addresses: [{ address: HOLDER }] }];
|
||||||
state.selectedWallet = 0;
|
state.selectedWallet = 0;
|
||||||
@@ -300,9 +317,10 @@ describe("a tracked token holding below 0.000001 never renders as zero", () => {
|
|||||||
await confirmSend("0.0000005", TOKEN);
|
await confirmSend("0.0000005", TOKEN);
|
||||||
expect(text("confirm-balance")).toBe("0.0000005 TOK");
|
expect(text("confirm-balance")).toBe("0.0000005 TOK");
|
||||||
expect(errors()).toBe("");
|
expect(errors()).toBe("");
|
||||||
|
expect(balanceError()).toBe("");
|
||||||
await confirmSend("0.0000006", TOKEN);
|
await confirmSend("0.0000006", TOKEN);
|
||||||
expect(errors()).toContain(
|
expect(balanceError()).toContain(
|
||||||
"You have 0.0000005 TOK but are trying to send 0.0000006 TOK.",
|
"Your TOK balance does not cover this amount.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -316,6 +334,7 @@ describe("a tracked token holding below 0.000001 never renders as zero", () => {
|
|||||||
await confirmSend("1.5", TOKEN);
|
await confirmSend("1.5", TOKEN);
|
||||||
expect(text("confirm-balance")).toBe("1.5000 TOK");
|
expect(text("confirm-balance")).toBe("1.5000 TOK");
|
||||||
expect(errors()).toBe("");
|
expect(errors()).toBe("");
|
||||||
|
expect(balanceError()).toBe("");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("with more than 18 decimals and a holding below 10^-18", async () => {
|
test("with more than 18 decimals and a holding below 10^-18", async () => {
|
||||||
@@ -329,9 +348,8 @@ describe("a tracked token holding below 0.000001 never renders as zero", () => {
|
|||||||
);
|
);
|
||||||
await confirmSend("0.000000000000000001", TOKEN);
|
await confirmSend("0.000000000000000001", TOKEN);
|
||||||
expect(text("confirm-balance")).toBe("0.000000000000000000000001 TOK");
|
expect(text("confirm-balance")).toBe("0.000000000000000000000001 TOK");
|
||||||
expect(errors()).toContain(
|
expect(balanceError()).toContain(
|
||||||
"You have 0.000000000000000000000001 TOK but are trying to send" +
|
"Your TOK balance does not cover this amount.",
|
||||||
" 0.000000000000000001 TOK.",
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -356,9 +374,10 @@ describe("an untracked token holding below 0.000001 never renders as zero", () =
|
|||||||
await confirmSend("0.0000005", TOKEN);
|
await confirmSend("0.0000005", TOKEN);
|
||||||
expect(text("confirm-balance")).toBe("0.0000005 TOK");
|
expect(text("confirm-balance")).toBe("0.0000005 TOK");
|
||||||
expect(errors()).toBe("");
|
expect(errors()).toBe("");
|
||||||
|
expect(balanceError()).toBe("");
|
||||||
await confirmSend("0.0000006", TOKEN);
|
await confirmSend("0.0000006", TOKEN);
|
||||||
expect(errors()).toContain(
|
expect(balanceError()).toContain(
|
||||||
"You have 0.0000005 TOK but are trying to send 0.0000006 TOK.",
|
"Your TOK balance does not cover this amount.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+13
-1
@@ -17,6 +17,7 @@
|
|||||||
// What the stub node answers, and the signed transactions it was handed.
|
// What the stub node answers, and the signed transactions it was handed.
|
||||||
const mockNode = {
|
const mockNode = {
|
||||||
balanceWei: 0n,
|
balanceWei: 0n,
|
||||||
|
tokenUnits: 0n,
|
||||||
feeData: null,
|
feeData: null,
|
||||||
broadcast: [],
|
broadcast: [],
|
||||||
};
|
};
|
||||||
@@ -30,6 +31,14 @@ jest.mock("ethers", () => {
|
|||||||
async getBalance() {
|
async getBalance() {
|
||||||
return mockNode.balanceWei;
|
return mockNode.balanceWei;
|
||||||
}
|
}
|
||||||
|
// balanceOf(), the one contract call these screens make before Sign
|
||||||
|
// & Send.
|
||||||
|
async call() {
|
||||||
|
return actual.AbiCoder.defaultAbiCoder().encode(
|
||||||
|
["uint256"],
|
||||||
|
[mockNode.tokenUnits],
|
||||||
|
);
|
||||||
|
}
|
||||||
async lookupAddress() {
|
async lookupAddress() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -187,9 +196,12 @@ function text(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The ETH balance the node reports and the token rows the explorer reports,
|
// The ETH balance the node reports and the token rows the explorer reports,
|
||||||
// fetched and stored exactly where the popup stores them.
|
// fetched and stored exactly where the popup stores them. The node reports the
|
||||||
|
// token holding the explorer does.
|
||||||
async function refreshWith(balanceWei, tokenItems = []) {
|
async function refreshWith(balanceWei, tokenItems = []) {
|
||||||
mockNode.balanceWei = balanceWei;
|
mockNode.balanceWei = balanceWei;
|
||||||
|
mockNode.tokenUnits =
|
||||||
|
tokenItems.length > 0 ? BigInt(tokenItems[0].value) : 0n;
|
||||||
mockExplorer.items = tokenItems;
|
mockExplorer.items = tokenItems;
|
||||||
state.wallets = [
|
state.wallets = [
|
||||||
{
|
{
|
||||||
|
|||||||
+128
-49
@@ -332,7 +332,13 @@ describe("uniswap decoder", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("decodes first-ever AutistMask swap (PERMIT2_PERMIT + V4_SWAP)", () => {
|
test("decodes first-ever AutistMask swap (PERMIT2_PERMIT + V4_SWAP)", () => {
|
||||||
const result = uniswap.decode(FIRST_SWAP_CALLDATA, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
FIRST_SWAP_CALLDATA,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
|
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result.name).toBe("Swap USDT \u2192 ETH");
|
expect(result.name).toBe("Swap USDT \u2192 ETH");
|
||||||
@@ -356,8 +362,10 @@ describe("uniswap decoder", () => {
|
|||||||
expect(result.details.find((d) => d.label === "Amount").value).toBe(
|
expect(result.details.find((d) => d.label === "Amount").value).toBe(
|
||||||
"Unlimited",
|
"Unlimited",
|
||||||
);
|
);
|
||||||
|
// This fixture's TAKE parameters are one byte long, so who it pays
|
||||||
|
// cannot be read, and the minimum is not said to be received.
|
||||||
expect(
|
expect(
|
||||||
result.details.find((d) => d.label === "Min. received").value,
|
result.details.find((d) => d.label === "Min. paid out").value,
|
||||||
).toBe("0.0002 ETH");
|
).toBe("0.0002 ETH");
|
||||||
|
|
||||||
// Real mainnet calldata is in the deployed shape, so its V4 step is
|
// Real mainnet calldata is in the deployed shape, so its V4 step is
|
||||||
@@ -373,6 +381,8 @@ describe("uniswap decoder", () => {
|
|||||||
v4SwapCalldata(id, deployed),
|
v4SwapCalldata(id, deployed),
|
||||||
ROUTER_ADDR,
|
ROUTER_ADDR,
|
||||||
"0x1",
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
);
|
);
|
||||||
expect(detail(result, "Steps").value).toBe("V4 Swap");
|
expect(detail(result, "Steps").value).toBe("V4 Swap");
|
||||||
},
|
},
|
||||||
@@ -389,6 +399,8 @@ describe("uniswap decoder", () => {
|
|||||||
v4SwapCalldata(id, newer),
|
v4SwapCalldata(id, newer),
|
||||||
ROUTER_ADDR,
|
ROUTER_ADDR,
|
||||||
"0x1",
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
);
|
);
|
||||||
expect(detail(result, "Amount")).toBeUndefined();
|
expect(detail(result, "Amount")).toBeUndefined();
|
||||||
expect(detail(result, "Min. received")).toBeUndefined();
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
@@ -419,7 +431,13 @@ describe("uniswap decoder", () => {
|
|||||||
],
|
],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(detail(result, "Steps").value).toBe(
|
expect(detail(result, "Steps").value).toBe(
|
||||||
"V4 Swap (could not be decoded)",
|
"V4 Swap (could not be decoded)",
|
||||||
);
|
);
|
||||||
@@ -440,7 +458,13 @@ describe("uniswap decoder", () => {
|
|||||||
[encodeV4Swap(new Uint8Array([id]), [newer])],
|
[encodeV4Swap(new Uint8Array([id]), [newer])],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(detail(result, "Steps").value).toBe(
|
expect(detail(result, "Steps").value).toBe(
|
||||||
"V4 Swap (could not be decoded)",
|
"V4 Swap (could not be decoded)",
|
||||||
);
|
);
|
||||||
@@ -470,7 +494,13 @@ describe("uniswap decoder", () => {
|
|||||||
],
|
],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
expect(detail(result, "Amount").value).toBe("2.0000 USDT");
|
expect(detail(result, "Amount").value).toBe("2.0000 USDT");
|
||||||
expect(detail(result, "Token Out").value).toBe(
|
expect(detail(result, "Token Out").value).toBe(
|
||||||
@@ -498,7 +528,13 @@ describe("uniswap decoder", () => {
|
|||||||
],
|
],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
expect(detail(result, "Token In").value).toBe(
|
expect(detail(result, "Token In").value).toBe(
|
||||||
"Unknown (could not be decoded)",
|
"Unknown (could not be decoded)",
|
||||||
@@ -520,7 +556,7 @@ describe("uniswap decoder", () => {
|
|||||||
],
|
],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(detail(result, "Token Out").value).toBe(
|
expect(detail(result, "Token Out").value).toBe(
|
||||||
"Unknown (could not be decoded)",
|
"Unknown (could not be decoded)",
|
||||||
);
|
);
|
||||||
@@ -540,7 +576,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result.name).toBe("Swap USDT \u2192 WETH");
|
expect(result.name).toBe("Swap USDT \u2192 WETH");
|
||||||
|
|
||||||
@@ -567,7 +603,7 @@ describe("uniswap decoder", () => {
|
|||||||
1767225600n,
|
1767225600n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result.name).toBe("Swap USDC → WETH");
|
expect(result.name).toBe("Swap USDC → WETH");
|
||||||
expect(detail(result, "Token In").address).toBe(USDC_ADDR);
|
expect(detail(result, "Token In").address).toBe(USDC_ADDR);
|
||||||
expect(detail(result, "Token Out").address).toBe(WETH_ADDR);
|
expect(detail(result, "Token Out").address).toBe(WETH_ADDR);
|
||||||
@@ -599,7 +635,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result.name).toBe("Swap ETH → USDC");
|
expect(result.name).toBe("Swap ETH → USDC");
|
||||||
|
|
||||||
const amount = detail(result, "Amount");
|
const amount = detail(result, "Amount");
|
||||||
@@ -628,7 +664,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result.name).toBe("Swap USDC → ETH");
|
expect(result.name).toBe("Swap USDC → ETH");
|
||||||
expect(detail(result, "Amount").value).toBe("Up to 1500.0000 USDC");
|
expect(detail(result, "Amount").value).toBe("Up to 1500.0000 USDC");
|
||||||
expect(detail(result, "Token Out").value).toBe("ETH");
|
expect(detail(result, "Token Out").value).toBe("ETH");
|
||||||
@@ -671,7 +707,13 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(detail(result, "Token Out").address).toBe(tokenOut);
|
expect(detail(result, "Token Out").address).toBe(tokenOut);
|
||||||
expect(detail(result, "Min. received").value).toBe(minReceived);
|
expect(detail(result, "Min. received").value).toBe(minReceived);
|
||||||
},
|
},
|
||||||
@@ -692,7 +734,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result.name).toBe("Swap USDT → USDC");
|
expect(result.name).toBe("Swap USDT → USDC");
|
||||||
expect(detail(result, "Token Out").address).toBe(USDC_ADDR);
|
expect(detail(result, "Token Out").address).toBe(USDC_ADDR);
|
||||||
expect(detail(result, "Min. received").value).toBe("1.9000 USDC");
|
expect(detail(result, "Min. received").value).toBe("1.9000 USDC");
|
||||||
@@ -725,7 +767,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(detail(result, "Token Out").value).toBe("ETH");
|
expect(detail(result, "Token Out").value).toBe("ETH");
|
||||||
expect(detail(result, "Min. received").value).toBe("0.4000 ETH");
|
expect(detail(result, "Min. received").value).toBe("0.4000 ETH");
|
||||||
});
|
});
|
||||||
@@ -744,7 +786,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(detail(result, "Token Out").value).toBe("ETH");
|
expect(detail(result, "Token Out").value).toBe("ETH");
|
||||||
expect(detail(result, "Min. received").value).toBe("0.0005 ETH");
|
expect(detail(result, "Min. received").value).toBe("0.0005 ETH");
|
||||||
});
|
});
|
||||||
@@ -769,7 +811,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(detail(result, "Token Out").value).toBe(
|
expect(detail(result, "Token Out").value).toBe(
|
||||||
"Unknown (not named in the calldata)",
|
"Unknown (not named in the calldata)",
|
||||||
);
|
);
|
||||||
@@ -792,7 +834,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result.name).toBe("Swap USDT \u2192 WETH");
|
expect(result.name).toBe("Swap USDT \u2192 WETH");
|
||||||
});
|
});
|
||||||
@@ -804,7 +846,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
const tokenIn = result.details.find((d) => d.label === "Token In");
|
const tokenIn = result.details.find((d) => d.label === "Token In");
|
||||||
@@ -827,12 +869,13 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
// UNWRAP_WETH means output is native ETH
|
// UNWRAP_WETH means output is native ETH
|
||||||
expect(result.name).toBe("Swap USDT \u2192 ETH");
|
expect(result.name).toBe("Swap USDT \u2192 ETH");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// No step pays anyone, so the minimum is not said to be received.
|
||||||
test("decodes BALANCE_CHECK_ERC20 for min output", () => {
|
test("decodes BALANCE_CHECK_ERC20 for min output", () => {
|
||||||
const data = buildExecute(
|
const data = buildExecute(
|
||||||
solidityPacked(["uint8", "uint8"], [0x0b, 0x0e]),
|
solidityPacked(["uint8", "uint8"], [0x0b, 0x0e]),
|
||||||
@@ -843,10 +886,10 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
const minOut = result.details.find((d) => d.label === "Min. received");
|
const minOut = result.details.find((d) => d.label === "Min. paid out");
|
||||||
expect(minOut).toBeDefined();
|
expect(minOut).toBeDefined();
|
||||||
expect(minOut.value).toContain("2.0000");
|
expect(minOut.value).toContain("2.0000");
|
||||||
expect(minOut.value).toContain("USDT");
|
expect(minOut.value).toContain("USDT");
|
||||||
@@ -863,7 +906,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
// The V4 swap action's parameters are empty, so that step is said to
|
// The V4 swap action's parameters are empty, so that step is said to
|
||||||
@@ -943,7 +986,13 @@ describe("uniswap decoder", () => {
|
|||||||
[subPlan],
|
[subPlan],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
expect(detail(result, "Steps").value).toBe(
|
expect(detail(result, "Steps").value).toBe(
|
||||||
"Execute Sub-Plan (its steps are not shown)",
|
"Execute Sub-Plan (its steps are not shown)",
|
||||||
@@ -1031,7 +1080,13 @@ describe("uniswap decoder", () => {
|
|||||||
"$beside an EXECUTE_SUB_PLAN step does not name either side",
|
"$beside an EXECUTE_SUB_PLAN step does not name either side",
|
||||||
({ commands, inputs, steps }) => {
|
({ commands, inputs, steps }) => {
|
||||||
const data = buildExecute(commands, inputs, 9999999999n);
|
const data = buildExecute(commands, inputs, 9999999999n);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(detail(result, "Steps").value).toBe(steps);
|
expect(detail(result, "Steps").value).toBe(steps);
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
expect(detail(result, "Token In").value).toBe(
|
expect(detail(result, "Token In").value).toBe(
|
||||||
@@ -1046,7 +1101,13 @@ describe("uniswap decoder", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
test("shows the deadline as a UTC date and time", () => {
|
test("shows the deadline as a UTC date and time", () => {
|
||||||
const result = uniswap.decode(FIRST_SWAP_CALLDATA, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
FIRST_SWAP_CALLDATA,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(detail(result, "Deadline").value).toBe("2026-02-27 08:25:51");
|
expect(detail(result, "Deadline").value).toBe("2026-02-27 08:25:51");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1064,7 +1125,7 @@ describe("uniswap decoder", () => {
|
|||||||
2n ** 256n - 1n,
|
2n ** 256n - 1n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result.name).toBe("Swap USDT \u2192 WETH");
|
expect(result.name).toBe("Swap USDT \u2192 WETH");
|
||||||
expect(detail(result, "Deadline").value).toBe(
|
expect(detail(result, "Deadline").value).toBe(
|
||||||
@@ -1079,7 +1140,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
const amount = result.details.find((d) => d.label === "Amount");
|
const amount = result.details.find((d) => d.label === "Amount");
|
||||||
@@ -1154,7 +1215,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
// Before decodeV4Swap fix: name would be "Swap USDT → ETH" or "Uniswap Swap"
|
// Before decodeV4Swap fix: name would be "Swap USDT → ETH" or "Uniswap Swap"
|
||||||
// After fix: correctly identifies both tokens from V4 sub-actions
|
// After fix: correctly identifies both tokens from V4 sub-actions
|
||||||
@@ -1188,7 +1249,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
// The amount and the token it is counted in come from the same hop.
|
// The amount and the token it is counted in come from the same hop.
|
||||||
@@ -1228,7 +1289,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token Out").value).toBe(
|
expect(detail(result, "Token Out").value).toBe(
|
||||||
@@ -1273,7 +1334,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token Out").value).toContain("USDC");
|
expect(detail(result, "Token Out").value).toContain("USDC");
|
||||||
@@ -1302,7 +1363,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token Out").value).toContain("USDC");
|
expect(detail(result, "Token Out").value).toContain("USDC");
|
||||||
@@ -1339,7 +1400,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token In").value).toContain("WETH");
|
expect(detail(result, "Token In").value).toContain("WETH");
|
||||||
@@ -1356,9 +1417,12 @@ describe("uniswap decoder", () => {
|
|||||||
// are written. Each is tried with three endings: SETTLE_ALL and TAKE_ALL,
|
// are written. Each is tried with three endings: SETTLE_ALL and TAKE_ALL,
|
||||||
// SETTLE and TAKE, and CLOSE_CURRENCY for each currency, which leaves the
|
// SETTLE and TAKE, and CLOSE_CURRENCY for each currency, which leaves the
|
||||||
// sides to the swap actions alone.
|
// sides to the swap actions alone.
|
||||||
|
// `minLabel` is the minimum's line: with no TAKE or TAKE_ALL, no step
|
||||||
|
// pays the user, so it is not said to be received.
|
||||||
const V4_STEP_ENDINGS = [
|
const V4_STEP_ENDINGS = [
|
||||||
{
|
{
|
||||||
ending: "SETTLE_ALL and TAKE_ALL",
|
ending: "SETTLE_ALL and TAKE_ALL",
|
||||||
|
minLabel: "Min. received",
|
||||||
ids: [V4_SETTLE_ALL_ID, V4_TAKE_ALL_ID],
|
ids: [V4_SETTLE_ALL_ID, V4_TAKE_ALL_ID],
|
||||||
params: [
|
params: [
|
||||||
encodeV4SettleAll(USDT_ADDR, 1000000000n),
|
encodeV4SettleAll(USDT_ADDR, 1000000000n),
|
||||||
@@ -1367,11 +1431,13 @@ describe("uniswap decoder", () => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
ending: "SETTLE and TAKE",
|
ending: "SETTLE and TAKE",
|
||||||
|
minLabel: "Min. received",
|
||||||
ids: [V4_SETTLE_ID, V4_TAKE_ID],
|
ids: [V4_SETTLE_ID, V4_TAKE_ID],
|
||||||
params: [encodeV4Settle(USDT_ADDR), encodeV4Take(USDC_ADDR)],
|
params: [encodeV4Settle(USDT_ADDR), encodeV4Take(USDC_ADDR)],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ending: "CLOSE_CURRENCY",
|
ending: "CLOSE_CURRENCY",
|
||||||
|
minLabel: "Min. paid out",
|
||||||
ids: [
|
ids: [
|
||||||
V4_CLOSE_CURRENCY_ID,
|
V4_CLOSE_CURRENCY_ID,
|
||||||
V4_CLOSE_CURRENCY_ID,
|
V4_CLOSE_CURRENCY_ID,
|
||||||
@@ -1520,7 +1586,7 @@ describe("uniswap decoder", () => {
|
|||||||
),
|
),
|
||||||
)(
|
)(
|
||||||
"a V4 step of $step, then $ending, reads Swap USDT → USDC",
|
"a V4 step of $step, then $ending, reads Swap USDT → USDC",
|
||||||
({ swaps, ids, params, amount, min }) => {
|
({ swaps, ids, params, amount, min, minLabel }) => {
|
||||||
const data = buildExecute(
|
const data = buildExecute(
|
||||||
"0x10",
|
"0x10",
|
||||||
[
|
[
|
||||||
@@ -1532,12 +1598,18 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(result.name).toBe("Swap USDT → USDC");
|
expect(result.name).toBe("Swap USDT → USDC");
|
||||||
expect(detail(result, "Token In").address).toBe(USDT_ADDR);
|
expect(detail(result, "Token In").address).toBe(USDT_ADDR);
|
||||||
expect(detail(result, "Token Out").address).toBe(USDC_ADDR);
|
expect(detail(result, "Token Out").address).toBe(USDC_ADDR);
|
||||||
expect(detail(result, "Amount")?.value).toBe(amount);
|
expect(detail(result, "Amount")?.value).toBe(amount);
|
||||||
expect(detail(result, "Min. received")?.value).toBe(min);
|
expect(detail(result, minLabel)?.value).toBe(min);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1584,7 +1656,13 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER_ADDR,
|
||||||
|
"0x1",
|
||||||
|
{},
|
||||||
|
USER_ADDR,
|
||||||
|
);
|
||||||
expect(detail(result, "Steps").value).toBe(
|
expect(detail(result, "Steps").value).toBe(
|
||||||
"V4 Swap (could not be decoded)",
|
"V4 Swap (could not be decoded)",
|
||||||
);
|
);
|
||||||
@@ -1643,7 +1721,7 @@ describe("uniswap decoder", () => {
|
|||||||
],
|
],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
expect(detail(result, "Token In").address).toBe(
|
expect(detail(result, "Token In").address).toBe(
|
||||||
USDT_ADDR.toLowerCase(),
|
USDT_ADDR.toLowerCase(),
|
||||||
@@ -1699,7 +1777,7 @@ describe("uniswap decoder", () => {
|
|||||||
],
|
],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
expect(detail(result, "Token In").value).toBe(
|
expect(detail(result, "Token In").value).toBe(
|
||||||
"Unknown (not named in the calldata)",
|
"Unknown (not named in the calldata)",
|
||||||
@@ -1722,7 +1800,7 @@ describe("uniswap decoder", () => {
|
|||||||
],
|
],
|
||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(detail(result, "Token Out").value).toBe(
|
expect(detail(result, "Token Out").value).toBe(
|
||||||
"Unknown (not named in the calldata)",
|
"Unknown (not named in the calldata)",
|
||||||
);
|
);
|
||||||
@@ -1756,7 +1834,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result.name).toBe("Swap USDT → USDC");
|
expect(result.name).toBe("Swap USDT → USDC");
|
||||||
expect(detail(result, "Token In").address).toBe(USDT_ADDR);
|
expect(detail(result, "Token In").address).toBe(USDT_ADDR);
|
||||||
expect(detail(result, "Token Out").address).toBe(USDC_ADDR);
|
expect(detail(result, "Token Out").address).toBe(USDC_ADDR);
|
||||||
@@ -1780,7 +1858,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token In").value).toContain("USDT");
|
expect(detail(result, "Token In").value).toContain("USDT");
|
||||||
@@ -1811,7 +1889,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token Out").value).toContain("WETH");
|
expect(detail(result, "Token Out").value).toContain("WETH");
|
||||||
@@ -1832,7 +1910,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token Out").value).toContain("USDC");
|
expect(detail(result, "Token Out").value).toContain("USDC");
|
||||||
@@ -1840,7 +1918,8 @@ describe("uniswap decoder", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// With no minimum stated before it, a zero balance check is what sets the
|
// With no minimum stated before it, a zero balance check is what sets the
|
||||||
// output side, and it guarantees nothing.
|
// output side, and it guarantees nothing. No step pays anyone, so the
|
||||||
|
// minimum is not said to be received.
|
||||||
test("a zero balance check with no earlier minimum states no minimum", () => {
|
test("a zero balance check with no earlier minimum states no minimum", () => {
|
||||||
const data = buildExecute(
|
const data = buildExecute(
|
||||||
solidityPacked(["uint8", "uint8"], [0x0b, 0x0e]),
|
solidityPacked(["uint8", "uint8"], [0x0b, 0x0e]),
|
||||||
@@ -1851,11 +1930,11 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
|
|
||||||
expect(detail(result, "Token Out").value).toContain("USDT");
|
expect(detail(result, "Token Out").value).toContain("USDT");
|
||||||
expect(detail(result, "Min. received").value).toBe(
|
expect(detail(result, "Min. paid out").value).toBe(
|
||||||
"None (no minimum guaranteed)",
|
"None (no minimum guaranteed)",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -1871,7 +1950,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
|
|
||||||
@@ -1891,7 +1970,7 @@ describe("uniswap decoder", () => {
|
|||||||
9999999999n,
|
9999999999n,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = uniswap.decode(data, ROUTER_ADDR, "0x1");
|
const result = uniswap.decode(data, ROUTER_ADDR, "0x1", {}, USER_ADDR);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result.name).toBe("Uniswap Swap");
|
expect(result.name).toBe("Uniswap Swap");
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,856 @@
|
|||||||
|
// The address a swap's output is paid to
|
||||||
|
// (https://git.eeqj.de/sneak/AutistMask/issues/594).
|
||||||
|
//
|
||||||
|
// Every swap command, SWEEP, WRAP_ETH, UNWRAP_WETH and V4 TAKE names the
|
||||||
|
// address it pays, and TAKE_ALL pays the sender. The decoder read none of
|
||||||
|
// them: a swap whose output went to another address still read "Min.
|
||||||
|
// received", as if the user received it. The router reads address(1) as the
|
||||||
|
// sender and address(2) as the router itself, which holds what it is paid
|
||||||
|
// until a later step pays it out.
|
||||||
|
//
|
||||||
|
// The screens are driven against a minimal DOM stub in the shape
|
||||||
|
// tests/uniswapRouterAddress.test.js uses.
|
||||||
|
|
||||||
|
const { AbiCoder, Interface, solidityPacked } = require("ethers");
|
||||||
|
|
||||||
|
jest.mock("../src/shared/log", () => ({
|
||||||
|
log: {
|
||||||
|
debugf: () => {},
|
||||||
|
infof: () => {},
|
||||||
|
warnf: () => {},
|
||||||
|
errorf: () => {},
|
||||||
|
},
|
||||||
|
debugFetch: async (url) => ({
|
||||||
|
ok: true,
|
||||||
|
json: async () => mockExplorerAnswer(url),
|
||||||
|
}),
|
||||||
|
setRuntimeDebug: () => {},
|
||||||
|
isDebug: () => false,
|
||||||
|
}));
|
||||||
|
|
||||||
|
globalThis.chrome = {
|
||||||
|
storage: { local: { get: async () => ({}), set: async () => {} } },
|
||||||
|
};
|
||||||
|
|
||||||
|
const uniswap = require("../src/shared/uniswap");
|
||||||
|
const { state } = require("../src/shared/state");
|
||||||
|
const approval = require("../src/popup/views/approval");
|
||||||
|
const transactionDetail = require("../src/popup/views/transactionDetail");
|
||||||
|
|
||||||
|
// UniversalRouterV2 on Ethereum Mainnet.
|
||||||
|
const ROUTER = "0x66a9893cc07d91d95644aedd05d03f95e1dba8af";
|
||||||
|
// UniversalRouterV2_1_2 on Ethereum Mainnet, whose mask reads 0x07 and 0x40.
|
||||||
|
const ROUTER_V2_1_2 = "0x23617e59A5925b2A4Bf75d73ff6711cD0b29De85";
|
||||||
|
const USER = "0x66133E8ea0f5D1d612D2502a968757D1048c214a";
|
||||||
|
const OTHER = "0x7777777777777777777777777777777777777777";
|
||||||
|
const MSG_SENDER = "0x0000000000000000000000000000000000000001";
|
||||||
|
const ADDRESS_THIS = "0x0000000000000000000000000000000000000002";
|
||||||
|
const ZERO = "0x0000000000000000000000000000000000000000";
|
||||||
|
|
||||||
|
const USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
|
||||||
|
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
|
||||||
|
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
|
||||||
|
const ONE_WETH = 1000000000000000000n;
|
||||||
|
const USDT_2000 = 2000000000n;
|
||||||
|
const USDC_1990 = 1990000000n;
|
||||||
|
|
||||||
|
// The Paid to line's value when no address can be named.
|
||||||
|
const UNDECODED = "Unknown (could not be decoded)";
|
||||||
|
const UNNAMED = "Unknown (not named in the calldata)";
|
||||||
|
const STAYS_IN_ROUTER =
|
||||||
|
"The router, where it stays (no later step pays it out)";
|
||||||
|
|
||||||
|
const coder = AbiCoder.defaultAbiCoder();
|
||||||
|
const routerIface = new Interface([
|
||||||
|
"function execute(bytes commands, bytes[] inputs, uint256 deadline)",
|
||||||
|
]);
|
||||||
|
|
||||||
|
// execute() of `steps`, each [command, input].
|
||||||
|
function execute(...steps) {
|
||||||
|
const commands = steps.map(([command]) => command);
|
||||||
|
return routerIface.encodeFunctionData("execute", [
|
||||||
|
solidityPacked(
|
||||||
|
commands.map(() => "uint8"),
|
||||||
|
commands,
|
||||||
|
),
|
||||||
|
steps.map(([, input]) => input),
|
||||||
|
9999999999n,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// V2_SWAP_EXACT_IN (0x08) and V2_SWAP_EXACT_OUT (0x09) share one layout.
|
||||||
|
function v2Swap(command, recipient, amount, limit, path, payerIsUser = true) {
|
||||||
|
return [
|
||||||
|
command,
|
||||||
|
coder.encode(
|
||||||
|
["address", "uint256", "uint256", "address[]", "bool"],
|
||||||
|
[recipient, amount, limit, path, payerIsUser],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function v3SwapExactIn(recipient, amountIn, amountOutMin, tokenIn, tokenOut) {
|
||||||
|
return [
|
||||||
|
0x00,
|
||||||
|
coder.encode(
|
||||||
|
["address", "uint256", "uint256", "bytes", "bool"],
|
||||||
|
[
|
||||||
|
recipient,
|
||||||
|
amountIn,
|
||||||
|
amountOutMin,
|
||||||
|
solidityPacked(
|
||||||
|
["address", "uint24", "address"],
|
||||||
|
[tokenIn, 3000, tokenOut],
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function sweep(token, recipient) {
|
||||||
|
return [
|
||||||
|
0x04,
|
||||||
|
coder.encode(["address", "address", "uint256"], [token, recipient, 0n]),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function wrapEth(recipient, amount) {
|
||||||
|
return [0x0b, coder.encode(["address", "uint256"], [recipient, amount])];
|
||||||
|
}
|
||||||
|
|
||||||
|
function unwrapWeth(recipient) {
|
||||||
|
return [0x0c, coder.encode(["address", "uint256"], [recipient, 0n])];
|
||||||
|
}
|
||||||
|
|
||||||
|
function balanceCheck(token, minBalance) {
|
||||||
|
return [
|
||||||
|
0x0e,
|
||||||
|
coder.encode(
|
||||||
|
["address", "address", "uint256"],
|
||||||
|
[USER, token, minBalance],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// `step`, a [command or action, input] pair, with the top byte of the input's
|
||||||
|
// word `index` set. The decoder cannot read that word as an address.
|
||||||
|
function withDirtyWord([id, input], index) {
|
||||||
|
const at = 2 + index * 64;
|
||||||
|
return [id, input.slice(0, at) + "ff" + input.slice(at + 2)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The V4 actions a step below is built from.
|
||||||
|
const SWAP_USDT_FOR_USDC = [
|
||||||
|
0x06, // SWAP_EXACT_IN_SINGLE
|
||||||
|
coder.encode(
|
||||||
|
[
|
||||||
|
"tuple(tuple(address,address,uint24,int24,address),bool,uint128,uint128,bytes)",
|
||||||
|
],
|
||||||
|
[[[USDT, USDC, 100, 1, ZERO], true, USDT_2000, USDC_1990, "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) {
|
||||||
|
return [
|
||||||
|
0x0e,
|
||||||
|
coder.encode(
|
||||||
|
["address", "address", "uint256"],
|
||||||
|
[currency, recipient, 0n],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
function takeAll(currency) {
|
||||||
|
return [0x0f, coder.encode(["address", "uint256"], [currency, 0n])];
|
||||||
|
}
|
||||||
|
|
||||||
|
// A V4_SWAP step of `actions`, each [action, params].
|
||||||
|
function v4Swap(...actions) {
|
||||||
|
return [
|
||||||
|
0x10,
|
||||||
|
coder.encode(
|
||||||
|
["bytes", "bytes[]"],
|
||||||
|
[
|
||||||
|
solidityPacked(
|
||||||
|
actions.map(() => "uint8"),
|
||||||
|
actions.map(([action]) => action),
|
||||||
|
),
|
||||||
|
actions.map(([, params]) => params),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function decode(data, sender = USER, router = ROUTER) {
|
||||||
|
return uniswap.decode(data, router, "0x1", {}, sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
function labels(result) {
|
||||||
|
return result.details.map((d) => d.label);
|
||||||
|
}
|
||||||
|
|
||||||
|
function detail(result, label) {
|
||||||
|
return result.details.find((d) => d.label === label);
|
||||||
|
}
|
||||||
|
|
||||||
|
function paidTo(result) {
|
||||||
|
return result.details
|
||||||
|
.filter((d) => d.label === "Paid to")
|
||||||
|
.map((d) => d.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A swap paid to the user, the lines it has always had.
|
||||||
|
const PAID_TO_USER = [
|
||||||
|
"Protocol",
|
||||||
|
"Token In",
|
||||||
|
"Amount",
|
||||||
|
"Token Out",
|
||||||
|
"Min. received",
|
||||||
|
"Steps",
|
||||||
|
"Deadline",
|
||||||
|
];
|
||||||
|
const PAID_ELSEWHERE = [
|
||||||
|
"Protocol",
|
||||||
|
"Token In",
|
||||||
|
"Amount",
|
||||||
|
"Token Out",
|
||||||
|
"Paid to",
|
||||||
|
"Min. paid out",
|
||||||
|
"Steps",
|
||||||
|
"Deadline",
|
||||||
|
];
|
||||||
|
|
||||||
|
// A swap of 2,000 USDT for at least 1 WETH, paid to `recipient`.
|
||||||
|
const swapToWeth = (recipient) =>
|
||||||
|
v3SwapExactIn(recipient, USDT_2000, ONE_WETH, USDT, WETH);
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
state.trackedTokens = [];
|
||||||
|
state.wallets = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("each swap command's recipient", () => {
|
||||||
|
test.each([
|
||||||
|
{
|
||||||
|
kind: "V2_SWAP_EXACT_IN",
|
||||||
|
data: (r) =>
|
||||||
|
execute(v2Swap(0x08, r, USDT_2000, ONE_WETH, [USDT, WETH])),
|
||||||
|
min: "1.0000 WETH",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "V2_SWAP_EXACT_OUT",
|
||||||
|
data: (r) =>
|
||||||
|
execute(v2Swap(0x09, r, ONE_WETH, USDT_2000, [USDT, WETH])),
|
||||||
|
min: "1.0000 WETH",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "V3_SWAP_EXACT_IN",
|
||||||
|
data: (r) => execute(swapToWeth(r)),
|
||||||
|
min: "1.0000 WETH",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "V4_SWAP with TAKE",
|
||||||
|
data: (r) =>
|
||||||
|
execute(v4Swap(SWAP_USDT_FOR_USDC, SETTLE_USDT, take(USDC, r))),
|
||||||
|
min: "1990.0000 USDC",
|
||||||
|
},
|
||||||
|
])(
|
||||||
|
"$kind: paid to the user it reads as before; paid to another address it names that address",
|
||||||
|
({ data, min }) => {
|
||||||
|
const viaPlaceholder = decode(data(MSG_SENDER));
|
||||||
|
expect(labels(viaPlaceholder)).toEqual(PAID_TO_USER);
|
||||||
|
expect(detail(viaPlaceholder, "Min. received").value).toBe(min);
|
||||||
|
// The sender's own address, in any case, reads the same.
|
||||||
|
expect(decode(data(USER), USER.toLowerCase()).details).toEqual(
|
||||||
|
viaPlaceholder.details,
|
||||||
|
);
|
||||||
|
|
||||||
|
const toOther = decode(data(OTHER));
|
||||||
|
expect(labels(toOther)).toEqual(PAID_ELSEWHERE);
|
||||||
|
expect(paidTo(toOther)).toEqual([OTHER]);
|
||||||
|
expect(detail(toOther, "Min. paid out").value).toBe(min);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("an output the router holds", () => {
|
||||||
|
const toRouter = v3SwapExactIn(
|
||||||
|
ADDRESS_THIS,
|
||||||
|
USDT_2000,
|
||||||
|
USDC_1990,
|
||||||
|
USDT,
|
||||||
|
USDC,
|
||||||
|
);
|
||||||
|
|
||||||
|
test("SWEEP pays it to the SWEEP's recipient", () => {
|
||||||
|
const direct = decode(
|
||||||
|
execute(
|
||||||
|
v3SwapExactIn(MSG_SENDER, USDT_2000, USDC_1990, USDT, USDC),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const toUser = decode(execute(toRouter, sweep(USDC, MSG_SENDER)));
|
||||||
|
expect(labels(toUser)).toEqual(PAID_TO_USER);
|
||||||
|
const withoutSteps = (r) =>
|
||||||
|
r.details.filter((d) => d.label !== "Steps");
|
||||||
|
expect(withoutSteps(toUser)).toEqual(withoutSteps(direct));
|
||||||
|
|
||||||
|
const toOther = decode(execute(toRouter, sweep(USDC, OTHER)));
|
||||||
|
expect(labels(toOther)).toEqual(PAID_ELSEWHERE);
|
||||||
|
expect(paidTo(toOther)).toEqual([OTHER]);
|
||||||
|
expect(detail(toOther, "Min. paid out").value).toBe("1990.0000 USDC");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("with nothing paying it out, it stays in the router", () => {
|
||||||
|
const result = decode(execute(toRouter));
|
||||||
|
expect(labels(result)).toEqual(PAID_ELSEWHERE);
|
||||||
|
expect(paidTo(result)).toEqual([STAYS_IN_ROUTER]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the router's own address as a recipient is read as address(2) is", () => {
|
||||||
|
const toRouterAddress = v3SwapExactIn(
|
||||||
|
ROUTER,
|
||||||
|
USDT_2000,
|
||||||
|
USDC_1990,
|
||||||
|
USDT,
|
||||||
|
USDC,
|
||||||
|
);
|
||||||
|
expect(paidTo(decode(execute(toRouterAddress)))).toEqual([
|
||||||
|
STAYS_IN_ROUTER,
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
labels(decode(execute(toRouterAddress, sweep(USDC, MSG_SENDER)))),
|
||||||
|
).toEqual(PAID_TO_USER);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("UNWRAP_WETH pays its WETH, as ETH, to the UNWRAP_WETH's recipient", () => {
|
||||||
|
const toWeth = swapToWeth(ADDRESS_THIS);
|
||||||
|
|
||||||
|
const toUser = decode(execute(toWeth, unwrapWeth(MSG_SENDER)));
|
||||||
|
expect(labels(toUser)).toEqual(PAID_TO_USER);
|
||||||
|
expect(detail(toUser, "Token Out").value).toBe("ETH");
|
||||||
|
expect(detail(toUser, "Min. received").value).toBe("1.0000 ETH");
|
||||||
|
|
||||||
|
const toOther = decode(execute(toWeth, unwrapWeth(OTHER)));
|
||||||
|
expect(labels(toOther)).toEqual(PAID_ELSEWHERE);
|
||||||
|
expect(paidTo(toOther)).toEqual([OTHER]);
|
||||||
|
expect(detail(toOther, "Min. paid out").value).toBe("1.0000 ETH");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("WRAP_ETH pays its WETH to the WRAP_ETH's recipient", () => {
|
||||||
|
const toUser = decode(
|
||||||
|
execute(wrapEth(ADDRESS_THIS, ONE_WETH), unwrapWeth(MSG_SENDER)),
|
||||||
|
);
|
||||||
|
expect(detail(toUser, "Token Out").value).toBe("ETH");
|
||||||
|
expect(paidTo(toUser)).toEqual([]);
|
||||||
|
|
||||||
|
const toOther = decode(
|
||||||
|
execute(wrapEth(OTHER, ONE_WETH), unwrapWeth(MSG_SENDER)),
|
||||||
|
);
|
||||||
|
expect(paidTo(toOther)).toEqual([OTHER]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a V4 TAKE to the router, then SWEEP, pays the SWEEP's recipient", () => {
|
||||||
|
const step = v4Swap(
|
||||||
|
SWAP_USDT_FOR_USDC,
|
||||||
|
SETTLE_USDT,
|
||||||
|
take(USDC, ADDRESS_THIS),
|
||||||
|
);
|
||||||
|
|
||||||
|
const toUser = decode(execute(step, sweep(USDC, MSG_SENDER)));
|
||||||
|
expect(labels(toUser)).toEqual(PAID_TO_USER);
|
||||||
|
|
||||||
|
const toOther = decode(execute(step, sweep(USDC, OTHER)));
|
||||||
|
expect(labels(toOther)).toEqual(PAID_ELSEWHERE);
|
||||||
|
expect(paidTo(toOther)).toEqual([OTHER]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Only a later SWEEP of the output token, or UNWRAP_WETH of WETH, pays the
|
||||||
|
// router's output out. A payment to the user of another token, of nothing, or
|
||||||
|
// before the swap leaves the output in the router.
|
||||||
|
describe("an output left in the router is not received", () => {
|
||||||
|
const toRouter = swapToWeth(ADDRESS_THIS);
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
{
|
||||||
|
kind: "a SWEEP of WETH to the user, then the swap",
|
||||||
|
data: execute(sweep(WETH, MSG_SENDER), toRouter),
|
||||||
|
min: "1.0000 WETH",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "an UNWRAP_WETH to the user, then the swap",
|
||||||
|
data: execute(unwrapWeth(MSG_SENDER), toRouter),
|
||||||
|
min: "1.0000 ETH",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "the swap, then a WRAP_ETH of zero to the user",
|
||||||
|
data: execute(toRouter, wrapEth(MSG_SENDER, 0n)),
|
||||||
|
min: "1.0000 WETH",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "the swap, then a SWEEP of a token it does not buy to the user",
|
||||||
|
data: execute(toRouter, sweep(USDC, MSG_SENDER)),
|
||||||
|
min: "1.0000 WETH",
|
||||||
|
},
|
||||||
|
])("$kind", ({ data, min }) => {
|
||||||
|
const result = decode(data);
|
||||||
|
expect(labels(result)).toEqual(PAID_ELSEWHERE);
|
||||||
|
expect(paidTo(result)).toEqual([STAYS_IN_ROUTER]);
|
||||||
|
expect(detail(result, "Min. paid out").value).toBe(min);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("one V4 step: a TAKE of what it buys to the router, then a TAKE_ALL of it, which takes nothing", () => {
|
||||||
|
const result = decode(
|
||||||
|
execute(
|
||||||
|
v4Swap(
|
||||||
|
SWAP_USDT_FOR_USDC,
|
||||||
|
SETTLE_USDT,
|
||||||
|
take(USDC, ADDRESS_THIS),
|
||||||
|
takeAll(USDC),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(detail(result, "Steps").value).toBe("V4 Swap");
|
||||||
|
expect(labels(result)).toEqual(PAID_ELSEWHERE);
|
||||||
|
expect(paidTo(result)).toEqual([STAYS_IN_ROUTER]);
|
||||||
|
expect(detail(result, "Min. paid out").value).toBe("1990.0000 USDC");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Uniswap's mixed routes pay a V2 pair directly when the next step swaps
|
||||||
|
// through it. That V2 swap spends what the pair holds: its amountIn is
|
||||||
|
// CONTRACT_BALANCE, paid from the router, or ALREADY_PAID.
|
||||||
|
describe("a swap paid to the pair the next V2 swap spends", () => {
|
||||||
|
const PAIR = "0x5555555555555555555555555555555555555555";
|
||||||
|
const CONTRACT_BALANCE = 2n ** 255n;
|
||||||
|
const swapToPair = v3SwapExactIn(PAIR, USDT_2000, 0n, USDT, WETH);
|
||||||
|
const pairSpends = (amountIn, path) =>
|
||||||
|
v2Swap(0x08, MSG_SENDER, amountIn, USDC_1990, path, false);
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
{ kind: "CONTRACT_BALANCE", amountIn: CONTRACT_BALANCE },
|
||||||
|
{ kind: "ALREADY_PAID", amountIn: 0n },
|
||||||
|
])(
|
||||||
|
"a V3 swap, then a V2 swap whose amountIn is $kind, reads as a swap paid to the user",
|
||||||
|
({ amountIn }) => {
|
||||||
|
const result = decode(
|
||||||
|
execute(swapToPair, pairSpends(amountIn, [WETH, USDC])),
|
||||||
|
);
|
||||||
|
expect(result.name).toBe("Swap USDT → USDC");
|
||||||
|
expect(labels(result)).toEqual(PAID_TO_USER);
|
||||||
|
expect(detail(result, "Amount").value).toBe("2000.0000 USDT");
|
||||||
|
expect(detail(result, "Min. received").value).toBe(
|
||||||
|
"1990.0000 USDC",
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test("a V4 step whose TAKE pays the pair, then the V2 swap, reads the same", () => {
|
||||||
|
const result = decode(
|
||||||
|
execute(
|
||||||
|
v4Swap(SWAP_USDT_FOR_USDC, SETTLE_USDT, take(USDC, PAIR)),
|
||||||
|
v2Swap(
|
||||||
|
0x08,
|
||||||
|
MSG_SENDER,
|
||||||
|
CONTRACT_BALANCE,
|
||||||
|
ONE_WETH,
|
||||||
|
[USDC, WETH],
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(labels(result)).toEqual(PAID_TO_USER);
|
||||||
|
expect(detail(result, "Min. received").value).toBe("1.0000 WETH");
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
{
|
||||||
|
kind: "takes its input from the user",
|
||||||
|
next: v2Swap(0x08, MSG_SENDER, ONE_WETH, USDC_1990, [WETH, USDC]),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "spends another token",
|
||||||
|
next: pairSpends(0n, [USDC, WETH]),
|
||||||
|
},
|
||||||
|
])("when the V2 swap $kind, the pair is named", ({ next }) => {
|
||||||
|
const result = decode(execute(swapToPair, next));
|
||||||
|
expect(paidTo(result)).toEqual([PAIR]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("every step's payee counts, whichever step sets the output", () => {
|
||||||
|
test("TAKE_ALL pays the user; a TAKE to another address beside it is named", () => {
|
||||||
|
const toUser = decode(
|
||||||
|
execute(v4Swap(SWAP_USDT_FOR_USDC, SETTLE_USDT, takeAll(USDC))),
|
||||||
|
);
|
||||||
|
expect(labels(toUser)).toEqual(PAID_TO_USER);
|
||||||
|
|
||||||
|
// TAKE with an amount of zero takes the whole open credit, so
|
||||||
|
// TAKE_ALL after it pays the user nothing.
|
||||||
|
const split = decode(
|
||||||
|
execute(
|
||||||
|
v4Swap(
|
||||||
|
SWAP_USDT_FOR_USDC,
|
||||||
|
SETTLE_USDT,
|
||||||
|
take(USDC, OTHER),
|
||||||
|
takeAll(USDC),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(paidTo(split)).toEqual([OTHER]);
|
||||||
|
expect(detail(split, "Min. received")).toBeUndefined();
|
||||||
|
expect(detail(split, "Min. paid out").value).toBe("1990.0000 USDC");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a swap paid to another address, then a V4 step that only takes the same token", () => {
|
||||||
|
const emptyStep = v4Swap(takeAll(WETH));
|
||||||
|
|
||||||
|
const result = decode(execute(swapToWeth(OTHER), emptyStep));
|
||||||
|
expect(paidTo(result)).toEqual([OTHER]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
|
||||||
|
const checked = decode(
|
||||||
|
execute(swapToWeth(OTHER), emptyStep, balanceCheck(WETH, ONE_WETH)),
|
||||||
|
);
|
||||||
|
expect(paidTo(checked)).toEqual([OTHER]);
|
||||||
|
expect(detail(checked, "Min. received")).toBeUndefined();
|
||||||
|
expect(detail(checked, "Min. paid out").value).toBe("1.0000 WETH");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a swap paid to the router, a V4 step that only takes, then SWEEP to another address", () => {
|
||||||
|
const result = decode(
|
||||||
|
execute(
|
||||||
|
v3SwapExactIn(ADDRESS_THIS, USDT_2000, USDC_1990, USDT, USDC),
|
||||||
|
v4Swap(takeAll(USDC)),
|
||||||
|
sweep(USDC, OTHER),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(paidTo(result)).toEqual([OTHER]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a swap paid to another address, then a small swap paid to the user", () => {
|
||||||
|
const result = decode(
|
||||||
|
execute(
|
||||||
|
swapToWeth(OTHER),
|
||||||
|
v2Swap(0x08, MSG_SENDER, 1000000n, 1n, [USDT, WETH]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(paidTo(result)).toEqual([OTHER]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
expect(detail(result, "Min. paid out")).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("one V4 step: a TAKE of what it buys to another address, then TAKE_ALL of another currency", () => {
|
||||||
|
const result = decode(
|
||||||
|
execute(
|
||||||
|
v4Swap(
|
||||||
|
SWAP_USDT_FOR_USDC,
|
||||||
|
SETTLE_USDT,
|
||||||
|
take(USDC, OTHER),
|
||||||
|
takeAll(USDT),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(paidTo(result)).toEqual([OTHER]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("a payout that cannot be read is never said to be received", () => {
|
||||||
|
test("a V4 TAKE whose recipient word has its top byte set", () => {
|
||||||
|
const result = decode(
|
||||||
|
execute(
|
||||||
|
v4Swap(
|
||||||
|
SWAP_USDT_FOR_USDC,
|
||||||
|
SETTLE_USDT,
|
||||||
|
withDirtyWord(take(USDC, OTHER), 1),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(paidTo(result)).toEqual([UNDECODED]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
expect(detail(result, "Min. paid out").value).toBe("1990.0000 USDC");
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
{
|
||||||
|
kind: "V2_SWAP_EXACT_IN",
|
||||||
|
step: v2Swap(0x08, OTHER, 1n, 1n, [USDT, WETH]),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "V2_SWAP_EXACT_OUT",
|
||||||
|
step: v2Swap(0x09, OTHER, 1n, 1n, [USDT, WETH]),
|
||||||
|
},
|
||||||
|
{ kind: "V3_SWAP_EXACT_IN", step: swapToWeth(OTHER) },
|
||||||
|
{ kind: "SWEEP", step: sweep(WETH, OTHER), word: 1 },
|
||||||
|
{ kind: "WRAP_ETH", step: wrapEth(OTHER, 1n) },
|
||||||
|
{ kind: "UNWRAP_WETH", step: unwrapWeth(OTHER) },
|
||||||
|
])(
|
||||||
|
"a $kind whose recipient word has its top byte set",
|
||||||
|
({ step, word = 0 }) => {
|
||||||
|
const result = decode(
|
||||||
|
execute(swapToWeth(MSG_SENDER), withDirtyWord(step, word)),
|
||||||
|
);
|
||||||
|
expect(paidTo(result)).toEqual([UNDECODED]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
expect(detail(result, "Min. paid out")).toBeDefined();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// The router reads only the low 32 bits of the action list's length, so
|
||||||
|
// the step still runs, and may pay anyone.
|
||||||
|
test("a V4_SWAP whose action list's length word has its top byte set", () => {
|
||||||
|
const step = v4Swap(SWAP_USDT_FOR_USDC, SETTLE_USDT, take(USDC, OTHER));
|
||||||
|
const result = decode(
|
||||||
|
execute(swapToWeth(MSG_SENDER), withDirtyWord(step, 2)),
|
||||||
|
);
|
||||||
|
expect(paidTo(result)).toEqual([UNDECODED]);
|
||||||
|
expect(detail(result, "Min. paid out").value).toBe("1.0000 WETH");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an output set only by BALANCE_CHECK_ERC20", () => {
|
||||||
|
const result = decode(execute(balanceCheck(WETH, ONE_WETH)));
|
||||||
|
expect(paidTo(result)).toEqual([UNNAMED]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
expect(detail(result, "Min. paid out").value).toBe("1.0000 WETH");
|
||||||
|
});
|
||||||
|
|
||||||
|
// https://git.eeqj.de/sneak/AutistMask/issues/599 is to read these. Until
|
||||||
|
// then each is a payout this decoder does not read.
|
||||||
|
const transferShape = (command) => [
|
||||||
|
command,
|
||||||
|
coder.encode(["address", "address", "uint256"], [WETH, OTHER, 1n]),
|
||||||
|
];
|
||||||
|
test.each([
|
||||||
|
{ kind: "PERMIT2_TRANSFER_FROM", step: transferShape(0x02) },
|
||||||
|
{ kind: "TRANSFER", step: transferShape(0x05) },
|
||||||
|
{ kind: "PAY_PORTION", step: transferShape(0x06) },
|
||||||
|
{ kind: "PAY_PORTION_FULL_PRECISION", step: transferShape(0x07) },
|
||||||
|
{
|
||||||
|
kind: "PERMIT2_TRANSFER_FROM_BATCH",
|
||||||
|
step: [
|
||||||
|
0x0d,
|
||||||
|
coder.encode(
|
||||||
|
["tuple(address,address,uint160,address)[]"],
|
||||||
|
[[[USER, OTHER, 1n, WETH]]],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "V3_SWAP_EXACT_OUT",
|
||||||
|
step: [0x01, swapToWeth(OTHER)[1]],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "EXECUTE_SUB_PLAN",
|
||||||
|
step: [
|
||||||
|
0x21,
|
||||||
|
coder.encode(
|
||||||
|
["bytes", "bytes[]"],
|
||||||
|
["0x05", [transferShape(0x05)[1]]],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "ACROSS_V4_DEPOSIT_V3",
|
||||||
|
step: [0x40, coder.encode(["address"], [OTHER])],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: "V4 TAKE_PORTION",
|
||||||
|
step: v4Swap([
|
||||||
|
0x10,
|
||||||
|
coder.encode(
|
||||||
|
["address", "address", "uint256"],
|
||||||
|
[WETH, OTHER, 10000n],
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
])("a swap paid to the user, then $kind", ({ step }) => {
|
||||||
|
const result = decode(
|
||||||
|
execute(swapToWeth(MSG_SENDER), step),
|
||||||
|
USER,
|
||||||
|
ROUTER_V2_1_2,
|
||||||
|
);
|
||||||
|
expect(paidTo(result)).toEqual([UNDECODED]);
|
||||||
|
expect(detail(result, "Min. received")).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("paths whose recipients were untested", () => {
|
||||||
|
test("BALANCE_CHECK_ERC20 after a swap leaves who is paid as the swap says", () => {
|
||||||
|
const check = balanceCheck(WETH, ONE_WETH);
|
||||||
|
|
||||||
|
const toUser = decode(execute(swapToWeth(MSG_SENDER), check));
|
||||||
|
expect(paidTo(toUser)).toEqual([]);
|
||||||
|
expect(detail(toUser, "Min. received").value).toBe("1.0000 WETH");
|
||||||
|
|
||||||
|
const toOther = decode(execute(swapToWeth(OTHER), check));
|
||||||
|
expect(paidTo(toOther)).toEqual([OTHER]);
|
||||||
|
expect(detail(toOther, "Min. paid out").value).toBe("1.0000 WETH");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a V4 step whose swap action cannot be read still has its TAKE read", () => {
|
||||||
|
const step = (r) => v4Swap(UNREADABLE_SWAP, SETTLE_USDT, take(USDC, r));
|
||||||
|
|
||||||
|
const toUser = decode(execute(step(MSG_SENDER)));
|
||||||
|
expect(detail(toUser, "Steps").value).toBe(
|
||||||
|
"V4 Swap (could not be decoded)",
|
||||||
|
);
|
||||||
|
expect(paidTo(toUser)).toEqual([]);
|
||||||
|
|
||||||
|
expect(paidTo(decode(execute(step(OTHER))))).toEqual([OTHER]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The DOM stub both screens are drawn into.
|
||||||
|
function makeElement(id) {
|
||||||
|
const classes = new Set();
|
||||||
|
const el = {
|
||||||
|
id,
|
||||||
|
textContent: "",
|
||||||
|
value: "",
|
||||||
|
innerHTML: "",
|
||||||
|
style: {},
|
||||||
|
dataset: {},
|
||||||
|
classList: {
|
||||||
|
add: (...names) => names.forEach((n) => classes.add(n)),
|
||||||
|
remove: (...names) => names.forEach((n) => classes.delete(n)),
|
||||||
|
contains: (n) => classes.has(n),
|
||||||
|
toggle: () => false,
|
||||||
|
},
|
||||||
|
addEventListener: () => {},
|
||||||
|
querySelectorAll: () => [],
|
||||||
|
appendChild: () => {},
|
||||||
|
};
|
||||||
|
Object.defineProperty(el, "parentElement", {
|
||||||
|
get: () => node(id + "-parent"),
|
||||||
|
});
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeDocument() {
|
||||||
|
const els = new Map();
|
||||||
|
return {
|
||||||
|
getElementById(id) {
|
||||||
|
if (id === "debug-banner") return null;
|
||||||
|
if (!els.has(id)) els.set(id, makeElement(id));
|
||||||
|
return els.get(id);
|
||||||
|
},
|
||||||
|
createElement: () => makeElement("created"),
|
||||||
|
body: { prepend: () => {} },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function node(id) {
|
||||||
|
return globalThis.document.getElementById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A swap of 2,000 USDT for at least 1 WETH, paid to `recipient`.
|
||||||
|
const swapPaidTo = (recipient) => execute(swapToWeth(recipient));
|
||||||
|
|
||||||
|
// Open the approval screen for a transaction from USER sending `data` to the
|
||||||
|
// router.
|
||||||
|
async function showApproval(data) {
|
||||||
|
globalThis.document = makeDocument();
|
||||||
|
globalThis.window = { location: { search: "" }, close: () => {} };
|
||||||
|
globalThis.chrome.runtime = {
|
||||||
|
connect: () => ({ postMessage: () => {} }),
|
||||||
|
sendMessage: (_msg, reply) =>
|
||||||
|
reply({
|
||||||
|
type: "tx",
|
||||||
|
origin: "https://dapp.example",
|
||||||
|
isPhishingDomain: false,
|
||||||
|
approvedFrom: USER,
|
||||||
|
approvedTx: {
|
||||||
|
type: 2,
|
||||||
|
from: USER,
|
||||||
|
chainId: "0x1",
|
||||||
|
nonce: "0x7",
|
||||||
|
gasLimit: "0x30d40",
|
||||||
|
maxPriorityFeePerGas: "0x3b9aca00",
|
||||||
|
maxFeePerGas: "0x77359400",
|
||||||
|
to: ROUTER,
|
||||||
|
value: "0x0",
|
||||||
|
data,
|
||||||
|
accessList: [],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
state.networkId = "mainnet";
|
||||||
|
state.currentView = null;
|
||||||
|
await approval.show(1);
|
||||||
|
return node("approve-tx-decoded-details").innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The transaction the explorer reports: from USER, sending `mockSentData` to
|
||||||
|
// the router.
|
||||||
|
const TX_HASH = "0x" + "5".repeat(64);
|
||||||
|
let mockSentData = null;
|
||||||
|
|
||||||
|
function mockExplorerAnswer(url) {
|
||||||
|
if (url.endsWith("/transactions/" + TX_HASH)) {
|
||||||
|
return {
|
||||||
|
from: { hash: USER },
|
||||||
|
to: { hash: ROUTER },
|
||||||
|
raw_input: mockSentData,
|
||||||
|
method: "execute",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open the transaction detail screen for that transaction, sending `data`.
|
||||||
|
async function showDetail(data) {
|
||||||
|
mockSentData = data;
|
||||||
|
globalThis.document = makeDocument();
|
||||||
|
globalThis.window = { location: { search: "" } };
|
||||||
|
state.networkId = "mainnet";
|
||||||
|
state.blockscoutUrl = "https://explorer.example/api/v2";
|
||||||
|
state.viewData = {};
|
||||||
|
state.viewStack = [];
|
||||||
|
state.currentView = null;
|
||||||
|
transactionDetail.show({
|
||||||
|
hash: TX_HASH,
|
||||||
|
from: USER,
|
||||||
|
to: ROUTER,
|
||||||
|
value: "",
|
||||||
|
symbol: "ETH",
|
||||||
|
timestamp: 1790000000,
|
||||||
|
isError: false,
|
||||||
|
direction: "contract",
|
||||||
|
directionLabel: "Swap",
|
||||||
|
method: "execute",
|
||||||
|
chainId: "0x1",
|
||||||
|
});
|
||||||
|
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
|
||||||
|
return node("tx-detail-calldata-details").innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("the screens judge the output against the transaction's sender", () => {
|
||||||
|
test("the approval screen, against its From address", async () => {
|
||||||
|
const toUser = await showApproval(swapPaidTo(USER));
|
||||||
|
expect(toUser).toContain("Min. received");
|
||||||
|
expect(toUser).not.toContain("Paid to");
|
||||||
|
|
||||||
|
const toOther = await showApproval(swapPaidTo(OTHER));
|
||||||
|
expect(toOther).toContain("Paid to");
|
||||||
|
expect(toOther).toContain(OTHER);
|
||||||
|
expect(toOther).not.toContain("Min. received");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the transaction detail screen, against the sender the explorer reports", async () => {
|
||||||
|
const toUser = await showDetail(swapPaidTo(USER));
|
||||||
|
expect(toUser).toContain("Min. received");
|
||||||
|
expect(toUser).not.toContain("Paid to");
|
||||||
|
|
||||||
|
const toOther = await showDetail(swapPaidTo(OTHER));
|
||||||
|
expect(toOther).toContain("Paid to");
|
||||||
|
expect(toOther).not.toContain("Min. received");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -53,7 +53,14 @@ function unwrapData() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function detail(data, label, sources) {
|
function detail(data, label, sources) {
|
||||||
const decoded = uniswap.decode(data, ROUTER, "0x1", sources || {});
|
// Sent by the address the swap pays, so the output is the user's.
|
||||||
|
const decoded = uniswap.decode(
|
||||||
|
data,
|
||||||
|
ROUTER,
|
||||||
|
"0x1",
|
||||||
|
sources || {},
|
||||||
|
RECIPIENT,
|
||||||
|
);
|
||||||
return decoded.details.find((d) => d.label === label);
|
return decoded.details.find((d) => d.label === label);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ function detail(data, label) {
|
|||||||
describe("an execute() whose input currency never decoded", () => {
|
describe("an execute() whose input currency never decoded", () => {
|
||||||
// A V4_SWAP whose sub-action params do not decode — an action encoding
|
// A V4_SWAP whose sub-action params do not decode — an action encoding
|
||||||
// this decoder does not know — leaves every V4 token null. The
|
// this decoder does not know — leaves every V4 token null. The
|
||||||
// BALANCE_CHECK still names the output, so the screen has a Min. received
|
// BALANCE_CHECK still names the output, so the screen has a minimum
|
||||||
// figure and a Token Out, and previously claimed the user was paying ETH
|
// figure and a Token Out, and previously claimed the user was paying ETH
|
||||||
// for them.
|
// for them.
|
||||||
const data = () =>
|
const data = () =>
|
||||||
@@ -132,7 +132,8 @@ describe("an execute() that names only an output token", () => {
|
|||||||
|
|
||||||
test("still states the output it did establish", () => {
|
test("still states the output it did establish", () => {
|
||||||
expect(detail(data(), "Token Out").value).toContain("USDT");
|
expect(detail(data(), "Token Out").value).toContain("USDT");
|
||||||
expect(detail(data(), "Min. received").value).toBe("2.0000 USDT");
|
// No step pays anyone, so the minimum is not said to be received.
|
||||||
|
expect(detail(data(), "Min. paid out").value).toBe("2.0000 USDT");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -105,7 +105,7 @@ function v3ExactIn(tokenIn, tokenOut, amountIn, amountOutMin) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function detail(data, label) {
|
function detail(data, label) {
|
||||||
const decoded = uniswap.decode(data, ROUTER, "0x1", {});
|
const decoded = uniswap.decode(data, ROUTER, "0x1", {}, USER);
|
||||||
expect(decoded).not.toBeNull();
|
expect(decoded).not.toBeNull();
|
||||||
return decoded.details.find((d) => d.label === label);
|
return decoded.details.find((d) => d.label === label);
|
||||||
}
|
}
|
||||||
@@ -134,7 +134,9 @@ describe("a V4 step that states a Min. received but no output currency", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("refuses to scale Min. received rather than assuming 18", () => {
|
test("refuses to scale Min. received rather than assuming 18", () => {
|
||||||
expect(detail(data(), "Min. received").value).toBe(
|
// With no TAKE, no step pays the user either, so the line is not
|
||||||
|
// labelled received.
|
||||||
|
expect(detail(data(), "Min. paid out").value).toBe(
|
||||||
unknownDecimalsAmount(MIN_OUT),
|
unknownDecimalsAmount(MIN_OUT),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -82,7 +82,8 @@ function walletsHolding(token, decimals) {
|
|||||||
// decodeCalldata() rather than uniswap.decode() directly, because the scale
|
// decodeCalldata() rather than uniswap.decode() directly, because the scale
|
||||||
// sources the screen supplies are part of what is under test.
|
// sources the screen supplies are part of what is under test.
|
||||||
function swapDetail(data, label) {
|
function swapDetail(data, label) {
|
||||||
const decoded = decodeCalldata(data, ROUTER, "0x1");
|
// Sent by the address the swap pays, so the output is the user's.
|
||||||
|
const decoded = decodeCalldata(data, ROUTER, "0x1", RECIPIENT);
|
||||||
return decoded.details.find((d) => d.label === label);
|
return decoded.details.find((d) => d.label === label);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,8 @@ jest.mock("../src/shared/log", () => ({
|
|||||||
|
|
||||||
// Everything the confirmation screen would reach the network for. The gas
|
// Everything the confirmation screen would reach the network for. The gas
|
||||||
// estimate is the point: with a usable scale it must succeed, so that a failure
|
// estimate is the point: with a usable scale it must succeed, so that a failure
|
||||||
// in these tests is a failure of the scale and not of the stub.
|
// in these tests is a failure of the scale and not of the stub. The address
|
||||||
|
// holds the 1 ETH the wallets below record, and `tokenUnits` of the token.
|
||||||
const mockProvider = {
|
const mockProvider = {
|
||||||
getFeeData: async () => ({
|
getFeeData: async () => ({
|
||||||
maxFeePerGas: 2000000000n,
|
maxFeePerGas: 2000000000n,
|
||||||
@@ -48,7 +49,14 @@ const mockProvider = {
|
|||||||
estimateGas: async () => 21000n,
|
estimateGas: async () => 21000n,
|
||||||
getCode: async () => "0x",
|
getCode: async () => "0x",
|
||||||
getTransactionCount: async () => 1,
|
getTransactionCount: async () => 1,
|
||||||
getBalance: async () => 0n,
|
getBalance: async () => 1000000000000000000n,
|
||||||
|
tokenUnits: 0n,
|
||||||
|
// The one contract call the screen makes, balanceOf().
|
||||||
|
call: async () =>
|
||||||
|
AbiCoder.defaultAbiCoder().encode(
|
||||||
|
["uint256"],
|
||||||
|
[mockProvider.tokenUnits],
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
jest.mock("../src/shared/balances", () => {
|
jest.mock("../src/shared/balances", () => {
|
||||||
@@ -114,7 +122,7 @@ global.document = {
|
|||||||
};
|
};
|
||||||
global.navigator = { clipboard: { writeText() {} } };
|
global.navigator = { clipboard: { writeText() {} } };
|
||||||
|
|
||||||
const { parseUnits } = require("ethers");
|
const { AbiCoder, parseUnits } = require("ethers");
|
||||||
const { fetchTokenBalances } = require("../src/shared/balances");
|
const { fetchTokenBalances } = require("../src/shared/balances");
|
||||||
const { debugFetch } = require("../src/shared/log");
|
const { debugFetch } = require("../src/shared/log");
|
||||||
const { state } = require("../src/shared/state");
|
const { state } = require("../src/shared/state");
|
||||||
@@ -155,8 +163,9 @@ function row(token = {}, value = FIVE_WETH) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the explorer's rows through the real fetcher and put them exactly where
|
// Fetch the explorer's rows through the real fetcher and put them exactly where
|
||||||
// refreshBalances() puts them.
|
// refreshBalances() puts them. The node reports the holding the explorer does.
|
||||||
async function fetchOnto(items) {
|
async function fetchOnto(items) {
|
||||||
|
mockProvider.tokenUnits = BigInt(items[0].value);
|
||||||
debugFetch.mockImplementation(async () => ({
|
debugFetch.mockImplementation(async () => ({
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -181,6 +190,7 @@ async function fetchOnto(items) {
|
|||||||
// is from the first. Two addresses is what it takes to reach
|
// is from the first. Two addresses is what it takes to reach
|
||||||
// explorerDecimals()'s disagreement check, which is only reachable across rows.
|
// explorerDecimals()'s disagreement check, which is only reachable across rows.
|
||||||
async function fetchOntoBoth(itemsA, itemsB) {
|
async function fetchOntoBoth(itemsA, itemsB) {
|
||||||
|
mockProvider.tokenUnits = BigInt(itemsA[0].value);
|
||||||
debugFetch.mockImplementation(async () => ({
|
debugFetch.mockImplementation(async () => ({
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -239,6 +249,12 @@ function errors() {
|
|||||||
return el("confirm-errors").innerHTML;
|
return el("confirm-errors").innerHTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The message for an amount the balance does not cover, while it is shown.
|
||||||
|
function balanceError() {
|
||||||
|
const box = el("confirm-balance-error");
|
||||||
|
return box.style.visibility === "visible" ? box.textContent : "";
|
||||||
|
}
|
||||||
|
|
||||||
function sendDisabled() {
|
function sendDisabled() {
|
||||||
return el("btn-confirm-send").disabled;
|
return el("btn-confirm-send").disabled;
|
||||||
}
|
}
|
||||||
@@ -270,7 +286,6 @@ describe("the Send screen resolves the scale rather than reading the stored one"
|
|||||||
const txInfo = await reviewSend(WETH, "1.5");
|
const txInfo = await reviewSend(WETH, "1.5");
|
||||||
expect(txInfo.tokenDecimals).toBe(18);
|
expect(txInfo.tokenDecimals).toBe(18);
|
||||||
expect(txInfo.tokenDecimals).not.toBe(balances[0].decimals);
|
expect(txInfo.tokenDecimals).not.toBe(balances[0].decimals);
|
||||||
expect(txInfo.tokenBalance).toBe("5.0");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("that scale estimates a fee and leaves Send enabled", async () => {
|
test("that scale estimates a fee and leaves Send enabled", async () => {
|
||||||
@@ -307,11 +322,10 @@ describe("the Send screen resolves the scale rather than reading the stored one"
|
|||||||
// No fallback was introduced: resolution answers null here, and the
|
// No fallback was introduced: resolution answers null here, and the
|
||||||
// null is what goes forward.
|
// null is what goes forward.
|
||||||
expect(txInfo.tokenDecimals).toBeNull();
|
expect(txInfo.tokenDecimals).toBeNull();
|
||||||
expect(txInfo.tokenBalance).toBeNull();
|
|
||||||
confirmTx.show(txInfo);
|
confirmTx.show(txInfo);
|
||||||
await settle();
|
await settle();
|
||||||
expect(text("confirm-balance")).toBe("unknown (NOVEL)");
|
expect(text("confirm-balance")).toBe("unknown (NOVEL)");
|
||||||
expect(errors()).toContain("This token's balance is unknown");
|
expect(balanceError()).toContain("This token's balance is unknown");
|
||||||
expect(sendDisabled()).toBe(true);
|
expect(sendDisabled()).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -355,7 +369,8 @@ describe("a scale the explorer's own rows disagree about", () => {
|
|||||||
const txInfo = await reviewSend(NOVEL, "1.5");
|
const txInfo = await reviewSend(NOVEL, "1.5");
|
||||||
expect(txInfo.tokenDecimals).toBeNull();
|
expect(txInfo.tokenDecimals).toBeNull();
|
||||||
// The regression this closes: null scale alongside a non-null balance.
|
// The regression this closes: null scale alongside a non-null balance.
|
||||||
expect(txInfo.tokenBalance).toBeNull();
|
send.updateSendBalance();
|
||||||
|
expect(text("send-balance")).toBe("Current balance: unknown (NOVEL)");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("so the user is told the balance is unknown, not only that the fee failed", async () => {
|
test("so the user is told the balance is unknown, not only that the fee failed", async () => {
|
||||||
@@ -367,8 +382,7 @@ describe("a scale the explorer's own rows disagree about", () => {
|
|||||||
// confirm-fee-unknown-error — "the network fee could not be
|
// confirm-fee-unknown-error — "the network fee could not be
|
||||||
// estimated... please go back and try again" — as the only explanation
|
// estimated... please go back and try again" — as the only explanation
|
||||||
// for a screen that can never proceed.
|
// for a screen that can never proceed.
|
||||||
expect(errors()).not.toBe("");
|
expect(balanceError()).toContain("This token's balance is unknown");
|
||||||
expect(errors()).toContain("This token's balance is unknown");
|
|
||||||
expect(text("confirm-balance")).toBe("unknown (NOVEL)");
|
expect(text("confirm-balance")).toBe("unknown (NOVEL)");
|
||||||
expect(sendDisabled()).toBe(true);
|
expect(sendDisabled()).toBe(true);
|
||||||
// The fee line still reports the estimate as unavailable, because it
|
// The fee line still reports the estimate as unavailable, because it
|
||||||
@@ -434,31 +448,20 @@ describe("a scale the explorer's own rows disagree about", () => {
|
|||||||
expect(text("send-balance")).toBe("Current balance: 5.0000 NOVEL");
|
expect(text("send-balance")).toBe("Current balance: 5.0000 NOVEL");
|
||||||
const txInfo = await reviewSend(NOVEL, "1.5");
|
const txInfo = await reviewSend(NOVEL, "1.5");
|
||||||
expect(txInfo.tokenDecimals).toBe(6);
|
expect(txInfo.tokenDecimals).toBe(6);
|
||||||
expect(txInfo.tokenBalance).toBe("5.0");
|
|
||||||
confirmTx.show(txInfo);
|
confirmTx.show(txInfo);
|
||||||
await settle();
|
await settle();
|
||||||
expect(text("confirm-balance")).toBe("5.0000 NOVEL");
|
expect(text("confirm-balance")).toBe("5.0000 NOVEL");
|
||||||
expect(errors()).toBe("");
|
expect(errors()).toBe("");
|
||||||
|
expect(balanceError()).toBe("");
|
||||||
expect(sendDisabled()).toBe(false);
|
expect(sendDisabled()).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("the confirmation screen tells an unknown balance from a zero one", () => {
|
describe("the confirmation screen tells an unknown balance from a zero one", () => {
|
||||||
function txInfo(tokenBalance) {
|
// A send of 1.5 NOVEL from an address the node reports none of, with the
|
||||||
return {
|
// token's scale `tokenDecimals`, or null for a scale nobody knows.
|
||||||
from: HOLDER,
|
async function render(tokenDecimals) {
|
||||||
to: RECIPIENT,
|
mockProvider.tokenUnits = 0n;
|
||||||
ensName: null,
|
|
||||||
amount: "1.5",
|
|
||||||
token: NOVEL,
|
|
||||||
balance: "1.0",
|
|
||||||
tokenSymbol: "NOVEL",
|
|
||||||
tokenBalance,
|
|
||||||
tokenDecimals: tokenBalance === null ? null : 18,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function render(tokenBalance) {
|
|
||||||
state.wallets = [
|
state.wallets = [
|
||||||
{
|
{
|
||||||
name: "Wallet 1",
|
name: "Wallet 1",
|
||||||
@@ -469,30 +472,40 @@ describe("the confirmation screen tells an unknown balance from a zero one", ()
|
|||||||
];
|
];
|
||||||
state.selectedWallet = 0;
|
state.selectedWallet = 0;
|
||||||
state.selectedAddress = 0;
|
state.selectedAddress = 0;
|
||||||
confirmTx.show(txInfo(tokenBalance));
|
confirmTx.show({
|
||||||
|
from: HOLDER,
|
||||||
|
to: RECIPIENT,
|
||||||
|
ensName: null,
|
||||||
|
amount: "1.5",
|
||||||
|
token: NOVEL,
|
||||||
|
tokenSymbol: "NOVEL",
|
||||||
|
tokenDecimals,
|
||||||
|
});
|
||||||
await settle();
|
await settle();
|
||||||
return { balance: text("confirm-balance"), errors: errors() };
|
return { balance: text("confirm-balance"), message: balanceError() };
|
||||||
}
|
}
|
||||||
|
|
||||||
test("the balance line states unknown rather than a quantity of zero", async () => {
|
test("the balance line states unknown rather than a quantity of zero", async () => {
|
||||||
const unknown = await render(null);
|
const unknown = await render(null);
|
||||||
const zero = await render("0.0");
|
const zero = await render(18);
|
||||||
expect(unknown.balance).not.toBe(zero.balance);
|
expect(unknown.balance).not.toBe(zero.balance);
|
||||||
expect(unknown.balance).toBe("unknown (NOVEL)");
|
expect(unknown.balance).toBe("unknown (NOVEL)");
|
||||||
expect(zero.balance).toBe("0.0000 NOVEL");
|
expect(zero.balance).toBe("0.0000 NOVEL");
|
||||||
});
|
});
|
||||||
|
|
||||||
// Both hit INSUFFICIENT_TOKEN — an unknown balance is treated as nothing to
|
// Both hit INSUFFICIENT_TOKEN — an unknown balance is treated as nothing to
|
||||||
// spend from, which is the fail-closed side — but "you have 0.0" is a claim
|
// spend from, which is the fail-closed side — but "your balance does not
|
||||||
// about the holding, and this one has no established quantity to claim.
|
// cover this amount" is a claim about the holding, and this one has no
|
||||||
test("the insufficient-balance message names the reason, not a figure", async () => {
|
// established quantity to claim.
|
||||||
|
test("the insufficient-balance message names the reason, not a shortfall", async () => {
|
||||||
const unknown = await render(null);
|
const unknown = await render(null);
|
||||||
const zero = await render("0.0");
|
const zero = await render(18);
|
||||||
expect(unknown.errors).not.toBe(zero.errors);
|
expect(unknown.message).toContain("This token's balance is unknown");
|
||||||
expect(unknown.errors).toContain("This token's balance is unknown");
|
expect(unknown.message).not.toContain("does not cover");
|
||||||
expect(unknown.errors).not.toContain("You have");
|
expect(zero.message).toBe(
|
||||||
expect(zero.errors).toContain("You have 0.0000 NOVEL");
|
"Your NOVEL balance does not cover this amount. Please go back and" +
|
||||||
expect(zero.errors).not.toContain("balance is unknown");
|
" send a smaller amount.",
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user