Repository navigation
perf(relay): batch reads through Tempo's genesis Multicall3 - #952
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
👁️ Cyclops Security Review✅ Reviewed 2a9fd94 (latest) · Coverage: partial ·
|
commit: |
⚡ Accounts Bench
Timings
ScoringEach value is the median of the passing runs. It is scored 0–100 on Lighthouse's log-normal curve: the good budget scores 90 and the poor budget scores 50. Rings are green from 90, orange from 50 and red below 50. A case score weights Total twice as much as Wallet ready and Confirm, and a renderer score is the mean of its case scores.
vs main runs the same bench against main's SDK in the same job, alternating which app goes first in each run, so both see the same network. 🟢 and 🔴 mark a Total change only when every run of one app beats every run of the other and the medians differ by 50 ms or more. A score change is marked when its cases agree. Commit 2a9fd94 · vs main 639cfe3 · 5 runs · Chrome 156.0.8078.47 · wallet https://wallet.tempo.xyz · workflow run |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. A human should still take a look, because every batched read in the relay and exchange on Tempo mainnet, Moderato and devnet now goes to a hardcoded Multicall3 address. I can't verify from the repo that the contract is deployed at genesis on those chains.
What was reviewed:
withMulticall3: returns the chain unchanged when it already declarescontracts.multicall3or its ID isn't in the set, so localnet (1337) and unknown chains still use deployless calls.- The relay and exchange client construction:
deploylessis now the negation of whether the wrapped chain has a Multicall3, and the external fee-payer client now takesclient.batch, so it gets the same 16 KBbatchSizeand deployless setting. - The local
getPoolin feeLiquidity.ts: callers only readreserveValidatorToken, so dropping the LPtotalSupplyread doesn't affect the reserve checks.
Extended reasoning...
The change touches the server relay and exchange handlers' viem client setup, the FeeAMM pool reads in feeLiquidity.ts, and a new chain helper in utils.ts, with tests and docs alongside. It touches no auth, crypto or data-exposure code. The logic is small and consistent, but it switches production RPC behavior on three live chains from self-contained deployless multicalls to a fixed contract address. If that address is missing or wrong on any of them, all batched reads there would fail, and the repo can't confirm the deployment. It also raises the relay's per-call calldata limit 16x. Neither risk shows up in the code, so a human who knows the chains should confirm them.
# Conflicts: # AGENTS.md # src/server/internal/handlers/relay.localnet.test.ts
| * 1 KB default split one fill's reads (e.g. a balance for each of 37 tokens) into calls that queued | ||
| * ahead of the fill. | ||
| */ | ||
| const batchSize = 16 * 1024 |
There was a problem hiding this comment.
Medium (exposure and trigger unconfirmed): Relay's 16 KB shared multicall batches let one request starve others' reads
The relay now batches up to 16 KB of reads per aggregate3 eth_call, on one client shared by every concurrent request. A read on a request-chosen contract that burns its gas leaves too little gas for the hundreds of reads queued after it. The whole eth_call then reverts, so other users' balance and pool reads fail.
Full finding
The relay now batches up to 16 KB of reads per aggregate3 eth_call, on one client shared by every concurrent request. A read on a request-chosen contract that burns its gas leaves too little gas for the hundreds of reads queued after it. The whole eth_call then reverts, so other users' balance and pool reads fail.
First reported at 979e315; recheck at this head: still present.
Valid? React with 👍 / 👎.
## Summary
To pick an unsponsored fill's fee token, `fillUnsponsored` started
`FeeLiquidity.prepare` (the fee-pool reserves against each recent block
producer's token) for every token in the list while their balances
loaded. On mainnet that meant ~370 `getPool` reads for 37 tokens. Under
viem's 1 KB batches and a Worker's six connections, they queued ahead of
`eth_fillTransaction`: ~39 upstream requests per unsponsored fill.
- Reserves are read only for tokens whose balance is positive, which are
the only tokens resolution can pick. Their reads start as soon as the
balances return, so the chosen token's reserves load alongside
`eth_fillTransaction`. The liquidity check before signing, the retry
that excludes an illiquid token, and the reuse of request-scoped
reserves are unchanged.
- The producers' fee tokens (`FeeLiquidity.prefetch`) still load from
the start of resolution. When no sponsor is asked they now start
alongside the token list, not after it. After a rejected sponsorship
they start when the self-paid fill starts.
- Balance reads go straight to `balanceOf`. `Actions.token.getBalance`
also read each token's `decimals()`, which doubled every balance
multicall, and the relay never used them.
- The autoSwap source token reuses the balances fee-token resolution
already read, instead of reading every token again.
The previous AGENTS.md fact ("Prefetch fee reserves with balance
discovery") described the old overlap. It's replaced by "Read fee
reserves only for held tokens". Changeset: `accounts` patch.
## Measurements
Localnet relay behind a recording transport that adds 30 ms per upstream
request and allows 6 concurrent connections (like a Worker). Warm
caches, 37-token list, a sender holding pathUSD and AlphaUSD, deployless
calls on both sides (#952 is separate).
| Scenario | Before | After |
| --- | --- | --- |
| Unsponsored fill | 8 requests, 70,010 calldata bytes, 36 `getPool`
reads issued ahead of the fill | 5 requests, 27,437 bytes, 1 `getPool`
read alongside the fill |
| Sponsorship rejected, then self-paid | 9 requests, 3 waves | 6
requests, 3 waves |
## Tests
`feeLiquidity.localnet.test.ts`: `reads reserves only for held tokens
and reuses them across retries` replaces the test that asserted the old
overlap. With an extra listed token the sender doesn't hold, pool reads
start after the balances return, the unheld token's pool is never read,
and the illiquid preferred token's pool is read once across the retry.
The producer-overlap, explicit-token, sponsored,
request-scoped-snapshot, two-hop and validator-token tests are unchanged
and pass.
## Verification
- `VITE_NODE_ENV=localnet VITE_NODE_TAG=latest pnpm test` on
`feeLiquidity.localnet.test.ts` (8) and `relay.localnet.test.ts` (62):
all pass.
- `pnpm check` (pre-commit) and `pnpm exec tsc -b --noEmit`.
## Summary
Three cold-cache stages of `eth_fillTransaction`:
- **The producers' fee tokens are served stale while they reload.** The
fee-liquidity check needs the fee tokens preferred by the last 10 block
producers: `getBlock(latest)`, then 9 `getBlockByNumber`, then a
`validatorTokens` multicall, which is three sequential rounds. With a 60
s TTL, the first unsponsored fill after each expiry waited for all three
before its liquidity check. `cached()` gains a `stale` option: an entry
up to `stale` seconds past its TTL is returned at once while `fn`
reloads it in the background, deduped per `Kv` object, and storage keeps
entries for `ttl + stale`. The producers' fee tokens use `{ ttl: 60,
stale: 600 }`. A stale set only delays noticing a producer's new
preference, as the TTL already did.
- **The token list loads alongside the fill.** Every fill awaited the
token list before it started, though only fee-token resolution and
fee-token defaults use it. It now starts at request start and is awaited
where it's needed. A sponsored fill whose fee token is known (the
sponsor's, or the request's) never waits for it. Without a known fee
token, Path B still waits for the list before `validate`, so a failure
to load it surfaces before `validate` (which may meter budgets) runs, as
before. Unsponsored resolution starts loading the producers' fee tokens
alongside it.
- **Decimals come from the token list.** For a listed token, the
post-fill fee-token balance check takes its decimals from the list
instead of a metadata read. Balance diffs and the fee breakdown do the
same for tokens that the simulation names. Symbols and names still come
from the simulation, or from the chain when the simulation doesn't name
the token, so displayed strings are unchanged.
Changeset: `accounts` patch. AGENTS.md gains a learned fact about
`stale`. The PR also adds a friction entry (`frog log --target viem`)
for the viem Tempo actions that #952 and #954 had to work around:
`Actions.amm.getPool` forces deployless multicalls, and
`Actions.token.getBalance` reads `decimals()` on every call.
## Measurements
Localnet relay over a chain declaring Multicall3, behind a recording
transport that adds 30 ms per upstream request and allows 6 concurrent
connections (like a Worker). Unsponsored fill, 37-token list. "Expired"
is a fill 61 s after a warm one (`Date` faked).
| Fill | main | This PR |
| --- | --- | --- |
| Expired producer cache | 15 requests, 4 sequential waves (the
liquidity check waits on getBlock, block reads, `validatorTokens`,
pools) | 2 waves (the stale producers answer the check and the reload
runs alongside) |
| First fill on a fresh cache | 16 requests, 4 waves | 15 requests, 4
waves (no metadata read for the listed fee token) |
| Sponsored fill, token list that never loads | waits for the list |
returns sponsored without it |
The background reload still issues its 11 requests during that fill, and
under a Worker's six connections they can delay the fill's own requests.
Batching those block reads would need the host's transport to batch
JSON-RPC, so I left it.
## Tests
- `kv.test.ts`: an entry within `stale` of expiring is served while one
reload runs, and concurrent stale reads start no second reload. Past the
window the caller waits. A store wrapped per request (empty L1) still
gets the stale entry from storage, which keeps it for `ttl + stale` (660
s).
- `relay.localnet.test.ts` (`behavior: cold caches`): a sponsored fill
with the sponsor's fee token returns sponsored while the token list
never resolves. An unsponsored fill whose fee token and transferred
token are listed sends no `decimals()` read, and still reports on-chain
symbols (`AlphaUSD`) with 6 decimals. Both fail on main.
## Verification
- `VITE_NODE_ENV=localnet VITE_NODE_TAG=latest pnpm test` on
`relay.localnet.test.ts` (67), `feeLiquidity.localnet.test.ts` (8),
`kv.test.ts` (17) and `utils.test.ts` (3): all pass.
- `pnpm check` (pre-commit) and `pnpm exec tsc -b --noEmit`.
Summary
Tempo mainnet, Moderato and devnet deploy Multicall3 at
0xcA11bde05977b3631167028862bE2a173976CA11at genesis (eth_getCodeat block 0 returns its bytecode on all three; localnet has it too). viem's Tempo chains don't declare it, soHandler.relayandHandler.exchangebuilt their clients withbatch.multicall.deployless: every batchedeth_callshipped Multicall3's ~6.6 KB of bytecode as constructor data.Utils.withMulticall3(chain)adds that Multicall3 (blockCreated: 0) to chains 4217, 42431 and 31318, and leaves a chain that declares its owncontracts.multicall3alone. Clients use deployless calls only for chains without one. Localnet (1337) keeps deployless calls, since its chain ID isn't Tempo's alone. I'm opening a viem PR that addscontracts.multicall3to the Tempo chains, which would make this redundant.FeeLiquidityreads pools withreadContract(client, Actions.amm.getPool.calls(...)[0]).Actions.amm.getPoolalways passesdeployless: truetomulticall, so on any client it sent its own deployless batch. It also read each pool's LPtotalSupply, which the relay doesn't use.eth_callinstead of viem's 1 KB default. A Worker opens at most six connections at once, and a 37-token balance discovery alone took two calls; reserve reads for every candidate took many more, and they queued ahead of the fill.Handler.exchangekeeps the default batch size, because its quote reads cost much more gas.Changeset:
accountspatch. AGENTS.md gains a learned fact.Measurements
Localnet relay over a chain that declares the Multicall3, behind a recording transport that adds 30 ms per upstream request and allows 6 concurrent connections (like a Worker). Warm caches and a 37-token list. The "before" column includes #947.
feeToken(one balance read)Tests
utils.test.ts:withMulticall3adds the Multicall3 to mainnet, Moderato and devnet, keeps their other contracts, and leaves localnet and a chain's own Multicall3 alone.relay.localnet.test.ts(behavior: multicall): over a chain declaring Multicall3, a fill sends everyeth_callto it, with no deployless calls, including the pool reads. The fill resolves the same fee token. A 37-token list's balances go out in oneeth_call. On main they split into 25 and 12.Verification
VITE_NODE_ENV=localnet VITE_NODE_TAG=latest pnpm testonrelay.localnet.test.ts(61),feeLiquidity.localnet.test.ts(8) andexchange.localnet.test.ts(17), plusutils.test.ts: all pass.pnpm check(pre-commit) andpnpm exec tsc -b --noEmit.