Skip to content

TypeScript + viem rewrite - #3

Merged
adraffy merged 40 commits into
mainfrom
typescript
Nov 18, 2026
Merged

adraffy merged 40 commits into
mainfrom
typescript

Conversation

@adraffy

@adraffy adraffy commented Nov 17, 2026 •

Copy link
Copy Markdown
Owner

Rewrites ezccip.js in TypeScript with bun and replaces ethers with viem. Intended to replace the current implementation, so the API has breaking changes (migration notes are in the README). The package is @adraffy/ezccip, version 0.2.0 (not yet published).

What changed

  • Stack: TypeScript (ESM-only, built with tsc), bun for tooling and tests, Biome for lint/format. viem is a peer dependency; dist/ is no longer committed. CI runs check, lint, tests, and build on bun, plus a smoke test of dist/ on Node 20/22/24.
  • Typed handlers: arguments and the result tuple are inferred from the ABI, so wrong output types are compile errors.
    • addFunctionHandler("function f(uint256 x) returns (string)" | abiFunction, (args, ctx, history) => result)
    • addAbiHandler(abi, "name", ...) for full ABIs, including human-readable ABIs with structs
  • Core has no HTTP: handleRequest(sender, calldata, { origin, chainId, protocol, signer, ttl, extra }) returns { data, context, history }. origin defaults to sender.
  • Context: ctx is one plain object per request, shared by every call in it (including multicall subcalls).
    • origin, protocol, signer, ttl are plain mutable fields, validated when signing.
    • ctx.extra is a Record<string, unknown> of caller values (eg. ip, Cloudflare env).
    • history (the log entry for that call) is the handler's third argument, like the original.
  • Signing: "raw", "ens", and "tor", with a private key or a viem LocalAccount. The default is "ens" with a signer, otherwise "raw" (was "tor"). ezccip.signer and ezccip.protocol can be changed after construction. verifyResponse() is exported.
  • HTTP adapters: both share cors, parseOrigin, and log.
    • serveEZCCIP(ezccip | resolve, options) (@adraffy/ezccip/serve) is a node:http server for Node, Bun, and Deno. It replaces serve(), sets ctx.extra.ip, and logs start, requests, errors, and shutdown.
    • createFetchHandler(ezccip) returns (request, extra?) => Response for Workers, Bun, Deno, and Hono.
  • Origin from the query: ?origin=0x...&chainId=1, both optional. ctx.chainId tells handlers the origin's network; it isn't signed. ⚠️ Origins in the URL path (/0xABCD.../) are no longer parsed; the README has a one-line parseOrigin for existing URLs.
  • ENSIP-10: enableENSIP10({ resolve, ...options }) takes an ENSRecordProvider.
    • If the provider returns nothing, resolve() reverts UnreachableName. If it returns {}, every profile answers empty. unreachableAsEmpty is removed.
    • EVM addr() values must be 20 bytes or empty.
    • pubkey() returns bigint | Hex coordinates and ABI() returns a bigint type.
    • processENSIP10(record, calldata, options?, history?) is standalone.
  • Multicall: recursionLimit is removed. multicall is only answered as the outer call, and its subcalls can't be multicall. resolve() may contain one multicall, so multicall([resolve(name, multicall([...]))]) works.
  • Errors: CCIPReadError messages and statuses reach clients: 400 bad input, 404 unknown function or profile, 405 method, 413 body too large. Any other error is a 500 with "internal error".
  • Layout: src/ is split by concern, with ENS code under src/ens/; tests mirror src/. AGENTS.md documents commands, layout, and conventions.
  • Housekeeping:
    • The package is renamed to @adraffy/ezccip, and repository links point to adraffy/ezccip.js.
    • LICENSE is MIT, © 2026 Andrew Raffensperger.
    • The demo is in scripts/demo.ts, signed by 0xd00d726b2aD6C81E894DC6B87BE6Ce9c5572D2cd, and reads its port from PORT (default 8016).
    • CCIP Postman is removed, moving to a separate project.

Fixes along the way

  • recursionLimit: 0 didn't actually disable multicall.
  • hasAddr() result was encoded incorrectly.
  • History.then() made history objects thenable, so awaiting one would hang or misbehave.

Testing

  • bun run check, bun run lint, bun test: 162 tests pass.
    • The tests include type assertions and "ens"/"tor" signature recovery, with the packed hash layouts pinned.
    • viem's ccipRequest works over a real server with POST and GET.
  • CI passes on bun and on Node 20, 22, and 24 (smoke test of the built dist/).
  • bun run start (the demo) serves "tor"; queried end to end, the responses verify as signed by 0xd00d726b2aD6C81E894DC6B87BE6Ce9c5572D2cd.
  • Not tested: deployed resolver contracts.

🤖 Generated with Claude Code

adraffy and others added 30 commits November 16, 2026 23:13
- TypeScript sources in src/, ESM-only build via tsc (dist/ no longer committed)
- ethers -> ox (abitype for typed ABI inference); viem only as dev dependency
- register(signature | AbiFunction, (args, context, history) => result)
  with args/outputs typed from the function
- remove "tor" protocol; "ens" signs via Hex private key or any
  { address, sign({hash}) } signer (eg. viem LocalAccount)
- replace node:http serve() with a bound fetch(Request) handler
  (Bun.serve / export default / Workers); GET + POST, CORS, origin from path
- handleRead({ sender, data, ...overrides }); generic extra context for
  handleRequest(request, extra)
- History.then() -> chain() (no longer thenable), head() -> last()
- CCIPReadError with HTTP status replaces error_with
- fix: recursionLimit 0 now actually disables multicall
- fix: hasAddr() result encoding
- tests rewritten with bun:test, including viem ccipRequest interop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- serveEZCCIP() (@namestone/ezccip/serve): Bun.serve wrapper that logs
  start, responses, errors, and shutdown by default; returns endpoint,
  signer, TOR context, idempotent shutdown(), and asyncDispose
- replace log/formatError options with onResponse/onError hooks
  (instance-level and per handleRequest call)
- handleRequest(request, { extra, onResponse, onError })
- "tor" protocol: getResponseHash/signResponse/verifyResponse handle
  both "ens" and "tor" (replaces *ENSResponse helpers)
- EZCCIP.protocol getter for the default protocol
- demo uses serveEZCCIP with "tor" and per-origin switch to "ens"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tsc rewrites .ts extensions in JS output but not in declarations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- viem is now a peer dependency (replaces ox); signers are viem
  LocalAccounts or private keys, DNS encoding uses viem's packetToBytes
- split ezccip.ts: types.ts, http.ts (request parsing, origin, hooks,
  handleRequest), errors.ts; merge signer.ts + protocol.ts -> signing.ts
- ENS code under src/ens/: abi, ensip10 (createENSIP10Handler,
  processENSIP10), coin-type, dns
- explicit public exports in index.ts
- renames: Handler -> FunctionHandler, RegisteredHandler ->
  RegisteredFunction, findHandler -> getFunction, RecordFunction ->
  GetRecord, ResponseEvent/ErrorEvent -> RequestSuccessEvent/
  RequestErrorEvent, labelsFromDnsEncoded -> dnsDecode,
  HandleReadResult -> HandleReadReturnType, Served -> EZCCIPServer
- verifyResponse is async (viem recoverAddress)
- tests mirror src/ and use viem; Biome lint/format (tabs, 120 cols)
- AGENTS.md (+ CLAUDE.md pointer) with commands, layout, conventions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…icall

- handlers are (args, ctx): CallContext is a per-call view of
  request-wide state (sender, calldata, request, origin, protocol,
  signer, ttl) plus that call's History; ctx.signer accepts SignerLike
- extra is a separate custom object (ctx.extra), no longer spread into
  the context; EZCCIP<extra = undefined>
- remove recursionLimit: multicall is only answered as the outer call
  and its subcalls cannot be multicall; resolve() may contain one
  multicall whose subcalls cannot be multicall
- History: drop level/record/last; enter() -> addChild(), chain() ->
  addInner(), next -> inner; logs args by default
- register -> addHandler, getFunction -> findHandler, functions ->
  handlers; FunctionHandler -> HandlerFunction, RegisteredFunction ->
  Handler, FunctionResult -> HandlerResult
- handleRead returns { data, context }
- ENSRecord.ABI(contentTypes) takes bigint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- serveEZCCIP() now uses node:http with a small Request/Response
  adapter instead of Bun.serve, so it runs on Node, Bun, and Deno;
  it is async again (awaits listen), `server` is a node:http Server,
  and shutdown() closes keep-alive connections
- drop the unneeded `const ccip = ezccip` alias (narrowing is
  preserved in closures after the last assignment)
- build types are ["node"], so dist .d.ts files don't need Bun types
- fix: `bun run build` failed with TS5096 since 56d2739
  (allowImportingTsExtensions left over after switching to .js
  specifiers); tsc still emitted, which hid the non-zero exit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…itch

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Bugs
- async hooks: rejections are now caught (were unhandled)
- fetch is typed `never` when `extra` is required (crashed at runtime)
- status codes: unknown function 404, bad calldata/origin 400 (were 500)
- empty bytes count as no value in addr/hasAddr (blocked ENSIP-19 fallback)
- fractional ttl no longer throws when signing
- "functionality()" signatures: prefix check requires "function "
- protocol is resolved after handlers run, so setting ctx.signer alone
  switches the default to "ens"

ENS
- addr(): values must be empty or exactly 20 bytes (no more truncation);
  same for addr(coinType) when the coin type is EVM
- chainFromCoinType returns undefined for non-EVM coin types
- profiles built from typed ABI items (no signature-keyed table)
- throwErrors -> throwUnsupported (404); ENSRecord.ABI type accepts number
- enableENSIP10/createENSIP10Handler take { resolve, ...options }

API
- EZCCIP options are private and copied; signer -> signerAddress
- `origin` option applies to handleRead(); parseOrigin defaults to
  originFromPath and replaces it when supplied
- ctx.calldata is this call's calldata
- non-CCIPReadError messages are hidden from clients ("internal error"),
  including multicall Error(string); onError gets the context
- HandlerResult allows void only for functions without outputs
- signing: object params everywhere, request -> calldata; verifyResponse
  checks expiry and an optional expected signer
- serveEZCCIP({ resolve, ... }) form; signer/context -> torContext
- drop exports: standalone handleRequest, ReadState, ExtraParameter,
  Awaitable, asciiize

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- handlers are (args, ctx, extra) and resolve is (name, ctx, extra);
  extra is threaded through calls (including multicall subcalls and
  resolve) instead of being stored on the context
- CallContext, RequestHooks, the request events, EZCCIPOptions, and
  HandleReadReturnType are no longer generic

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- validate handler results (non-hex strings), ctx.origin, and ttl
  (constructor, handleRead, ctx.ttl) instead of failing at signing time
- multicall is handled by the dispatcher, not registered as a handler,
  so it can't be replaced and isn't listed in handlers
- CallContext is a public interface; the class is internal
- History only builds the log line: name, show (array | false), error,
  children, inner
- dnsDecode -> dnsDecodeLabels + dnsDecodeName
- RESOLVE_ABI -> resolverAbi; ABI items, encodeErrorString,
  publicErrorMessage, formatCoinType, FetchHandler no longer exported
- shared ResponseOptions type for EZCCIPOptions and handleRead()
- cors option for handleRequest() and serveEZCCIP() (default true)
- serveEZCCIP splits ENSIP-10 options with a compiler-checked key list
- engines: node >= 20; scripts/smoke.mjs runs dist/ on any runtime
- GitHub Actions CI: bun (check, lint, test, build, smoke) and node
  20/22/24 (build, smoke)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… hardening

- serveEZCCIP takes an EZCCIP or a resolve function, then options; the
  resolve form signs with a random key unless signer is set; context
  (was torContext)
- enableENSIP10() returns the instance for chaining
- validate protocol (checkProtocol) and origin (checkOrigin) everywhere
- shared decodeArgs() for core and ENSIP-10
- serve: reject bodies over 1 MiB (413), log server errors instead of
  crashing
- callHook is async and never rejects; History escapes error messages
- verifyResponse: a response is valid through its expiry second

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… serve()

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- EZCCIP has no HTTP: handleRequest(sender, calldata, { origin, protocol,
  signer, ttl, extra }) replaces handleRead() and the Request-based
  handleRequest(); origin defaults to sender, like the original
- removed from EZCCIP: fetch, cors, parseOrigin, origin default, and the
  onResponse/onError hooks; ctx.request is gone
- serveEZCCIP reads {sender, data} straight from the node:http request
  (no fetch Request conversion) and owns cors, parseOrigin, log, and an
  extra(req) option for per-request data (eg. client IP)
- createFetchHandler(ezccip, { cors, parseOrigin, log, extra }) for
  fetch-based runtimes; extra gets the handler's extra arguments
  (eg. Cloudflare env)
- shared http.ts: parseCCIPReadPath/Body/Request, originFromPath, and an
  internal answer()/logAnswer() used by both adapters
- demo passes the client IP through extra, like the original context.ip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ument

- ctx is one plain object per request: origin, protocol, signer, ttl, extra
  are mutable fields, validated once when signing
- extra is a Record<string, unknown> on ctx (no EZCCIP<extra> generic);
  serveEZCCIP sets ip, createFetchHandler copies its second argument
- handlers are (args, ctx, history), like the original
- sign the request calldata, not ctx.calldata
- remove errorContext and answer()/logAnswer(); adapters handle errors inline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gnatures

- addHandler() requires a valid "function ..." signature (no implicit prefix)
- EZCCIP stores a Protocol ("ens" with a signer, otherwise "raw");
  checkProtocol only runs in the constructor and setter
- ezccip.signer (settable, undefined clears) and ezccip.protocol setters
- ctx.protocol is always a Protocol

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- EZCCIPOptions is defined directly; HandleRequestOptions extends it;
  ResponseOptions removed
- FetchHandlerOptions alias removed (createFetchHandler takes HTTPOptions);
  ServeOptions no longer redeclares log
- processENSIP10(record, calldata, options?, history?): history is its own
  argument, like the original; ENSIP10Options (an Omit<>) removed and
  ENSIP10Parameters = ProcessENSIP10Options & { resolve, unreachableAsEmpty? }

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
abi is an Abi or human-readable signatures (which may declare structs);
args and outputs are typed from the named function. Overloaded names throw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One signature each instead of three overloads:
- addFunctionHandler(signature | AbiFunction, handler)
- addAbiHandler(abi, functionName, handler)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- GetRecord -> ENSRecordProvider
- processENSIP10(record: ENSRecord, ...): pass {} for an empty record
  (resolve() returning nothing with unreachableAsEmpty still answers empty)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The empty-record default moves into processENSIP10; the internal answer()
still requires a record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Hex coordinates must be at most 32 bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…igint

- resolve returning nothing (undefined/null) reverts UnreachableName,
  returning {} answers every profile empty
- ENSRecord.ABI() returns type as bigint (no number)
- README: Unknown names vs empty records section, migration notes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ccip.js

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
adraffy and others added 10 commits November 17, 2026 18:43
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- default parseOrigin is originFromQuery: ?origin=0x...&chainId=1 (both
  optional, chainId decimal); returns { origin?, chainId? }
- handleRequest takes chainId; ctx.chainId (readonly, not signed)
- originFromPath removed; README shows a parseOrigin for path URLs
- LICENSE: Copyright (c) 2026 Andrew Raffensperger

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both adapters; ? when the chain is unknown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@adraffy
adraffy merged commit ac05ac1 into main Nov 18, 2026
4 checks passed
@adraffy
adraffy deleted the typescript branch November 18, 2026 07:51
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.

1 participant