2 Commits
Author SHA1 Message Date
sneak 6aa65ccdc6 fix: the swap decoder reads who the router's transfer commands pay (closes #599)
check / check (push) Waiting to run
e2e / e2e-chrome (push) Waiting to run
e2e / e2e-firefox (push) Waiting to run
TRANSFER, PAY_PORTION, PAY_PORTION_FULL_PRECISION (0x07, on the routers with
the 0x7f mask), PERMIT2_TRANSFER_FROM, ACROSS_V4_DEPOSIT_V3 (0x40) and V4
TAKE_PORTION were payouts the decoder did not read, so a swap using one read
Min. paid out with an unknown payee. Each recipient is now read: the sender,
the router, a hop into the next V2 pair, or another address, which is named.
Paying all the router holds of a token pays it out as SWEEP does. A
PERMIT2_TRANSFER_FROM into the router is shown with the amount it moves, and a
bridge deposit names the bridge and each of its recipient and depositor that
is not the sender; either keeps the minimum from reading received.

Model: opus-5-5
2026-10-19 11:06:10 +00:00
clawbot 20e4f1652f fix: a recipient warning on the confirmation screen is about the recipient on screen (closes #575)
check / check (push) Waiting to run
e2e / e2e-chrome (push) Waiting to run
e2e / e2e-firefox (push) Waiting to run
checkRecipientHistory() showed the warning boxes whenever its lookups
answered, so after Back and a review to another recipient, a late answer
about the first recipient could show the never-sent-a-transaction, contract
or Etherscan phishing box on the second recipient's screen. It now drops a
result for a transaction no longer on screen, as estimateGas() and
readBalances() already do.

tests/confirmTxLateResult.test.js holds back the first screen's answer until
the second screen is shown, for each of the three boxes, the balance read and
the fee estimate.

Model: opus-5-5
2026-10-19 12:27:09 +02:00
5 changed files with 616 additions and 71 deletions
+42 -30
View File
@@ -2973,40 +2973,52 @@ Currently supported:
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. `UniversalRouterV1` alone pays a `PERMIT2_TRANSFER_FROM` to `address(1)`
or `address(2)` as those addresses, and the decoder names them. When a swap
or `address(2)` as those addresses, and the decoder names them. A
`PERMIT2_TRANSFER_FROM` into the router is named with the amount it moves,
because the decoder does not check that later steps spend all of it.
`ACROSS_V4_DEPOSIT_V3` pays the bridge, which pays the deposit's recipient on
another network and refunds a deposit nobody fills to its depositor; the
router passes both on as written, so `address(1)` and `address(2)` there are
addresses, and each that is not the transaction's sender is named. When a swap
step, `TAKE` or `TAKE_PORTION` pays the router the swap's output token, the
output stays in the router unless a later step pays all the router holds of it
to anyone but the router: a `SWEEP` of that token, an `UNWRAP_WETH` when it is
WETH, or a `TRANSFER` of `CONTRACT_BALANCE`, a `PAY_PORTION` of 10,000 bips or
a `PAY_PORTION_FULL_PRECISION` of 1e18 of that token. A step paying a token to
the V2 pair that the very next step spends, as a V2 exact-in of that 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. The decoder checks that the address paid is
that pair, deriving it from the V2 factory and pair init code hash the
network's routers were deployed with and the first two tokens of that step's
path; a payment to any other address is named. (Sepolia's
`UniversalRouterV1_2_V2Support` was deployed with placeholders for both
values, so no V2 swap step can succeed on that router.) Every other payment
counts, in whichever step and of whatever token, a share of the output
included: an interface fee paid to another address by `PAY_PORTION`,
`TRANSFER` or `TAKE_PORTION` is named, and the minimum reads `Min. paid out`,
because the swap's minimum includes the fee. 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
WETH, a `TRANSFER` of `CONTRACT_BALANCE`, a `PAY_PORTION` of 10,000 bips or a
`PAY_PORTION_FULL_PRECISION` of 1e18 of that token, or an
`ACROSS_V4_DEPOSIT_V3` of `CONTRACT_BALANCE` of that token, or of ETH when it
sets `useNative`. A step paying a token to the V2 pair that the very next step
spends, as a V2 exact-in of that 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. The decoder checks that the address paid is that pair, deriving it
from the V2 factory and pair init code hash the network's routers were
deployed with and the first two tokens of that step's path; a payment to any
other address is named. (Sepolia's `UniversalRouterV1_2_V2Support` was
deployed with placeholders for both values, so no V2 swap step can succeed on
that router.) Every other payment counts, in whichever step and of whatever
token, a share of the output included: an interface fee paid to another
address by `PAY_PORTION`, `TRANSFER` or `TAKE_PORTION` is named, and the
minimum reads `Min. paid out`, because the swap's minimum includes the fee.
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) and no `Paid to` line is shown. `Paid to` lines after
`Token Out` name each other address paid; one reads
`The bridge, which pays the deposit's recipient on another network` for a
bridge deposit; one reads, for example,
`The router, 2000.0000 USDT from the sender (later steps may not spend all of it)`
for each move into the router; 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 the decoder does not read: every command other than
`PERMIT2_PERMIT`, `PERMIT2_TRANSFER_FROM`, `V2_SWAP_EXACT_IN`,
`V2_SWAP_EXACT_OUT`, `V3_SWAP_EXACT_IN`, `V4_SWAP`, `SWEEP`, `TRANSFER`,
`PAY_PORTION`, `PAY_PORTION_FULL_PRECISION`, `WRAP_ETH`, `UNWRAP_WETH` and
`BALANCE_CHECK_ERC20` (`V3_SWAP_EXACT_OUT`, `PERMIT2_TRANSFER_FROM_BATCH`,
`EXECUTE_SUB_PLAN` and `ACROSS_V4_DEPOSIT_V3` among them).
in the router; and one more reads `Unknown (could not be decoded)` when a step
that may pay an address went unread. When no step pays anyone, a single line
reads `Unknown (not named in the calldata)`. Wherever there is a `Paid to`
line, the minimum reads `Min. paid out`. A step goes unread when its recipient
does not decode as an address, or when it is a command the decoder does not
read: every command other than `PERMIT2_PERMIT`, `PERMIT2_TRANSFER_FROM`,
`V2_SWAP_EXACT_IN`, `V2_SWAP_EXACT_OUT`, `V3_SWAP_EXACT_IN`, `V4_SWAP`,
`SWEEP`, `TRANSFER`, `PAY_PORTION`, `PAY_PORTION_FULL_PRECISION`,
`ACROSS_V4_DEPOSIT_V3`, `WRAP_ETH`, `UNWRAP_WETH` and `BALANCE_CHECK_ERC20`
(`V3_SWAP_EXACT_OUT`, `PERMIT2_TRANSFER_FROM_BATCH` and `EXECUTE_SUB_PLAN`
among them).
### Non-Goals Forever
+3
View File
@@ -609,6 +609,9 @@ async function checkRecipientHistory(txInfo) {
fromAddress: txInfo.from,
chainId: txInfo.chainId,
});
// The user may have left this transaction while the checks were in
// flight; its warnings must not reach another recipient's screen.
if (pendingTx !== txInfo) return;
for (const w of asyncWarnings) {
if (w.type === "contract") {
$("confirm-contract-warning").style.visibility = "visible";
+117 -26
View File
@@ -180,6 +180,11 @@ const UNDECODED_CURRENCY = "Unknown (could not be decoded)";
const STAYS_IN_ROUTER =
"The router, where it stays (no later step pays it out)";
// The Paid to line for an ACROSS_V4_DEPOSIT_V3 step (see
// decodeAcrossV4DepositV3()).
const PAID_TO_BRIDGE =
"The bridge, which pays the deposit's recipient on another network";
// 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
// amount of 0n is, and a gate that cannot tell a genuine zero from an absent
@@ -460,14 +465,50 @@ function decodeTransfer(input) {
}
// Decode PERMIT2_TRANSFER_FROM (command 0x02) input bytes. Permit2 moves
// `token` from the transaction's sender to the recipient. UniversalRouterV1
// hands Permit2 the recipient as written, without map(), so on that router
// address(1) and address(2) are paid as those addresses.
// `amount` of `token` from the transaction's sender to the recipient.
// UniversalRouterV1 hands Permit2 the recipient as written, without map(), so
// on that router address(1) and address(2) are paid as those addresses.
// ABI: (address token, address recipient, uint160 amount)
function decodePermit2TransferFrom(input) {
try {
const d = coder.decode(["address", "address", "uint160"], input);
return { token: d[0], recipient: d[1] };
return { token: d[0], recipient: d[1], amount: d[2] };
} catch {
return null;
}
}
// Decode ACROSS_V4_DEPOSIT_V3 (command 0x40) input bytes. The router hands
// the bridge `inputAmount` of `inputToken`, or all it holds of it when that is
// CONTRACT_BALANCE; with `useNative` set it hands over its ETH instead. It
// passes `depositor` and `recipient` on as written, without map(). The bridge
// pays the recipient on another network what the deposit states, and refunds
// a deposit nobody fills to the depositor, who may also change the deposit's
// recipient.
// - UniversalRouterV2_1_1: https://github.com/Uniswap/universal-router/blob/999d561c3ad58fb5cab91b602911f3c75591a9c7/contracts/modules/ChainedActions.sol
// - UniversalRouterV2_1_2: https://github.com/Uniswap/universal-router/blob/802fe4c18f47300e0f183e2a42e9146ec2ea9fc3/contracts/modules/ChainedActions.sol
// - parameters, the same at both commits: https://github.com/Uniswap/universal-router/blob/802fe4c18f47300e0f183e2a42e9146ec2ea9fc3/contracts/interfaces/IUniversalRouter.sol
// - the bridge's depositV3() and its refund to the depositor: https://github.com/across-protocol/contracts/blob/950e9154f3d61e59590eb7d4403fae5d3cae84f8/contracts/spoke-pools/SpokePool.sol
// ABI: (tuple(address depositor, address recipient, address inputToken,
// address outputToken, uint256 inputAmount, uint256 outputAmount,
// uint256 destinationChainId, address exclusiveRelayer,
// uint32 quoteTimestamp, uint32 fillDeadline,
// uint32 exclusivityDeadline, bytes message, bool useNative))
function decodeAcrossV4DepositV3(input) {
try {
const d = coder.decode(
[
"tuple(address,address,address,address,uint256,uint256,uint256,address,uint32,uint32,uint32,bytes,bool)",
],
input,
);
return {
depositor: d[0][0],
recipient: d[0][1],
inputToken: d[0][2],
inputAmount: d[0][4],
useNative: d[0][12],
};
} catch {
return null;
}
@@ -881,11 +922,17 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
const paidElsewhere = [];
// Set when a step may pay an address this decoder did not read.
let payeeUnread = false;
// Set when an ACROSS_V4_DEPOSIT_V3 step pays the bridge.
let bridgeDeposit = false;
// What each PERMIT2_TRANSFER_FROM moved from the sender into the
// router, as { token, amount }. Later steps may leave part of it
// there: nothing here checks that they spend all of it.
const movedIntoRouter = [];
// The tokens, lowercased, that a swap step or a V4 TAKE or
// TAKE_PORTION paid to the router and no later step paid out of it in
// full: a SWEEP of that token, an UNWRAP_WETH of WETH, or a TRANSFER,
// PAY_PORTION or PAY_PORTION_FULL_PRECISION of all the router holds of
// that token.
// PAY_PORTION, PAY_PORTION_FULL_PRECISION or ACROSS_V4_DEPOSIT_V3 of
// all the router holds of that token.
const heldByRouter = new Set();
const isRouter = (recipient) => {
const r = recipient.toLowerCase();
@@ -976,6 +1023,8 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
// pays address(1) and address(2) as written (see
// decodePermit2TransferFrom()).
addPaidElsewhere(p.recipient);
} else if (isRouter(p.recipient)) {
movedIntoRouter.push(p);
} else if (!isHop(i, p.token, p.recipient)) {
addPayee(p.recipient);
}
@@ -1062,6 +1111,31 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
} else {
payeeUnread = true;
}
} else if (cmdId === 0x40) {
// Only the routers with the 0x7f mask read a command type
// of 0x40.
const a = decodeAcrossV4DepositV3(inputs[i]);
if (a) {
bridgeDeposit = true;
// The bridge pays or refunds these as written, so
// only the sender's own address is the sender.
for (const r of [a.recipient, a.depositor]) {
if (r.toLowerCase() !== sender) {
addPaidElsewhere(r);
}
}
// A deposit of CONTRACT_BALANCE pays all the router
// holds of its token, or of ETH with useNative set.
if (a.inputAmount === CONTRACT_BALANCE) {
heldByRouter.delete(
a.useNative
? "0x0000000000000000000000000000000000000000"
: a.inputToken.toLowerCase(),
);
}
} else {
payeeUnread = true;
}
} else if (cmdId === 0x0b) {
const w = decodeWrapEth(inputs[i]);
if (w) {
@@ -1130,9 +1204,8 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
}
} else {
// Any other command may pay an address this decoder does
// not read: V3_SWAP_EXACT_OUT,
// PERMIT2_TRANSFER_FROM_BATCH and ACROSS_V4_DEPOSIT_V3
// among them.
// not read: V3_SWAP_EXACT_OUT and
// PERMIT2_TRANSFER_FROM_BATCH among them.
payeeUnread = true;
}
} catch {
@@ -1283,30 +1356,48 @@ function decode(data, toAddress, chainId, sources, fromAddress) {
});
}
// 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.
// A Paid to line names each other address paid, and says when a
// step pays the bridge, when one moves the sender's tokens into the
// router, when the output stays in the router, and when a payout
// could not be read. The output is received by the sender only when
// some step pays the sender and there is no such line. When no step
// names anyone paid, one line says so.
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 });
const paidTo = paidElsewhere.map((address) => ({
label: "Paid to",
value: address,
address,
}));
if (bridgeDeposit) {
paidTo.push({ label: "Paid to", value: PAID_TO_BRIDGE });
}
for (const m of movedIntoRouter) {
const info = tokenInfo(m.token, sources);
// amountText() names the token only when it knows both its
// symbol and its scale.
const ofToken =
info.symbol && info.decimals !== null ? "" : " of " + m.token;
paidTo.push({
label: "Paid to",
value:
"The router, " +
amountText(m.amount, info).display +
ofToken +
" from the sender (later steps may not spend all of it)",
});
}
if (outputHeld) {
details.push({ label: "Paid to", value: STAYS_IN_ROUTER });
paidTo.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 });
paidTo.push({ label: "Paid to", value: UNDECODED_CURRENCY });
}
const received = paidToSender && paidTo.length === 0;
if (!paidToSender && paidTo.length === 0) {
paidTo.push({ label: "Paid to", value: UNNAMED_CURRENCY });
}
details.push(...paidTo);
if (present(minOutput)) {
// A zero floor is the one case the user most needs stated: the
+221
View File
@@ -0,0 +1,221 @@
// A late answer for a confirmation screen the user has left changes nothing on
// the screen shown since (https://git.eeqj.de/sneak/AutistMask/issues/575).
//
// The confirmation screen asks the node and the explorer about its transaction
// without waiting for the answers: the recipient checks, which can show three
// warning boxes, the balance read and the fee estimate. Back, a new recipient
// and Review again show the screen for another transaction while those
// questions may still be open. The recipient checks showed their boxes
// whenever they answered, so a box about the first recipient could appear on
// the second recipient's screen.
//
// Driven through the real confirmation screen, with only the node, the
// explorer and the DOM stubbed. Each test holds back the first screen's answer
// to one question, and gives it once the screen it tests is shown.
"use strict";
// The From address of every transaction here. The jest.mock() factory below
// may only name outside variables whose names start with "mock".
const mockFrom = "0x66133E8ea0f5D1d612D2502a968757D1048c214a";
jest.mock("ethers", () => {
const actual = jest.requireActual("ethers");
// Every answer is a mock, so a test can hold one back. Every address has
// sent one transaction and has no code, and only the From address holds
// anything: 5 ETH.
class StubProvider {}
Object.assign(StubProvider.prototype, {
getBalance: jest.fn(async (address) =>
address === mockFrom ? actual.parseEther("5") : 0n,
),
getCode: jest.fn(async () => "0x"),
getTransactionCount: jest.fn(async () => 1),
// 10 gwei expected, 20 gwei reserved per gas.
getFeeData: jest.fn(async () => ({
maxFeePerGas: 20000000000n,
maxPriorityFeePerGas: 1000000000n,
gasPrice: 10000000000n,
})),
estimateGas: jest.fn(async () => 21000n),
});
return { ...actual, JsonRpcProvider: StubProvider };
});
// An explorer address page whose title is `title`.
function explorerPage(title) {
return { ok: true, text: async () => "<title>" + title + "</title>" };
}
// The explorer labels no address.
global.fetch = jest.fn(async () => explorerPage("Etherscan"));
const { makeStorageStub } = require("./support/storageStub");
global.chrome = { storage: makeStorageStub(), runtime: { sendMessage() {} } };
// A stub DOM: every id resolves to a recording element.
const elements = new Map();
function makeEl(id) {
return {
id,
textContent: "",
innerHTML: "",
value: "",
disabled: false,
style: {},
dataset: {},
classList: {
add() {},
remove() {},
toggle() {},
contains: () => false,
},
addEventListener() {},
querySelectorAll: () => [],
remove() {},
};
}
global.document = {
getElementById(id) {
if (!elements.has(id)) elements.set(id, makeEl(id));
return elements.get(id);
},
};
const { JsonRpcProvider, parseEther } = require("ethers");
const { loadState } = require("../src/shared/state");
const confirmTx = require("../src/popup/views/confirmTx");
const node = JsonRpcProvider.prototype;
const FIRST = "0xC0FfEE0000000000000000000000000000c0fFEe";
const SECOND = "0xE2E0000000000000000000000000000000000E2e";
function el(id) {
return global.document.getElementById(id);
}
function shown(id) {
return el(id).style.visibility === "visible";
}
// Show the confirmation screen for 1 ETH to `to` on mainnet, as Review on the
// Send screen does.
function review(to) {
confirmTx.show({
from: mockFrom,
to,
ensName: null,
amount: "1",
token: "ETH",
tokenSymbol: null,
tokenDecimals: null,
max: false,
});
}
// show() does not wait for its questions; this lets every answer not held
// back arrive.
async function settle() {
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
}
// Hold back the next answer `question` gives. Returns the function that gives
// it.
function holdNextAnswer(question) {
let give;
question.mockImplementationOnce(() => new Promise((r) => (give = r)));
return (answer) => give(answer);
}
beforeAll(async () => {
await loadState();
});
beforeEach(() => {
elements.clear();
});
// The three boxes the recipient checks show, each with the question whose
// answer shows it for FIRST, and that answer. FIRST holds no ETH, so the
// answer that it has sent no transaction is what shows the box saying so.
describe.each([
{
box: "confirm-contract-warning",
question: node.getCode,
answer: "0x6080604052",
},
{
box: "confirm-recipient-warning",
question: node.getTransactionCount,
answer: 0,
},
{
box: "confirm-etherscan-warning",
question: global.fetch,
answer: explorerPage(
"Fake_Phishing1 | Address: " + FIRST + " | Etherscan",
),
},
])("the $box box", ({ box, question, answer }) => {
test("is shown when the answer about the recipient arrives while its screen is shown", async () => {
const give = holdNextAnswer(question);
review(FIRST);
await settle();
expect(shown(box)).toBe(false);
give(answer);
await settle();
expect(shown(box)).toBe(true);
});
test("is not shown on the next recipient's screen when the answer about the first arrives after that screen is shown", async () => {
const give = holdNextAnswer(question);
review(FIRST);
await settle();
review(SECOND);
await settle();
expect(shown(box)).toBe(false);
give(answer);
await settle();
expect(shown(box)).toBe(false);
});
});
test("a balance read answered after the next screen is shown leaves that screen's balance and balance check as they are", async () => {
const give = holdNextAnswer(node.getBalance);
review(FIRST);
await settle();
review(SECOND);
await settle();
expect(el("confirm-balance").textContent).toBe("5.0000 ETH");
give(parseEther("0.5"));
await settle();
expect(el("confirm-balance").textContent).toBe("5.0000 ETH");
expect(shown("confirm-balance-error")).toBe(false);
expect(el("btn-confirm-send").disabled).toBe(false);
});
test("a fee estimate answered after the next screen is shown leaves that screen's fee as it is", async () => {
const give = holdNextAnswer(node.getFeeData);
review(FIRST);
await settle();
review(SECOND);
await settle();
expect(el("confirm-fee-amount").textContent).toBe("~0.0002 ETH");
// 100 times the fee the second screen was quoted.
give({
maxFeePerGas: 2000000000000n,
maxPriorityFeePerGas: 100000000000n,
gasPrice: 1000000000000n,
});
await settle();
expect(el("confirm-fee-amount").textContent).toBe("~0.0002 ETH");
expect(el("confirm-fee-reserve").textContent).toBe(
"up to 0.0004 ETH reserved",
);
});
+233 -15
View File
@@ -3,12 +3,12 @@
// https://git.eeqj.de/sneak/AutistMask/issues/599).
//
// Every swap command, SWEEP, WRAP_ETH, UNWRAP_WETH, TRANSFER, PAY_PORTION,
// PAY_PORTION_FULL_PRECISION, PERMIT2_TRANSFER_FROM and V4 TAKE and
// TAKE_PORTION 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.
// PAY_PORTION_FULL_PRECISION, PERMIT2_TRANSFER_FROM, ACROSS_V4_DEPOSIT_V3 and
// V4 TAKE and TAKE_PORTION 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.
@@ -65,6 +65,13 @@ 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 PAID_TO_BRIDGE =
"The bridge, which pays the deposit's recipient on another network";
// The Paid to line for a PERMIT2_TRANSFER_FROM of `amount` into the router.
const movedIntoRouter = (amount) =>
"The router, " +
amount +
" from the sender (later steps may not spend all of it)";
const coder = AbiCoder.defaultAbiCoder();
const routerIface = new Interface([
@@ -150,6 +157,42 @@ function permit2TransferFrom(token, recipient, amount) {
];
}
// ACROSS_V4_DEPOSIT_V3 (0x40) of `inputAmount` of `inputToken`, bridged to
// chain id 8453.
function acrossDeposit(
depositor,
recipient,
inputToken,
inputAmount,
useNative = false,
) {
return [
0x40,
coder.encode(
[
"tuple(address,address,address,address,uint256,uint256,uint256,address,uint32,uint32,uint32,bytes,bool)",
],
[
[
depositor,
recipient,
inputToken,
inputToken,
inputAmount,
1n,
8453n,
ZERO,
0,
0,
0,
"0x",
useNative,
],
],
),
];
}
function wrapEth(recipient, amount) {
return [0x0b, coder.encode(["address", "uint256"], [recipient, amount])];
}
@@ -185,6 +228,15 @@ const SWAP_USDT_FOR_USDC = [
[[[USDT, USDC, 100, 1, ZERO], true, USDT_2000, USDC_1990, "0x"]],
),
];
const SWAP_USDT_FOR_ETH = [
0x06, // SWAP_EXACT_IN_SINGLE
coder.encode(
[
"tuple(tuple(address,address,uint24,int24,address),bool,uint128,uint128,bytes)",
],
[[[ZERO, USDT, 500, 10, ZERO], false, USDT_2000, ONE_WETH, "0x"]],
),
];
// SWAP_EXACT_IN_SINGLE with no parameters, which cannot be read.
const UNREADABLE_SWAP = [0x06, "0x"];
const SETTLE_USDT = [
@@ -535,17 +587,16 @@ describe("each transfer command's recipient", () => {
},
);
// The user's USDT, moved to `r`, then a swap of it paid to the user.
// The router spends what it is moved, so a move to the router pays no
// one. A move to another address is the issue's second shape.
// The user's USDT, moved to `r`, then a swap of it paid to the user. A
// move to another address is the issue's second shape.
const movedThenSwapped = (r) =>
execute(
permit2TransferFrom(USDT, r, USDT_2000),
v3SwapExactIn(MSG_SENDER, USDT_2000, ONE_WETH, USDT, WETH, false),
);
test("PERMIT2_TRANSFER_FROM: to the user or the router it pays no one else, to another address that address is named", () => {
for (const r of [MSG_SENDER, USER, ADDRESS_THIS, ROUTER]) {
test("PERMIT2_TRANSFER_FROM: to the user it pays no one else, to another address that address is named", () => {
for (const r of [MSG_SENDER, USER]) {
const result = decode(movedThenSwapped(r));
expect(labels(result)).toEqual(PAID_TO_USER);
expect(detail(result, "Min. received").value).toBe("1.0000 WETH");
@@ -563,6 +614,60 @@ describe("each transfer command's recipient", () => {
expect(paidTo(alone)).toEqual([OTHER]);
});
// Later steps may leave part of what a move into the router moves there,
// where anyone can sweep it in a later transaction.
test.each([
{ kind: "address(2)", r: ADDRESS_THIS },
{ kind: "the router's own address", r: ROUTER },
])(
"PERMIT2_TRANSFER_FROM into the router as $kind names what it moves, and nothing is received",
({ r }) => {
const result = decode(movedThenSwapped(r));
expect(labels(result)).toEqual(PAID_ELSEWHERE);
expect(paidTo(result)).toEqual([movedIntoRouter("2000.0000 USDT")]);
expect(detail(result, "Min. paid out").value).toBe("1.0000 WETH");
},
);
test.each([
{ kind: "from the router's balance", payerIsUser: false },
{ kind: "from the user's", payerIsUser: true },
])(
"a move of 2,000 USDT into the router, then a swap of 1 USDT $kind paid to the user",
({ payerIsUser }) => {
const result = decode(
execute(
permit2TransferFrom(USDT, ADDRESS_THIS, USDT_2000),
v3SwapExactIn(
MSG_SENDER,
1000000n,
1n,
USDT,
WETH,
payerIsUser,
),
),
);
expect(detail(result, "Amount").value).toBe("1.0000 USDT");
expect(paidTo(result)).toEqual([movedIntoRouter("2000.0000 USDT")]);
expect(detail(result, "Min. received")).toBeUndefined();
expect(detail(result, "Min. paid out")).toBeDefined();
},
);
test("a move into the router of a token the wallet does not know names the token", () => {
const unknown = "0x5555555555555555555555555555555555555555";
const result = decode(
execute(
permit2TransferFrom(unknown, ADDRESS_THIS, 5n),
swapToWeth(MSG_SENDER),
),
);
expect(paidTo(result)).toEqual([
movedIntoRouter("5 base units (decimals unknown) of " + unknown),
]);
});
test("UniversalRouterV1 pays a PERMIT2_TRANSFER_FROM to address(1) or address(2) as written, and maps a TRANSFER's", () => {
for (const r of [MSG_SENDER, ADDRESS_THIS]) {
const result = decode(movedThenSwapped(r), USER, ROUTER_V1);
@@ -581,6 +686,22 @@ describe("each transfer command's recipient", () => {
expect(labels(transferred)).toEqual(PAID_TO_USER);
});
test("TAKE_PORTION does not set Token Out: a TAKE_PORTION of another currency after the TAKE_ALL of the bought one", () => {
const result = decode(
execute(
v4Swap(
SWAP_USDT_FOR_USDC,
SETTLE_USDT,
takeAll(USDC),
takePortion(USDT, OTHER, 25n),
),
),
);
expect(detail(result, "Token Out").address).toBe(USDC);
expect(paidTo(result)).toEqual([OTHER]);
expect(detail(result, "Min. paid out").value).toBe("1990.0000 USDC");
});
test("a router without command 0x07 does not read it as PAY_PORTION_FULL_PRECISION", () => {
const result = decode(
execute(
@@ -676,6 +797,102 @@ describe("a payout of part of the router's output", () => {
);
});
// ACROSS_V4_DEPOSIT_V3 hands the bridge what the router holds. The bridge
// pays the deposit's recipient on another network, and refunds a deposit
// nobody fills to its depositor; the router passes both on as written.
describe("a bridge deposit", () => {
// A swap of 2,000 USDT for at least 1 WETH paid to the router, then a
// deposit of all the router's WETH.
const bridged = (depositor, recipient) =>
execute(
swapToWeth(ADDRESS_THIS),
acrossDeposit(depositor, recipient, WETH, CONTRACT_BALANCE),
);
test.each([
{
kind: "the user is its recipient and its depositor",
recipient: USER,
depositor: USER,
named: [],
},
{
kind: "another address is its recipient",
recipient: OTHER,
depositor: USER,
named: [OTHER],
},
{
kind: "another address is its depositor",
recipient: USER,
depositor: OTHER,
named: [OTHER],
},
{
kind: "address(1) is its recipient and address(2) its depositor",
recipient: MSG_SENDER,
depositor: ADDRESS_THIS,
named: [MSG_SENDER, ADDRESS_THIS],
},
])(
"when $kind, each that is not the user is named, and nothing is received",
({ recipient, depositor, named }) => {
const result = decode(
bridged(depositor, recipient),
USER,
ROUTER_V2_1_2,
);
expect(detail(result, "Steps").value).toBe(
"V3 Swap (Exact In) → Across Bridge Deposit",
);
expect(paidTo(result)).toEqual([...named, PAID_TO_BRIDGE]);
expect(detail(result, "Min. received")).toBeUndefined();
expect(detail(result, "Min. paid out").value).toBe("1.0000 WETH");
},
);
test("a deposit of part of the router's WETH leaves the rest there", () => {
const result = decode(
execute(
swapToWeth(ADDRESS_THIS),
acrossDeposit(USER, USER, WETH, ONE_WETH / 2n),
),
USER,
ROUTER_V2_1_2,
);
expect(paidTo(result)).toEqual([PAID_TO_BRIDGE, STAYS_IN_ROUTER]);
});
test("a deposit of all the router's ETH pays out the ETH it holds; one of all its WETH does not", () => {
const ethToRouter = v4Swap(
SWAP_USDT_FOR_ETH,
SETTLE_USDT,
take(ZERO, ADDRESS_THIS),
);
const native = decode(
execute(
ethToRouter,
acrossDeposit(USER, USER, WETH, CONTRACT_BALANCE, true),
),
USER,
ROUTER_V2_1_2,
);
expect(detail(native, "Token Out").value).toBe("ETH");
expect(paidTo(native)).toEqual([PAID_TO_BRIDGE]);
const weth = decode(
execute(
ethToRouter,
acrossDeposit(USER, USER, WETH, CONTRACT_BALANCE),
),
USER,
ROUTER_V2_1_2,
);
expect(paidTo(weth)).toEqual([PAID_TO_BRIDGE, STAYS_IN_ROUTER]);
});
});
// 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. The pairs below
@@ -996,6 +1213,11 @@ describe("a payout that cannot be read is never said to be received", () => {
step: permit2TransferFrom(WETH, OTHER, 1n),
word: 1,
},
{
kind: "ACROSS_V4_DEPOSIT_V3",
step: acrossDeposit(USER, OTHER, WETH, 1n),
word: 2,
},
])(
"a $kind whose recipient word has its top byte set",
({ step, word = 0 }) => {
@@ -1054,10 +1276,6 @@ describe("a payout that cannot be read is never said to be received", () => {
),
],
},
{
kind: "ACROSS_V4_DEPOSIT_V3",
step: [0x40, coder.encode(["address"], [OTHER])],
},
])("a swap paid to the user, then $kind", ({ step }) => {
const result = decode(
execute(swapToWeth(MSG_SENDER), step),