Skip to content

perf: encode and decode hex RLP without converting through bytes - #5539

Closed
jxom wants to merge 1 commit into
mainfrom
perf/rlp-hex
Closed

jxom wants to merge 1 commit into
mainfrom
perf/rlp-hex

Conversation

@jxom

@jxom jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member

Speeds up hex RLP and transaction serialize/parse (B5 from the perf audit). Outputs and errors are unchanged. serializeTransaction and parseTransaction only call toRlp/fromRlp, so the transaction files themselves are unchanged.

Changes

  • toRlp(value, 'hex') builds the un-prefixed hex output directly. Hex leaves are lowercased and odd lengths get a leading zero, the same bytes hexToBytes would produce. Byte leaves go through bytesToHex. Anything else, such as invalid hex, a missing 0x, numbers or other objects, falls back to the existing byte encoder for the whole value, so it throws the same error. The result is flattened with one join. 'bytes' output is unchanged.
  • fromRlp(hex, 'hex') walks a valid hex string directly, with the same prefix, length, canonical-form, depth, list-boundary, trailing-byte and cursor PositionOutOfBoundsError checks (shared readLength). Invalid hex and 'bytes' output use the existing path.
  • Retention: a slice keeps its whole input alive.
    • For inputs up to 4096 hex characters, leaves are slices, so a kept leaf retains at most about 4 KiB.
    • For longer inputs, only leaves of at least 1/8 of the input (blobs, large calldata) are slices. Other leaves are copied with join.
    • This follows Ox's rule (perf: harden and speed up ABI, RLP, Hex and transport codecs ox#689). Instead of Bytes.fromHex + Hex.fromBytes for long inputs, it validates with a regex and copies short leaves, which measured about 3× faster on a 13 KiB list.
  • Benches: added hex RLP benches and realistic transaction benches: ERC-20 transfer, access list with 1 KiB calldata, EIP-7702 with 2 authorizations, EIP-4844 wrapper with 2 blobs. parseTransaction.bench.ts failed to load on main because its legacy fixture was signed with yParity and no v; it now uses v: 28n.

Benchmarks

SKIP_GLOBAL_SETUP=true ./node_modules/.bin/vitest bench -c ./test/vitest.config.ts --project core --run src/utils/encoding/toRlp.bench.ts src/utils/encoding/fromRlp.bench.ts src/utils/transaction/serializeTransaction.bench.ts src/utils/transaction/parseTransaction.bench.ts, origin/main vs this branch (ops/s):

Bench Before After
serializeTransaction legacy 244,518 353,919 1.45×
serializeTransaction EIP-1559 ERC-20 transfer 106,960 217,428 2.0×
serializeTransaction EIP-1559 access list + 1 KiB calldata 22,159 69,095 3.1×
serializeTransaction EIP-7702 56,050 99,431 1.8×
serializeTransaction EIP-4844, 2 blobs 128 920 7.2×
parseTransaction legacy 231,552 340,400 1.5×
parseTransaction EIP-1559 ERC-20 transfer 108,904 216,201 2.0×
parseTransaction EIP-1559 access list 20,948 48,739 2.3×
parseTransaction EIP-7702 62,824 108,137 1.7×
parseTransaction EIP-4844, 2 blobs 156 853 5.5×
toRlp hex, 200 × bytes32 7,546 18,782 2.5×
toRlp hex, 128 KiB blob 390 1,849 4.7×
fromRlp hex, 40 × bytes32 (short input) 36,275 120,145 3.3×
fromRlp hex, 200 × bytes32 (long input, copies) 7,658 17,514 2.3×
fromRlp hex, 2 × 128 KiB blobs 152 1,043 6.9×

The existing byte-input and byte-output RLP benches are unchanged, within noise.

Memory (node --expose-gc):

Case Allocated before → after Retained per result before → after
serializeTransaction EIP-4844 wrapper 8.53 → 1.01 MiB 513 → 513 KiB (the output)
parseTransaction EIP-4844 wrapper 8.52 → 1.01 MiB 8.01 MiB → 515 KiB
serializeTransaction access list 78.6 → 18.1 KiB
parseTransaction access list 69.7 → 20.0 KiB
toRlp 200 × bytes32 304.6 → 72.2 KiB 206 → 12.9 KiB

main retained 8 MiB per parsed blob wrapper, and 16× its size for a toRlp output, because bytesToHex output stays un-flattened. That primitive is outside this PR.

What a kept leaf retains of its input (r of a parsed blob wrapper, a leaf of a decoded list):

Case Input Retained before → after
parseTransaction(4844 wrapper).r 513 KiB 3.8 → 4.3 KiB
parseTransaction(4844 wrapper).sidecars 513 KiB 8.0 MiB → 514 KiB (blobs are slices)
fromRlp(200 × bytes32)[0] 12.9 KiB 0.0 → 0.2 KiB (copied)
fromRlp(40 × bytes32)[0] 2.6 KiB 0.7 → 2.6 KiB (slice of a short input, bounded at 4 KiB)

Correctness

  • Equivalence with origin/main: a scratch harness compared values, error class and message against copies of the origin/main modules. It ran 3 seeds, each with about 6k toRlp trees (hex and bytes output), 24k fromRlp inputs (hex and bytes output), 510 serializeTransaction and 228 parseTransaction cases. Everything matched.
    • toRlp leaves: empty, 0x0, odd lengths, mixed case, 0X, no prefix, trailing space, invalid characters, 55/56/255/256/2047/2048/70000-byte leaves, Uint8Array, Uint16Array, DataView, undefined, null, numbers, booleans and objects.
    • fromRlp: encodings around 4096 characters (each byte length from 2040 to 2050) and the 1/8 ratio, plus truncation, extra bytes, uppercase, 0X, no prefix, odd length, invalid characters at the start and end, random byte flips, depth 1023/1024/1100, and non-canonical and out-of-bounds lengths.
    • Transactions: random field corruption, then mutations of every serialized fixture type.
  • Ox fuzz: Ox's Rlp fuzz properties were ported to Viem's API, plus differential toRlp and fromRlp properties against origin/main on Ox's arbitraries: larger trees that cross 4096 characters, and changed, dropped, appended, recased or removed-nibble encodings. At 20,000 runs each, all 5 properties passed.
  • New tests in fromRlp.test.ts, with snapshots written against origin/main: mixed-case and odd-length input, short and long lists on both sides of the threshold (including uppercase), a blob leaf, a truncated long input's PositionOutOfBoundsError, and toRlp hex leaves in any case or length plus an invalid leaf's error. The toRlp cases live here because toRlp.test.ts only runs with TEST_RLP=true.
  • src/utils and src/accounts pass against Anvil: 171 files, 1878 tests. The OP Stack, Celo and zkSync serializer and parser tests, which CI's core project excludes, also pass (6 files, 101 tests). So does toRlp.test.ts without its 16 MiB cases, which run out of memory on main too.

Bundle size (needs a maintainer decision)

Adds about 100–400 B. Measured locally with the same tsc build and size-limit:

Entry main This PR Old limit → new limit
import * from 'viem' (esm) 91,274 91,650 92 → 92.5 kB
require('viem') (cjs) 118.5 → 119 kB
privateKeyToAccount 21,696 21,876 22 → 22.5 kB
viem/actions 72,793 73,206 73.5 → 74 kB
viem/chains 136,793 137,091 137.5 → 138 kB

CI measures about 200–300 B more than this local build. #5525, #5532 and #5533 raise the same limits, so whichever lands later needs another bump.

toRlp builds hex output straight from hex and byte leaves, falling back to
the byte encoder for anything else so errors are unchanged. fromRlp walks
hex input as a string with the cursor's bounds errors. Leaves of inputs up
to 4096 hex characters, and leaves of at least an eighth of a longer
input, are slices of it; other leaves are copied so they do not keep a
long input alive.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1e1b3-ce83-72d3-b448-f29dd09b6e57
Co-authored-by: jxom <[email protected]>
@vercel

vercel Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
viem Error Error Nov 16, 2026 2:33am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 16, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 61b183c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
viem Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T02:33:32.992659Z 61b183c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

Copy link
Copy Markdown
Contributor

Published [email protected] under the pr-5539 dist-tag, which follows this pull request until it closes.

pnpm add viem@pr-5539
pnpm add [email protected]

jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Bundled into #5543 as its own commit, so this PR is superseded. Closing in favour of the bundle.

@jxom jxom closed this Nov 16, 2026

This branch had an error being deployed

1 failed deployment
Preview — 61b183ca Deployed Nov 16, 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