Skip to content

perf(relay): batch reads through Tempo's genesis Multicall3 - #952

Merged
gakonst merged 3 commits into
mainfrom
perf/relay-multicall3
Nov 3, 2026
Merged

gakonst merged 3 commits into
mainfrom
perf/relay-multicall3

Conversation

@gakonst

@gakonst gakonst commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Summary

Tempo mainnet, Moderato and devnet deploy Multicall3 at 0xcA11bde05977b3631167028862bE2a173976CA11 at genesis (eth_getCode at block 0 returns its bytecode on all three; localnet has it too). viem's Tempo chains don't declare it, so Handler.relay and Handler.exchange built their clients with batch.multicall.deployless: every batched eth_call shipped 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 own contracts.multicall3 alone. 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 adds contracts.multicall3 to the Tempo chains, which would make this redundant.
  • FeeLiquidity reads pools with readContract(client, Actions.amm.getPool.calls(...)[0]). Actions.amm.getPool always passes deployless: true to multicall, so on any client it sent its own deployless batch. It also read each pool's LP totalSupply, which the relay doesn't use.
  • The relay batches up to 16 KB of calldata per eth_call instead 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.exchange keeps the default batch size, because its quote reads cost much more gas.
  • An app fee payer URL's client reuses the relay client's chain and batch settings.

Changeset: accounts patch. 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.

Scenario Before After
Unsponsored fill (fee-token discovery) 8 requests, 70,010 calldata bytes 3 requests, 24,677 bytes
Unsponsored fill, explicit feeToken (one balance read) 6,638 bytes 484 bytes
Sponsored fill, cold metadata read 9,294 bytes 3,140 bytes

Tests

  • utils.test.ts: withMulticall3 adds 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 every eth_call to 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 one eth_call. On main they split into 25 and 12.

Verification

  • VITE_NODE_ENV=localnet VITE_NODE_TAG=latest pnpm test on relay.localnet.test.ts (61), feeLiquidity.localnet.test.ts (8) and exchange.localnet.test.ts (17), plus utils.test.ts: all pass.
  • pnpm check (pre-commit) and pnpm exec tsc -b --noEmit.

@vercel

vercel Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
accounts-site Ready Ready Preview Nov 3, 2026 9:28pm UTC

Request Review

@tempoxyz-bot

tempoxyz-bot commented Nov 3, 2026 •

Copy link
Copy Markdown

👁️ Cyclops Security Review

✅ Reviewed 2a9fd94 (latest) · Coverage: partial · ⚠️ 1 open finding · report
⚠️ Not checked: Multicall3 batching config, the feeLiquidity getPool rewrite, and the external fee-payer client batch reuse: ruled out without reading the cited code at this commit
⚠️ Not checked: Fee-liquidity reserve-read replacement: ruled out without reading the cited code at this commit
⚠️ Not checked: Batch partitioning and external sponsor transport separation: ruled out without reading the cited code at this commit
ℹ️ Not verifiable from the source alone (needs running code or deployed state): The source hardcodes Multicall3 at block zero for three public chain IDs. PR assertions and localnet fixtures do not independently prove that the expected bytecode exists at that address on each publi (1 more in the report)

# Severity Finding Introduced Status
1 🟡 Medium Relay's 16 KB shared multicall batches let one request starve others' reads 979e315 🟠 Open

@pkg-pr-new

pkg-pr-new Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/tempoxyz/accounts@952

commit: 2a9fd94

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

⚡ Accounts Bench

RendererScorevs main
Tempo Wallet · popup62−2
Tempo Wallet · iframe92±0
WebAuthn99±0
Timings
Renderer Case Wallet ready Confirm Total Total vs main Score Runs
Tempo Wallet · popup register 754 ms 1046 ms 1928 ms +34 ms (+2%) 52 5/5
Tempo Wallet · popup login 565 ms 542 ms 1239 ms +187 ms (+18%) 64 5/5
Tempo Wallet · popup send 908 ms 781 ms 1866 ms +268 ms (+17%) 72 5/5
Tempo Wallet · popup register-siwe 532 ms 544 ms 1272 ms −93 ms (−7%) 64 5/5
Tempo Wallet · popup register-key 545 ms 569 ms 1381 ms +148 ms (+12%) 62 5/5
Tempo Wallet · popup register-siwe-key 614 ms 582 ms 1388 ms −8 ms (−1%) 62 5/5
Tempo Wallet · popup login-siwe 563 ms 689 ms 1420 ms −48 ms (−3%) 61 5/5
Tempo Wallet · popup login-key 610 ms 579 ms 1333 ms −5 ms (−0%) 62 5/5
Tempo Wallet · popup login-siwe-key 586 ms 638 ms 1445 ms −1 ms (−0%) 61 5/5
Tempo Wallet · iframe register 207 ms 56 ms 469 ms +7 ms (+2%) 87 5/5
Tempo Wallet · iframe login 23 ms 58 ms 219 ms −17 ms (−7%) 96 5/5
Tempo Wallet · iframe send 421 ms 1003 ms 1572 ms +469 ms (+43%) 78 5/5
Tempo Wallet · iframe register-siwe 18 ms 147 ms 311 ms +7 ms (+2%) 93 5/5
Tempo Wallet · iframe register-key 23 ms 91 ms 266 ms +1 ms (+0%) 95 5/5
Tempo Wallet · iframe register-siwe-key 20 ms 180 ms 340 ms −46 ms (−12%) 92 5/5
Tempo Wallet · iframe login-siwe 20 ms 103 ms 271 ms −11 ms (−4%) 94 5/5
Tempo Wallet · iframe login-key 21 ms 28 ms 185 ms ±0 ms (±0%) 97 5/5
Tempo Wallet · iframe login-siwe-key 27 ms 125 ms 287 ms +15 ms (+6%) 94 5/5
WebAuthn register – – 17 ms ±0 ms (±0%) 100 5/5
WebAuthn login – – 19 ms +1 ms (+6%) 100 5/5
WebAuthn send – – 490 ms −132 ms (−21%) 97 5/5
WebAuthn register-siwe – – 95 ms −3 ms (−3%) 98 5/5
WebAuthn register-key – – 18 ms ±0 ms (±0%) 100 5/5
WebAuthn register-siwe-key – – 99 ms +5 ms (+5%) 98 5/5
WebAuthn login-siwe – – 92 ms −11 ms (−11%) 98 5/5
WebAuthn login-key – – 17 ms ±0 ms (±0%) 100 5/5
WebAuthn login-siwe-key – – 98 ms +8 ms (+9%) 98 5/5
Scoring

Each 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.

Metric Measures register / login, with any SIWE or access key (good · poor) send (good · poor)
Wallet ready App click → wallet approval button visible and enabled 100 · 800 ms 100 · 800 ms
Confirm Wallet approval click → app callback 200 · 1200 ms 800 · 3000 ms
Total App click → app callback 300 · 2000 ms 1000 · 4000 ms

send runs eth_sendTransactionSync, so it includes block inclusion on Tempo Testnet (Moderato). -siwe cases sign in to the bench app's Handler.auth server, and -key cases also authorize an access key.

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

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 declares contracts.multicall3 or its ID isn't in the set, so localnet (1337) and unknown chains still use deployless calls.
  • The relay and exchange client construction: deployless is now the negation of whether the wrapped chain has a Multicall3, and the external fee-payer client now takes client.batch, so it gets the same 16 KB batchSize and deployless setting.
  • The local getPool in feeLiquidity.ts: callers only read reserveValidatorToken, so dropping the LP totalSupply read 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
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

* 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 👍 / 👎.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

@gakonst
gakonst merged commit bd3974a into main Nov 3, 2026
42 checks passed
@gakonst
gakonst deleted the perf/relay-multicall3 branch November 3, 2026 21:37
gakonst added a commit that referenced this pull request Nov 3, 2026
## 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`.
gakonst added a commit that referenced this pull request Nov 3, 2026
## 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`.

This branch was successfully deployed

1 active deployment
Preview — 2a9fd94c Deployed Nov 3, 2026 by vercel[bot]
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