@adraffy/soltype
v0.1.0
Published
Type-level Solidity parser: get a fully-typed ABI from Solidity source at compile time
Maintainers
Readme
soltype.js
Type-level Solidity parser: get a fully-typed ABI from Solidity source at compile time.
import { extractAbi } from '@adraffy/soltype';
const abi = extractAbi(`contract C {
function f(uint256 x, string memory b) external view returns (uint256 c) {}
}`);
// const abi: readonly [{
// type: "function";
// name: "f";
// inputs: readonly [
// { name: "x"; type: "uint256"; internalType: "uint256" },
// { name: "b"; type: "string"; internalType: "string" }
// ];
// outputs: readonly [{ name: "c"; type: "uint256"; internalType: "uint256" }];
// stateMutability: "view";
// }]The output has the same shape as solc's JSON ABI and works with abitype and viem:
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';
const client = createPublicClient({ chain: mainnet, transport: http() });
const total = await client.readContract({
address: '0x...',
abi: extractAbi(`interface IERC20 {
function totalSupply() external view returns (uint256);
}`),
functionName: 'totalSupply', // autocompleted
}); // bigintExamples:
- examples/ens.ts builds typed contracts with
getContractand readsvitalik.ethfrom the ENS registry and resolver (bun examples/ens.ts). - examples/deploy.ts is a
deploySolidity(code, { args })that returns a typed contract instance. The constructor args are typed from the source too. - examples/run.ts is
runFunction(code, args). You give it a single function, likerunFunction(`(uint a, uint b) returns (uint) { return a + b; }`, [1n, 2n]), and it wraps the function in a contract, compiles it with solc, deploys it to anvil, and calls it. The args and return value are typed (bun examples/run.ts, needs anvil).
Install
npm i @adraffy/soltypeAPI
// { [contractName]: Abi }
parseSolidity(src);
type T = ParseSolidity<typeof src>;
// ABI of one contract (default: the last contract in the source)
extractAbi(src, name?);
type T = ExtractAbi<typeof src, Name?>;
// parameter types for your own functions that take Solidity source:
// parse errors become compile errors at their call sites
function deploy<const S extends string>(code: ValidSolidity<S>) {} // checks the contract you extract
function compileAll<const S extends string>(code: ValidSoliditySource<S>) {} // checks every contract
// the intermediate AST
parseSource(src);
type T = ParseSource<typeof src>;Types only
@adraffy/soltype/types exports only the types (ExtractAbi, ParseSolidity, ParseSource, ValidSolidity, ValidSoliditySource, the Abi* and AST types) and contains no runtime code. Use it to type an ABI you already have, or to build your own wrappers:
import type { ExtractAbi } from '@adraffy/soltype/types';
import json from './C.abi.json';
const src = `contract C { function f(uint256 x) external view returns (bool) {} }`;
const abi = json as ExtractAbi<typeof src>;The main entry re-exports all of these types too.
If the source isn't a string literal (eg. string, or `contract C { function f${string} }` inside a generic function), there's nothing to parse at compile time: ExtractAbi gives Abi, ParseSolidity gives Record<string, Abi>, and the validators accept it.
Errors
The runtime functions return the same values the types describe. If the source doesn't parse, you get a compile error at the call site:
extractAbi(`contract C { function f(Foo x) external {} }`);
// Argument of type '"contract C { ... }"' is not assignable to parameter of type
// '"contract C { ... }" & ["soltype: unknown type \"Foo\""]'.At runtime the same input throws a SoltypeError.
Supported
contract,abstract contract,interface,library, inheritance (is A, B(args)), overrides, diamondsfunction,constructor,fallback,receive,event(indexed,anonymous),errorpublicstate variables become getters (mappings, named mapping params, arrays, struct getters that skip array/mapping fields)structbecomes a tuple withcomponents,enumbecomesuint8, user-defined value types (type P is uint128), contracts/interfaces asaddress,address payable, external function types, fixed and dynamic arrays- type resolution through contract scope, base contracts, file level, and qualified names (
IShape.Info) - file-level errors and events are included when used via
revert X(...)oremit X(...) - comments, strings, assembly blocks and modifiers are skipped correctly
Limitations
- Single source: imported symbols can't be resolved (you get
unknown type "X"), andimport {A as B}aliases are ignored. - Array lengths must be literals:
uint[N]givesuint256[N]. - A used error or event is only found when
revert/emitcomes after whitespace.require(cond, MyError())isn't detected. - Items come out in declaration order (most-derived contract first), not in solc's sorted order.
- C3 linearization is approximated, which is exact for typical hierarchies.
- Pre-0.5 syntax (the unnamed
function()fallback) isn't supported. - Library-specific ABI encoding of
storageparameters isn't modeled.
How it works
In TypeScript's type system, every template-literal match that captures "the rest of the string" creates a new string type that is never freed. A naive type-level parser therefore copies the rest of the file for every token, so its memory grows quadratically. soltype avoids that in three ways:
- Windowed input. The source is consumed through a window of about 32 lines. All scanning happens inside the window, so every intermediate string is small, and the window is only extended when a scan can't finish within it.
- Two tiers. A structural scanner jumps between
;,{,}, quotes and comments. It cuts out each declaration's header (eg.function f(uint x) external returns (bool)) and skips bodies, modifier arguments and initializers without tokenizing them. Only the short header strings are tokenized. - Chunked loops. TypeScript caps any single loop at 1000 iterations, so long loops yield every 400 steps and an outer loop resumes them. There's no limit on the number of declarations.
A second stage resolves names into ABI types. src/runtime.ts mirrors the type-level code step for step, so the value matches its type.
Performance (an interface of N functions, each with 3 inputs and 2 outputs):
| N | source | TS 7 | TS 5.9 | TS 5.9 memory | |---|---|---|---|---| | 100 | 12KB | 0.12s | 0.16s | 108MB | | 400 | 49KB | 0.35s | 0.44s | 253MB | | 1200 | 147KB | 1.7s | 1.8s | 921MB | | 2000 | 245KB | 4.4s | 5.1s | 1.8GB |
Function bodies are cheap: a contract with 400 implemented functions (79KB) takes 0.48s.
Development
bun install
bun run test # runtime vs solc, then tsc (type-level vs runtime)
bun run gen # regenerate test/types.gen.ts after changing fixtures
bun run buildTests check a chain of equalities on every fixture in test/fixtures.ts:
test/runtime.test.ts: the runtime parser's output equals solc's ABI.test/types.gen.ts: the type-level parser's output equals the runtime output exactly.test/api.test-d.ts: abitype interop and compile-time errors.
License
MIT
