Skip to content

D2 - #496

Open
liquid-8 wants to merge 89 commits into
uniswap-python:masterfrom
liquid-8:v4_UF_grant_D2
Open

D2#496
liquid-8 wants to merge 89 commits into
uniswap-python:masterfrom
liquid-8:v4_UF_grant_D2

Conversation

@liquid-8

@liquid-8 liquid-8 commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Added: V2 and V3 custom routes for quoting and swaps in Uniswap/AsyncUniswap
Added: Single- and multi-hop V2 and V3 swaps via UnivesalRouter in Uniswap4/AsyncUniswap4
Added: UniversalRouter v2.1.2; supports the full set of commands and actions
Added: all-chain testing workflows for Uniswap/AsyncUniswap and Uniswap4/AsyncUniswap4

@greptile-apps

greptile-apps Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The latest changes appear safe to merge and fix the remaining wrap-amount mismatch.

Summary

The PR adds native-ETH routes across V2 and V3 and legacy swap methods to the V4 clients.

  • Standard clients can quote and swap across custom V2 and V3 routes.
  • Uniswap4 trade helpers can swap along legacy V2 and V3 routes.
  • Uniswap clients now use version 3 when callers omit the version.

Reviews (8) · Last reviewed commit: "review fix" · Reviewed by Greptile

Comment thread uniswap/uniswap.py Resolved
Comment thread uniswap/uniswap.py Resolved
Comment thread uniswap/uniswap.py Resolved
Comment thread uniswap/asyncuniswap.py Resolved
Comment thread uniswap/asyncuniswap.py Resolved
@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.63736% with 90 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.59%. Comparing base (5fa5c57) to head (35bfc4c).
⚠️ Report is 25 commits behind head on master.

Files with missing lines Patch % Lines
uniswap/tokens.py 40.67% 70 Missing ⚠️
uniswap/asyncuniswap4.py 97.29% 5 Missing ⚠️
uniswap/uniswap4.py 97.29% 5 Missing ⚠️
uniswap/asyncuniswap.py 96.39% 4 Missing ⚠️
uniswap/uniswap.py 96.26% 4 Missing ⚠️
uniswap/util.py 87.50% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #496      +/-   ##
==========================================
+ Coverage   71.03%   74.59%   +3.56%     
==========================================
  Files          14       14              
  Lines        4302     4909     +607     
==========================================
+ Hits         3056     3662     +606     
- Misses       1246     1247       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@liquid-8

Copy link
Copy Markdown
Member Author

@greptileai review

@liquid-8

liquid-8 commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

@greptileai review

…yncUniswap4;

update UniversalRouter commands ABIs;

Misc: Uniswap and AsyncUniswap default version set to 3; version 1 removed from supported; encode_v3_path() methods moved to util.py
@liquid-8

Copy link
Copy Markdown
Member Author

@greptileai review

Comment thread uniswap/uniswap4.py Resolved
Comment thread uniswap/uniswap4.py Resolved
Comment thread uniswap/uniswap.py Resolved
@liquid-8

Copy link
Copy Markdown
Member Author

@greptileai review

Comment thread uniswap/uniswap4.py Resolved
@liquid-8

Copy link
Copy Markdown
Member Author

@greptileai review

…v3 trades via universal router when input token is native token
@liquid-8

Copy link
Copy Markdown
Member Author

@greptileai review

@liquid-8

Copy link
Copy Markdown
Member Author

@greptileai review

@liquid-8

liquid-8 commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

@TimeToBuildBob
Should be addressed in f155dfe

  • Only test_get_price_input / test_get_price_output carry the marker, so no v2/v3 swaps run cross-chain. Is that intended?

Yes, that's intended. We only need to test quoting for the legacy classes. Moreover, I think using markers is overkill. In fact, we test against the same contract as on mainnet. It's enough to set custom IDs, like edgecase, on certain parameters for these methods and run make test -k edgecase in the test workflow. If one succeeds, all succeed, and vice versa. There is no reason to run it with all parameters like on mainnet; we only increase the chance of the node failing.

Actually, I think this approach should fit the v4 workflow too. We can pick crucial tests, like approvals/quoting/swaps, and skip heavy or non-critical ones for the very same reasons. In both cases, we have the full test results (and that's really meticulous) on the PR as proof and reference. Thoughts?

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 f155dfe covers my last points. All checks are green, and the 15 token addresses on Optimism, Base and Unichain return the expected symbol and decimals.

A smaller cross-chain set: agreed. But "if one succeeds, all succeed" doesn't hold, because each case depends on that chain's pool liquidity. I replayed the currently marked quote cases as read-only eth_calls against the quoter/router (latest block, not through your test suite):

test_get_price_input test_get_price_output
Optimism v2 9/11 3/10
Optimism v3 8/11 7/10
Base v2 11/11 5/10
Base v3 11/11 8/10

So all four legs would fail today. Some v2 pools are tiny (Optimism WETH/UNI holds about 0.0005 UNI). On Optimism, DAI/USDC has no v2 pair, and its v3 0.3% pool has no in-range liquidity.

This set passed 5/5 in both directions on all four:

Case exact-in qty exact-out qty
ETH→UNI 10**14 10**14
UNI→ETH 10**18 10**11
ETH→DAI 10**18 10**18
DAI→ETH 10**18 10**14
USDC→DAI via [USDC, WETH, DAI] 10**6 10**18

That multihop is token-to-token. The ETH-anchored [WETH, USDC, DAI] routes work on Base but not on Optimism.

Selecting the cases

  • make test -k edgecase won't filter: make takes -k for itself, runs the whole suite, then fails with No rule to make target 'edgecase'. It needs make test TESTARGS="-k edgecase".
  • I'd keep the marker and apply it per case with pytest.param(..., marks=pytest.mark.crosschain). It's as precise as a custom ID and keeps the descriptive test names. Registering it in pyproject.toml would also remove the unknown-mark warning.

v4

The same approach makes sense, with two conditions:

  • Choose by contract, not only by test weight. There are eight per-chain v4 address maps, and skipping every liquidity test would leave addresses such as the position manager unexercised.
  • The full reference on this PR is narrower than "all chains". In the test.yml runs since 11-17, v2/v3 only ran on mainnet. Outside mainnet and Arbitrum, I found one green v4 job (Base at 57fe6b7), and none for Optimism or Unichain. If you have full local runs for those, it's worth posting them here.

@liquid-8

liquid-8 commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

@TimeToBuildBob, thanks for the research; that will help to explain. First, I don't consider the state PR to be final. Sure, there are networks to add. Regarding failed tests on previous runs: most were caused by an overly optimistic anvil configuration. However, according to

  • GitHub only accepts workflow_dispatch once the file is on the default branch, so you can't trigger these from this PR before it merges.

I still need it to merge. You don't have any concerns regarding the codebase, do you? I will add the missing networks and configure tests in the next PR, which will be the final one for this delivery. That merge would also unlock the possibility of building an agent skill for Uniswap v4, similar to #497, which is part of D3. Sepolia addresses have been added. They miss the PositionDescriptor contract deployment on that network, but it is non-crucial, and the constructor can handle that case.

  • I'd keep the marker and apply it per case with pytest.param(..., marks=pytest.mark.crosschain)

Totally makes sense.

Regarding tokens, pool liquidity, etc. The only thing guaranteed on a random EVM network is a native token and its wrapped version, nothing more. Some networks we need to test have no proper pools for multi-hops. Just a bunch of (native token/some ERC20) and a couple of (ERC20 A/ERC20 B) not connected to other pools. You're right that we must test contracts. So, we must pick a bare minimum of parameters for certain methods. E.g., we need to test get_price_input(). What do we know for sure? There is a pool (native token/some ERC20 token), if there is such a pool at all. That's the data that we should use. We can check the whole quoting v2-v4 using only these two addresses. Single-hop tests are trivial in any direction. Multi-hop tests are just passing the same two tokens as a multi-hop route. Yes, there is only one hop, but it is treated as multi-hop, and it just works. Same with swaps on V4. I believe the idea is clear. And we don't even need to test every contract function; they are the same as on mainnet. We need to ensure that every contract works in general, and this is pretty much what you said.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 Yes, I do. Please don't merge f155dfe yet. The v4 clients' legacy v2/v3 swap helpers (token_to_token_swap_{input,output}_v{2,3}) have fund-affecting bugs. I missed them earlier, so my "no remaining concerns" was wrong.

I ran the sync Uniswap4 helpers on a local mainnet fork with a fresh account:

Case Result at f155dfe
v3 exact-out, ETH → buy 100 USDC Tx succeeds, trade is reversed: wraps 1.01 ETH, sells 2 raw units of USDC for a dust amount of WETH
USDC → ETH exact-in, qtycap=1 (as in tests) Succeeds, but you receive WETH, not ETH
USDC → ETH exact-in, non-zero minimum Reverts
USDC → ETH exact-out Reverts
ETH → USDC, no WETH Permit2 approval Reverts
v2 ETH → USDC exact-out Succeeds, but the change comes back as WETH

The same code is in asyncuniswap4.py (read, not run).

Fixes, in all four helpers, sync and async (ADDRESS_THIS is 0x0000000000000000000000000000000000000002, the router itself):

  1. v3 exact-out: pass is_exact_out=True to encode_v3_path (uniswap4.py:2605, asyncuniswap4.py:2663).
  2. ETH output: set the swap recipient to ADDRESS_THIS, so UNWRAP_WETH has something to unwrap.
  3. ETH input: WRAP_ETH to ADDRESS_THIS and set payerIsUser=False.
  4. ETH input, exact-out: append UNWRAP_WETH(self.address, 0) to return the change as ETH.

With those four applied to a scratch copy of the sync file, all the swaps above succeeded: ETH arrived as ETH, no WETH approval was needed, and v3 exact-out bought exactly 100 USDC.

CI stays green because these tests check only tx_receipt["status"], use qtycap=1, and approve WETH first. There is also no token → ETH exact-out case. Please assert balance changes (ETH, WETH and the token) with a non-zero minimum.

Two smaller things in constants.py (found by reading and a format check):

  • The Polygon v4 router is "xDc2647…", missing the leading 0.
  • PERMIT2_PERMIT_BATCH gained a trailing []. The Universal Router decodes a single PermitBatch struct, so the old form looks right.

Also worth a release note: the default version changes from 1 to 3, and chain 56 now resolves to Uniswap's v2 contracts instead of PancakeSwap's.

I haven't verified the rest of the new address maps on-chain.

On your testing plan: agreed. A (WETH, one ERC20) pool passed as a one-hop route is a good per-chain smoke test, and the mainnet suite can keep covering intermediate-hop ordering. A one-hop route would even catch the reversed v3 path above, but only if the test asserts balances rather than status.

@liquid-8

liquid-8 commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

@liquid-8 Yes, I do. Please don't merge f155dfe yet. The v4 clients' legacy v2/v3 swap helpers (token_to_token_swap_{input,output}_v{2,3}) have fund-affecting bugs. I missed them earlier, so my "no remaining concerns" was wrong.

I ran the sync Uniswap4 helpers on a local mainnet fork with a fresh account:
Case Result at f155dfe
v3 exact-out, ETH → buy 100 USDC Tx succeeds, trade is reversed: wraps 1.01 ETH, sells 2 raw units of USDC for a dust amount of WETH
USDC → ETH exact-in, qtycap=1 (as in tests) Succeeds, but you receive WETH, not ETH
USDC → ETH exact-in, non-zero minimum Reverts
USDC → ETH exact-out Reverts
ETH → USDC, no WETH Permit2 approval Reverts
v2 ETH → USDC exact-out Succeeds, but the change comes back as WETH

The same code is in asyncuniswap4.py (read, not run).

Fixes, in all four helpers, sync and async (ADDRESS_THIS is 0x0000000000000000000000000000000000000002, the router itself):

1. **v3 exact-out:** pass `is_exact_out=True` to `encode_v3_path` (`uniswap4.py:2605`, `asyncuniswap4.py:2663`).

2. **ETH output:** set the swap recipient to `ADDRESS_THIS`, so `UNWRAP_WETH` has something to unwrap.

3. **ETH input:** `WRAP_ETH` to `ADDRESS_THIS` and set `payerIsUser=False`.

4. **ETH input, exact-out:** append `UNWRAP_WETH(self.address, 0)` to return the change as ETH.

With those four applied to a scratch copy of the sync file, all the swaps above succeeded: ETH arrived as ETH, no WETH approval was needed, and v3 exact-out bought exactly 100 USDC.

CI stays green because these tests check only tx_receipt["status"], use qtycap=1, and approve WETH first. There is also no token → ETH exact-out case. Please assert balance changes (ETH, WETH and the token) with a non-zero minimum.

Two smaller things in constants.py (found by reading and a format check):

* The Polygon v4 router is `"xDc2647…"`, missing the leading `0`.

* `PERMIT2_PERMIT_BATCH` gained a trailing `[]`. The Universal Router [decodes a single `PermitBatch` struct](https://github.com/Uniswap/universal-router/blob/main/contracts/base/Dispatcher.sol), so the old form looks right.

Also worth a release note: the default version changes from 1 to 3, and chain 56 now resolves to Uniswap's v2 contracts instead of PancakeSwap's.

I haven't verified the rest of the new address maps on-chain.

On your testing plan: agreed. A (WETH, one ERC20) pool passed as a one-hop route is a good per-chain smoke test, and the mainnet suite can keep covering intermediate-hop ordering. A one-hop route would even catch the reversed v3 path above, but only if the test asserts balances rather than status.

@TimeToBuildBob Should be addressed in 6422f17 Please verify

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 The four swap fixes are correct at 6422f17. I replayed them on a local mainnet fork against the unmodified commit, this time with both Uniswap4 and AsyncUniswap4, using fresh accounts with no WETH approvals.

All 16 swaps passed: v2/v3 × exact-input/exact-output × ETH→USDC/USDC→ETH × sync/async. I checked ETH balances after accounting for gas, USDC balances, and WETH balances—not just transaction status:

  • ETH input works without either ERC20 WETH approval or WETH Permit2 allowance.
  • Both v3 exact-output buys deliver exactly 100 USDC, in the correct direction.
  • Token→ETH pays native ETH with a non-zero minimum; exact-output delivers at least the requested ETH (v2 can round slightly upward).
  • ETH-input exact-output returns the unused input as ETH. No WETH is left in the user's wallet.
  • The caller's route list remains unchanged.

The Polygon address typo, PERMIT2_PERMIT_BATCH tuple ABI, and both release notes are also fixed in the diff.

The regression-test part of my last request is still outstanding. This commit changes no tests: test_make_swap_input_v2/v3 still use qtycap = 1, the legacy swap tests still assert only receipt status, and token→ETH exact-output is still absent in both test files. Please carry the balance assertions above into the suite, including a fresh-account ETH-input case without WETH approval. Those checks distinguish the fixed behavior from the old green-but-wrong transactions.

For clarity, I am withdrawing the previously reproduced swap-code blockers, not claiming the whole deployment matrix is verified. At this check, the current-head Test workflow is queued (run); only the Docs build has completed. I have not reproduced a current-head v3 CI failure, and broader cross-chain coverage can remain in your planned follow-up.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 Checked a1e7a82. The four swap-code fixes from 6422f17 are unchanged, so those blockers stay withdrawn. This commit does not land the regression coverage I asked for, and current-head CI is red for bugs in these tests.

The new cases still only assert tx_receipt["status"]. Quoting a real qtycap and adding token→ETH exact-output is the right shape, but status-only still would not have caught the reversed v3 path, WETH delivered instead of ETH, or ETH-input without a WETH approval.

Current-head Test is red (run 47454886736):

  1. Async fixtures do not inject. In tests/test_asyncuniswap4.py, the v2 tests request client_legacy_V2 while the fixture is named client_legacy_v2. client_legacy_v3 is missing @pytest.fixture. All 8 async v2/v3 swap cases ERROR with fixture ... not found.

  2. Sync quotes pass ETH_ADDRESS as the route endpoint. Uniswap.get_price_input/get_price_output now require route[0]/route[-1] to be WETH. The new params use [ETH_ADDRESS, USDC] / [USDC, ETH_ADDRESS], so all 8 sync cases raise ValueError: route[0] must be wrapped ETH when input_token is ETH (and the route[-1] variant). Use WETH in the quote route; Uniswap4 can keep taking ETH_ADDRESS if that is its public convention.

v4/arbitrum is the clean signal: 8 errors + 8 failures, all on these new cases. v4/mainnet stopped at --maxfail=20 on max fee per gas less than block base fee starting at test_approve — that looks like a fork-tip gas issue, not these helpers. v3/mainnet's 9 errors are Anvil connection refused on test_v4_examples.py after 234 passes.

Please keep the four swap fixes, fix the fixture names/decorators and the WETH quote routes, and add the balance assertions: ETH net of gas, WETH stays 0, token delta, plus a fresh-account ETH-input case with no WETH approval. I can re-run the fork checks once those are in.

Please don't merge this head.

@liquid-8

liquid-8 commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

@liquid-8 Checked a1e7a82. The four swap-code fixes from 6422f17 are unchanged, so those blockers stay withdrawn. This commit does not land the regression coverage I asked for, and current-head CI is red for bugs in these tests.

The new cases still only assert tx_receipt["status"]. Quoting a real qtycap and adding token→ETH exact-output is the right shape, but status-only still would not have caught the reversed v3 path, WETH delivered instead of ETH, or ETH-input without a WETH approval.

Current-head Test is red (run 47454886736):

1. **Async fixtures do not inject.** In `tests/test_asyncuniswap4.py`, the v2 tests request `client_legacy_V2` while the fixture is named `client_legacy_v2`. `client_legacy_v3` is missing `@pytest.fixture`. All 8 async v2/v3 swap cases ERROR with `fixture ... not found`.

2. **Sync quotes pass `ETH_ADDRESS` as the route endpoint.** `Uniswap.get_price_input`/`get_price_output` now require `route[0]`/`route[-1]` to be WETH. The new params use `[ETH_ADDRESS, USDC]` / `[USDC, ETH_ADDRESS]`, so all 8 sync cases raise `ValueError: route[0] must be wrapped ETH when input_token is ETH` (and the `route[-1]` variant). Use WETH in the _quote_ route; Uniswap4 can keep taking `ETH_ADDRESS` if that is its public convention.

v4/arbitrum is the clean signal: 8 errors + 8 failures, all on these new cases. v4/mainnet stopped at --maxfail=20 on max fee per gas less than block base fee starting at test_approve — that looks like a fork-tip gas issue, not these helpers. v3/mainnet's 9 errors are Anvil connection refused on test_v4_examples.py after 234 passes.

Please keep the four swap fixes, fix the fixture names/decorators and the WETH quote routes, and add the balance assertions: ETH net of gas, WETH stays 0, token delta, plus a fresh-account ETH-input case with no WETH approval. I can re-run the fork checks once those are in.

Please don't merge this head.

@TimeToBuildBob
Should be addressed in 64e6d49
The only thing

ETH net of gas

I have no idea why we should check anything on that. This type of swap behaves like any other, like, what's the point

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 The point is not to test gas pricing. It's to distinguish “the wallet received native ETH” from the old bug where the transaction succeeded but delivered WETH instead. A receipt with status == 1 doesn't distinguish those. The sender also pays gas, so its ETH balance change contains both the swap and the transaction fee; subtracting that fee is how we isolate the swap.

For example, for token→ETH, using raw wei balances immediately before and after the swap:

fee = receipt["gasUsed"] * receipt["effectiveGasPrice"]
eth_received = eth_after - eth_before + fee

Assert eth_received >= minimum_output for exact-input, or >= qty for exact-output (v2 can round up slightly), alongside the token debit and unchanged WETH balance. For ETH→token, eth_before - eth_after - fee is the ETH actually spent; exact-output should spend no more than its input cap and return the change. This formula applies to the ordinary Anvil receipts here; a live L2 receipt may need an additional chain-specific fee component. No gas benchmark or fixed gas expectation is needed.

Checked 64e6d49: the fixture spelling/decorator fixes and WETH quote routes are addressed. The new balance assertions still need corrections, in both test files:

  1. Signs are reversed: input spent is before - after; output received is after - before. Currently both are calculated the other way round.
  2. Units differ: get_token_balance() and get_balance() return human-unit Decimals, while qty/qtycap are raw integer units. Use raw w3.eth.get_balance() / ERC20 balanceOf() for these assertions, or explicitly scale each side by that token's decimals. In the current Arbitrum log, receiving 1 USDC becomes Decimal('-1.000000') and is compared to 1000000.
  3. Sync test_make_swap_input_v2 uses exact-output assertions. For exact-input, check input spent equals qty (after removing gas for ETH input), and output received meets the minimum derived from qtycap. The current assertions compare the output to the input quantity.
  4. The fresh clients aren't connected to the fresh fork. client_fresh / client_legacy_v2_fresh still receive web3, which is built from anvil.provider, not anvil_fresh.provider. They use a different account on the original fork; the new Anvil instance is unused. Either wire a web3_fresh fixture to it, or deliberately use a fresh funded account on the existing fork. For the no-WETH-approval regression, ETH→USDC alone is enough. The reverse USDC→ETH case needs USDC ERC20/Permit2 approvals; it currently reverts. Check both WETH allowances are zero before the ETH-input swap.

Current-head CI confirms the test problems: v4/Arbitrum has 20 failures in these new cases, rather than the previous missing-fixture/invalid-route errors. The other red legs are still v4/mainnet's max fee per gas less than block base fee and nine v3/mainnet example-fixture connection-refused errors.

The previously verified swap-code fixes remain unchanged; I'm not reopening those or asking for a broader deployment sweep in this PR. The remaining work is to make these regression tests measure the intended transfers correctly and get CI green. I can't call this head merge-ready yet.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 Checked the new head d509d75 and its Test run. The raw-unit balances, delta signs, fresh-fork wiring, and removal of the unapproved fresh-account USDC→ETH case are addressed. The fresh test now checks the router's Permit2 WETH allowance too.

Two of the previous test corrections remain:

  1. Account for the swap transaction fee in native-ETH deltas, in both files, including the fresh case. This is now a concrete CI failure: async v2 ETH-input on Arbitrum measures 1000136105122648782 wei spent against 1000000000000000000 wei input. The extra 136105122648782 wei must not be counted as swap input. After calculating the raw deltas, apply:

    fee = tx_receipt["gasUsed"] * tx_receipt["effectiveGasPrice"]
    if is_same_address(input_token, ETH_ADDRESS):
        input_token_balance_delta -= fee
    if is_same_address(output_token, ETH_ADDRESS):
        output_token_balance_delta += fee

    This is for these local Anvil transactions, not a general live-L2 fee formula. It corrects the measurement; it does not prove every remaining failure is only gas. Re-run the assertions afterwards and investigate any residual mismatch.

  2. Sync test_make_swap_input_v2 still compares the wrong quantities. It currently compares input spent with the output quote and output received with qty. After the fee adjustment above, it should match the async exact-input test:

    assert input_token_balance_delta == qty
    assert output_token_balance_delta >= int((1 - client.max_slippage) * qtycap)

For exact-output native ETH, use output_token_balance_delta >= qty, rather than strict equality: v2 can round up slightly, as in my earlier fork replay. For ERC20 exact-output, keep equality. Also, approval(WETH_ADDRESS) checks only Permit2→router; the fresh-account regression should separately assert ERC20 WETH→Permit2 allowance is zero.

Current CI: v4/Arbitrum has 18 failures, all in these legacy/fresh balance tests, with 307 passes. v4/mainnet stops at 20 failures, including reverted transactions in the older v4 tests; unlike the previous run, this is not just the base-fee rejection, so I have not established their cause. v3/mainnet still has the nine example-fixture connection-refused errors (234 passes). Build, typecheck and v2/mainnet pass.

I'm keeping this review scoped to the outstanding regressions, not reopening the verified swap fixes or the broader deployment sweep. This head is not merge-ready while those assertions and CI remain red.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 Checked 165846e8 against Test run 47477620193. The gas-fee adjustment is in both files, including the fresh case. ETH→token exact-input and the fresh no-WETH-approval case now pass on Arbitrum.

1. Sync test_make_swap_input_v2 still uses the exact-output comparison. After the fee lines it is:

assert input_token_balance_delta >= int((1 - client.max_slippage) * qtycap)
assert output_token_balance_delta == qty

Arbitrum CI: ETH→USDC asserts 1306107538 == 1000000000000000000 (USDC received vs ONE_ETH). USDC→ETH asserts 1000000 >= 806445576159143 (USDC spent vs the ETH quote). Match the async exact-input test, which is already right:

assert input_token_balance_delta == qty
assert output_token_balance_delta >= int((1 - client.max_slippage) * qtycap)

2. Token→ETH still shows zero native ETH after the fee correction. On Arbitrum, every USDC→ETH legacy case (v2/v3 × exact-in/exact-out × sync/async) failed with output_token_balance_delta == 0 (exact-in: assert 0 >= ~8e14; exact-out: assert 0 == 10000000000000000). ETH→token with the same formula passes, so this is not a broken fee adjustment. It is the old signature: the tx succeeds and the wallet's native ETH only moves by gas. Please print WETH on those failures; I expect it is non-zero. I reproduced token→ETH correctly on a mainnet fork at 6422f17; Arbitrum is now catching that it does not hold here. For exact-output native ETH, once ETH actually arrives, use >= qty rather than == qty (v2 can round up).

v4/mainnet and v3/mainnet are still running, so I have not used them. Please don't merge this head.

@liquid-8

liquid-8 commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

It is the old signature: the tx succeeds and the wallet's native ETH only moves by gas. Please print WETH on those failures; I expect it is non-zero. I reproduced token→ETH correctly on a mainnet fork at 6422f17

Elaborate on this, please

@TimeToBuildBob

TimeToBuildBob commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

@liquid-8 I meant that CI measured eth_after - eth_before + gas_fee == 0, despite a successful token→ETH transaction. That observation does not prove WETH was delivered. My “I expect it is non-zero” was an unverified hypothesis, and I overstated it as an Arbitrum swap regression.

There is a concrete fixture problem I should have checked first: both test accounts have EIP-7702 delegation code on both mainnet and Arbitrum. I just queried eth_getCode on the public RPCs for:

  • normal fixture: 0xa0Ee7A142d267C1f36714E4a8F75612F20a79720
  • “fresh” fixture: 0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f

All four responses were 0xef01008a67b5020ee254ef48e3b6a04927f39baf7e408a, an EIP-7702 delegation to 0x8a67b5020ee254ef48e3b6a04927f39baf7e408a. These are public Anvil keys, not clean EOAs on a fork. Receiving ETH can execute delegated code, so a zero retained ETH balance is not enough to distinguish a broken unwrap from the recipient forwarding ETH away. Launching a second fork with another known Anvil key doesn't remove this problem.

My earlier 6422f17 replay used randomly generated, locally funded accounts, not these fixture accounts. The four legacy swap implementations are unchanged between that commit and 165846e8 (the client diff only adds raw balance support). So that earlier successful replay and the current fixture failure are not contradictory.

Next test change: generate a genuinely new account with Account.create(), fund it only on the local fork using anvil_setBalance, and assert w3.eth.get_code(account.address) == b"". Use that account for the regression cases in both files. Keep the gas-corrected native-ETH and WETH balance assertions. If ETH is still missing, inspect the transaction trace and WETH balances before attributing it to the router.

Verified with an isolated Arbitrum fork: I sent 10**15 wei of native ETH to each fixture account, with no Uniswap call involved. Both transactions succeeded, both accounts retained 0 wei, and debug_traceTransaction showed each account forwarding the full 10**15 wei to 0xcc04506d439d338bde8ebbb074f17a54b7673b95. A randomly generated empty-code account retained all 10**15 wei in the control transaction. That reproduces the misleading zero-ETH signature independently of the swap code.

The sync exact-input v2 assertion mismatch from my previous comment is independently visible in the test source and still needs fixing. But please do not change the already-fixed swap/unwrap code based on my WETH hypothesis. I have not rerun the current-head swap matrix with clean accounts, so this is a confirmed fixture defect, not a claim that the full suite now passes.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 Checked 8562026 and the async follow-up 9ce4b65. Both v4 test files now create random accounts, assert empty code, and fund them on the corresponding local fork; the normal and fresh swap clients no longer use the delegated public Anvil accounts. The sync v2 exact-input assertions are also corrected. These address the two concrete findings in my last comment, without changing the already-verified swap/unwrap implementation.

The legacy quote-only clients still use the Anvil addresses, but that does not reintroduce the ETH-recipient problem: the regression swaps and balance measurements use the new v4 client accounts.

At this check, current-head CI has passed build, typecheck and v2/mainnet; v3/mainnet and both v4 legs are still running. I have not rerun the swap matrix locally at this head, so this is confirmation of the fixture/assertion fixes, not an all-green or merge-ready verdict. The next verification is the balance regression results from those v4 jobs; there is no basis to change the swap code on the earlier WETH hypothesis.

@liquid-8

liquid-8 commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

@TimeToBuildBob Looks good innit. As far as I can see, there are no concerns anymore, right?

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 Yes, no blocking concerns from me at 9965b65.

CI at this head is all green: build, typecheck, v2/mainnet, v3/mainnet (the earlier connection-refused errors are gone), v4/mainnet (337 passed) and v4/arbitrum (325 passed). In both v4 legs, all 18 regression cases ran and passed rather than being skipped. They cover v2/v3 × exact-in/exact-out × sync/async in both directions, plus the fresh-account no-WETH-approval case. That includes USDC→ETH, so with clean empty-code accounts, the gas-corrected native-ETH delta and the WETH-stays-zero assertion both hold. The earlier zero-ETH result came from the delegated fixture accounts, not the swap code.

One optional nit, not a blocker: the last commit changed the exact-output check to >= qty for ERC20 outputs too. Only native ETH needs the slack from v2 rounding. Keeping == qty when the output is an ERC20 would be slightly tighter. Either way the WETH-instead-of-ETH regression is still caught.

The merge decision is the maintainers'; from the review side, I consider my findings addressed.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

Checked the follow-up 1495173. Sharing the existing fork is fine: client_fresh still creates a separate random account, asserts empty code, funds that account locally, and checks its own WETH allowance and balances. A fresh account, not a second Anvil process, is what this regression needs. The legacy client is only used for quoting, so its Anvil address does not become the swap recipient.

This change only rewires the fixtures in the two v4 test files; it does not change the swap implementation or assertions. No new blocking concern from that diff. Current-head CI is still running (Test run); the all-green result in my previous comment applies to 9965b65, not yet to this head.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

@liquid-8 Checked 35bfc4c5 (and 6c49c1f0).

PR CI at this head is all green: build, typecheck, v2/v3/v4 mainnet, v4/arbitrum. The swap/unwrap implementation and the empty-code regression accounts are unchanged. 6c49c1f0 only deletes the leftover anvil_fresh/web3_fresh fixtures after client_fresh moved onto the shared fork; that matches what I already accepted. No new blocking concern on the library code or on test.yml.

35bfc4c5 is the dispatch-workflow commit. Those files still do not run on this PR, so the green checks above do not cover them. Three name mismatches will make the new jobs a no-op or a crash once you can dispatch:

  1. avalalance is a typo. _netid_to_name, get_tokens/get_decimals/get_pool_data, and both v4 networks lists use avalanche. The v2/v3 anvil fixture does _netid_to_name.values().index(NETWORK), so NETWORK=avalalance raises during setup. The v4 files skip the whole module when the name is not in networks, so that job would pass with every test skipped.

  2. worldchain is missing from both v4 networks lists (tests/test_uniswap4.py and tests/test_asyncuniswap4.py). The v4 dispatch job sets NETWORK=worldchain, then both files skip at import. Add worldchain (and zora if you uncomment that job). get_decimals / get_pool_data also have no zora branch; get_tokens does.

  3. Per-param crosschain is the right shape. Dispatch TESTARGS=" tests/test_*uniswap.py -m crosschain" currently selects only the ETH↔DAI quote cases. UNI stays on PR CI. That matches the thin smoke you wanted; just don't read it as coverage of UNI or of swaps. Register the mark in pyproject.toml so pytest 8 stops warning.

Smaller, not blocking the library:

  • Put ALCHEMY_API_KEY in the step env, not in matrix.provider. Matrix values are visible on the run and are not reliably masked.
  • v4 dispatch still runs the full v4 files on every network. That is a lot of forks per dispatch; a marker subset like v2/v3 would match the plan we already agreed.

The merge click is still the maintainers'. From the review side, I would not hold the library on the dispatch YAML, and I would not treat a post-merge dispatch as coverage until the network names match.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants