Update after learnings or mistakes -- when a correction, new convention, or hard-won lesson emerges during development, append it to the relevant section of this file immediately. AGENTS.md is the source of truth for project conventions and should grow as the project does.
- Exact optional properties --
exactOptionalPropertyTypesis enabled in tsconfig. Optional properties must include| undefinedin their type if they can be assignedundefined(e.g.foo?: string | undefined, notfoo?: string). - No unchecked indexed reads --
noUncheckedIndexedAccessis enabled. Narrow indexed reads before use, or make the invariant obvious with the smallest possible assertion. readonlyarrays -- usereadonly T[]for array types in type definitions.- Existing
readonlyproperties are fine -- ox has DOM-shaped WebAuthn types, type snapshots, and inference-heavy literals that intentionally preservereadonlyproperties. Do not churn them just to satisfy a style preference. typeoverinterfaceby default -- usetypefor project-owned shapes. Ambient declarations and DOM-shaped compatibility types may useinterface..jsextensions -- all relative source imports include.jsfor ESM compatibility.- Follow local import style -- ox uses both namespace imports and named internal imports. Match the surrounding file instead of mass-converting import lists.
- Zod import aliases -- import
zod/miniasz, and import zod module namespaces asz_<Module>(for example,import * as z_Hex from '../Hex.js'). - Classes for errors only -- all other APIs use functions and plain data.
- Errors live next to the code that throws them -- module-specific failure classes live inside the module that owns the failure mode. Place each error class near the bottom of the module so the public functions and types are what the reader sees first. Set
nameto the namespaced form ('Hex.InvalidHexValueError','SignatureEnvelope.VerificationError', etc.). - No enums -- use union types or
as constobjects for fixed sets. - camelCase constants -- prefer
camelCasefor local constants unless the surrounding file already uses protocol-style uppercase names for numeric constants. constgeneric modifier -- use to preserve literal types for full inference.- Options default
= {}-- useoptions: Options = {}notoptions?: Options. - Namespace params and return types -- place function parameter, return, and error types in a
declare namespacematching the function name (e.g.from.Options,serialize.ErrorType). Do not lift the params type to a sibling export unless the surrounding module already has a shared type. optionsoverargs-- useoptionsfor typed option bags. Use domain nouns only when the parameter is not an options bag.- Minimal variable names -- prefer short, obvious names. Use
optionsnotserializeOptions,fnnotcallbackFunction, etc. Context makes meaning clear. - No redundant type annotations -- if the return type of a function already covers it, do not annotate intermediate variables. Let the return type do the work.
- No inline object types on locals -- when a local variable needs an explicit object-type annotation, declare a named
typeon the line directly above and reference it. - Return directly -- do not declare a variable just to return it. Use
return { ... }unless the variable is needed for reuse or readability. - IIFE expressions for fallible local derivations -- when a local needs
try/catchto parse or normalize a value, prefer an IIFE expression overlet value: Tfollowed by assignment insidetry. - Skip braces for single-statement blocks -- omit
{}for single-statementif,for, etc., when the surrounding file follows that style. - No section separator comments -- do not use
// ---or// ===divider comments. Let JSDoc and whitespace provide structure. - Static imports by default -- use static
importdeclarations. Dynamic imports are reserved for real runtime boundaries already present in ox, such as worker or WASM loading. - Minimize
as any-- avoid newas anywhere a safer assertion is practical, but do not mass-rewrite existing crypto, tuple, and inference glue that already relies on it. - Destructure when accessing multiple properties -- prefer
const { a, b } = optionsover repeatedoptions.a,options.b. - Read from
options.xwhen normalizing a single field -- when transforming exactly one option into a local of the same name, read it directly fromoptionsinstead of destructuring and inventing a second name. - Hex helpers over ad hoc conversion -- use ox helpers like
Hex.fromNumber,Hex.toBytes,Bytes.fromHex,Value.fromGwei, etc. instead of open-coded conversions. - Use ox branded types -- prefer existing ox types such as
Hex.Hex,Bytes.Bytes, andAddress.Addressover raw template literal types when the branded module type exists. - Alphabetize type properties -- order object type properties alphabetically, keeping each property’s TSDoc with it. Preserve positional order in tuples, arrays, ABI parameters, and other wire formats.
- Alphabetize object properties -- order properties in object literals alphabetically, including examples and tests. Preserve spread override precedence and evaluation order when reordering could change behavior.
- Preserve literals -- use
constgenerics and narrow helper signatures when an API should preserve literal inputs. - Type tests in
.test-d.ts-- use Vitest'sexpectTypeOfin colocated.test-d.tsfiles to assert generic inference works. Type tests are first-class; write them alongside implementation. - Snapshot inferred public types -- use
.snap-d.tswhen the repo's existing type snapshot pattern fits the change. - No
anyleakage -- user-facing callback, return, and option types should not leakanyunless the surrounding API already intentionally does. - Type inference after every feature -- after implementing any feature, check if new types can be narrowed. Add or update type tests alongside behavioral tests when public inference changes.
- Construct Ox objects through module APIs -- use constructors such as
TxEnvelopeEip8141.from,Frame.from, andFrameSignature.fromin examples and test setup. Use plain nested objects when the enclosing constructor validates them and encoding supplies omitted-field defaults. Use raw objects when testing raw input handling or invalid values. - Stateless module APIs -- public APIs are module namespaces full of functions and types. Do not introduce stateful classes for normal library behavior.
- Public export checks -- update
src/core/_test/index.test.tswhen adding a root module export, and runpnpm zile examples:checkfor new JSDoc examples. - Public entrypoint docs -- when adding a public module or export, update
src/index.tswith the module export and TSDoc block. - Package exports are generated -- run
pnpm exports:updateonly when intentionally adding, removing, or renaming public subpath exports. - Keep public APIs lean -- avoid exposing options for values the library can derive from existing inputs.
- Wire formats stay explicit -- serialization, RPC, RLP, ABI, and transaction-envelope code should keep wire-order and field-shape decisions visible at the call site.
- Internal helpers stay internal -- keep helper modules under
internal/unless they are part of the public API. - Global registries are for delegation and caching only --
Engine(implementation delegation) andCaches(memoization) are the sanctioned exceptions to stateless module APIs. A new one needs aresetfor test isolation, must not change type-level behavior, and must not require a side-effect import to install (sideEffects: falselets bundlers drop those, so the registration would silently vanish). - Engine slots hold overrides, never defaults --
src/core/internal/engine.tsimports nothing and holds only whatEngine.setinstalled. Pre-populating the registry with defaults would put them on a complete slot object, and a slot object is a single reachable value that esbuild cannot shake the properties off, so every default's@noble/*import survives into any bundle touching the slot. Measured on a keccak256-only bundle, 3.8 kB becomes 8.8 kB gzip. - One resolver module per slot, one binding per primitive -- each slot has an
internal/<slot>.tsthat pairs a<name>Defaultbinding with an exported resolver pickingoverrides.<Slot>?.<name> ?? <name>Default. Separate bindings are what keep the primitives independently shakeable: grouping a slot's defaults into one object regressesKeystore.pbkdf2by 3.7 kB gzip by tying@noble/ciphers/aesand@noble/hashes/scryptto it. - Declare defaults and resolvers against the contract -- both are typed
Complete<Slot>['name'].Completemakes every slot function required, so a default that goes missing or drifts from the contract fails to compile at the declaration rather than at a call site. - Public modules never spell the fallback -- they do
import * as engine from './internal/<slot>.js'and callengine.<name>(...). A?? defaultat a call site means the slot is missing a resolver. - Provider modules stay usable as Ox modules --
ox/nodeandox/wasmslot namespaces re-export the corresponding core API and exposeengine()for their raw installable slot. CoreEngine.installresolves slot promises in parallel and installs only after all resolve.
- TSDoc on public exports -- every exported public function, type, and constant gets a TSDoc comment. Type properties get TSDoc when they are part of the public surface.
- Doc-driven API changes -- write or update the TSDoc before or alongside the implementation, not as an afterthought.
- Examples should be small -- public examples should show the minimum useful shape and avoid unrelated setup.
- Source docs first -- public API documentation usually belongs in TSDoc near the exported source.
- Site pages -- human guides live under
site/src/pages/. - Generated docs --
site/src/pages/api,site/src/pages/ercs,site/src/pages/node,site/src/pages/tempo,site/src/pages/wasm,site/src/pages/webauthn,site/src/pages/glossary, andsite/src/pages.gen.tsare generated outputs. Do not edit them by hand unless explicitly requested. - Check TSDoc when touching docs -- run
pnpm docs:genafter changing public comments or examples. - No
{@link}to error classes in descriptions -- error classes share one generatederrorspage, so{@link ox#Module.SomeError}in a function description renders a link to a page that does not exist andvocs buildfails on the dead link. Write the name in backticks instead.pnpm docs:gendoes not catch this; onlypnpm docs:builddoes. - SEO descriptions are auto-derived -- every generated docs page emits a
descriptionfrontmatter (used for<meta name="description">and OG images), targeting 5-15 words. It is derived from the TSDoc summary (markdown stripped, first paragraph, clamped). Add an optional@descriptionTSDoc block tag to a function/namespace/schema to override the auto-derived text with hand-written SEO copy. Hand-written site pages should set their owndescriptionfrontmatter (or a# Title [description]heading).
- No eager type definitions -- do not extract a named type until it is used in more than one place or makes a difficult local shape easier to read.
- Shared domain types live near their module -- keep reusable public types in the module that owns the domain concept.
- Error unions live in namespaces -- exported function error unions should live in that function's namespace as
ErrorType.
- Prefer duplication over the wrong abstraction -- duplicated code with a clear bug-fix burden is better than a bad abstraction that is scary to change.
- Do not abstract until the commonalities scream -- wait for 3+ concrete use cases where the right abstraction becomes obvious. Do not abstract for 1-2 instances.
- Optimize for change -- code that is easy to change beats code that is cleverly DRY. We do not know future requirements.
- No flags or mode parameters -- if an abstraction needs
ifbranches or boolean params to handle different call sites, it is usually the wrong abstraction. Inline it. - Start concrete, extract later -- begin inline. Extract only when a clear pattern emerges across multiple real usages.
- Use
pnpm testfor tests -- run tests through package scripts, notvitestdirectly. - Target the relevant project -- prefer
pnpm test --project core --bail=1,pnpm test --project browser --bail=1, orpnpm test --project tempo-unit --project tempo --bail=1over the full matrix while iterating. - Colocate tests -- unit tests live beside their modules in
src/**/_test/*.test.ts. - Wrap function exports in
describe-- every test file targets one or more exported functions; each function gets its owndescribe('functionName', () => { ... })block. - Inline snapshots over direct assertions -- prefer
toMatchInlineSnapshot()over.toBe(),.toEqual(), etc. for stable return values. UsetoThrowErrorMatchingInlineSnapshot()for error assertions. - Snapshot whole objects, omit nondeterministic properties -- destructure out nondeterministic fields and snapshot the rest, rather than cherry-picking individual fields to assert.
- Browser tests use browser suffixes -- browser-specific behavior uses
*.browser.test.tsand thebrowserVitest project. - Fuzz tests stay gated -- fuzz harnesses use
*.fuzz.tsand run throughpnpm test:fuzz; defaultpnpm testshould not pick them up. - Fuzz regressions become deterministic -- when a property fails, add the minimized case as a regular
*.test.tsor vector fixture. - Vectors use Bun -- run vector tests with
pnpm vectors. That covers the generated corpora undervectors/only. Published upstream fixtures (NIST.rsp, XKCP intermediate values) live intest/vectors/, are consumed by colocated*.vectors.test.tssuites, and run in thecoreproject instead --pnpm vectorswill not touch them. - Match neighboring module tests -- group envelope tests by public function, use named cases and inline error snapshots, assert complete inferred types, and show the API calls directly in integration tests.
- Unit and type tests as you go -- write unit tests and
.test-d.tstype tests alongside implementation for each public behavior change.
- Use targeted commands -- prefer the smallest command that covers the touched behavior.
- Reusable workflow concurrency identity -- use a literal identity instead of
github.workflowin a called workflow's concurrency group. GitHub resolvesgithub.workflowto the caller, which can self-cancel when the groups match. - Types -- run
pnpm check:typesafter TypeScript changes. - Repo checks -- run
pnpm check:repowhen package metadata or workspace shape changes. - Docs dev server -- use
pnpm docs:devfor documentation UI work. pnpm checkmutates -- it runsvp check --fix. Use it only when intentionally applying lint/format fixes.- Format workflow edits before release --
pnpm changeset:versionrunspnpm check, so unformatted workflow YAML enters the release commit and its push is rejected byGITHUB_TOKEN. Runpnpm exec vp fmt .github/workflows/<file>.ymlwhen editing workflows. pnpm exports:updatemutates -- it rewritespackage.json#exports.pnpm docs:genandpnpm docs:buildmutate generated docs output -- run only when docs generation is part of the task.FC_NUM_RUNSsets the fuzz budget, and CI owns the number --pnpm test:fuzzruns thefuzzproject on Node at 100 cases per property; the workflow raises it to 2000 through the environment. Size it against a runner rather than a laptop: 10k timed out at the default per-test limit in CI. Browsers are opt-in viapnpm test:fuzz --project fuzz-browser, since they triple the wall time and their unique risk (native codecs differing between engine versions) is already pinned per pull request by the*.conformance.tssuites. Thefuzzprojects raisetestTimeout: onetestis thousands of cases, so the unit-test default does not apply.pnpm bench:enginesneeds a C compiler for native references -- it compares every Ox engine slot, plusox/node,ox/wasm, and native C for every WASM primitive. It builds a temporary executable frombench/native. Without a C compiler, C reports unavailable while the Ox columns still run. A full run takes several minutes.- Native C benchmarks mirror WASM target configuration -- compile the same wrappers, vendored sources, and target defines for the host. Use raw Engine inputs, preserve encodings, and exclude C from fastest-engine calculations.
pnpm contracts:buildmutates generated contract artifacts -- it runs Forge andcontracts/scripts/generate-typed-artifacts.ts.- Install hooks can mutate --
pnpm installrunspostinstall, which initializes submodules, builds contracts with the compiler pinned incontracts/foundry.toml, and runspnpm dev.
- Changesets only for public behavior -- add or update a changeset when a change affects public API or existing behavior.
- Update existing changesets first -- if the branch already has a changeset for the same area, update it instead of adding a duplicate.
- One sentence, past tense -- changeset entries are a single sentence written in past tense.
- Breaking changes include migration shape -- major changes include a
difffence showing the before/after migration shape.
- Conventional commits -- use
feat:,fix:,refactor:,docs:,test:,chore:prefixes. Scope is optional (e.g.feat(abi): add tuple formatter). - Preserve dirty work -- do not revert, clean, or overwrite existing local changes unless explicitly asked.
-
Source layout -- source lives in
src/; tests live undersrc/**/_test; docs live insite; shared test utilities live intest; vectors live invectors; contracts live incontracts. -
Node and pnpm -- the repo expects Node.js
>=22andpnpm@12.16.1. -
Generated exports --
scripts/exports:update.tsderivespackage.json#exportsfromsrc/. It flattenssrc/core/<Name>.tsto root package subpaths and ignores test/bench/snapshot files. -
Generated site pages -- API/reference pages under
site/src/pages/api,site/src/pages/ercs,site/src/pages/node,site/src/pages/tempo,site/src/pages/webauthn,site/src/pages/wasm, andsite/src/pages/glossaryare generated. -
Contracts submodule --
contracts/lib/forge-stdis a submodule path. Treat submodule status changes as user work unless the task is specifically about contracts setup. -
WASM artifacts are generated -- C lives in
wasm/src, targets inwasm/targets.ts, and the committed base64 modules (src/wasm/internal/*.wasm.ts,src/tempo/internal/mine.wasm.ts) are written bypnpm wasm:build. Never hand-edit them. After changing any C or target config, runpnpm wasm:buildand commit the result;pnpm wasm:checkfails CI otherwise. The toolchain is pinned inwasm/toolchain.jsonbecause compiled bytes depend on the exact compiler version. Seewasm/README.md. -
Trusted setup artifacts are generated --
src/trusted-setups/internal/setups/mainnet.jsonis canonical. Refresh it from an explicitc-kzg-4844release withpnpm trusted-setups:update <tag>;pnpm trusted-setups:checkverifies its recorded hash and packed TypeScript artifact. Seesrc/trusted-setups/README.md. -
KZG WASM disables LTO -- full LTO makes valid c-kzg trusted-setup initialization trap. Preserve
-fno-ltoand the KZG conformance tests. -
Secrets are local --
.envis local. Do not print, rewrite, or commit secrets. -
Tempo configurable accounts -- TIP-1107 accounts are modeled by
AccountConfigand theconfigurablesignature type. Every configurable signature carries[account, config, primitive approvals]; config includes a uint64 version. RPC uses the RLP bytes without the0x05prefix. Account addresses derive from the initial config alone, with no factory; configurable delegates require keychain V2. The relay layer is configurable-account scoped too (AccountOperation, theaccount_RPC namespace), since every configurable transaction carries its config. Hash domains follow Tempo main (tempo:configurable-account:*, renamed in tempoxyz/tempo#8502). On the wire the key type isconfigurableAccountand the simulation field isconfigurableAccountSimulation(tempoxyz/tempojoshie/configurable-t14-devnet-checkpoint); ox maps theconfigurablekey type toconfigurableAccountat the RPC boundary. The node allows configurable accounts as admin keys and as admin-key authorizers. -
Zone chain IDs -- Presto and Moderato use separate fixed bases and ranges. Derive chain IDs as
base + (zoneId % range). -
Offline core tests -- Set
SKIP_GLOBAL_SETUP=1for focused core tests that do not need Anvil. -
Docgen export comments --
extractNamespaceDocCommentsshould read the nearest JSDoc on an export declaration. ts-morph can include earlier file-level JSDoc descendants on the first export. -
Type snapshot config --
@ark/attest0.16 does not follow root project references. PointATTEST_CONFIG.tsconfigattest/tsconfig.json. -
Node local storage -- Node 24+ needs a valid
--localstorage-filefor the@typescript/vfsdependency used by attest. -
Frame nonce encodings -- omitted
nonceKeyspreserves seven-field EIP-8141 encoding; explicit keys, including[0n], select eight-field EIP-8250 encoding. RPC keepsnonceas the shared sequence. Infereip8141from either definedframesornonceKeys.