diff --git a/.gitignore b/.gitignore index 6ec14b5..419dca5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,6 @@ dist .tsbuildinfo tsconfig.vitest-temp.json tsconfig.build.tsbuildinfo +.zig-cache .cursorrules llm_refs \ No newline at end of file diff --git a/README.md b/README.md index f36a74f..c56b4fb 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ const trace = await traceState({ ```typescript import { createMemoryClient, http } from "tevm"; import { mainnet } from "tevm/common"; + import { traceState } from "@polareth/evmstate"; // Initialize client @@ -137,6 +138,7 @@ The `Tracer` class provides an object-oriented interface for reusing client inst ```typescript import { createMemoryClient, http } from "tevm"; import { mainnet } from "tevm/common"; + import { Tracer } from "@polareth/evmstate"; // Initialize client @@ -363,6 +365,7 @@ For more control over the environment, you can provide your own Tevm client: ```typescript import { createMemoryClient, http } from "tevm"; import { mainnet } from "tevm/common"; + import { watchState } from "@polareth/evmstate"; // Create custom client with specific configuration @@ -412,3 +415,70 @@ The library combines several techniques to provide comprehensive state analysis: ## License MIT + +## Development Setup (Building from Source) + +If you want to contribute to `@polareth/evmstate` or build it from source, you'll need to set up your environment to compile both the TypeScript and the Zig code. The Zig code is compiled to WebAssembly (WASM) and called from TypeScript. Communication between TypeScript and Zig is handled using JSON strings (can be improved later with msgpack or flatbuffers). + +### Prerequisites + +1. **Node.js and pnpm**: + + - Node.js (LTS version recommended). + - [pnpm](https://pnpm.io/installation) (This project uses pnpm for package management). You can also use npm or yarn, but pnpm is preferred. + +2. **Zig Compiler**: + - Install the Zig compiler (latest stable version recommended). Follow the official installation guide: [Zig Installation](https://ziglang.org/learn/getting-started/) + - Ensure `zig` is available in your system's PATH. + +### Build Steps + +1. **Clone the Repository**: + + ```bash + git clone https://github.com/polareth/evmstate.git + cd evmstate + ``` + +2. **Install Dependencies**: + + ```bash + pnpm install + ``` + +3. **Compile Zig to WASM**: + Compile the Zig source code (in `src/zig/`) into a WebAssembly module: + + ```bash + pnpm build:zig + ``` + + This will output the WASM file to `dist/wasm/`. + +4. **Build the library**: + Compile both the TypeScript and Zig code: + ```bash + pnpm build + ``` + This command bundles the TypeScript code and ensures the Zig WASM module (expected in `dist/wasm/`) can be loaded, into the final distributable files in the `dist/` directory. + +### Development Workflow + +For active development, you can use watch scripts that automatically rebuild parts of the project when files change: + +- **Watch Zig and TypeScript tests**: + + ```bash + pnpm dev + ``` + + This will start parallel watchers for: + + - Zig source files (`.zig` files): Recompiles the WASM module and runs the tests. + - TypeScript tests (`.test.ts` files): Runs the tests in watch mode. + +- **Update zabi**: + + ```bash + zig fetch --save git+https://github.com/Raiden1411/zabi.git#zig_version_0.14.0 + ``` diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..f97e3fa --- /dev/null +++ b/build.zig @@ -0,0 +1,75 @@ +const std = @import("std"); + +pub fn build(b: *std.Build) void { + // Standard optimization options. This will respect -Doptimize= from the command line. + // We'll use -Doptimize=ReleaseSmall in the package.json script. + const optimize = b.standardOptimizeOption(.{}); + + // --- Zabi Dependency --- + // Add zabi as a dependency for the build. + // The .{} for the second argument means we are not overriding target or optimize for the dependency itself here. + const zabi = b.dependency("zabi", .{}); + + // Explicitly define the target for our WASM build + const wasm_target = b.resolveTargetQuery(.{ + .cpu_arch = .wasm32, + .os_tag = .freestanding, + }); + + // Create a module for our WASM library code. + // This points to your actual Zig code. + const wasm_lib_module = b.createModule(.{ + .root_source_file = b.path("src/zig/lib.zig"), // Path to your main Zig library file + .target = wasm_target, // Target this module for WASM + .optimize = optimize, // Apply optimization + }); + + // Create the WebAssembly artifact using addExecutable + const wasm_exe = b.addExecutable(.{ + .name = "evmstate", // The output filename will be evmstate.wasm + .root_module = wasm_lib_module, // Use the module we defined + // .target = wasm_target, // Target is implicitly taken from the root_module's target + // .optimize = optimize, // Optimize is implicitly taken from the root_module's optimize + }); + wasm_exe.rdynamic = true; // Required for exported functions to be callable from JS + wasm_exe.entry = .disabled; // Crucial: we are building a library, not an application + wasm_exe.root_module.addImport("zabi-abi", zabi.module("zabi-abi")); + + // Define the desired output path for the WASM file directly in the dist directory + const wasm_install_path = "dist/wasm/evmstate.wasm"; + + // Create a step to install the compiled WASM binary to the specified path. + // This handles the "copying" of the file. + const install_wasm_step = b.addInstallFile(wasm_exe.getEmittedBin(), wasm_install_path); + + // Define a "wasm" step in the build graph. + // Running `zig build wasm` will execute this step. + const build_wasm_step = b.step("wasm", "Build the WebAssembly artifact and install it"); + build_wasm_step.dependOn(&install_wasm_step.step); + + // If you want `zig build` (with no arguments from project root) + // to also build and install the WASM by default: + b.default_step.dependOn(build_wasm_step); + + // Get the native target for running tests. + // Pass .{} to use the host's native target. + const native_target = b.standardTargetOptions(.{}); + + // Add a test executable that includes all test blocks from lib.zig. + // Tests should generally run with the native target. + const main_tests = b.addTest(.{ + .root_source_file = b.path("src/zig/lib.zig"), // Points to the file containing the tests + .target = native_target, // Compile tests for the native architecture + .optimize = optimize, // Use the same optimization mode as the rest of the build (can be overridden) + // .filter = b.option([]const u8, "test-filter", "Filter for tests to run"), // Optional: allow test filtering + }); + // Make zabi available to your test code + // main_tests.root_module.addImport("zabi", zabi_module); + + // Create a "test" step that runs the test executable. + const run_main_tests_step = b.addRunArtifact(main_tests); + + // The `test` step will execute `run_main_tests_step` + const test_step = b.step("test", "Run unit tests for lib.zig"); + test_step.dependOn(&run_main_tests_step.step); +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..1af8c2c --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,52 @@ +.{ + // This is the default name used by packages depending on this one. For + // example, when a user runs `zig fetch --save `, this field is used + // as the key in the `dependencies` table. Although the user can choose a + // different name, most users will stick with this provided value. + // + // It is redundant to include "zig" in this name because it is already + // within the Zig package namespace. + .name = .evmstate, + + // This is a [Semantic Version](https://semver.org/). + // In a future version of Zig it will be used for package deduplication. + .version = "0.0.0", + + // Together with name, this represents a globally unique package + // identifier. This field is generated by the Zig toolchain when the + // package is first created, and then *never changes*. This allows + // unambiguous detection of one package being an updated version of + // another. + // + // When forking a Zig project, this id should be regenerated (delete the + // field and run `zig build`) if the upstream project is still maintained. + // Otherwise, the fork is *hostile*, attempting to take control over the + // original project's identity. Thus it is recommended to leave the comment + // on the following line intact, so that it shows up in code reviews that + // modify the field. + .fingerprint = 0xa34aadc5b3670a97, // Changing this has security and trust implications. + + // Tracks the earliest Zig version that the package considers to be a + // supported use case. + .minimum_zig_version = "0.14.0", + + // This field is optional. + // Each dependency must either provide a `url` and `hash`, or a `path`. + // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. + // Once all dependencies are fetched, `zig build` no longer requires + // internet connectivity. + .dependencies = .{ + .zabi = .{ + .url = "git+https://github.com/Raiden1411/zabi.git?ref=zig_version_0.14.0#b91004e008f81b34aee13fd78f1a3c8cf597eac3", + .hash = "zabi-0.16.1-UB4phl86SABdBvFceyCgBARQTki8rNko7MLouY-TeGVQ", + }, + }, + .paths = .{ + "build.zig", + "build.zig.zon", + "src", + // For example... + //"LICENSE", + //"README.md", + }, +} diff --git a/claude/plan.md b/claude/plan.md new file mode 100644 index 0000000..47324b0 --- /dev/null +++ b/claude/plan.md @@ -0,0 +1,549 @@ +## Plan: Transitioning TypeScript EVM State Labeling Library to Zig + +**1. Overall Goal & Scope** + +- **Objective:** Replace specific TypeScript modules (`@config.ts`, `@explore-storage.ts`, `@label-state-diff.ts`, `@mapping.ts`, `@utils.ts`) of an EVM state labeling library with a Zig implementation for improved performance and control. +- **Entry Point:** A single Zig function, `labelStateDiff`, will serve as the interface. +- **Interaction Model:** The TypeScript host will call the Zig `labelStateDiff` function. + - **Input:** Arguments will be passed from TypeScript to Zig, likely as a single JSON string. + + - **Output:** The Zig function will return its results to TypeScript, also likely as a single JSON string. +- **Core Task for Zig:** To take a state diff, storage layouts, transaction trace information, and ABIs to produce a human-readable, labeled version of the state diff. + +**2. Key Considerations & Zig Philosophy** + +- **Memory Management:** Rigorous use of `std.mem.Allocator` is required. All dynamically allocated structures will need `deinit` functions. An arena allocator for the top-level `labelStateDiff` call is recommended. + +- **Data Representation:** + - Prioritize `[N]u8` byte arrays for EVM-native data like addresses (`[20]u8`), slots (`[32]u8`), and `uint256` values (`[32]u8`). This directly mirrors EVM storage and is highly efficient. + + - Hexadecimal strings are primarily for the I/O boundary (JSON parsing/serialization). Internal processing should use binary representations. + + - `std.math.big.Int` usage should be minimized, especially if TypeScript can handle final interpretation of hex values based on type labels. It remains an option for complex `u256` arithmetic if needed internally. + +- **Error Handling:** Utilize Zig's error unions (`!T`) for robust error management. +- **String Handling:** `OwnedString` (e.g., `std.ArrayList(u8)`) for dynamic strings requiring ownership, and `[]const u8` (slices) for borrowed string data. + +**3. Proposed Zig Data Structures** + +This section details the Zig types for inputs, intermediate data, and final outputs. + +**3.1. Core Primitives & Basic Types** + +- `Address`: `[20]u8` +- `Slot`: `[32]u8` +- `StorageValue`: `[32]u8` +- `HexString`: `[]const u8` +- `ByteSlice`: `[]const u8` +- `OwnedString`: `std.ArrayList(u8)` +- `U256Bytes`: `[32]u8` +- `KeccakHash`: `[32]u8` + +**3.2. Input Structures (Derived from TypeScript `LabelStateDiffArgs`)** + +These will be parsed from the input JSON. + +```zig +// Equivalent to parts of TypeScript's LabeledIntrinsicsState +const ZigLabeledIntrinsicsState = struct { + balance: U256Bytes, // Parsed from input hex string. + nonce: u64, // Parsed from input hex string or number + code_hash: KeccakHash, // + deployed_bytecode_length: usize, +}; + +const ZigSlotDiff = struct { + current: ?StorageValue = null, // + next: ?StorageValue = null, // + modified: bool, +}; + +const ZigAddressState = struct { + intrinsics: ZigLabeledIntrinsicsState, + storage: std.HashMap(Slot, ZigSlotDiff, SlotContext, std.hash_map.default_max_load_percentage), // + + pub fn deinit(self: *ZigAddressState, allocator: std.mem.Allocator) void { + // Deinitialize storage HashMap + var iterator = self.storage.iterator(); + while (iterator.next()) |entry| { + // Assuming Slot and ZigSlotDiff don't have nested allocations needing deinit + // If they did, deinit them here. + } + self.storage.deinit(allocator); + } +}; + +// For SolcStorageLayout.types values +const ZigStructMember = struct { + label: OwnedString, + offset_in_slot_bytes: u8, + slot_offset_from_base: u64, // 'slot' in TS + type_id: OwnedString, // Reference to a key in ZigSolcStorageLayout.types + + pub fn deinit(self: *ZigStructMember, allocator: std.mem.Allocator) void { + self.label.deinit(allocator); + self.type_id.deinit(allocator); + } +}; + +const ZigTypeInfo = union(enum) { + inplace_primitive: struct { label: OwnedString, num_bytes: u8 }, + inplace_struct: struct { label: OwnedString, num_bytes: u32, members: std.ArrayList(ZigStructMember) }, + inplace_static_array: struct { label: OwnedString, num_bytes: u32, base_type_id: OwnedString, length: u64 }, + mapping: struct { label: OwnedString, num_bytes: u8, key_type_id: OwnedString, value_type_id: OwnedString }, // num_bytes usually 32 for the slot pointer + dynamic_array: struct { label: OwnedString, num_bytes: u8, base_type_id: OwnedString }, // num_bytes usually 32 for the slot pointer + bytes_or_string: struct { label: OwnedString, num_bytes: u8 }, // num_bytes usually 32 for the slot pointer + + pub fn deinit(self: *ZigTypeInfo, allocator: std.mem.Allocator) void { + switch (self.*) { + .inplace_primitive => |*p| p.label.deinit(allocator), + .inplace_struct => |*s| { + s.label.deinit(allocator); + for (s.members.items) |*member| member.deinit(allocator); + s.members.deinit(allocator); + }, + .inplace_static_array => |*a| { + a.label.deinit(allocator); + a.base_type_id.deinit(allocator); + }, + .mapping => |*m| { + m.label.deinit(allocator); + m.key_type_id.deinit(allocator); + m.value_type_id.deinit(allocator); + }, + .dynamic_array => |*a| { + a.label.deinit(allocator); + a.base_type_id.deinit(allocator); + }, + .bytes_or_string => |*b| b.label.deinit(allocator), + } + } +}; + +// For SolcStorageLayout.storage variables +const ZigStorageVariable = struct { + label: OwnedString, + offset_in_slot_bytes: u8, + base_slot_index: u64, // 'slot' in TS for top-level vars + type_id: OwnedString, // Reference to a key in ZigSolcStorageLayout.types + + pub fn deinit(self: *ZigStorageVariable, allocator: std.mem.Allocator) void { + self.label.deinit(allocator); + self.type_id.deinit(allocator); + } +}; + +const ZigSolcStorageLayout = struct { + storage_vars: std.ArrayList(ZigStorageVariable), + types: std.HashMap(OwnedString, ZigTypeInfo, std.hash_map.StringContext, std.hash_map.default_max_load_percentage), + + pub fn deinit(self: *ZigSolcStorageLayout, allocator: std.mem.Allocator) void { + for (self.storage_vars.items) |*var| var.deinit(allocator); + self.storage_vars.deinit(allocator); + + var type_iterator = self.types.iterator(); + while (type_iterator.next()) |entry| { + entry.key_ptr.*.deinit(allocator); // Deinit OwnedString key + entry.value_ptr.*.deinit(allocator); // Deinit ZigTypeInfo + } + self.types.deinit(allocator); + } +}; + +// For structLogs from transaction trace +const ZigStructLog = struct { + op: OwnedString, + stack: std.ArrayList(StorageValue), // Stack values are 32 bytes (U256Bytes) + + pub fn deinit(self: *ZigStructLog, allocator: std.mem.Allocator) void { + self.op.deinit(allocator); + // Assuming StorageValue items don't need deinit + self.stack.deinit(allocator); + } +}; + +// For ABI definitions +// +// +// +const ZigAbiInput = struct { + name: ?OwnedString = null, // Name can be null (e.g. for unnamed return values) + type_str: OwnedString, // e.g., "uint256", "address[]" + // components for tuples could be added if deep ABI parsing is needed later + + pub fn deinit(self: *ZigAbiInput, allocator: std.mem.Allocator) void { + if (self.name) |*n| n.deinit(allocator); + self.type_str.deinit(allocator); + } +}; + +const ZigAbiFunction = struct { + name: OwnedString, + selector: [4]u8, // + inputs: std.ArrayList(ZigAbiInput), + + pub fn deinit(self: *ZigAbiFunction, allocator: std.mem.Allocator) void { + self.name.deinit(allocator); + for (self.inputs.items) |*input| input.deinit(allocator); + self.inputs.deinit(allocator); + } +}; + +// Configuration for storage exploration +const ZigExploreConfig = struct { + mapping_exploration_limit: usize = 10, // Default value + max_mapping_depth: usize = 5, // Default value + early_termination_threshold: usize = 100, // Default value +}; + +// Simplified options (parts of TraceStateOptions relevant to Zig) +const ZigTraceStateOptions = struct { + config: ZigExploreConfig, + // Potential for other relevant options if identified +}; + +// Overall Input Arguments to `labelStateDiff` +const ZigLabelStateDiffArgs = struct { + allocator: std.mem.Allocator, // Allocator passed in for managing memory of this struct itself and its children + state_diff: std.HashMap(Address, ZigAddressState, AddressContext, std.hash_map.default_max_load_percentage), // + layouts: std.HashMap(Address, ZigSolcStorageLayout, AddressContext, std.hash_map.default_max_load_percentage), // + unique_addresses: std.ArrayList(Address), // + struct_logs: std.ArrayList(ZigStructLog), + abi_functions: std.ArrayList(ZigAbiFunction), // + options: ZigTraceStateOptions, + + pub fn deinit(self: *ZigLabelStateDiffArgs) void { + // Deinitialize all HashMaps and ArrayLists, including their contents + var state_diff_iter = self.state_diff.iterator(); + while (state_diff_iter.next()) |entry| entry.value_ptr.*.deinit(self.allocator); + self.state_diff.deinit(self.allocator); + + var layouts_iter = self.layouts.iterator(); + while (layouts_iter.next()) |entry| entry.value_ptr.*.deinit(self.allocator); + self.layouts.deinit(self.allocator); + + self.unique_addresses.deinit(self.allocator); + + for (self.struct_logs.items) |*log| log.deinit(self.allocator); + self.struct_logs.deinit(self.allocator); + + for (self.abi_functions.items) |*func| func.deinit(self.allocator); + self.abi_functions.deinit(self.allocator); + // ZigExploreConfig in options is by value, no deinit needed unless it contains pointers/allocations + } +}; +``` + +**3.3. Context Structs for HashMap Keys** + +```zig +// +// +// +const AddressContext = struct { + pub fn hash(_: AddressContext, key: Address) u64 { // + return std.hash.Wyhash.hash(0, key[0..]); // Hash the slice + } + pub fn eql(_: AddressContext, a: Address, b: Address) bool { // + return std.mem.eql(u8, &a, &b); + } +}; + +const SlotContext = struct { + pub fn hash(_: SlotContext, key: Slot) u64 { // + return std.hash.Wyhash.hash(0, key[0..]); // Hash the slice + } + pub fn eql(_: SlotContext, a: Slot, b: Slot) bool { // + return std.mem.eql(u8, &a, &b); + } +}; +// For OwnedString keys in HashMaps, use std.hash_map.StringContext +``` + +**3.4. Intermediate & Output Structures (for JSON Serialization)** + + + + +```zig +// Represents a path segment in the labeled state (e.g., struct field, array index) +const ZigPathSegmentPayload = union(enum) { + struct_field: struct { name: OwnedString }, + array_index: struct { index_hex: OwnedString }, // Hex string of u256 index + mapping_key: struct { key_hex: OwnedString, key_type_label: OwnedString }, // Hex string of the key + array_length: struct { name: []const u8 = "_length" }, + bytes_length: struct { name: []const u8 = "_length" }, + + pub fn deinit(self: *ZigPathSegmentPayload, allocator: std.mem.Allocator) void { + switch (self.*) { + .struct_field => |*s| s.name.deinit(allocator), + .array_index => |*a| a.index_hex.deinit(allocator), + .mapping_key => |*m| { + m.key_hex.deinit(allocator); + m.key_type_label.deinit(allocator); + }, + else => {}, // _length variants are const slices + } + } +}; + +// Mirroring PathSegmentKind from TypeScript +const ZigPathSegmentKind = enum { + StructField, + ArrayIndex, + MappingKey, + ArrayLength, + BytesLength, + // ... any other kinds +}; + +const ZigPathSegment = struct { + kind: ZigPathSegmentKind, + payload: ZigPathSegmentPayload, + + pub fn deinit(self: *ZigPathSegment, allocator: std.mem.Allocator) void { + self.payload.deinit(allocator); + } +}; + +// Simplified output value: just the hex of the extracted bytes. +// TypeScript will use the associated type_label to interpret this. +const ZigOutputValue = struct { + value_hex: OwnedString, // e.g., "fe" for an int8(-2), "0x..." for an address or full u256 + // + + pub fn deinit(self: *ZigOutputValue, allocator: std.mem.Allocator) void { + self.value_hex.deinit(allocator); + } +}; + +// Intermediate result from exploreStorage for one variable/path element +const ZigDecodedStorageItem = struct { + root_name: OwnedString, + root_type_label: OwnedString, + path: std.ArrayList(ZigPathSegment), + slots_used: std.ArrayList(Slot), // Slots contributing to this item + current_value: ?ZigOutputValue = null, + next_value: ?ZigOutputValue = null, + note: ?OwnedString = null, + full_expression_str: OwnedString, // Generated a.b.c[0] + + pub fn deinit(self: *ZigDecodedStorageItem, allocator: std.mem.Allocator) void { + self.root_name.deinit(allocator); + self.root_type_label.deinit(allocator); + for (self.path.items) |*p| p.deinit(allocator); + self.path.deinit(allocator); + self.slots_used.deinit(allocator); // Assuming Slot items don't need deinit + if (self.current_value) |*cv| cv.deinit(allocator); + if (self.next_value) |*nv| nv.deinit(allocator); + if (self.note) |*n| n.deinit(allocator); + self.full_expression_str.deinit(allocator); + } +}; + +// Final trace entry for a specific path within a variable +const ZigLabeledTraceEntry = struct { + modified: bool, + current: ?ZigOutputValue = null, + next: ?ZigOutputValue = null, + slots_touched: std.ArrayList(Slot), + path_segments: std.ArrayList(ZigPathSegment), + full_expression_str: OwnedString, + note: ?OwnedString = null, + + pub fn deinit(self: *ZigLabeledTraceEntry, allocator: std.mem.Allocator) void { + if (self.current) |*cv| cv.deinit(allocator); + if (self.next) |*nv| nv.deinit(allocator); + self.slots_touched.deinit(allocator); + for (self.path_segments.items) |*ps| ps.deinit(allocator); + self.path_segments.deinit(allocator); + self.full_expression_str.deinit(allocator); + if (self.note) |*n| n.deinit(allocator); + } +}; + +// Kind of storage variable +const ZigStorageVariableKind = enum { + primitive, + struct_type, // Renamed from 'struct' to avoid keyword clash + static_array, + dynamic_array, + bytes_type, // Renamed from 'bytes' + string_type, // Added for clarity + mapping, +}; + +// Final labeled information for a top-level storage variable +const ZigLabeledStorageVariable = struct { + name: OwnedString, // e.g., "myMapping", "userBalance" + type_label: OwnedString, // e.g., "mapping(address => uint256)", "uint8" + kind: ZigStorageVariableKind, + trace_entries: std.ArrayList(ZigLabeledTraceEntry), + + pub fn deinit(self: *ZigLabeledStorageVariable, allocator: std.mem.Allocator) void { + self.name.deinit(allocator); + self.type_label.deinit(allocator); + for (self.trace_entries.items) |*entry| entry.deinit(allocator); + self.trace_entries.deinit(allocator); + } +}; + +// Final labeled state for a single address +const ZigLabeledAddressStateResult = struct { + intrinsics: ZigLabeledIntrinsicsState, // Same as input, passed through + storage: std.HashMap(OwnedString, ZigLabeledStorageVariable, std.hash_map.StringContext, std.hash_map.default_max_load_percentage), + + pub fn deinit(self: *ZigLabeledAddressStateResult, allocator: std.mem.Allocator) void { + // Intrinsics are by value, no deinit needed unless they change to pointers + var iter = self.storage.iterator(); + while (iter.next()) |entry| { + entry.key_ptr.*.deinit(allocator); + entry.value_ptr.*.deinit(allocator); + } + self.storage.deinit(allocator); + } +}; + +// Final overall result structure to be serialized to JSON +const ZigTraceStateResult = struct { + allocator: std.mem.Allocator, + data: std.HashMap(Address, ZigLabeledAddressStateResult, AddressContext, std.hash_map.default_max_load_percentage), // + + pub fn deinit(self: *ZigTraceStateResult) void { + var iter = self.data.iterator(); + while (iter.next()) |entry| { + // Address key doesn't need deinit + entry.value_ptr.*.deinit(self.allocator); + } + self.data.deinit(self.allocator); + } +}; +``` + +**4. Proposed Zig Module Structure & Core Functions** + +- **`lib.zig` (or `main.zig` if building an executable for standalone testing):** + + - `pub fn labelStateDiff(allocator: std.mem.Allocator, args_json_string: []const u8) ![]u8` + - **FFI Entry Point.** + - Parses `args_json_string` into `ZigLabelStateDiffArgs` (e.g., using `std.json.parseFromSlice` ). This is a major component. + - Calls the main internal logic function (e.g., `state_labeler.processLabeling`). + - Serializes the returned `ZigTraceStateResult` to a JSON string (e.g., using `std.json.stringifyAlloc` ). + - Returns the allocated JSON string. The caller (TypeScript interop layer) is responsible for freeing this memory. + +- **`state_labeler.zig` (Orchestrates the labeling process):** + + - `fn processLabeling(gpa: std.mem.Allocator, args: *const ZigLabelStateDiffArgs) !ZigTraceStateResult` + - Prepares a slimmed/deduplicated version of `args.struct_logs` if needed for `extractPotentialKeys`. + - `potential_mapping_keys = try mapping_utils.extractPotentialKeys(gpa, slim_trace_log, args.unique_addresses.items, args.abi_functions.items, &args.options.config)` + + + - Iterates `args.unique_addresses`. For each address: + - Retrieves `ZigAddressState` and `ZigSolcStorageLayout`. + - If no layout, creates fallback "slot_0x..." entries. + - `explored_items_list = try storage_explorer.exploreStorage(gpa, layout, address_state_diff.storage, potential_mapping_keys.items, &args.options.config)` + - Processes `explored_items_list` and any unexplored slots from `address_state_diff.storage` into `ZigLabeledStorageVariable` map. + - Builds `ZigLabeledAddressStateResult`. + - Aggregates results into `ZigTraceStateResult` and returns it. + +- **`storage_explorer.zig` (Core storage decoding logic):** + + + + - `pub fn exploreStorage(gpa: std.mem.Allocator, layout: *const ZigSolcStorageLayout, storage_diff: *const std.HashMap(Slot, ZigSlotDiff, SlotContext, ...), candidate_keys: []const mapping_utils.MappingKey, config: *const ZigExploreConfig) !std.ArrayList(ZigDecodedStorageItem)` + - Initializes `explored_slots: std.HashSet(Slot, SlotContext, ...)` and `results_list: std.ArrayList(ZigDecodedStorageItem)`. + - Sorts `layout.storage_vars` by complexity/type if necessary (e.g., primitives first, then structs, then dynamic types). + - Iterates sorted `layout.storage_vars`, calling a recursive/iterative `exploreType` helper. + - `fn exploreType(ctx: *ExplorationContext) !void` + - `ExplorationContext` struct would bundle `gpa, layout, storage_diff, candidate_keys, config, current_type_id, current_base_slot, current_path: *std.ArrayList(ZigPathSegment), root_info: struct{name, type_label}, results_list: *std.ArrayList(ZigDecodedStorageItem), explored_slots_set: *std.HashSet(Slot, ...), etc.` + - Handles logic based on `ZigTypeInfo`: `inplace_primitive`, `inplace_struct` (recursive calls for members), `inplace_static_array` (iterative/recursive calls for elements), `mapping` (calls `exploreMapping`), `dynamic_array`, `bytes_or_string` (calls `decodeBytesOrStringContent`). + - `fn exploreMapping(ctx: *ExplorationContext, mapping_type: *const ZigTypeInfo.mapping) !void` + - Implements BFS/DFS logic to explore mapping entries using `candidate_keys` and `computeMappingSlot`. Respects `config.mapping_exploration_limit` and `config.max_mapping_depth`. + - `fn decodeBytesOrStringContent(gpa: std.mem.Allocator, storage_diff: *const std.HashMap(Slot, ZigSlotDiff, ...), base_data_slot: Slot, length_indicator_value: StorageValue, type_info: *const ZigTypeInfo.bytes_or_string, is_next_state: bool, explored_slots_set: *std.HashSet(Slot, ...)) !?struct { value_hex: OwnedString, slots_used: std.ArrayList(Slot), note: ?OwnedString }` + - Reads bytes for dynamic arrays, bytes, or strings. Handles short and long forms. + - Returns the hex of the assembled bytes and any notes (e.g., truncation). + + +- **`mapping_utils.zig` (Mapping key extraction and slot calculation):** + + - `const MappingKey = struct { hex_padded: U256Bytes, decoded_variant_hex: ?OwnedString, type_label: ?OwnedString };` + - `pub fn extractPotentialKeys(gpa: std.mem.Allocator, trace: *const RelevantStructLogInfo, addresses: []const Address, abi_functions: []const ZigAbiFunction, config: *const ZigExploreConfig) !std.ArrayList(MappingKey)` + + + + - Extracts potential mapping keys from stack values in struct logs, ABI inputs, etc. + - `pub fn sortCandidateKeys(gpa: std.mem.Allocator, keys: []MappingKey) void` (or sort in-place if `keys` is an `ArrayList`). + - `pub fn computeMappingSlot(key_bytes_padded: U256Bytes, base_mapping_slot: Slot) !Slot` + - Performs `keccak256(key_bytes_padded ++ base_mapping_slot)`. + +- **`decoding_utils.zig` (Primitive value decoding helpers):** + + + - `pub fn decodeSlotDiffToOutputValues(gpa: std.mem.Allocator, storage_diff: *const std.HashMap(Slot, ZigSlotDiff, ...), slot_key: Slot, type_info_primitive: *const ZigTypeInfo.inplace_primitive, offset_in_slot_bytes: u8) !struct { current: ?ZigOutputValue, next: ?ZigOutputValue }` + - Calls `decodePrimitiveFromStorageValue` for current and next states. + - `fn decodePrimitiveFromStorageValue(gpa: std.mem.Allocator, type_label: []const u8, num_bytes_for_type: u8, raw_slot_value: StorageValue, offset_in_slot_bytes: u8) !ZigOutputValue` + + - Extracts the relevant byte slice from `raw_slot_value` using `offset_in_slot_bytes` and `num_bytes_for_type`. + - Converts this byte slice to its hex string representation (e.g., `bytesToHex` ). + - Returns `ZigOutputValue{ .value_hex = hex_string }`. No sign extension or conversion to specific Zig integer types is done here for the final output; TypeScript will interpret the hex based on `type_label`. + - `fn extractRelevantBytesFromSlot(raw_slot_value: StorageValue, offset_from_right_bytes: u8, length_bytes: u8) ![]const u8` + + - Returns a slice of `raw_slot_value` corresponding to the field. Handles endianness if `raw_slot_value` is treated as little-endian by mistake (EVM is big-endian, so bytes are typically read from left/MSB). + +- **`config_parser.zig` (Handles parsing of `ZigExploreConfig` from JSON):** + + + - `pub fn parseExploreConfig(gpa: std.mem.Allocator, raw_config_json_value: std.json.Value) !ZigExploreConfig` + +- **`common_types.zig` (or split into multiple type files):** + + - Contains shared struct, enum, union definitions, and HashMap contexts if not defined locally. + + +- **`crypto.zig`:** + + - `pub fn keccak256(gpa: std.mem.Allocator, data: []const u8) !KeccakHash` + - Wrapper around a chosen Keccak256/SHA3 implementation (C library or pure Zig). + + +- **`abi_light_decoder.zig` (Minimal ABI decoding for key extraction):** + + - Functions to encode simple ABI parameters to their `U256Bytes` representation for `extractPotentialKeys` if needed. + + - `fn encodeAbiValueToPaddedBytes(gpa: std.mem.Allocator, type_str: []const u8, value_json: std.json.Value) !U256Bytes` + + +**5. Logic Changes & Considerations** + +- **Logic to be Replaced/Less Relevant (from TypeScript):** + - Most direct hex string manipulations (e.g., `padHex`, `toHexFullBytes`): Zig will work with `[N]u8` byte arrays and convert to/from hex strings only at I/O boundaries or for `ZigOutputValue.value_hex` . + - Complex ABI decoding (`viem`'s `decodeAbiParameters`): Replaced by targeted, simpler ABI value encoding/decoding as needed for key extraction and primitive interpretation + - `BigInt` for basic value representation and sign handling in `decodePrimitiveField`: Zig's `decodePrimitiveFromStorageValue` will now primarily extract bytes and convert to hex. Type information is passed alongside for TS to interpret. + - JavaScript-specific logging: Replace with `std.log`. + - TypeScript type assertions (`as X`), `@ts-expect-error`. +- **Additional Logic Needed in Zig:** + - **FFI Marshalling/Unmarshalling:** Robust JSON parsing for `ZigLabelStateDiffArgs` and serialization for `ZigTraceStateResult` using `std.json` . This is a critical and substantial part. + - **Allocator Management:** Meticulous `init` and `deinit` patterns for all allocated data. + - **Custom Hash Functions & Equality Checks:** For `Address`, `Slot` to be used as `HashMap` keys (examples provided). + - **Keccak256 Implementation:** Integrate a reliable Keccak256. + - **Targeted ABI Encoding:** For `extractPotentialKeys`, to get the 32-byte representation of potential key values from trace data. + - **UTF-8 Handling:** If `decodeBytesOrStringContent` needs to validate or specifically operate on UTF-8 strings (Zig's `std.unicode`). For `ZigOutputValue`, string types might be output as hex if non-ASCII, or as UTF-8 strings if valid. + +**6. Zig Specificities & Potential Optimizations** + +- **Memory Layout:** Default struct layout is usually fine. `packed struct` could be considered if memory is extremely critical and padding is an issue, but often not necessary. +- **Slices vs. Owned Data:** Use slices (`[]const u8`, `[]const T`) extensively for read-only access to avoid copies. `OwnedString` or `std.ArrayList(T)` where data needs to be owned, modified, or have a lifetime independent of its source. +- **Comptime:** Can be used for parsing/validating fixed configuration aspects or generating small lookup tables if beneficial. +- **Iterative vs. Recursive Exploration:** For deep structures (structs, static arrays), ensure the recursive `exploreType` doesn't risk stack overflow. An iterative approach with an explicit stack can be an alternative if depth is extreme. Mapping exploration (`exploreMapping`) is already planned as iterative (BFS/DFS). +- **JSON (De)serialization Performance:** While `std.json` is convenient, it can be a bottleneck for very large inputs/outputs. If performance here becomes critical, schema-aware parsers or alternative binary formats (if interop allows) could be explored, but start with `std.json`. + +**7. Development Strategy** + +- Start with the core data structures and simple utility functions (e.g., `decoding_utils.extractRelevantBytesFromSlot`, `crypto.keccak256` ). +- Implement robust JSON parsing for a subset of `ZigLabelStateDiffArgs` and serialization for a simple `ZigTraceStateResult`. +- Incrementally build out `storage_explorer.zig`, testing type by type (primitives, then structs, etc.). +- Develop and test `mapping_utils.zig` in parallel or subsequently, +- Integrate pieces into `state_labeler.zig` and finally `lib.zig`. +- Write comprehensive Zig tests for each module and function. + +This plan provides a detailed roadmap for the transition. The emphasis on `[N]u8` for EVM data (often via `zabi.types`), hex for I/O, and letting TypeScript handle final interpretation of `ZigOutputValue.value_hex` based on type labels should streamline the Zig implementation. Leveraging `zabi` for ABI handling, core types, crypto, and potentially JSON processing will significantly reduce boilerplate and ensure usage of optimized, well-tested components. diff --git a/claude/zabi-relevant-docs.html b/claude/zabi-relevant-docs.html new file mode 100644 index 0000000..9fd59eb --- /dev/null +++ b/claude/zabi-relevant-docs.html @@ -0,0 +1,8799 @@ +-------------------------------------------------------------------------------- +/docs/pages/index.mdx: +-------------------------------------------------------------------------------- + 1 | --- + 2 | title: 'Zabi: A zig library to interact with EVM blockchains' + 3 | --- + 4 | + 5 |
+ 6 | + 7 |

+ 8 | + 9 | ZAbi logo + 10 | + 11 |

+ 12 | + 13 |

+ 14 | A zig library to interact with ethereum and other EVM blockchains + 15 |

+ 16 | + 17 | # Overview + 18 | Zabi aims to add support for interacting with ethereum or any compatible EVM based chain. + 19 | + 20 | ### Zig Versions + 21 | + 22 | Zabi will support zig v0.13 in seperate branches. If you would like to use it you can find it in the `zig_version_0.13.0` branch where you can build it against zig 0.13.0. + 23 | The main branch of zabi will follow the latest commits from zig and the other branch will be stable in terms of zig versions but not features from zabi. + 24 | + 25 | ### Example Usage + 26 | ```zig + 27 | const args_parser = zabi.args; + 28 | const std = @import("std"); + 29 | const zabi = @import("zabi"); + 30 | const Wallet = zabi.clients.wallet.Wallet(.http); + 31 | + 32 | const CliOptions = struct { + 33 | priv_key: [32]u8, + 34 | url: []const u8, + 35 | }; + 36 | + 37 | pub fn main() !void { + 38 | var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + 39 | defer _ = gpa.deinit(); + 40 | + 41 | var iter = try std.process.argsWithAllocator(gpa.allocator()); + 42 | defer iter.deinit(); + 43 | + 44 | const parsed = args_parser.parseArgs(CliOptions, gpa.allocator(), &iter); + 45 | + 46 | const uri = try std.Uri.parse(parsed.url); + 47 | + 48 | var wallet = try Wallet.init(parsed.priv_key, .{ + 49 | .allocator = gpa.allocator(), + 50 | .network_config = .{ .endpoint = .{ .uri = uri } }, + 51 | }, false); + 52 | defer wallet.deinit(); + 53 | + 54 | const message = try wallet.signEthereumMessage("Hello World"); + 55 | + 56 | const hexed = try message.toHex(wallet.allocator); + 57 | defer gpa.allocator().free(hexed); + 58 | + 59 | std.debug.print("Ethereum message: {s}\n", .{hexed}); + 60 | } + 61 | ``` + 62 | + 63 | ### Installing Zig + 64 | + 65 | You can install the latest version of zig [here](https://ziglang.org/download/) or you can also use a version manager like [zvm](https://www.zvm.app/guides/install-zvm/) to manage your zig version. + 66 | + 67 | ### Features + 68 | + 69 | - Json RPC with support for http/s, ws/s and ipc connections. + 70 | - EVM Interpreter that you can use to run contract bytecode. + 71 | - Wallet instances and contract instances to use for interacting with nodes/json rpc. + 72 | - Wallet nonce manager that uses a json rpc as a source of truth. + 73 | - BlockExplorer support. Only the free methods from those api endpoints are supported. + 74 | - Custom Secp256k1 ECDSA signer using only Zig and implementation of RFC6979 nonce generator. + 75 | - Custom Schnorr signer. BIP0340 and ERC-7816 are both supported. + 76 | - Custom JSON Parser that can be used to deserialize and serialized RPC data at runtime. + 77 | - Custom solidity tokenizer and parser generator. + 78 | - Ability to translate solidity source code to zig. + 79 | - ABI to zig types. + 80 | - Support for EIP712. + 81 | - Support for EIP3074 authorization message. Also supports EIP7702 transactions. + 82 | - Parsing of human readable ABIs into zig types with custom Parser and Lexer. + 83 | - HD Wallet and Mnemonic passphrases. + 84 | - RLP Encoding/Decoding. + 85 | - SSZ Encoding/Decoding. + 86 | - ABI Encoding/Decoding with support for Log topics encoding and decoding. + 87 | - Parsing of encoded transactions and serialization of transaction objects. + 88 | - Support for all transaction types and the new EIP4844 KZG commitments. + 89 | - Support for OPStack and ENS. + 90 | - Custom meta programming functions to translate ABI's into zig types. + 91 | - Support for interacting with test chains such as Anvil or Hardhat. + 92 | - Custom cli args parser that translates commands to zig types and can be used to pass data to methods. + 93 | - Custom data generator usefull for fuzzing. + 94 | + 95 | And a lot more to come yet to come... + 96 | + 97 | ### Goal + 98 | + 99 | The goal of zabi is to be one of the best library to use by the ethereum ecosystem and to expose to more people to the zig programming language. +100 | +101 | # Sponsors +102 | +103 | ::sponsors +104 | + + +-------------------------------------------------------------------------------- +/docs/pages/integration.md: +-------------------------------------------------------------------------------- + 1 | # Integrating ZAbi + 2 | + 3 | ### Zig Package Manager + 4 | In the `build.zig.zon` file, add the following to the dependencies object. + 5 | + 6 | ```zig + 7 | .zabi = .{ + 8 | .url = "https://github.com/Raiden1411/zabi/archive/VERSION_NUMBER.tar.gz", + 9 | } +10 | ``` +11 | +12 | The compiler will produce a hash mismatch error, add the `.hash` field to `build.zig.zon` +13 | with the hash the compiler tells you it found. +14 | +15 | You can also use `zig fetch` to automatically do the above steps. +16 | +17 | ```bash +18 | zig fetch --save https://github.com/Raiden1411/zabi/archive/VERSION_NUMBER.tar.gz +19 | zig fetch --save git+https://github.com/Raiden1411/zabi.git#LATEST_COMMIT +20 | ``` +21 | +22 | To install zabi with the latest zig version you can install it like so +23 | +24 | ```bash +25 | zig fetch --save git+https://github.com/Raiden1411/zabi.git#zig_version_0.14.0 +26 | ``` +27 | +28 | Zabi will only maintain the latest version available. So when 0.15.0 eventually releases it use that and 0.14.0 will no longer be supported and so on. +29 | +30 | This should only be until zig reaches 1.0. +31 | +32 | Then in your `build.zig` file add the following to the `exe` section for the executable where you wish to have `zabi` available. +33 | +34 | ```zig +35 | const zabi_module = b.dependency("zabi", .{}).module("zabi"); +36 | // for exe, lib, tests, etc. +37 | exe.root_module.addImport("zabi", zabi_module); +38 | ``` +39 | +40 | Now in the code, you can import components like this: +41 | +42 | ```zig +43 | const zabi = @import("zabi"); +44 | const meta = zabi.meta; +45 | const encoder = zabi.encoder; +46 | ``` +47 | +48 | Zabi is a modular library meaning that you can import separete modules if you just need some components of zabi. +49 | +50 | ```zig +51 | const zabi = b.dependency("zabi", .{}); +52 | // for exe, lib, tests, etc. +53 | exe.root_module.addImport("zabi-evm", zabi.module("zabi-evm")); +54 | ``` +55 | +56 | Now in the code, you can import components like this: +57 | +58 | ```zig +59 | const zabi_evm = @import("zabi-evm"); +60 | ``` +61 | +62 | Currently these are all of the modules available for you to use in `zabi`: +63 | +64 | - zabi -> contains all modules. +65 | - zabi-abi -> contains all abi types and eip712. +66 | - zabi-ast -> contains a solidity tokenizer, parser and Ast. +67 | - zabi-clients -> contains all supported RPC clients and a block explorer clients. Also include a multicall clients as well as the wallet and contract client. +68 | - zabi-crypto -> contains the signer used in zabi as well BIP32 and BIP39 +69 | - zabi-decoding -> contains all decoding methods supported. +70 | - zabi-encoding -> contains all encoding methods supported. +71 | - zabi-ens -> contains a custom ens client and utils. +72 | - zabi-evm -> contains the EVM interpreter. +73 | - zabi-human -> contains a custom human readable abi parser. +74 | - zabi-meta -> contains all of the meta programming utils used in zabi. +75 | - zabi-op-stack -> contains custom op-stack clients and utils. +76 | - zabi-types -> contains all of the types used in zabi. +77 | - zabi-utils -> contains all of the utils used in zabi as well as the custom cli parser data generator. +78 | + + +-------------------------------------------------------------------------------- + + + +└── docs + └── pages + └── api + └── abi + ├── abi.md + ├── abi_parameter.md + ├── eip712.md + └── param_type.md + + +/docs/pages/api/abi/abi.md: +-------------------------------------------------------------------------------- + 1 | ## StateMutability + 2 | + 3 | Solidity abi stat mutability definition of functions and constructors. + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | enum { + 9 | nonpayable + 10 | payable + 11 | view + 12 | pure + 13 | } + 14 | ``` + 15 | + 16 | ## Abitype + 17 | + 18 | Set of possible abi values according to the abi spec. + 19 | + 20 | ### Properties + 21 | + 22 | ```zig + 23 | enum { + 24 | function + 25 | @"error" + 26 | event + 27 | constructor + 28 | fallback + 29 | receive + 30 | } + 31 | ``` + 32 | + 33 | ## PrepareErrors + 34 | + 35 | Set of possible errors when running `allocPrepare` + 36 | + 37 | ```zig + 38 | Allocator.Error || error{NoSpaceLeft} + 39 | ``` + 40 | + 41 | ## Function + 42 | + 43 | Solidity Abi function representation. + 44 | Reference: ["function"](https://docs.soliditylang.org/en/latest/abi-spec.html#json) + 45 | + 46 | ### Properties + 47 | + 48 | ```zig + 49 | struct { + 50 | type: Extract(Abitype, "function") + 51 | /// Deprecated. Use either 'pure' or 'view'. + 52 | /// + 53 | /// https://github.com/ethereum/solidity/issues/992 + 54 | constant: ?bool = null + 55 | /// Deprecated. Older vyper compiler versions used to provide gas estimates. + 56 | /// + 57 | /// https://github.com/vyperlang/vyper/issues/2151 + 58 | gas: ?i64 = null + 59 | inputs: []const AbiParameter + 60 | name: []const u8 + 61 | outputs: []const AbiParameter + 62 | /// Deprecated. Use 'nonpayable' or 'payable'. Consider using `StateMutability`. + 63 | /// + 64 | /// https://github.com/ethereum/solidity/issues/992 + 65 | payable: ?bool = null + 66 | stateMutability: StateMutability + 67 | } + 68 | ``` + 69 | + 70 | ### EncodeFromReflection + 71 | Abi Encode the struct signature based on the values provided. + 72 | + 73 | Compile time reflection is used to encode based on type of the values provided. + 74 | + 75 | ### Signature + 76 | + 77 | ```zig + 78 | pub fn encodeFromReflection( + 79 | self: @This(), + 80 | allocator: Allocator, + 81 | values: anytype, + 82 | ) (AbiEncoder.Errors || error{NoSpaceLeft})![]u8 + 83 | ``` + 84 | + 85 | ### Encode + 86 | Abi Encode the struct signature based on the values provided. + 87 | + 88 | This is only available if `self` is know at comptime. With this we will know the exact type + 89 | of what the `values` should be. + 90 | + 91 | ### Signature + 92 | + 93 | ```zig + 94 | pub fn encode( + 95 | comptime self: @This(), + 96 | allocator: Allocator, + 97 | values: AbiParametersToPrimative(self.inputs), + 98 | ) (AbiEncoder.Errors || error{NoSpaceLeft})![]u8 + 99 | ``` +100 | +101 | ### EncodeOutputs +102 | Encode the struct signature based on the values provided. +103 | Runtime reflection based on the provided values will occur to determine +104 | what is the correct method to use to encode the values. +105 | This methods will run the values against the `outputs` proprety. +106 | +107 | Caller owns the memory. +108 | +109 | ### Signature +110 | +111 | ```zig +112 | pub fn encodeOutputs( +113 | comptime self: @This(), +114 | allocator: Allocator, +115 | values: AbiParametersToPrimative(self.outputs), +116 | ) AbiEncoder.Errors![]u8 +117 | ``` +118 | +119 | ### Decode +120 | Decode a encoded function based on itself. +121 | Runtime reflection based on the provided values will occur to determine +122 | what is the correct method to use to encode the values. +123 | This methods will run the values against the `inputs` proprety. +124 | +125 | Caller owns the memory. +126 | +127 | Consider using `decodeAbiFunction` if the struct is +128 | comptime know and you dont want to provided the return type. +129 | +130 | ### Signature +131 | +132 | ```zig +133 | pub fn decode( +134 | self: @This(), +135 | comptime T: type, +136 | allocator: Allocator, +137 | encoded: []const u8, +138 | options: DecodeOptions, +139 | ) DecodeErrors!AbiDecoded(T) +140 | ``` +141 | +142 | ### DecodeOutputs +143 | Decode a encoded function based on itself. +144 | Runtime reflection based on the provided values will occur to determine +145 | what is the correct method to use to encode the values. +146 | This methods will run the values against the `outputs` proprety. +147 | +148 | Caller owns the memory. +149 | +150 | Consider using `decodeAbiFunction` if the struct is +151 | comptime know and you dont want to provided the return type. +152 | +153 | ### Signature +154 | +155 | ```zig +156 | pub fn decodeOutputs( +157 | self: @This(), +158 | comptime T: type, +159 | allocator: Allocator, +160 | encoded: []const u8, +161 | options: DecodeOptions, +162 | ) DecodeErrors!AbiDecoded(T) +163 | ``` +164 | +165 | ### AllocPrepare +166 | Format the struct into a human readable string. +167 | Intended to use for hashing purposes. +168 | +169 | Caller owns the memory. +170 | +171 | ### Signature +172 | +173 | ```zig +174 | pub fn allocPrepare( +175 | self: @This(), +176 | allocator: Allocator, +177 | ) PrepareErrors![]u8 +178 | ``` +179 | +180 | ### Prepare +181 | Format the struct into a human readable string. +182 | Intended to use for hashing purposes. +183 | +184 | ### Signature +185 | +186 | ```zig +187 | pub fn prepare( +188 | self: @This(), +189 | writer: anytype, +190 | ) PrepareErrors!void +191 | ``` +192 | +193 | ## Event +194 | +195 | Solidity Abi function representation. +196 | Reference: ["event"](https://docs.soliditylang.org/en/latest/abi-spec.html#json) +197 | +198 | ### Properties +199 | +200 | ```zig +201 | struct { +202 | type: Extract(Abitype, "event") +203 | name: []const u8 +204 | inputs: []const AbiEventParameter +205 | anonymous: ?bool = null +206 | } +207 | ``` +208 | +209 | ### Encode +210 | Generates the hash of the struct signatures. +211 | +212 | ### Signature +213 | +214 | ```zig +215 | pub fn encode(self: @This()) PrepareErrors!Hash +216 | ``` +217 | +218 | ### EncodeLogTopics +219 | Encode the struct signature based on the values provided. +220 | Runtime reflection based on the provided values will occur to determine +221 | what is the correct method to use to encode the values +222 | +223 | Caller owns the memory. +224 | +225 | ### Signature +226 | +227 | ```zig +228 | pub fn encodeLogTopics( +229 | self: @This(), +230 | allocator: Allocator, +231 | values: anytype, +232 | ) EncodeLogsErrors![]const ?Hash +233 | ``` +234 | +235 | ### DecodeLogTopics +236 | Decode the encoded log topics based on the event signature and the provided type. +237 | +238 | Caller owns the memory. +239 | +240 | ### Signature +241 | +242 | ```zig +243 | pub fn decodeLogTopics( +244 | self: @This(), +245 | comptime T: type, +246 | encoded: []const ?Hash, +247 | options: LogDecoderOptions, +248 | ) LogsDecoderErrors!T +249 | ``` +250 | +251 | ### AllocPrepare +252 | Format the struct into a human readable string. +253 | Intended to use for hashing purposes. +254 | +255 | Caller owns the memory. +256 | +257 | ### Signature +258 | +259 | ```zig +260 | pub fn allocPrepare( +261 | self: @This(), +262 | allocator: Allocator, +263 | ) PrepareErrors![]u8 +264 | ``` +265 | +266 | ### Prepare +267 | Format the struct into a human readable string. +268 | Intended to use for hashing purposes. +269 | +270 | ### Signature +271 | +272 | ```zig +273 | pub fn prepare( +274 | self: @This(), +275 | writer: anytype, +276 | ) PrepareErrors!void +277 | ``` +278 | +279 | ## Error +280 | +281 | Solidity Abi function representation. +282 | Reference: ["error"](https://docs.soliditylang.org/en/latest/abi-spec.html#json) +283 | +284 | ### Properties +285 | +286 | ```zig +287 | struct { +288 | type: Extract(Abitype, "error") +289 | name: []const u8 +290 | inputs: []const AbiParameter +291 | } +292 | ``` +293 | +294 | ### Encode +295 | Abi Encode the struct signature based on the values provided. +296 | +297 | This is only available if `self` is know at comptime. With this we will know the exact type +298 | of what the `values` should be. +299 | +300 | ### Signature +301 | +302 | ```zig +303 | pub fn encode( +304 | comptime self: @This(), +305 | allocator: Allocator, +306 | values: AbiParametersToPrimative(self.inputs), +307 | ) (AbiEncoder.Errors || error{NoSpaceLeft})![]u8 +308 | ``` +309 | +310 | ### Decode +311 | Decode a encoded error based on itself. +312 | Runtime reflection based on the provided values will occur to determine +313 | what is the correct method to use to encode the values. +314 | This methods will run the values against the `inputs` proprety. +315 | +316 | Caller owns the memory. +317 | +318 | Consider using `decodeAbiError` if the struct is +319 | comptime know and you dont want to provided the return type. +320 | +321 | ### Signature +322 | +323 | ```zig +324 | pub fn decode( +325 | self: @This(), +326 | comptime T: type, +327 | allocator: Allocator, +328 | encoded: []const u8, +329 | options: DecodeOptions, +330 | ) DecodeErrors!AbiDecoded(T) +331 | ``` +332 | +333 | ### AllocPrepare +334 | Format the struct into a human readable string. +335 | Intended to use for hashing purposes. +336 | +337 | Caller owns the memory. +338 | +339 | ### Signature +340 | +341 | ```zig +342 | pub fn allocPrepare( +343 | self: @This(), +344 | allocator: Allocator, +345 | ) PrepareErrors![]u8 +346 | ``` +347 | +348 | ### Prepare +349 | Format the struct into a human readable string. +350 | Intended to use for hashing purposes. +351 | +352 | ### Signature +353 | +354 | ```zig +355 | pub fn prepare( +356 | self: @This(), +357 | writer: anytype, +358 | ) PrepareErrors!void +359 | ``` +360 | +361 | ## Constructor +362 | +363 | Solidity Abi function representation. +364 | Reference: ["constructor"](https://docs.soliditylang.org/en/latest/abi-spec.html#json) +365 | +366 | ### Properties +367 | +368 | ```zig +369 | struct { +370 | type: Extract(Abitype, "constructor") +371 | inputs: []const AbiParameter +372 | /// Deprecated. Use 'nonpayable' or 'payable'. Consider using `StateMutability`. +373 | /// +374 | /// https://github.com/ethereum/solidity/issues/992 +375 | payable: ?bool = null +376 | stateMutability: Extract(StateMutability, "payable,nonpayable") +377 | } +378 | ``` +379 | +380 | ### EncodeFromReflection +381 | Abi Encode the struct signature based on the values provided. +382 | +383 | Compile time reflection is used to encode based on type of the values provided. +384 | +385 | ### Signature +386 | +387 | ```zig +388 | pub fn encodeFromReflection( +389 | self: @This(), +390 | allocator: Allocator, +391 | values: anytype, +392 | ) AbiEncoder.Errors![]u8 +393 | ``` +394 | +395 | ### Encode +396 | Abi Encode the struct signature based on the values provided. +397 | +398 | This is only available if `self` is know at comptime. With this we will know the exact type +399 | of what the `values` should be. +400 | +401 | ### Signature +402 | +403 | ```zig +404 | pub fn encode( +405 | comptime self: @This(), +406 | allocator: Allocator, +407 | values: AbiParametersToPrimative(self.inputs), +408 | ) AbiEncoder.Errors![]u8 +409 | ``` +410 | +411 | ### Decode +412 | Decode a encoded constructor arguments based on itself. +413 | Runtime reflection based on the provided values will occur to determine +414 | what is the correct method to use to encode the values. +415 | This methods will run the values against the `inputs` proprety. +416 | +417 | Caller owns the memory. +418 | +419 | Consider using `decodeAbiConstructor` if the struct is +420 | comptime know and you dont want to provided the return type. +421 | +422 | ### Signature +423 | +424 | ```zig +425 | pub fn decode( +426 | self: @This(), +427 | comptime T: type, +428 | allocator: Allocator, +429 | encoded: []const u8, +430 | options: DecodeOptions, +431 | ) DecodeErrors!AbiDecoded(T) +432 | ``` +433 | +434 | ## Fallback +435 | +436 | Solidity Abi function representation. +437 | Reference: ["fallback"](https://docs.soliditylang.org/en/latest/abi-spec.html#json) +438 | +439 | ### Properties +440 | +441 | ```zig +442 | struct { +443 | type: Extract(Abitype, "fallback") +444 | /// Deprecated. Use 'nonpayable' or 'payable'. Consider using `StateMutability`. +445 | /// +446 | /// https://github.com/ethereum/solidity/issues/992 +447 | payable: ?bool = null +448 | stateMutability: Extract(StateMutability, "payable,nonpayable") +449 | } +450 | ``` +451 | +452 | ## Receive +453 | +454 | Solidity Abi function representation. +455 | Reference: ["receive"](https://docs.soliditylang.org/en/latest/abi-spec.html#json) +456 | +457 | ### Properties +458 | +459 | ```zig +460 | struct { +461 | type: Extract(Abitype, "receive") +462 | stateMutability: Extract(StateMutability, "payable") +463 | } +464 | ``` +465 | +466 | ## AbiItem +467 | +468 | Union representing all of the possible Abi members. +469 | +470 | ### Properties +471 | +472 | ```zig +473 | union(enum) { +474 | abiFunction: Function +475 | abiEvent: Event +476 | abiError: Error +477 | abiConstructor: Constructor +478 | abiFallback: Fallback +479 | abiReceive: Receive +480 | } +481 | ``` +482 | +483 | ## Abi +484 | +485 | Abi representation in ZIG. +486 | +487 | ```zig +488 | []const AbiItem +489 | ``` +490 | +491 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/abi/abi_parameter.md: +-------------------------------------------------------------------------------- + 1 | ## PrepareErrors + 2 | + 3 | Set of possible errors when running `allocPrepare` + 4 | + 5 | ```zig + 6 | Allocator.Error || error{NoSpaceLeft} + 7 | ``` + 8 | + 9 | ## AbiParameter + 10 | + 11 | Struct to represent solidity Abi Paramters + 12 | + 13 | ### Properties + 14 | + 15 | ```zig + 16 | struct { + 17 | name: []const u8 + 18 | type: ParamType + 19 | internalType: ?[]const u8 = null + 20 | components: ?[]const AbiParameter = null + 21 | } + 22 | ``` + 23 | + 24 | ### Encode + 25 | Encode the paramters based on the values provided and `self`. + 26 | Runtime reflection based on the provided values will occur to determine + 27 | what is the correct method to use to encode the values + 28 | + 29 | Caller owns the memory. + 30 | + 31 | Consider using `encodeAbiParametersComptime` if the parameter is + 32 | comptime know and you want better typesafety from the compiler + 33 | + 34 | ### Signature + 35 | + 36 | ```zig + 37 | pub fn encode( + 38 | self: @This(), + 39 | allocator: Allocator, + 40 | values: anytype, + 41 | ) EncodeErrors![]u8 + 42 | ``` + 43 | + 44 | ### Decode + 45 | Decode the paramters based on self. + 46 | Runtime reflection based on the provided values will occur to determine + 47 | what is the correct method to use to encode the values + 48 | + 49 | Caller owns the memory only if the param type is a dynamic array + 50 | + 51 | Consider using `decodeAbiParameters` if the parameter is + 52 | comptime know and you want better typesafety from the compiler + 53 | + 54 | ### Signature + 55 | + 56 | ```zig + 57 | pub fn decode( + 58 | self: @This(), + 59 | comptime T: type, + 60 | allocator: Allocator, + 61 | encoded: []const u8, + 62 | options: DecodeOptions, + 63 | ) DecoderErrors!AbiDecoded(T) + 64 | ``` + 65 | + 66 | ### Prepare + 67 | Format the struct into a human readable string. + 68 | Intended to use for hashing purposes. + 69 | + 70 | ### Signature + 71 | + 72 | ```zig + 73 | pub fn prepare( + 74 | self: @This(), + 75 | writer: anytype, + 76 | ) PrepareErrors!void + 77 | ``` + 78 | + 79 | ## AbiEventParameter + 80 | + 81 | Struct to represent solidity Abi Event Paramters + 82 | + 83 | ### Properties + 84 | + 85 | ```zig + 86 | struct { + 87 | name: []const u8 + 88 | type: ParamType + 89 | internalType: ?[]const u8 = null + 90 | indexed: bool + 91 | components: ?[]const AbiParameter = null + 92 | } + 93 | ``` + 94 | + 95 | ### Prepare + 96 | Format the struct into a human readable string. + 97 | Intended to use for hashing purposes. + 98 | + 99 | ### Signature +100 | +101 | ```zig +102 | pub fn prepare( +103 | self: @This(), +104 | writer: anytype, +105 | ) PrepareErrors!void +106 | ``` +107 | +108 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/abi/eip712.md: +-------------------------------------------------------------------------------- + 1 | ## TypedDataDomain + 2 | + 3 | EIP712 typed data domain. Spec is defined [here](https://eips.ethereum.org/EIPS/eip-712) + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | struct { + 9 | chainId: ?u64 = null + 10 | name: ?[]const u8 = null + 11 | verifyingContract: ?[]const u8 = null + 12 | version: ?[]const u8 = null + 13 | salt: ?[]const u8 = null + 14 | } + 15 | ``` + 16 | + 17 | ## MessageProperty + 18 | + 19 | EIP712 message property type. Spec is defined [here](https://eips.ethereum.org/EIPS/eip-712) + 20 | + 21 | ### Properties + 22 | + 23 | ```zig + 24 | struct { + 25 | name: []const u8 + 26 | type: []const u8 + 27 | } + 28 | ``` + 29 | + 30 | ## EncodeTypeErrors + 31 | + 32 | Set of possible errors when encoding struct into human-readable format. + 33 | + 34 | ```zig + 35 | Allocator.Error || error{InvalidPrimaryType} + 36 | ``` + 37 | + 38 | ## EIP712Errors + 39 | + 40 | Set of possible errors when encoding the struct values. + 41 | + 42 | ```zig + 43 | EncodeTypeErrors || ParamErrors || error{ UnexpectTypeFound, NoSpaceLeft, InvalidLength } + 44 | ``` + 45 | + 46 | ## HashTypedData + 47 | Performs hashing of EIP712 according to the expecification + 48 | https://eips.ethereum.org/EIPS/eip-712 + 49 | + 50 | `types` parameter is expected to be a struct where the struct + 51 | keys are used to grab the solidity type information so that the + 52 | encoding and hashing can happen based on it. See the specification + 53 | for more details. + 54 | + 55 | `primary_type` is the expected main type that you want to hash this message. + 56 | Compilation will fail if the provided string doesn't exist on the `types` parameter + 57 | + 58 | `domain` is the values of the defined EIP712Domain. Currently it doesnt not support custom + 59 | domain types. + 60 | + 61 | `message` is expected to be a struct where the solidity types are transalated to the native + 62 | zig types. I.E string -> []const u8 or int256 -> i256 and so on. + 63 | In the future work will be done where the compiler will offer more clearer types + 64 | base on a meta programming type function. + 65 | + 66 | **Example** + 67 | ```zig + 68 | const domain: TypedDataDomain = .{ + 69 | .name = "Ether Mail", + 70 | .version = "1", + 71 | .chainId = 1, + 72 | .verifyingContract = "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", + 73 | }; + 74 | + 75 | const types = .{ + 76 | .EIP712Domain = &.{ + 77 | .{ .type = "string", .name = "name" }, + 78 | .{ .name = "version", .type = "string" }, + 79 | .{ .name = "chainId", .type = "uint256" }, + 80 | .{ .name = "verifyingContract", .type = "address" }, + 81 | }, + 82 | .Person = &.{ + 83 | .{ .name = "name", .type = "string" }, + 84 | .{ .name = "wallet", .type = "address" }, + 85 | }, + 86 | .Mail = &.{ + 87 | .{ .name = "from", .type = "Person" }, + 88 | .{ .name = "to", .type = "Person" }, + 89 | .{ .name = "contents", .type = "string" }, + 90 | }, + 91 | }; + 92 | + 93 | const hash = try hashTypedData(testing.allocator, types, "Mail", domain, .{ + 94 | .from = .{ + 95 | .name = "Cow", + 96 | .wallet = "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", + 97 | }, + 98 | .to = .{ + 99 | .name = "Bob", +100 | .wallet = "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", +101 | }, +102 | .contents = "Hello, Bob!", +103 | }); +104 | ``` +105 | +106 | ### Signature +107 | +108 | ```zig +109 | pub fn hashTypedData( +110 | allocator: Allocator, +111 | comptime types: anytype, +112 | comptime primary_type: []const u8, +113 | domain: ?TypedDataDomain, +114 | message: anytype, +115 | ) EIP712Errors![Keccak256.digest_length]u8 +116 | ``` +117 | +118 | ## HashStruct +119 | Performs hashing of EIP712 structs according to the expecification +120 | https://eips.ethereum.org/EIPS/eip-712 +121 | +122 | `types` parameter is expected to be a struct where the struct +123 | keys are used to grab the solidity type information so that the +124 | encoding and hashing can happen based on it.\ +125 | See the specification for more details. +126 | +127 | `primary_type` is the expected main type that you want to hash this message.\ +128 | Compilation will fail if the provided string doesn't exist on the `types` parameter +129 | +130 | `data` is expected to be a struct where the solidity types are transalated to the native +131 | zig types. I.E string -> []const u8 or int256 -> i256 and so on. +132 | +133 | In the future work will be done where the compiler will offer more clearer types +134 | base on a meta programming type function. +135 | +136 | **Example** +137 | ```zig +138 | const domain: TypedDataDomain = .{ +139 | .name = "Ether Mail", +140 | .version = "1", +141 | .chainId = 1, +142 | .verifyingContract = "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", +143 | }; +144 | const types = .{ +145 | .EIP712Domain = &.{ +146 | .{ .type = "string", .name = "name" }, +147 | .{ .name = "version", .type = "string" }, +148 | .{ .name = "chainId", .type = "uint256" }, +149 | .{ .name = "verifyingContract", .type = "address" }, +150 | }, +151 | .Person = &.{ +152 | .{ .name = "name", .type = "string" }, +153 | .{ .name = "wallet", .type = "address" }, +154 | }, +155 | .Mail = &.{ +156 | .{ .name = "from", .type = "Person" }, +157 | .{ .name = "to", .type = "Person" }, +158 | .{ .name = "contents", .type = "string" }, +159 | }, +160 | }; +161 | +162 | const hash = try hashStruct(testing.allocator, types, "EIP712Domain", domain); +163 | ``` +164 | +165 | ### Signature +166 | +167 | ```zig +168 | pub fn hashStruct( +169 | allocator: Allocator, +170 | comptime types: anytype, +171 | comptime primary_type: []const u8, +172 | data: anytype, +173 | ) EIP712Errors![Keccak256.digest_length]u8 +174 | ``` +175 | +176 | ## EncodeStruct +177 | Performs encoding of EIP712 structs according to the expecification +178 | https://eips.ethereum.org/EIPS/eip-712 +179 | +180 | `types` parameter is expected to be a struct where the struct +181 | keys are used to grab the solidity type information so that the +182 | encoding and hashing can happen based on it. See the specification +183 | for more details. +184 | +185 | `primary_type` is the expected main type that you want to hash this message. +186 | Compilation will fail if the provided string doesn't exist on the `types` parameter +187 | +188 | `data` is expected to be a struct where the solidity types are transalated to the native +189 | zig types. I.E string -> []const u8 or int256 -> i256 and so on. +190 | In the future work will be done where the compiler will offer more clearer types +191 | base on a meta programming type function. +192 | +193 | Slices, arrays, strings and bytes will all be encoded as "bytes32" instead of their +194 | usual encoded values. +195 | +196 | ### Signature +197 | +198 | ```zig +199 | pub fn encodeStruct( +200 | allocator: Allocator, +201 | comptime types: anytype, +202 | comptime primary_type: []const u8, +203 | data: anytype, +204 | writer: anytype, +205 | ) EIP712Errors!void +206 | ``` +207 | +208 | ## EncodeStructField +209 | Encodes a singular struct field. +210 | +211 | ### Signature +212 | +213 | ```zig +214 | pub fn encodeStructField( +215 | allocator: Allocator, +216 | comptime types: anytype, +217 | comptime primary_type: []const u8, +218 | value: anytype, +219 | writer: anytype, +220 | ) EIP712Errors!void +221 | ``` +222 | +223 | ## HashType +224 | Hash the main types and it's nested children +225 | +226 | ### Signature +227 | +228 | ```zig +229 | pub fn hashType( +230 | allocator: Allocator, +231 | comptime types_fields: anytype, +232 | comptime primary_type: []const u8, +233 | ) EncodeTypeErrors![Keccak256.digest_length]u8 +234 | ``` +235 | +236 | ## EncodeType +237 | Encodes the main type from a struct into a "human-readable" format. +238 | +239 | *Ex: struct { Mail: []const struct {type: "address", name: "foo"}} into "Mail(address foo)"* +240 | +241 | ### Signature +242 | +243 | ```zig +244 | pub fn encodeType( +245 | allocator: Allocator, +246 | comptime types_fields: anytype, +247 | comptime primary_type: []const u8, +248 | writer: anytype, +249 | ) !void +250 | ``` +251 | +252 | ## FindTypeDependencies +253 | Finds the main type child type and recursivly checks their children as well. +254 | +255 | ### Signature +256 | +257 | ```zig +258 | pub fn findTypeDependencies( +259 | comptime types_fields: anytype, +260 | comptime primary_type: []const u8, +261 | result: *std.StringArrayHashMap(void), +262 | ) Allocator.Error!void +263 | ``` +264 | +265 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/abi/param_type.md: +-------------------------------------------------------------------------------- + 1 | ## ParamErrors + 2 | + 3 | Set of errors when converting `[]const u8` into `ParamType`. + 4 | + 5 | ```zig + 6 | error{ InvalidEnumTag, InvalidCharacter, LengthMismatch, Overflow } || Allocator.Error + 7 | ``` + 8 | + 9 | ## FixedArray + 10 | + 11 | Representation of the solidity fixed array type. + 12 | + 13 | ### Properties + 14 | + 15 | ```zig + 16 | struct { + 17 | child: *const ParamType + 18 | size: usize + 19 | } + 20 | ``` + 21 | + 22 | ## ParamType + 23 | + 24 | Type that represents solidity types in zig. + 25 | + 26 | ### Properties + 27 | + 28 | ```zig + 29 | union(enum) { + 30 | address + 31 | string + 32 | bool + 33 | bytes + 34 | tuple + 35 | uint: usize + 36 | int: usize + 37 | fixedBytes: usize + 38 | @"enum": usize + 39 | fixedArray: FixedArray + 40 | dynamicArray: *const ParamType + 41 | } + 42 | ``` + 43 | + 44 | ### FromHumanReadableTokenTag + 45 | Converts a human readable token into `ParamType`. + 46 | + 47 | ### Signature + 48 | + 49 | ```zig + 50 | pub fn fromHumanReadableTokenTag(tag: TokenTags) ?ParamType + 51 | ``` + 52 | + 53 | ### FreeArrayParamType + 54 | User must call this if the union type contains a fixedArray or dynamicArray field. + 55 | They create pointers so they must be destroyed after. + 56 | + 57 | ### Signature + 58 | + 59 | ```zig + 60 | pub fn freeArrayParamType( + 61 | self: @This(), + 62 | alloc: Allocator, + 63 | ) void + 64 | ``` + 65 | + 66 | ### TypeToJsonStringify + 67 | Converts the tagname of `self` into a writer. + 68 | + 69 | ### Signature + 70 | + 71 | ```zig + 72 | pub fn typeToJsonStringify( + 73 | self: @This(), + 74 | writer: anytype, + 75 | ) @TypeOf(writer).Error!void + 76 | ``` + 77 | + 78 | ### TypeToString + 79 | Converts `self` into its tagname. + 80 | + 81 | ### Signature + 82 | + 83 | ```zig + 84 | pub fn typeToString( + 85 | self: @This(), + 86 | writer: anytype, + 87 | ) @TypeOf(writer).Error!void + 88 | ``` + 89 | + 90 | ### TypeToUnion + 91 | Helper function that is used to convert solidity types into zig unions, + 92 | the function will allocate if a array or a fixed array is used. + 93 | + 94 | Consider using `freeArrayParamType` to destroy the pointers + 95 | or call the destroy method on your allocator manually + 96 | + 97 | ### Signature + 98 | + 99 | ```zig +100 | pub fn typeToUnion( +101 | abitype: []const u8, +102 | alloc: Allocator, +103 | ) ParamErrors!ParamType +104 | ``` +105 | +106 | ### TypeToUnionWithTag +107 | ### Signature +108 | +109 | ```zig +110 | pub fn typeToUnionWithTag( +111 | allocator: Allocator, +112 | abitype: []const u8, +113 | token_tag: TokenTags, +114 | ) ParamErrors!ParamType +115 | ``` +116 | +117 | + + +-------------------------------------------------------------------------------- + + + +└── docs + └── pages + └── api + └── decoding + ├── decoder.md + ├── logs_decode.md + ├── parse_transaction.md + ├── rlp_decode.md + └── ssz_decode.md + + +/docs/pages/api/decoding/decoder.md: +-------------------------------------------------------------------------------- + 1 | ## DecoderErrors + 2 | + 3 | Set of possible errors when the decoder runs. + 4 | + 5 | ```zig + 6 | error{ NoJunkDataAllowed, BufferOverrun, InvalidBitFound } || Allocator.Error + 7 | ``` + 8 | + 9 | ## DecodeOptions + 10 | + 11 | Set of options to control the abi decoder behaviour. + 12 | + 13 | ### Properties + 14 | + 15 | ```zig + 16 | struct { + 17 | /// Max amount of bytes allowed to be read by the decoder. + 18 | /// This avoid a DoS vulnerability discovered here: + 19 | /// https://github.com/paulmillr/micro-eth-signer/discussions/20 + 20 | max_bytes: u16 = 1024 + 21 | /// By default this is false. + 22 | allow_junk_data: bool = false + 23 | /// Tell the decoder if an allocation should be made. + 24 | /// Allocations are always made if dealing with a type that will require a list i.e `[]const u64`. + 25 | allocate_when: enum { alloc_always, alloc_if_needed } = .alloc_if_needed + 26 | /// Tells the endianess of the bytes that you want to decode + 27 | /// Addresses are encoded in big endian and bytes1..32 are encoded in little endian. + 28 | /// There might be some cases where you will need to decode a bytes20 and address at the same time. + 29 | /// Since they can represent the same type it's advised to decode the address as `u160` and change this value to `little`. + 30 | /// since it already decodes as big-endian and then `std.mem.writeInt` the value to the expected endianess. + 31 | bytes_endian: Endian = .big + 32 | } + 33 | ``` + 34 | + 35 | ## Decoded + 36 | Result type of decoded objects. + 37 | + 38 | ### Signature + 39 | + 40 | ```zig + 41 | pub fn Decoded(comptime T: type) type + 42 | ``` + 43 | + 44 | ## AbiDecoded + 45 | Result type of a abi decoded slice. Allocations are managed via an arena. + 46 | + 47 | Allocations: + 48 | `Bool`, `Int`, `Enum`, `Array` => **false**. + 49 | `Array` => **false**. + 50 | `Pointer` => **true**. If the child is `u8` only allocates if the option `alloc_always` is passed. + 51 | `Optional` => Depends on the child. + 52 | `Struct` => Depends on the child. + 53 | Other types are not supported. + 54 | + 55 | If the type provided doesn't make allocations consider using `decodeAbiParameterLeaky`. + 56 | + 57 | ### Signature + 58 | + 59 | ```zig + 60 | pub fn AbiDecoded(comptime T: type) type + 61 | ``` + 62 | + 63 | ## Deinit + 64 | ### Signature + 65 | + 66 | ```zig + 67 | pub fn deinit(self: @This()) void + 68 | ``` + 69 | + 70 | ## DecodeAbiFunction + 71 | Decodes the abi encoded slice. All allocations are managed in an `ArenaAllocator`. + 72 | Assumes that the encoded slice contains the function signature and removes it from the + 73 | encoded slice. + 74 | + 75 | Allocations: + 76 | `Bool`, `Int`, `Enum`, `Array` => **false**. + 77 | `Pointer` => **true**. If the child is `u8` only allocates if the option `alloc_always` is passed. + 78 | `Optional` => Depends on the child. + 79 | `Struct` => Depends on the child. + 80 | Other types are not supported. + 81 | + 82 | + 83 | **Example:** + 84 | ```zig + 85 | var buffer: [1024]u8 = undefined; + 86 | const bytes = try std.fmt.hexToBytes(&buffer, "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000"); + 87 | const decoded = try decodeAbiFunction([]const i256, testing.allocator, bytes, .{}); + 88 | defer decoded.deinit(); + 89 | ``` + 90 | + 91 | If the type provided doesn't make allocations consider using `decodeAbiParameterLeaky`. + 92 | + 93 | ### Signature + 94 | + 95 | ```zig + 96 | pub fn decodeAbiFunction(comptime T: type, allocator: Allocator, encoded: []u8, options: DecodeOptions) DecoderErrors!AbiDecoded(T) + 97 | ``` + 98 | + 99 | ## DecodeAbiError +100 | Decodes the abi encoded slice. All allocations are managed in an `ArenaAllocator`. +101 | Assumes that the encoded slice contracts the error signature and removes it from the +102 | encoded slice. +103 | +104 | Allocations: +105 | `Bool`, `Int`, `Enum`, `Array` => **false**. +106 | `Pointer` => **true**. If the child is `u8` only allocates if the option `alloc_always` is passed. +107 | `Optional` => Depends on the child. +108 | `Struct` => Depends on the child. +109 | Other types are not supported. +110 | +111 | +112 | **Example:** +113 | ```zig +114 | var buffer: [1024]u8 = undefined; +115 | const bytes = try std.fmt.hexToBytes(&buffer, "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000"); +116 | const decoded = try decodeAbiError([]const i256, testing.allocator, bytes, .{}); +117 | defer decoded.deinit(); +118 | ``` +119 | +120 | If the type provided doesn't make allocations consider using `decodeAbiParameterLeaky`. +121 | +122 | ### Signature +123 | +124 | ```zig +125 | pub fn decodeAbiError(comptime T: type, allocator: Allocator, encoded: []u8, options: DecodeOptions) DecoderErrors!AbiDecoded(T) +126 | ``` +127 | +128 | ## DecodeAbiFunctionOutputs +129 | Decodes the abi encoded slice. All allocations are managed in an `ArenaAllocator`. +130 | Since abi encoded function output values don't have signature in the encoded slice this is essentially a wrapper for `decodeAbiParameter`. +131 | +132 | Allocations: +133 | `Bool`, `Int`, `Enum`, `Array` => **false**. +134 | `Pointer` => **true**. If the child is `u8` only allocates if the option `alloc_always` is passed. +135 | `Optional` => Depends on the child. +136 | `Struct` => Depends on the child. +137 | Other types are not supported. +138 | +139 | +140 | **Example:** +141 | ```zig +142 | var buffer: [1024]u8 = undefined; +143 | const bytes = try std.fmt.hexToBytes(&buffer, "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000"); +144 | const decoded = try decodeAbiFunctionOutputs([]const i256, testing.allocator, bytes, .{}); +145 | defer decoded.deinit(); +146 | ``` +147 | +148 | If the type provided doesn't make allocations consider using `decodeAbiParameterLeaky`. +149 | +150 | ### Signature +151 | +152 | ```zig +153 | pub fn decodeAbiFunctionOutputs(comptime T: type, allocator: Allocator, encoded: []u8, options: DecodeOptions) DecoderErrors!AbiDecoded(T) +154 | ``` +155 | +156 | ## DecodeAbiConstructor +157 | Decodes the abi encoded slice. All allocations are managed in an `ArenaAllocator`. +158 | Since abi encoded constructor values don't have signature in the encoded slice this is essentially a wrapper for `decodeAbiParameter`. +159 | +160 | Allocations: +161 | `Bool`, `Int`, `Enum`, `Array` => **false**. +162 | `Pointer` => **true**. If the child is `u8` only allocates if the option `alloc_always` is passed. +163 | `Optional` => Depends on the child. +164 | `Struct` => Depends on the child. +165 | Other types are not supported. +166 | +167 | +168 | **Example:** +169 | ```zig +170 | var buffer: [1024]u8 = undefined; +171 | const bytes = try std.fmt.hexToBytes(&buffer, "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000"); +172 | const decoded = try decodeAbiConstructor([]const i256, testing.allocator, bytes, .{}); +173 | defer decoded.deinit(); +174 | ``` +175 | +176 | If the type provided doesn't make allocations consider using `decodeAbiParameterLeaky`. +177 | +178 | ### Signature +179 | +180 | ```zig +181 | pub fn decodeAbiConstructor(comptime T: type, allocator: Allocator, encoded: []u8, options: DecodeOptions) DecoderErrors!AbiDecoded(T) +182 | ``` +183 | +184 | ## DecodeAbiParameter +185 | Decodes the abi encoded slice. All allocations are managed in an `ArenaAllocator`. +186 | This is usefull when you have to grab ownership of the memory from the slice or the type you need requires the creation +187 | of an `ArrayList`. +188 | +189 | Allocations: +190 | `Bool`, `Int`, `Enum`, `Array` => **false**. +191 | `Pointer` => **true**. If the child is `u8` only allocates if the option `alloc_always` is passed. +192 | `Optional` => Depends on the child. +193 | `Struct` => Depends on the child. +194 | Other types are not supported. +195 | +196 | +197 | **Example:** +198 | ```zig +199 | var buffer: [1024]u8 = undefined; +200 | const bytes = try std.fmt.hexToBytes(&buffer, "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000"); +201 | const decoded = try decodeParameter([]const i256, testing.allocator, bytes, .{}); +202 | defer decoded.deinit(); +203 | ``` +204 | +205 | If the type provided doesn't make allocations consider using `decodeAbiParameterLeaky`. +206 | +207 | ### Signature +208 | +209 | ```zig +210 | pub fn decodeAbiParameter(comptime T: type, allocator: Allocator, encoded: []u8, options: DecodeOptions) DecoderErrors!AbiDecoded(T) +211 | ``` +212 | +213 | ## DecodeAbiParameterLeaky +214 | Decodes the abi encoded slice. This doesn't clean any allocated memory. +215 | Usefull if the type that you want do decode to doesn't create any allocations or you already +216 | own the memory that this will decode from. Otherwise you will be better off using `decodeAbiParameter`. +217 | +218 | Allocations: +219 | `Bool`, `Int`, `Enum`, `Array` => **false**. +220 | `Pointer` => **true**. If the child is `u8` only allocates if the option `alloc_always` is passed. +221 | `Optional` => Depends on the child. +222 | `Struct` => Depends on the child. +223 | Other types are not supported. +224 | +225 | +226 | **Example:** +227 | ```zig +228 | var buffer: [1024]u8 = undefined; +229 | const bytes = try std.fmt.hexToBytes(&buffer, "00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000002"); +230 | const decoded = try decodeParameter([2]i256, testing.allocator, bytes, .{}); +231 | defer decoded.deinit(); +232 | ``` +233 | +234 | ### Signature +235 | +236 | ```zig +237 | pub fn decodeAbiParameterLeaky(comptime T: type, allocator: Allocator, encoded: []u8, options: DecodeOptions) DecoderErrors!T +238 | ``` +239 | +240 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/decoding/logs_decode.md: +-------------------------------------------------------------------------------- + 1 | ## LogsDecoderErrors + 2 | + 3 | Set of possible errors while performing logs decoding. + 4 | + 5 | ```zig + 6 | Allocator.Error || error{ InvalidLength, UnexpectedTupleFieldType, ExpectedAllocator } + 7 | ``` + 8 | + 9 | ## LogDecoderErrors +10 | +11 | Set of possible errors while performing logs decoding. +12 | +13 | ```zig +14 | Allocator.Error || error{ExpectedAllocator} +15 | ``` +16 | +17 | ## LogDecoderOptions +18 | +19 | Set of options that can alter the decoder behaviour. +20 | +21 | ### Properties +22 | +23 | ```zig +24 | struct { +25 | /// Optional allocation in the case that you want to create a pointer +26 | /// That pointer must be destroyed later. +27 | allocator: ?Allocator = null +28 | /// Tells the endianess of the bytes that you want to decode +29 | /// Addresses are encoded in big endian and bytes1..32 are encoded in little endian. +30 | /// There might be some cases where you will need to decode a bytes20 and address at the same time. +31 | /// Since they can represent the same type it's advised to decode the address as `u160` and change this value to `little`. +32 | /// since it already decodes as big-endian and then `std.mem.writeInt` the value to the expected endianess. +33 | bytes_endian: Endian = .big +34 | } +35 | ``` +36 | +37 | ## DecodeLogs +38 | Decodes the abi encoded slice. This will ensure that the provided type +39 | is always a tuple struct type and that the first member type is a [32]u8 type. +40 | No allocations are made unless you want to create a pointer type and provide the optional +41 | allocator. +42 | +43 | **Example:** +44 | ```zig +45 | const encodeds = try decodeLogs( +46 | struct { [32]u8 }, +47 | &.{try utils.hashToBytes("0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0")}, +48 | .{}, +49 | ); +50 | ``` +51 | +52 | ### Signature +53 | +54 | ```zig +55 | pub fn decodeLogs(comptime T: type, encoded: []const ?Hash, options: LogDecoderOptions) LogsDecoderErrors!T +56 | ``` +57 | +58 | ## DecodeLog +59 | Decodes the abi encoded bytes. Not all types are supported. +60 | Bellow there is a list of supported types. +61 | +62 | Supported: +63 | - Bool, Int, Optional, Arrays, Pointer. +64 | +65 | For Arrays only u8 child types are supported and must be 32 or lower of length. +66 | For Pointer types the pointers on `One` size are supported. All other are unsupported. +67 | +68 | **Example:** +69 | ```zig +70 | const decoded = try decodeLog(u256, try utils.hashToBytes("0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0"), .{}); +71 | ``` +72 | +73 | ### Signature +74 | +75 | ```zig +76 | pub fn decodeLog(comptime T: type, encoded: Hash, options: LogDecoderOptions) LogDecoderErrors!T +77 | ``` +78 | +79 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/decoding/parse_transaction.md: +-------------------------------------------------------------------------------- + 1 | ## ParsedTransaction + 2 | Return type of `parseTransaction`. + 3 | + 4 | ### Signature + 5 | + 6 | ```zig + 7 | pub fn ParsedTransaction(comptime T: type) type + 8 | ``` + 9 | + 10 | ## Deinit + 11 | Cleans memory and destroys `ArenaAllocator` pointer. + 12 | + 13 | ### Signature + 14 | + 15 | ```zig + 16 | pub fn deinit(self: @This()) void + 17 | ``` + 18 | + 19 | ## ParseTransactionErrors + 20 | + 21 | ```zig + 22 | RlpDecodeErrors || error{ InvalidRecoveryId, InvalidTransactionType, NoSpaceLeft, InvalidLength } + 23 | ``` + 24 | + 25 | ## ParseTransaction + 26 | Parses unsigned serialized transactions. Creates and arena to manage memory.\ + 27 | This is for the cases where we need to decode access list or if the serialized transaction contains data. + 28 | + 29 | **Example** + 30 | ```zig + 31 | const tx: LondonTransactionEnvelope = .{ + 32 | .chainId = 1, + 33 | .nonce = 0, + 34 | .maxPriorityFeePerGas = 0, + 35 | .maxFeePerGas = 0, + 36 | .gas = 0, + 37 | .to = null, + 38 | .value = 0, + 39 | .data = null, + 40 | .accessList = &.{}, + 41 | }; + 42 | const min = try serialize.serializeTransaction(testing.allocator, .{ .london = tx }, null); + 43 | defer testing.allocator.free(min); + 44 | + 45 | const parsed = try parseTransaction(testing.allocator, min); + 46 | defer parsed.deinit(); + 47 | ``` + 48 | + 49 | ### Signature + 50 | + 51 | ```zig + 52 | pub fn parseTransaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!ParsedTransaction(TransactionEnvelope) + 53 | ``` + 54 | + 55 | ## ParseTransactionLeaky + 56 | Parses unsigned serialized transactions. Recommend to use an arena or similar otherwise its expected to leak memory. + 57 | + 58 | This is usefull for cases where the transaction object is expected to not have any allocated memory and it faster to decode because of it. + 59 | + 60 | **Example** + 61 | ```zig + 62 | const tx: LondonTransactionEnvelope = .{ + 63 | .chainId = 1, + 64 | .nonce = 0, + 65 | .maxPriorityFeePerGas = 0, + 66 | .maxFeePerGas = 0, + 67 | .gas = 0, + 68 | .to = null, + 69 | .value = 0, + 70 | .data = null, + 71 | .accessList = &.{}, + 72 | }; + 73 | const min = try serialize.serializeTransaction(testing.allocator, .{ .london = tx }, null); + 74 | defer testing.allocator.free(min); + 75 | + 76 | const parsed = try parseTransactionLeaky(testing.allocator, min); + 77 | ``` + 78 | + 79 | ### Signature + 80 | + 81 | ```zig + 82 | pub fn parseTransactionLeaky(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!TransactionEnvelope + 83 | ``` + 84 | + 85 | ## ParseEip7702Transaction + 86 | Parses unsigned serialized eip7702 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. + 87 | + 88 | ### Signature + 89 | + 90 | ```zig + 91 | pub fn parseEip7702Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!Eip7702TransactionEnvelope + 92 | ``` + 93 | + 94 | ## ParseEip4844Transaction + 95 | Parses unsigned serialized eip1559 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. + 96 | + 97 | ### Signature + 98 | + 99 | ```zig +100 | pub fn parseEip4844Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!CancunTransactionEnvelope +101 | ``` +102 | +103 | ## ParseEip1559Transaction +104 | Parses unsigned serialized eip1559 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +105 | +106 | ### Signature +107 | +108 | ```zig +109 | pub fn parseEip1559Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!LondonTransactionEnvelope +110 | ``` +111 | +112 | ## ParseEip2930Transaction +113 | Parses unsigned serialized eip2930 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +114 | +115 | ### Signature +116 | +117 | ```zig +118 | pub fn parseEip2930Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!BerlinTransactionEnvelope +119 | ``` +120 | +121 | ## ParseLegacyTransaction +122 | Parses unsigned serialized legacy transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +123 | +124 | ### Signature +125 | +126 | ```zig +127 | pub fn parseLegacyTransaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!LegacyTransactionEnvelope +128 | ``` +129 | +130 | ## ParseSignedTransaction +131 | Parses signed serialized transactions. Creates and arena to manage memory. +132 | Caller needs to call deinit to free memory. +133 | +134 | ### Signature +135 | +136 | ```zig +137 | pub fn parseSignedTransaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!ParsedTransaction(TransactionEnvelopeSigned) +138 | ``` +139 | +140 | ## ParseSignedTransactionLeaky +141 | Parses signed serialized transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +142 | +143 | ### Signature +144 | +145 | ```zig +146 | pub fn parseSignedTransactionLeaky(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!TransactionEnvelopeSigned +147 | ``` +148 | +149 | ## ParseSignedEip7702Transaction +150 | Parses unsigned serialized eip7702 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +151 | +152 | ### Signature +153 | +154 | ```zig +155 | pub fn parseSignedEip7702Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!Eip7702TransactionEnvelopeSigned +156 | ``` +157 | +158 | ## ParseSignedEip4844Transaction +159 | Parses signed serialized eip1559 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +160 | +161 | ### Signature +162 | +163 | ```zig +164 | pub fn parseSignedEip4844Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!CancunTransactionEnvelopeSigned +165 | ``` +166 | +167 | ## ParseSignedEip1559Transaction +168 | Parses signed serialized eip1559 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +169 | +170 | ### Signature +171 | +172 | ```zig +173 | pub fn parseSignedEip1559Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!LondonTransactionEnvelopeSigned +174 | ``` +175 | +176 | ## ParseSignedEip2930Transaction +177 | Parses signed serialized eip2930 transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +178 | +179 | ### Signature +180 | +181 | ```zig +182 | pub fn parseSignedEip2930Transaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!BerlinTransactionEnvelopeSigned +183 | ``` +184 | +185 | ## ParseSignedLegacyTransaction +186 | Parses signed serialized legacy transactions. Recommend to use an arena or similar otherwise its expected to leak memory. +187 | +188 | ### Signature +189 | +190 | ```zig +191 | pub fn parseSignedLegacyTransaction(allocator: Allocator, serialized: []const u8) ParseTransactionErrors!LegacyTransactionEnvelopeSigned +192 | ``` +193 | +194 | ## ParseAccessList +195 | Parses serialized transaction accessLists. Recommend to use an arena or similar otherwise its expected to leak memory. +196 | +197 | ### Signature +198 | +199 | ```zig +200 | pub fn parseAccessList(allocator: Allocator, access_list: []const StructToTupleType(AccessList)) Allocator.Error![]const AccessList +201 | ``` +202 | +203 | ## ParseAuthorizationList +204 | Parses serialized transaction accessLists. Recommend to use an arena or similar otherwise its expected to leak memory. +205 | +206 | ### Signature +207 | +208 | ```zig +209 | pub fn parseAuthorizationList(allocator: Allocator, auth_list: []const StructToTupleType(AuthorizationPayload)) Allocator.Error![]const AuthorizationPayload +210 | ``` +211 | +212 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/decoding/rlp_decode.md: +-------------------------------------------------------------------------------- + 1 | ## RlpDecodeErrors + 2 | + 3 | Set of errors while performing RLP decoding. + 4 | + 5 | ```zig + 6 | error{ UnexpectedValue, InvalidEnumTag, LengthMissmatch, Overflow } || Allocator.Error + 7 | ``` + 8 | + 9 | ## DecodeRlp +10 | RLP decoding wrapper function. Encoded string must follow the RLP specification. +11 | +12 | Supported types: +13 | * `bool` +14 | * `int` +15 | * `enum`, `enum_literal` +16 | * `null` +17 | * `?T` +18 | * `[N]T` array types. +19 | * `[]const T` slices. +20 | * `structs`. Both tuple and non tuples. +21 | +22 | All other types are currently not supported. +23 | +24 | ### Signature +25 | +26 | ```zig +27 | pub fn decodeRlp(comptime T: type, allocator: Allocator, encoded: []const u8) RlpDecodeErrors!T +28 | ``` +29 | +30 | ## RlpDecoder +31 | +32 | RLP Decoder structure. Decodes based on the RLP specification. +33 | +34 | ### Properties +35 | +36 | ```zig +37 | struct { +38 | /// The RLP encoded slice. +39 | encoded: []const u8 +40 | /// The position into the encoded slice. +41 | position: usize +42 | } +43 | ``` +44 | +45 | ### Init +46 | Sets the decoder initial state. +47 | +48 | ### Signature +49 | +50 | ```zig +51 | pub fn init(encoded: []const u8) RlpDecoder +52 | ``` +53 | +54 | ### AdvancePosition +55 | Advances the decoder position by `new` size. +56 | +57 | ### Signature +58 | +59 | ```zig +60 | pub fn advancePosition(self: *RlpDecoder, new: usize) void +61 | ``` +62 | +63 | ### Decode +64 | Decodes a rlp encoded slice into a provided type. +65 | The encoded slice must follow the RLP specification. +66 | +67 | Supported types: +68 | * `bool` +69 | * `int` +70 | * `enum`, `enum_literal` +71 | * `null` +72 | * `?T` +73 | * `[N]T` array types. +74 | * `[]const T` slices. +75 | * `structs`. Both tuple and non tuples. +76 | +77 | All other types are currently not supported. +78 | +79 | ### Signature +80 | +81 | ```zig +82 | pub fn decode(self: *RlpDecoder, comptime T: type, allocator: Allocator) RlpDecodeErrors!T +83 | ``` +84 | +85 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/decoding/ssz_decode.md: +-------------------------------------------------------------------------------- + 1 | ## SSZDecodeErrors + 2 | + 3 | Set of possible errors while performing ssz decoding. + 4 | + 5 | ```zig + 6 | Allocator.Error || error{ InvalidEnumType, IndexOutOfBounds } + 7 | ``` + 8 | + 9 | ## DecodeSSZ +10 | Performs ssz decoding according to the [specification](https://ethereum.org/developers/docs/data-structures-and-encoding/ssz). +11 | +12 | ### Signature +13 | +14 | ```zig +15 | pub fn decodeSSZ(comptime T: type, serialized: []const u8) SSZDecodeErrors!T +16 | ``` +17 | +18 | + + +-------------------------------------------------------------------------------- + + + +└── docs + └── pages + └── api + └── encoding + ├── encoder.md + ├── logs.md + ├── rlp.md + ├── serialize.md + └── ssz.md + + +/docs/pages/api/encoding/encoder.md: +-------------------------------------------------------------------------------- + 1 | ## EncodeErrors + 2 | + 3 | Set of errors while perfoming abi encoding. + 4 | + 5 | ```zig + 6 | AbiEncoder.Errors || error{NoSpaceLeft} + 7 | ``` + 8 | + 9 | ## AbiEncodedValues + 10 | + 11 | Runtime value representation for abi encoding. + 12 | + 13 | ### Properties + 14 | + 15 | ```zig + 16 | union(enum) { + 17 | bool: bool + 18 | uint: u256 + 19 | int: i256 + 20 | address: Address + 21 | fixed_bytes: []u8 + 22 | string: []const u8 + 23 | bytes: []const u8 + 24 | fixed_array: []const AbiEncodedValues + 25 | dynamic_array: []const AbiEncodedValues + 26 | tuple: []const AbiEncodedValues + 27 | } + 28 | ``` + 29 | + 30 | ### IsDynamic + 31 | Checks if the given values is a dynamic abi value. + 32 | + 33 | ### Signature + 34 | + 35 | ```zig + 36 | pub fn isDynamic(self: @This()) bool + 37 | ``` + 38 | + 39 | ## PreEncodedStructure + 40 | + 41 | The encoded values inner structure representation. + 42 | + 43 | ### Properties + 44 | + 45 | ```zig + 46 | struct { + 47 | type: ParameterType + 48 | encoded: []const u8 + 49 | } + 50 | ``` + 51 | + 52 | ### Deinit + 53 | ### Signature + 54 | + 55 | ```zig + 56 | pub fn deinit(self: @This(), allocator: Allocator) void + 57 | ``` + 58 | + 59 | ## EncodeAbiFunction + 60 | Encode an Solidity `Function` type with the signature and the values encoded. + 61 | The signature is calculated by hashing the formated string generated from the `Function` signature. + 62 | + 63 | ### Signature + 64 | + 65 | ```zig + 66 | pub fn encodeAbiFunction( + 67 | comptime func: Function, + 68 | allocator: Allocator, + 69 | values: AbiParametersToPrimative(func.inputs), + 70 | ) (AbiEncoder.Errors || error{NoSpaceLeft})![]u8 + 71 | ``` + 72 | + 73 | ## EncodeAbiFunctionOutputs + 74 | Encode an Solidity `Function` type with the signature and the values encoded. + 75 | This is will use the `func` outputs values as the parameters. + 76 | + 77 | ### Signature + 78 | + 79 | ```zig + 80 | pub fn encodeAbiFunctionOutputs( + 81 | comptime func: Function, + 82 | allocator: Allocator, + 83 | values: AbiParametersToPrimative(func.outputs), + 84 | ) AbiEncoder.Errors![]u8 + 85 | ``` + 86 | + 87 | ## EncodeAbiError + 88 | Encode an Solidity `Error` type with the signature and the values encoded. + 89 | The signature is calculated by hashing the formated string generated from the `Error` signature. + 90 | + 91 | ### Signature + 92 | + 93 | ```zig + 94 | pub fn encodeAbiError( + 95 | comptime err: Error, + 96 | allocator: Allocator, + 97 | values: AbiParametersToPrimative(err.inputs), + 98 | ) (AbiEncoder.Errors || error{NoSpaceLeft})![]u8 + 99 | ``` +100 | +101 | ## EncodeAbiConstructor +102 | Encode an Solidity `Constructor` type with the signature and the values encoded. +103 | +104 | ### Signature +105 | +106 | ```zig +107 | pub fn encodeAbiConstructor( +108 | comptime constructor: Constructor, +109 | allocator: Allocator, +110 | values: AbiParametersToPrimative(constructor.inputs), +111 | ) AbiEncoder.Errors![]u8 +112 | ``` +113 | +114 | ## EncodeAbiParameters +115 | Encodes the `values` based on the [specification](https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types) +116 | +117 | The values types are checked at comptime based on the provided `params`. +118 | +119 | ### Signature +120 | +121 | ```zig +122 | pub fn encodeAbiParameters( +123 | comptime params: []const AbiParameter, +124 | allocator: Allocator, +125 | values: AbiParametersToPrimative(params), +126 | ) AbiEncoder.Errors![]u8 +127 | ``` +128 | +129 | ## EncodeAbiParametersValues +130 | Encodes the `values` based on the [specification](https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types) +131 | +132 | Use this if for some reason you don't know the `Abi` at comptime. +133 | +134 | It's recommended to use `encodeAbiParameters` whenever possible but this is provided as a fallback +135 | you cannot use it. +136 | +137 | ### Signature +138 | +139 | ```zig +140 | pub fn encodeAbiParametersValues( +141 | allocator: Allocator, +142 | values: []const AbiEncodedValues, +143 | ) (AbiEncoder.Errors || error{InvalidType})![]u8 +144 | ``` +145 | +146 | ## EncodeAbiParametersFromReflection +147 | Encodes the `values` based on the [specification](https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types) +148 | +149 | This will use zig's ability to provide compile time reflection based on the `values` provided. +150 | The `values` must be a tuple struct. Otherwise it will trigger a compile error. +151 | +152 | By default this provides more support for a greater range on zig types that can be used for encoding. +153 | Bellow you will find the list of all supported types and what will they be encoded as. +154 | +155 | * Zig `bool` -> Will be encoded like a boolean value +156 | * Zig `?T` -> Only encodes if the value is not null. +157 | * Zig `int`, `comptime_int` -> Will be encoded based on the signedness of the integer. +158 | * Zig `[N]u8` -> Only support max size of 32. `[20]u8` will be encoded as address types and all other as bytes1..32. +159 | This is the main limitation because abi encoding of bytes1..32 follows little endian and for address follows big endian. +160 | * Zig `enum` -> The tagname of the enum encoded as a string/bytes value. +161 | * Zig `*T` -> will encoded the child type. If the child type is an `array` it will encode as string/bytes. +162 | * Zig `[]const u8`, `[]u8` -> Will encode according the string/bytes specification. +163 | * Zig `[]const T` -> Will encode as a dynamic array +164 | * Zig `[N]T` -> Will encode as a dynamic value if the child type is of a dynamic type. +165 | * Zig `struct` -> Will encode as a dynamic value if the child type is of a dynamic type. +166 | +167 | All other types are currently not supported. +168 | +169 | ### Signature +170 | +171 | ```zig +172 | pub fn encodeAbiParametersFromReflection( +173 | allocator: Allocator, +174 | values: anytype, +175 | ) AbiEncoder.Errors![]u8 +176 | ``` +177 | +178 | ## EncodePacked +179 | Encode values based on solidity's `encodePacked`. +180 | Solidity types are infered from zig ones since it closely follows them. +181 | +182 | Supported zig types: +183 | +184 | * Zig `bool` -> Will be encoded like a boolean value +185 | * Zig `?T` -> Only encodes if the value is not null. +186 | * Zig `int`, `comptime_int` -> Will be encoded based on the signedness of the integer. +187 | * Zig `[N]u8` -> Only support max size of 32. `[20]u8` will be encoded as address types and all other as bytes1..32. +188 | This is the main limitation because abi encoding of bytes1..32 follows little endian and for address follows big endian. +189 | * Zig `enum`, `enum_literal`, `error_set` -> The tagname of the enum or the error_set names will be encoded as a string/bytes value. +190 | * Zig `*T` -> will encoded the child type. If the child type is an `array` it will encode as string/bytes. +191 | * Zig `[]const u8`, `[]u8` -> Will encode according the string/bytes specification. +192 | * Zig `[]const T` -> Will encode as a dynamic array +193 | * Zig `[N]T` -> Will encode as a dynamic value if the child type is of a dynamic type. +194 | * Zig `struct` -> Will encode as a dynamic value if the child type is of a dynamic type. +195 | +196 | All other types are currently not supported. +197 | +198 | If the value provided is either a `[]const T`, `[N]T`, `[]T`, or `tuple`, +199 | the child values will be 32 bit padded. +200 | +201 | ### Signature +202 | +203 | ```zig +204 | pub fn encodePacked( +205 | allocator: Allocator, +206 | value: anytype, +207 | ) EncodePacked.Errors![]u8 +208 | ``` +209 | +210 | ## AbiEncoder +211 | +212 | The abi encoding structure used to encoded values with the abi encoding [specification](https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types) +213 | +214 | You can initialize this structure like this: +215 | ```zig +216 | var encoder: AbiEncoder = .empty; +217 | +218 | try encoder.encodeAbiParameters(params, allocator, .{69, 420}); +219 | defer allocator.free(allocator); +220 | ``` +221 | +222 | ### Properties +223 | +224 | ```zig +225 | struct { +226 | /// Essentially a `stack` of encoded values that will need to be analysed +227 | /// in the `encodePointers` step to re-arrange the location in the encoded slice based on +228 | /// if they are dynamic or static types. +229 | pre_encoded: ArrayListUnmanaged(PreEncodedStructure) +230 | /// Stream of encoded values that should show up at the top of the encoded slice. +231 | heads: ArrayListUnmanaged(u8) +232 | /// Stream of encoded values that should show up at the end of the encoded slice. +233 | tails: ArrayListUnmanaged(u8) +234 | /// Used to calculated the initial pointer when facing `dynamic` types. +235 | /// Also used to know the memory size of the `heads` stream. +236 | heads_size: u32 +237 | /// Only used to know the memory size of the `tails` stream. +238 | tails_size: u32 +239 | } +240 | ``` +241 | +242 | ## Self +243 | +244 | ```zig +245 | @This() +246 | ``` +247 | +248 | ## Errors +249 | +250 | Set of possible error when running this encoder. +251 | +252 | ```zig +253 | error{ DivisionByZero, Overflow } || Allocator.Error +254 | ``` +255 | +256 | ## empty +257 | +258 | Sets the initial state of the encoder. +259 | +260 | ```zig +261 | .{ +262 | .pre_encoded = .empty, +263 | .heads = .empty, +264 | .tails = .empty, +265 | .heads_size = 0, +266 | .tails_size = 0, +267 | } +268 | ``` +269 | +270 | ### EncodeAbiParametersFromReflection +271 | Encodes the `values` based on the [specification](https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types) +272 | +273 | Uses compile time reflection to determine the behaviour. Please check `encodeAbiParametersFromReflection` for more details. +274 | +275 | ### Signature +276 | +277 | ```zig +278 | pub fn encodeAbiParametersFromReflection( +279 | self: *Self, +280 | allocator: Allocator, +281 | values: anytype, +282 | ) Errors![]u8 +283 | ``` +284 | +285 | ### EncodeAbiParametersValues +286 | Encodes the `values` based on the [specification](https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types) +287 | +288 | Uses the `AbiEncodedValues` type to determine the correct behaviour. +289 | +290 | ### Signature +291 | +292 | ```zig +293 | pub fn encodeAbiParametersValues( +294 | self: *Self, +295 | allocator: Allocator, +296 | values: []const AbiEncodedValues, +297 | ) Errors![]u8 +298 | ``` +299 | +300 | ### EncodeAbiParameters +301 | Encodes the `values` based on the [specification](https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types) +302 | +303 | The values types are checked at comptime based on the provided `params`. +304 | +305 | ### Signature +306 | +307 | ```zig +308 | pub fn encodeAbiParameters( +309 | self: *Self, +310 | comptime params: []const AbiParameter, +311 | allocator: Allocator, +312 | values: AbiParametersToPrimative(params), +313 | ) Errors![]u8 +314 | ``` +315 | +316 | ### EncodePointers +317 | Re-arranges the inner stack based on if the value that it's dealing with is either dynamic or now. +318 | Places those values in the `heads` or `tails` streams based on that. +319 | +320 | ### Signature +321 | +322 | ```zig +323 | pub fn encodePointers( +324 | self: *Self, +325 | allocator: Allocator, +326 | ) Allocator.Error![]u8 +327 | ``` +328 | +329 | ### PreEncodeAbiParameters +330 | Encodes the values and places them on the `inner` stack. +331 | +332 | ### Signature +333 | +334 | ```zig +335 | pub fn preEncodeAbiParameters( +336 | self: *Self, +337 | comptime params: []const AbiParameter, +338 | allocator: Allocator, +339 | values: AbiParametersToPrimative(params), +340 | ) Errors!void +341 | ``` +342 | +343 | ### PreEncodeAbiParameter +344 | Encodes a single value and places them on the `inner` stack. +345 | +346 | ### Signature +347 | +348 | ```zig +349 | pub fn preEncodeAbiParameter( +350 | self: *Self, +351 | comptime param: AbiParameter, +352 | allocator: Allocator, +353 | value: AbiParameterToPrimative(param), +354 | ) Errors!void +355 | ``` +356 | +357 | ### PreEncodeRuntimeValues +358 | Pre encodes the parameter values according to the specification and places it on `pre_encoded` arraylist. +359 | +360 | ### Signature +361 | +362 | ```zig +363 | pub fn preEncodeRuntimeValues( +364 | self: *Self, +365 | allocator: Allocator, +366 | values: []const AbiEncodedValues, +367 | ) (Errors || error{InvalidType})!void +368 | ``` +369 | +370 | ### PreEncodeRuntimeValue +371 | Pre encodes the parameter value according to the specification and places it on `pre_encoded` arraylist. +372 | +373 | This methods and some runtime checks to see if the parameter are valid like `preEncodeAbiParameter` that instead uses +374 | comptime to get the exact expected types. +375 | +376 | ### Signature +377 | +378 | ```zig +379 | pub fn preEncodeRuntimeValue( +380 | self: *Self, +381 | allocator: Allocator, +382 | value: AbiEncodedValues, +383 | ) (Errors || error{InvalidType})!void +384 | ``` +385 | +386 | ### PreEncodeValuesFromReflection +387 | This will use zig's ability to provide compile time reflection based on the `values` provided. +388 | The `values` must be a tuple struct. Otherwise it will trigger a compile error. +389 | +390 | ### Signature +391 | +392 | ```zig +393 | pub fn preEncodeValuesFromReflection( +394 | self: *Self, +395 | allocator: Allocator, +396 | values: anytype, +397 | ) Errors!void +398 | ``` +399 | +400 | ### PreEncodeReflection +401 | This will use zig's ability to provide compile time reflection based on the `value` provided. +402 | +403 | ### Signature +404 | +405 | ```zig +406 | pub fn preEncodeReflection( +407 | self: *Self, +408 | allocator: Allocator, +409 | value: anytype, +410 | ) Errors!void +411 | ``` +412 | +413 | ## Self +414 | +415 | ```zig +416 | @This() +417 | ``` +418 | +419 | ## Errors +420 | +421 | Set of possible error when running this encoder. +422 | +423 | ```zig +424 | error{ DivisionByZero, Overflow } || Allocator.Error +425 | ``` +426 | +427 | ## empty +428 | +429 | Sets the initial state of the encoder. +430 | +431 | ```zig +432 | .{ +433 | .pre_encoded = .empty, +434 | .heads = .empty, +435 | .tails = .empty, +436 | .heads_size = 0, +437 | .tails_size = 0, +438 | } +439 | ``` +440 | +441 | ## EncodePacked +442 | +443 | Similar to `AbiEncoder` but used for packed encoding. +444 | +445 | ### Properties +446 | +447 | ```zig +448 | struct { +449 | /// Changes the encoder behaviour based on the type of the parameter. +450 | param_type: ParameterType +451 | /// List that is used to write the encoded values too. +452 | list: ArrayList(u8) +453 | } +454 | ``` +455 | +456 | ## Errors +457 | +458 | Set of possible error when running this encoder. +459 | +460 | ```zig +461 | error{ DivisionByZero, Overflow } || Allocator.Error +462 | ``` +463 | +464 | ### Init +465 | Sets the initial state of the encoder. +466 | +467 | ### Signature +468 | +469 | ```zig +470 | pub fn init( +471 | allocator: Allocator, +472 | param_type: ParameterType, +473 | ) EncodePacked +474 | ``` +475 | +476 | ### EncodePacked +477 | Abi encodes the values. If the values are dynamic all of the child values +478 | will be encoded as 32 sized values with the expection of []u8 slices. +479 | +480 | ### Signature +481 | +482 | ```zig +483 | pub fn encodePacked( +484 | self: *EncodePacked, +485 | value: anytype, +486 | ) Errors![]u8 +487 | ``` +488 | +489 | ### EncodePackedValue +490 | Handles the encoding based on the value type and writes them to the list. +491 | +492 | ### Signature +493 | +494 | ```zig +495 | pub fn encodePackedValue( +496 | self: *EncodePacked, +497 | value: anytype, +498 | ) Errors!void +499 | ``` +500 | +501 | ### ChangeParameterType +502 | Used to change the type of value it's dealing with. +503 | +504 | ### Signature +505 | +506 | ```zig +507 | pub fn changeParameterType( +508 | self: *EncodePacked, +509 | param_type: ParameterType, +510 | ) void +511 | ``` +512 | +513 | ## Errors +514 | +515 | Set of possible error when running this encoder. +516 | +517 | ```zig +518 | error{ DivisionByZero, Overflow } || Allocator.Error +519 | ``` +520 | +521 | ## EncodeBoolean +522 | Encodes a boolean value according to the abi encoding specification. +523 | +524 | ### Signature +525 | +526 | ```zig +527 | pub fn encodeBoolean(boolean: bool) [32]u8 +528 | ``` +529 | +530 | ## EncodeNumber +531 | Encodes a integer value according to the abi encoding specification. +532 | +533 | ### Signature +534 | +535 | ```zig +536 | pub fn encodeNumber(comptime T: type, number: T) [32]u8 +537 | ``` +538 | +539 | ## EncodeAddress +540 | Encodes an solidity address value according to the abi encoding specification. +541 | +542 | ### Signature +543 | +544 | ```zig +545 | pub fn encodeAddress(address: Address) [32]u8 +546 | ``` +547 | +548 | ## EncodeFixedBytes +549 | Encodes an bytes1..32 value according to the abi encoding specification. +550 | +551 | ### Signature +552 | +553 | ```zig +554 | pub fn encodeFixedBytes( +555 | comptime size: usize, +556 | payload: [size]u8, +557 | ) [32]u8 +558 | ``` +559 | +560 | ## EncodeString +561 | Encodes an solidity string or bytes value according to the abi encoding specification. +562 | +563 | ### Signature +564 | +565 | ```zig +566 | pub fn encodeString( +567 | allocator: Allocator, +568 | payload: []const u8, +569 | ) (error{ DivisionByZero, Overflow } || Allocator.Error)![]u8 +570 | ``` +571 | +572 | ## IsDynamicType +573 | Checks if a given parameter is a dynamic abi type. +574 | +575 | ### Signature +576 | +577 | ```zig +578 | pub inline fn isDynamicType(comptime param: AbiParameter) bool +579 | ``` +580 | +581 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/encoding/logs.md: +-------------------------------------------------------------------------------- + 1 | ## EncodeLogsErrors + 2 | + 3 | Set of errors while performing logs abi encoding. + 4 | + 5 | ```zig + 6 | Allocator.Error || error{NoSpaceLeft} + 7 | ``` + 8 | + 9 | ## EncodeLogTopicsFromReflection + 10 | Performs compile time reflection to decided on which way to encode the values. + 11 | Uses the [specification](https://docs.soliditylang.org/en/latest/abi-spec.html#indexed-event-encoding) as the base of encoding. + 12 | + 13 | Bellow you will find the list of all supported types and what will they be encoded as. + 14 | + 15 | * Zig `bool` -> Will be encoded like a boolean value + 16 | * Zig `?T` -> Encodes the values if not null otherwise it appends the null value to the topics. + 17 | * Zig `int`, `comptime_int` -> Will be encoded based on the signedness of the integer. + 18 | * Zig `[N]u8` -> Only support max size of 32. All are encoded as little endian. If you need to use `[20]u8` for address + 19 | please consider encoding as a `u160` and then `@bitCast` that value to an `[20]u8` array. + 20 | * Zig `enum`, `enum_literal` -> The tagname of the enum encoded as a string/bytes value. + 21 | * Zig `*T` -> will encoded the child type. If the child type is an `array` it will encode as string/bytes. + 22 | * Zig `[]const u8`, `[]u8` -> Will encode according the string/bytes specification. + 23 | + 24 | All other types are currently not supported. + 25 | + 26 | ### Signature + 27 | + 28 | ```zig + 29 | pub fn encodeLogTopicsFromReflection( + 30 | allocator: Allocator, + 31 | event: AbiEvent, + 32 | values: anytype, + 33 | ) EncodeLogsErrors![]const ?Hash + 34 | ``` + 35 | + 36 | ## EncodeLogTopics + 37 | Encodes the values based on the [specification](https://docs.soliditylang.org/en/latest/abi-spec.html#indexed-event-encoding) + 38 | + 39 | Most of solidity types are supported, only `fixedArray`, `dynamicArray` and `tuples` + 40 | are not supported. These are quite niche and in previous version of zabi they were supported. + 41 | + 42 | However I don't see the benifit of supporting them anymore. If the need arises in the future + 43 | this will be added again. But for now this as been disabled. + 44 | + 45 | ### Signature + 46 | + 47 | ```zig + 48 | pub fn encodeLogTopics( + 49 | comptime event: AbiEvent, + 50 | allocator: Allocator, + 51 | values: AbiEventParametersDataToPrimative(event.inputs), + 52 | ) Allocator.Error![]const ?Hash + 53 | ``` + 54 | + 55 | ## AbiLogTopicsEncoderReflection + 56 | + 57 | Structure used to encode event log topics based on the [specification](https://docs.soliditylang.org/en/latest/abi-spec.html#indexed-event-encoding) + 58 | + 59 | ### Properties + 60 | + 61 | ```zig + 62 | struct { + 63 | /// List of encoded log topics. + 64 | topics: ArrayListUnmanaged(?Hash) + 65 | } + 66 | ``` + 67 | + 68 | ## empty + 69 | + 70 | Initializes the structure. + 71 | + 72 | ```zig + 73 | .{ + 74 | .topics = .empty, + 75 | } + 76 | ``` + 77 | + 78 | ### EncodeLogTopicsWithSignature + 79 | Generates the signature hash from the provided event and appends it to the `topics`. + 80 | + 81 | If the event inputs are of length 0 it will return the slice with just that hash. + 82 | For more details please checkout `encodeLogTopicsFromReflection`. + 83 | + 84 | ### Signature + 85 | + 86 | ```zig + 87 | pub fn encodeLogTopicsWithSignature( + 88 | self: *Self, + 89 | allocator: Allocator, + 90 | event: AbiEvent, + 91 | values: anytype, + 92 | ) EncodeLogsErrors![]const ?Hash + 93 | ``` + 94 | + 95 | ### EncodeLogTopics + 96 | Performs compile time reflection to decided on which way to encode the values. + 97 | Uses the [specification](https://docs.soliditylang.org/en/latest/abi-spec.html#indexed-event-encoding) as the base of encoding. + 98 | + 99 | Bellow you will find the list of all supported types and what will they be encoded as. +100 | +101 | * Zig `bool` -> Will be encoded like a boolean value +102 | * Zig `?T` -> Encodes the values if not null otherwise it appends the null value to the topics. +103 | * Zig `int`, `comptime_int` -> Will be encoded based on the signedness of the integer. +104 | * Zig `[N]u8` -> Only support max size of 32. All are encoded as little endian. If you need to use `[20]u8` for address +105 | please consider encoding as a `u160` and then `@bitCast` that value to an `[20]u8` array. +106 | * Zig `enum`, `enum_literal` -> The tagname of the enum encoded as a string/bytes value. +107 | * Zig `*T` -> will encoded the child type. If the child type is an `array` it will encode as string/bytes. +108 | * Zig `[]const u8`, `[]u8` -> Will encode according the string/bytes specification. +109 | +110 | All other types are currently not supported. +111 | +112 | ### Signature +113 | +114 | ```zig +115 | pub fn encodeLogTopics( +116 | self: *Self, +117 | allocator: Allocator, +118 | values: anytype, +119 | ) Allocator.Error![]const ?Hash +120 | ``` +121 | +122 | ### EncodeLogTopic +123 | Uses compile time reflection to decide how to encode the value. +124 | +125 | For more information please checkout `AbiLogTopicsEncoderReflection.encodeLogTopics` or `encodeLogTopicsFromReflection`. +126 | +127 | ### Signature +128 | +129 | ```zig +130 | pub fn encodeLogTopic(self: *Self, value: anytype) void +131 | ``` +132 | +133 | ## empty +134 | +135 | Initializes the structure. +136 | +137 | ```zig +138 | .{ +139 | .topics = .empty, +140 | } +141 | ``` +142 | +143 | ## AbiLogTopicsEncoder +144 | Generates a structure based on the provided `event`. +145 | +146 | This generates the event hash as well as the indexed parameters used by `encodeLogTopics`. +147 | +148 | ### Signature +149 | +150 | ```zig +151 | pub fn AbiLogTopicsEncoder(comptime event: AbiEvent) type +152 | ``` +153 | +154 | ## empty +155 | +156 | Initialize the structure. +157 | +158 | ```zig +159 | .{ +160 | .topics = .empty, +161 | } +162 | ``` +163 | +164 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/encoding/rlp.md: +-------------------------------------------------------------------------------- + 1 | ## RlpEncoder + 2 | RLP Encoding according to the [spec](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + 3 | This also supports generating a `Writer` interface. + 4 | + 5 | Supported types: + 6 | * `bool` + 7 | * `int` + 8 | * `enum`, `enum_literal` + 9 | * `error_set`, + 10 | * `null` + 11 | * `?T` + 12 | * `[N]T` array types. + 13 | * `[]const T` slices. + 14 | * `*T` pointer types. + 15 | * `structs`. Both tuple and non tuples. + 16 | + 17 | All other types are currently not supported. + 18 | + 19 | Depending on your use case you case use this in to ways. + 20 | + 21 | Use `encodeNoList` if the type that you need to encode isn't a tuple, slice or array (doesn't apply for u8 slices and arrays.) + 22 | and use `encodeList` if you need to encode the above mentioned. + 23 | + 24 | Only `encodeList` will allocate memory when using this interface. + 25 | + 26 | ### Signature + 27 | + 28 | ```zig + 29 | pub fn RlpEncoder(comptime OutWriter: type) type + 30 | ``` + 31 | + 32 | ## Error + 33 | + 34 | Set of errors that can be produced when encoding values. + 35 | + 36 | ```zig + 37 | OutWriter.Error || error{ Overflow, NegativeNumber } + 38 | ``` + 39 | + 40 | ## Writer + 41 | + 42 | The writer interface that can rlp encode. + 43 | + 44 | ```zig + 45 | std.io.Writer(*Self, Error, encodeString) + 46 | ``` + 47 | + 48 | ## RlpSizeTag + 49 | + 50 | Value that are used to identifity the size depending on the type + 51 | + 52 | ### Properties + 53 | + 54 | ```zig + 55 | enum { + 56 | number = 0x80 + 57 | string = 0xb7 + 58 | list = 0xf7 + 59 | } + 60 | ``` + 61 | + 62 | ## Init + 63 | Sets the initial state. + 64 | + 65 | ### Signature + 66 | + 67 | ```zig + 68 | pub fn init(stream: OutWriter) Self + 69 | ``` + 70 | + 71 | ## EncodeNoList + 72 | RLP Encoding according to the [spec](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + 73 | For non `u8` slices and arrays use `encodeList`. Same applies for tuples and structs. + 74 | + 75 | ### Signature + 76 | + 77 | ```zig + 78 | pub fn encodeNoList(self: *Self, payload: anytype) Error!void + 79 | ``` + 80 | + 81 | ## EncodeList + 82 | RLP Encoding according to the [spec](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + 83 | Only use this if you payload contains a slice, array or tuple/struct. + 84 | + 85 | This will allocate memory because it creates a `ArrayList` writer for the recursive calls. + 86 | + 87 | ### Signature + 88 | + 89 | ```zig + 90 | pub fn encodeList(self: *Self, allocator: Allocator, payload: anytype) Error!void + 91 | ``` + 92 | + 93 | ## EncodeString + 94 | Performs RLP encoding on a "string" type. + 95 | + 96 | For more information please check the [spec](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). + 97 | + 98 | ### Signature + 99 | +100 | ```zig +101 | pub fn encodeString(self: *Self, slice: []const u8) Error!void +102 | ``` +103 | +104 | ## WriteSize +105 | Finds the bit size of the passed number and writes it to the stream. +106 | +107 | Example: +108 | ```zig +109 | const slice = "dog"; +110 | +111 | try rlp_encoder.writeSize(usize, slice.len, .number); +112 | // Encodes as 0x80 + slice.len +113 | +114 | try rlp_encoder.writeSize(usize, slice.len, .string); +115 | // Encodes as 0xb7 + slice.len +116 | +117 | try rlp_encoder.writeSize(usize, slice.len, .list); +118 | // Encodes as 0xf7 + slice.len +119 | ``` +120 | +121 | ### Signature +122 | +123 | ```zig +124 | pub fn writeSize(self: *Self, comptime T: type, number: T, tag: RlpSizeTag) Error!void +125 | ``` +126 | +127 | ## Writer +128 | RLP encoding writer interface. +129 | +130 | ### Signature +131 | +132 | ```zig +133 | pub fn writer(self: *Self) Writer +134 | ``` +135 | +136 | ## EncodeRlp +137 | RLP Encoding according to the [spec](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). +138 | +139 | Supported types: +140 | * `bool` +141 | * `int` +142 | * `enum`, `enum_literal` +143 | * `error_set`, +144 | * `null` +145 | * `?T` +146 | * `[N]T` array types. +147 | * `[]const T` slices. +148 | * `*T` pointer types. +149 | * `structs`. Both tuple and non tuples. +150 | +151 | All other types are currently not supported. +152 | +153 | **Example** +154 | ```zig +155 | const encoded = try encodeRlp(allocator, 69420); +156 | defer allocator.free(encoded); +157 | ``` +158 | +159 | ### Signature +160 | +161 | ```zig +162 | pub fn encodeRlp(allocator: Allocator, payload: anytype) RlpEncoder(ArrayListWriter).Error![]u8 +163 | ``` +164 | +165 | ## EncodeRlpFromArrayListWriter +166 | RLP Encoding according to the [spec](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/). +167 | +168 | Supported types: +169 | * `bool` +170 | * `int` +171 | * `enum`, `enum_literal` +172 | * `error_set`, +173 | * `null` +174 | * `?T` +175 | * `[N]T` array types. +176 | * `[]const T` slices. +177 | * `*T` pointer types. +178 | * `structs`. Both tuple and non tuples. +179 | +180 | All other types are currently not supported. +181 | +182 | **Example** +183 | ```zig +184 | var list = std.ArrayList(u8).init(allocator); +185 | errdefer list.deinit(); +186 | +187 | try encodeRlpFromArrayListWriter(allocator, 69420, list); +188 | const encoded = try list.toOwnedSlice(); +189 | ``` +190 | +191 | ### Signature +192 | +193 | ```zig +194 | pub fn encodeRlpFromArrayListWriter(allocator: Allocator, payload: anytype, list: ArrayListWriter) RlpEncoder(ArrayListWriter).Error!void +195 | ``` +196 | +197 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/encoding/serialize.md: +-------------------------------------------------------------------------------- + 1 | ## SerializeErrors + 2 | + 3 | Set of possible errors when serializing a transaction. + 4 | + 5 | ```zig + 6 | RlpEncodeErrors || error{InvalidRecoveryId} + 7 | ``` + 8 | + 9 | ## CancunSerializeErrors + 10 | + 11 | Set of possible errors when serializing cancun blobs. + 12 | + 13 | ```zig + 14 | RlpEncodeErrors || Allocator.Error || error{ + 15 | SetupMustBeInitialized, + 16 | FailedToConvertBlobToCommitment, + 17 | FailedToComputeBlobKZGProof, + 18 | } + 19 | ``` + 20 | + 21 | ## SerializeTransaction + 22 | Main function to serialize transactions. + 23 | + 24 | Supports cancun, london, berlin and legacy transaction envelopes.\ + 25 | This uses the underlaying rlp encoding to serialize the transaction and takes an optional `Signature` in case + 26 | you want to serialize with the transaction signed. + 27 | + 28 | For cancun transactions with blobs use the `serializeCancunTransactionWithBlobs` or `serializeCancunTransactionWithSidecars` functions.\ + 29 | + 30 | **Example** + 31 | ```zig + 32 | const to = try utils.addressToBytes("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); + 33 | const base_legacy = try serializeTransaction(testing.allocator, .{ + 34 | .legacy = .{ + 35 | .nonce = 69, + 36 | .gasPrice = try utils.parseGwei(2), + 37 | .gas = 0, + 38 | .to = to, + 39 | .value = try utils.parseEth(1), + 40 | .data = null, + 41 | }, + 42 | }, null); + 43 | defer testing.allocator.free(base_legacy); + 44 | ``` + 45 | + 46 | ### Signature + 47 | + 48 | ```zig + 49 | pub fn serializeTransaction( + 50 | allocator: Allocator, + 51 | tx: TransactionEnvelope, + 52 | sig: ?Signature, + 53 | ) SerializeErrors![]u8 + 54 | ``` + 55 | + 56 | ## SerializeTransactionEIP7702 + 57 | Function to serialize eip7702 transactions. + 58 | Caller ownes the memory + 59 | + 60 | ### Signature + 61 | + 62 | ```zig + 63 | pub fn serializeTransactionEIP7702( + 64 | allocator: Allocator, + 65 | tx: Eip7702TransactionEnvelope, + 66 | sig: ?Signature, + 67 | ) SerializeErrors![]u8 + 68 | ``` + 69 | + 70 | ## SerializeCancunTransaction + 71 | Serializes a cancun type transactions without blobs. + 72 | + 73 | Please use `serializeCancunTransactionWithSidecars` or + 74 | `serializeCancunTransactionWithBlobs` if you want to + 75 | serialize them as a wrapper. + 76 | + 77 | ### Signature + 78 | + 79 | ```zig + 80 | pub fn serializeCancunTransaction( + 81 | allocator: Allocator, + 82 | tx: CancunTransactionEnvelope, + 83 | sig: ?Signature, + 84 | ) SerializeErrors![]u8 + 85 | ``` + 86 | + 87 | ## SerializeCancunTransactionWithBlobs + 88 | Serializes a cancun sidecars into the eip4844 wrapper. + 89 | + 90 | ### Signature + 91 | + 92 | ```zig + 93 | pub fn serializeCancunTransactionWithBlobs( + 94 | allocator: Allocator, + 95 | tx: CancunTransactionEnvelope, + 96 | sig: ?Signature, + 97 | blobs: []const Blob, + 98 | trusted_setup: *KZG4844, + 99 | ) CancunSerializeErrors![]u8 +100 | ``` +101 | +102 | ## SerializeCancunTransactionWithSidecars +103 | Serializes a cancun sidecars into the eip4844 wrapper. +104 | +105 | ### Signature +106 | +107 | ```zig +108 | pub fn serializeCancunTransactionWithSidecars( +109 | allocator: Allocator, +110 | tx: CancunTransactionEnvelope, +111 | sig: ?Signature, +112 | sidecars: Sidecars, +113 | ) SerializeErrors![]u8 +114 | ``` +115 | +116 | ## SerializeTransactionEIP1559 +117 | Function to serialize eip1559 transactions. +118 | Caller ownes the memory +119 | +120 | ### Signature +121 | +122 | ```zig +123 | pub fn serializeTransactionEIP1559( +124 | allocator: Allocator, +125 | tx: LondonTransactionEnvelope, +126 | sig: ?Signature, +127 | ) SerializeErrors![]u8 +128 | ``` +129 | +130 | ## SerializeTransactionEIP2930 +131 | Function to serialize eip2930 transactions. +132 | Caller ownes the memory +133 | +134 | ### Signature +135 | +136 | ```zig +137 | pub fn serializeTransactionEIP2930( +138 | allocator: Allocator, +139 | tx: BerlinTransactionEnvelope, +140 | sig: ?Signature, +141 | ) SerializeErrors![]u8 +142 | ``` +143 | +144 | ## SerializeTransactionLegacy +145 | Function to serialize legacy transactions. +146 | Caller ownes the memory +147 | +148 | ### Signature +149 | +150 | ```zig +151 | pub fn serializeTransactionLegacy( +152 | allocator: Allocator, +153 | tx: LegacyTransactionEnvelope, +154 | sig: ?Signature, +155 | ) SerializeErrors![]u8 +156 | ``` +157 | +158 | ## PrepareAccessList +159 | Serializes the access list into a slice of tuples of hex values. +160 | +161 | ### Signature +162 | +163 | ```zig +164 | pub fn prepareAccessList( +165 | allocator: Allocator, +166 | access_list: []const AccessList, +167 | ) Allocator.Error![]const StructToTupleType(AccessList) +168 | ``` +169 | +170 | ## PrepareAuthorizationList +171 | Serializes the authorization list into a slice of tuples of hex values. +172 | +173 | ### Signature +174 | +175 | ```zig +176 | pub fn prepareAuthorizationList( +177 | allocator: Allocator, +178 | authorization_list: []const AuthorizationPayload, +179 | ) Allocator.Error![]const StructToTupleType(AuthorizationPayload) +180 | ``` +181 | +182 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/encoding/ssz.md: +-------------------------------------------------------------------------------- + 1 | ## EncodeSSZ + 2 | Performs ssz encoding according to the [specification](https://ethereum.org/developers/docs/data-structures-and-encoding/ssz). + 3 | Almost all zig types are supported. + 4 | + 5 | Caller owns the memory + 6 | + 7 | ### Signature + 8 | + 9 | ```zig +10 | pub fn encodeSSZ(allocator: Allocator, value: anytype) Allocator.Error![]u8 +11 | ``` +12 | +13 | + + +-------------------------------------------------------------------------------- + + + +└── docs + └── pages + └── api + └── human-readable + ├── Ast.md + ├── HumanAbi.md + ├── Parser.md + ├── abi_parsing.md + ├── lexer.md + └── tokens.md + + +/docs/pages/api/human-readable/Ast.md: +-------------------------------------------------------------------------------- + 1 | ## Offset + 2 | + 3 | Offset used in the parser. + 4 | + 5 | ```zig + 6 | u32 + 7 | ``` + 8 | + 9 | ## TokenIndex + 10 | + 11 | Index used for the parser. + 12 | + 13 | ```zig + 14 | u32 + 15 | ``` + 16 | + 17 | ## NodeList + 18 | + 19 | Struct of arrays for the `Node` members. + 20 | + 21 | ```zig + 22 | std.MultiArrayList(Node) + 23 | ``` + 24 | + 25 | ## TokenList + 26 | + 27 | Struct of arrays for the `Token.Tag` members. + 28 | + 29 | ```zig + 30 | std.MultiArrayList(struct { + 31 | tag: TokenTag, + 32 | start: Offset, + 33 | }) + 34 | ``` + 35 | + 36 | ## Parse + 37 | Parses the source and build the Ast based on it. + 38 | + 39 | ### Signature + 40 | + 41 | ```zig + 42 | pub fn parse( + 43 | allocator: Allocator, + 44 | source: [:0]const u8, + 45 | ) Parser.ParserErrors!Ast + 46 | ``` + 47 | + 48 | ## Deinit + 49 | Clears any allocated memory from the `Ast`. + 50 | + 51 | ### Signature + 52 | + 53 | ```zig + 54 | pub fn deinit(self: *Ast, allocator: Allocator) void + 55 | ``` + 56 | + 57 | ## FunctionProto + 58 | Build the ast representation for a `function_proto` node. + 59 | + 60 | ### Signature + 61 | + 62 | ```zig + 63 | pub fn functionProto( + 64 | self: Ast, + 65 | node: Node.Index, + 66 | ) ast.FunctionDecl + 67 | ``` + 68 | + 69 | ## FunctionProtoOne + 70 | Build the ast representation for a `function_proto_one` node. + 71 | + 72 | ### Signature + 73 | + 74 | ```zig + 75 | pub fn functionProtoOne( + 76 | self: Ast, + 77 | node_buffer: *[1]Node.Index, + 78 | node: Node.Index, + 79 | ) ast.FunctionDecl + 80 | ``` + 81 | + 82 | ## FunctionProtoMulti + 83 | Build the ast representation for a `function_proto_multi` node. + 84 | + 85 | ### Signature + 86 | + 87 | ```zig + 88 | pub fn functionProtoMulti( + 89 | self: Ast, + 90 | node: Node.Index, + 91 | ) ast.FunctionDecl + 92 | ``` + 93 | + 94 | ## FunctionProtoSimple + 95 | Build the ast representation for a `function_proto_simple` node. + 96 | + 97 | ### Signature + 98 | + 99 | ```zig +100 | pub fn functionProtoSimple( +101 | self: Ast, +102 | node_buffer: *[1]Node.Index, +103 | node: Node.Index, +104 | ) ast.FunctionDecl +105 | ``` +106 | +107 | ## ReceiveProto +108 | Build the ast representation for a `receive_proto` node. +109 | +110 | ### Signature +111 | +112 | ```zig +113 | pub fn receiveProto( +114 | self: Ast, +115 | node: Node.Index, +116 | ) ast.ReceiveDecl +117 | ``` +118 | +119 | ## FallbackProtoMulti +120 | Build the ast representation for a `fallback_proto_multi` node. +121 | +122 | ### Signature +123 | +124 | ```zig +125 | pub fn fallbackProtoMulti( +126 | self: Ast, +127 | node: Node.Index, +128 | ) ast.FallbackDecl +129 | ``` +130 | +131 | ## FallbackProtoSimple +132 | Build the ast representation for a `fallback_proto_simple` node. +133 | +134 | ### Signature +135 | +136 | ```zig +137 | pub fn fallbackProtoSimple( +138 | self: Ast, +139 | node_buffer: *[1]Node.Index, +140 | node: Node.Index, +141 | ) ast.FallbackDecl +142 | ``` +143 | +144 | ## ConstructorProtoMulti +145 | Build the ast representation for a `constructor_proto_multi` node. +146 | +147 | ### Signature +148 | +149 | ```zig +150 | pub fn constructorProtoMulti( +151 | self: Ast, +152 | node: Node.Index, +153 | ) ast.ConstructorDecl +154 | ``` +155 | +156 | ## ConstructorProtoSimple +157 | Build the ast representation for a `constructor_proto_simple` node. +158 | +159 | ### Signature +160 | +161 | ```zig +162 | pub fn constructorProtoSimple( +163 | self: Ast, +164 | node_buffer: *[1]Node.Index, +165 | node: Node.Index, +166 | ) ast.ConstructorDecl +167 | ``` +168 | +169 | ## EventProtoMulti +170 | Build the ast representation for a `event_proto_multi` node. +171 | +172 | ### Signature +173 | +174 | ```zig +175 | pub fn eventProtoMulti( +176 | self: Ast, +177 | node: Node.Index, +178 | ) ast.EventDecl +179 | ``` +180 | +181 | ## EventProtoSimple +182 | Build the ast representation for a `event_proto_simple` node. +183 | +184 | ### Signature +185 | +186 | ```zig +187 | pub fn eventProtoSimple( +188 | self: Ast, +189 | node_buffer: *[1]Node.Index, +190 | node: Node.Index, +191 | ) ast.EventDecl +192 | ``` +193 | +194 | ## ErrorProtoMulti +195 | Build the ast representation for a `error_proto_multi` node. +196 | +197 | ### Signature +198 | +199 | ```zig +200 | pub fn errorProtoMulti( +201 | self: Ast, +202 | node: Node.Index, +203 | ) ast.ErrorDecl +204 | ``` +205 | +206 | ## ErrorProtoSimple +207 | Build the ast representation for a `error_proto_simple` node. +208 | +209 | ### Signature +210 | +211 | ```zig +212 | pub fn errorProtoSimple( +213 | self: Ast, +214 | node_buffer: *[1]Node.Index, +215 | node: Node.Index, +216 | ) ast.ErrorDecl +217 | ``` +218 | +219 | ## StructDecl +220 | Build the ast representation for a `struct_decl` node. +221 | +222 | ### Signature +223 | +224 | ```zig +225 | pub fn structDecl( +226 | self: Ast, +227 | node: Node.Index, +228 | ) ast.StructDecl +229 | ``` +230 | +231 | ## StructDeclOne +232 | Build the ast representation for a `struct_decl_one` node. +233 | +234 | ### Signature +235 | +236 | ```zig +237 | pub fn structDeclOne( +238 | self: Ast, +239 | node_buffer: *[1]Node.Index, +240 | node: Node.Index, +241 | ) ast.StructDecl +242 | ``` +243 | +244 | ## ExtraData +245 | Converts the data in `extra_data` into `T`. +246 | +247 | ### Signature +248 | +249 | ```zig +250 | pub fn extraData( +251 | self: Ast, +252 | comptime T: type, +253 | node: Node.Index, +254 | ) T +255 | ``` +256 | +257 | ## FirstToken +258 | Finds the first `TokenIndex` based on the provided node. +259 | +260 | ### Signature +261 | +262 | ```zig +263 | pub fn firstToken( +264 | self: Ast, +265 | node: Node.Index, +266 | ) TokenIndex +267 | ``` +268 | +269 | ## LastToken +270 | Finds the last `TokenIndex` based on the provided node. +271 | +272 | ### Signature +273 | +274 | ```zig +275 | pub fn lastToken( +276 | self: Ast, +277 | node: Node.Index, +278 | ) TokenIndex +279 | ``` +280 | +281 | ## TokenSlice +282 | Takes the associated token slice based on the provided token index. +283 | +284 | ### Signature +285 | +286 | ```zig +287 | pub fn tokenSlice( +288 | self: Ast, +289 | token_index: TokenIndex, +290 | ) []const u8 +291 | ``` +292 | +293 | ## GetNodeSource +294 | Gets the source code associated with the provided node. +295 | +296 | ### Signature +297 | +298 | ```zig +299 | pub fn getNodeSource( +300 | self: Ast, +301 | node: Node.Index, +302 | ) []const u8 +303 | ``` +304 | +305 | ## ast +306 | +307 | Ast representation of some of the "main" nodes. +308 | +309 | ### Properties +310 | +311 | ```zig +312 | struct { +313 | } +314 | ``` +315 | +316 | ## ReceiveDecl +317 | +318 | ### Properties +319 | +320 | ```zig +321 | struct { +322 | main_token: TokenIndex +323 | view: ?TokenIndex +324 | pure: ?TokenIndex +325 | payable: ?TokenIndex +326 | public: ?TokenIndex +327 | external: ?TokenIndex +328 | virtual: ?TokenIndex +329 | override: ?TokenIndex +330 | } +331 | ``` +332 | +333 | ## FallbackDecl +334 | +335 | ### Properties +336 | +337 | ```zig +338 | struct { +339 | ast: ComponentDecl +340 | main_token: TokenIndex +341 | view: ?TokenIndex +342 | pure: ?TokenIndex +343 | payable: ?TokenIndex +344 | public: ?TokenIndex +345 | external: ?TokenIndex +346 | virtual: ?TokenIndex +347 | override: ?TokenIndex +348 | } +349 | ``` +350 | +351 | ## ConstructorDecl +352 | +353 | ### Properties +354 | +355 | ```zig +356 | struct { +357 | ast: ComponentDecl +358 | main_token: TokenIndex +359 | view: ?TokenIndex +360 | pure: ?TokenIndex +361 | payable: ?TokenIndex +362 | public: ?TokenIndex +363 | external: ?TokenIndex +364 | virtual: ?TokenIndex +365 | override: ?TokenIndex +366 | } +367 | ``` +368 | +369 | ## FunctionDecl +370 | +371 | ### Properties +372 | +373 | ```zig +374 | struct { +375 | ast: ComponentDecl +376 | main_token: TokenIndex +377 | name: TokenIndex +378 | view: ?TokenIndex +379 | pure: ?TokenIndex +380 | payable: ?TokenIndex +381 | public: ?TokenIndex +382 | external: ?TokenIndex +383 | virtual: ?TokenIndex +384 | override: ?TokenIndex +385 | } +386 | ``` +387 | +388 | ## ErrorDecl +389 | +390 | ### Properties +391 | +392 | ```zig +393 | struct { +394 | ast: ComponentDecl +395 | main_token: TokenIndex +396 | name: TokenIndex +397 | } +398 | ``` +399 | +400 | ## EventDecl +401 | +402 | ### Properties +403 | +404 | ```zig +405 | struct { +406 | ast: ComponentDecl +407 | main_token: TokenIndex +408 | name: TokenIndex +409 | anonymous: ?TokenIndex +410 | } +411 | ``` +412 | +413 | ## StructDecl +414 | +415 | ### Properties +416 | +417 | ```zig +418 | struct { +419 | ast: ComponentDecl +420 | main_token: TokenIndex +421 | name: TokenIndex +422 | } +423 | ``` +424 | +425 | ## ReceiveDecl +426 | +427 | ### Properties +428 | +429 | ```zig +430 | struct { +431 | main_token: TokenIndex +432 | view: ?TokenIndex +433 | pure: ?TokenIndex +434 | payable: ?TokenIndex +435 | public: ?TokenIndex +436 | external: ?TokenIndex +437 | virtual: ?TokenIndex +438 | override: ?TokenIndex +439 | } +440 | ``` +441 | +442 | ## FallbackDecl +443 | +444 | ### Properties +445 | +446 | ```zig +447 | struct { +448 | ast: ComponentDecl +449 | main_token: TokenIndex +450 | view: ?TokenIndex +451 | pure: ?TokenIndex +452 | payable: ?TokenIndex +453 | public: ?TokenIndex +454 | external: ?TokenIndex +455 | virtual: ?TokenIndex +456 | override: ?TokenIndex +457 | } +458 | ``` +459 | +460 | ## ConstructorDecl +461 | +462 | ### Properties +463 | +464 | ```zig +465 | struct { +466 | ast: ComponentDecl +467 | main_token: TokenIndex +468 | view: ?TokenIndex +469 | pure: ?TokenIndex +470 | payable: ?TokenIndex +471 | public: ?TokenIndex +472 | external: ?TokenIndex +473 | virtual: ?TokenIndex +474 | override: ?TokenIndex +475 | } +476 | ``` +477 | +478 | ## FunctionDecl +479 | +480 | ### Properties +481 | +482 | ```zig +483 | struct { +484 | ast: ComponentDecl +485 | main_token: TokenIndex +486 | name: TokenIndex +487 | view: ?TokenIndex +488 | pure: ?TokenIndex +489 | payable: ?TokenIndex +490 | public: ?TokenIndex +491 | external: ?TokenIndex +492 | virtual: ?TokenIndex +493 | override: ?TokenIndex +494 | } +495 | ``` +496 | +497 | ## ErrorDecl +498 | +499 | ### Properties +500 | +501 | ```zig +502 | struct { +503 | ast: ComponentDecl +504 | main_token: TokenIndex +505 | name: TokenIndex +506 | } +507 | ``` +508 | +509 | ## EventDecl +510 | +511 | ### Properties +512 | +513 | ```zig +514 | struct { +515 | ast: ComponentDecl +516 | main_token: TokenIndex +517 | name: TokenIndex +518 | anonymous: ?TokenIndex +519 | } +520 | ``` +521 | +522 | ## StructDecl +523 | +524 | ### Properties +525 | +526 | ```zig +527 | struct { +528 | ast: ComponentDecl +529 | main_token: TokenIndex +530 | name: TokenIndex +531 | } +532 | ``` +533 | +534 | ## Node +535 | +536 | Ast Node representation. +537 | +538 | ### Properties +539 | +540 | ```zig +541 | struct { +542 | /// Associated tag of the node +543 | tag: Tag +544 | /// The node or token index of the `lhs` and `rhs` fields. +545 | data: Data +546 | /// The main token index associated with the node. +547 | main_token: TokenIndex +548 | } +549 | ``` +550 | +551 | ## Index +552 | +553 | Index type into the slice. +554 | +555 | ```zig +556 | u32 +557 | ``` +558 | +559 | ## Tag +560 | +561 | Enum of all of the possible node tags. +562 | +563 | ### Properties +564 | +565 | ```zig +566 | enum { +567 | root +568 | struct_type +569 | unreachable_node +570 | constructor_proto_simple +571 | constructor_proto_multi +572 | fallback_proto_simple +573 | fallback_proto_multi +574 | receive_proto +575 | event_proto_simple +576 | event_proto_multi +577 | error_proto_simple +578 | error_proto_multi +579 | function_proto +580 | function_proto_one +581 | function_proto_multi +582 | function_proto_simple +583 | array_type +584 | elementary_type +585 | tuple_type +586 | tuple_type_one +587 | specifiers +588 | struct_decl +589 | struct_decl_one +590 | struct_field +591 | var_decl +592 | error_var_decl +593 | event_var_decl +594 | } +595 | ``` +596 | +597 | ## Data +598 | +599 | ### Properties +600 | +601 | ```zig +602 | struct { +603 | lhs: Index +604 | rhs: Index +605 | } +606 | ``` +607 | +608 | ## Range +609 | +610 | ### Properties +611 | +612 | ```zig +613 | struct { +614 | start: Index +615 | end: Index +616 | } +617 | ``` +618 | +619 | ## FunctionProto +620 | +621 | ### Properties +622 | +623 | ```zig +624 | struct { +625 | specifiers: Node.Index +626 | identifier: TokenIndex +627 | params_start: Node.Index +628 | params_end: Node.Index +629 | } +630 | ``` +631 | +632 | ## FunctionProtoOne +633 | +634 | ### Properties +635 | +636 | ```zig +637 | struct { +638 | specifiers: Node.Index +639 | identifier: TokenIndex +640 | param: Node.Index +641 | } +642 | ``` +643 | +644 | ## FunctionProtoMulti +645 | +646 | ### Properties +647 | +648 | ```zig +649 | struct { +650 | identifier: TokenIndex +651 | params_start: Node.Index +652 | params_end: Node.Index +653 | } +654 | ``` +655 | +656 | ## FunctionProtoSimple +657 | +658 | ### Properties +659 | +660 | ```zig +661 | struct { +662 | identifier: TokenIndex +663 | param: Node.Index +664 | } +665 | ``` +666 | +667 | ## Index +668 | +669 | Index type into the slice. +670 | +671 | ```zig +672 | u32 +673 | ``` +674 | +675 | ## Tag +676 | +677 | Enum of all of the possible node tags. +678 | +679 | ### Properties +680 | +681 | ```zig +682 | enum { +683 | root +684 | struct_type +685 | unreachable_node +686 | constructor_proto_simple +687 | constructor_proto_multi +688 | fallback_proto_simple +689 | fallback_proto_multi +690 | receive_proto +691 | event_proto_simple +692 | event_proto_multi +693 | error_proto_simple +694 | error_proto_multi +695 | function_proto +696 | function_proto_one +697 | function_proto_multi +698 | function_proto_simple +699 | array_type +700 | elementary_type +701 | tuple_type +702 | tuple_type_one +703 | specifiers +704 | struct_decl +705 | struct_decl_one +706 | struct_field +707 | var_decl +708 | error_var_decl +709 | event_var_decl +710 | } +711 | ``` +712 | +713 | ## Data +714 | +715 | ### Properties +716 | +717 | ```zig +718 | struct { +719 | lhs: Index +720 | rhs: Index +721 | } +722 | ``` +723 | +724 | ## Range +725 | +726 | ### Properties +727 | +728 | ```zig +729 | struct { +730 | start: Index +731 | end: Index +732 | } +733 | ``` +734 | +735 | ## FunctionProto +736 | +737 | ### Properties +738 | +739 | ```zig +740 | struct { +741 | specifiers: Node.Index +742 | identifier: TokenIndex +743 | params_start: Node.Index +744 | params_end: Node.Index +745 | } +746 | ``` +747 | +748 | ## FunctionProtoOne +749 | +750 | ### Properties +751 | +752 | ```zig +753 | struct { +754 | specifiers: Node.Index +755 | identifier: TokenIndex +756 | param: Node.Index +757 | } +758 | ``` +759 | +760 | ## FunctionProtoMulti +761 | +762 | ### Properties +763 | +764 | ```zig +765 | struct { +766 | identifier: TokenIndex +767 | params_start: Node.Index +768 | params_end: Node.Index +769 | } +770 | ``` +771 | +772 | ## FunctionProtoSimple +773 | +774 | ### Properties +775 | +776 | ```zig +777 | struct { +778 | identifier: TokenIndex +779 | param: Node.Index +780 | } +781 | ``` +782 | +783 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/human-readable/HumanAbi.md: +-------------------------------------------------------------------------------- + 1 | ## HumanAbiErrors + 2 | + 3 | Set of errors when converting to the abi + 4 | + 5 | ```zig + 6 | ParamErrors || Allocator.Error || error{ NoSpaceLeft, MissingTypeDeclaration } + 7 | ``` + 8 | + 9 | ## Errors + 10 | + 11 | Set of erros when generating the ABI + 12 | + 13 | ```zig + 14 | HumanAbiErrors || Parser.ParserErrors || error{ UnexpectedMutability, UnexpectedNode } + 15 | ``` + 16 | + 17 | ## Parse + 18 | Parses the source, builds the Ast and generates the ABI. + 19 | + 20 | It's recommend to use an `ArenaAllocator` for this. + 21 | + 22 | ### Signature + 23 | + 24 | ```zig + 25 | pub fn parse( + 26 | arena: Allocator, + 27 | source: [:0]const u8, + 28 | ) Errors!Abi + 29 | ``` + 30 | + 31 | ## ToAbi + 32 | Generates the `Abi` from the ast nodes. + 33 | + 34 | ### Signature + 35 | + 36 | ```zig + 37 | pub fn toAbi(self: *HumanAbi) (HumanAbiErrors || error{ UnexpectedNode, UnexpectedMutability })!Abi + 38 | ``` + 39 | + 40 | ## ToAbiItem + 41 | Generates an `AbiItem` based on the provided node. Not all nodes are supported. + 42 | + 43 | ### Signature + 44 | + 45 | ```zig + 46 | pub fn toAbiItem( + 47 | self: HumanAbi, + 48 | node: Node.Index, + 49 | ) (HumanAbiErrors || error{ UnexpectedNode, UnexpectedMutability })!AbiItem + 50 | ``` + 51 | + 52 | ## ToAbiFunction + 53 | Generates a `AbiFunction` from a `function_proto`. + 54 | + 55 | ### Signature + 56 | + 57 | ```zig + 58 | pub fn toAbiFunction(self: HumanAbi, node: Node.Index) HumanAbiErrors!AbiFunction + 59 | ``` + 60 | + 61 | ## ToAbiFunctionOne + 62 | Generates a `AbiFunction` from a `function_proto_one`. + 63 | + 64 | ### Signature + 65 | + 66 | ```zig + 67 | pub fn toAbiFunctionOne( + 68 | self: HumanAbi, + 69 | node: Node.Index, + 70 | ) HumanAbiErrors!AbiFunction + 71 | ``` + 72 | + 73 | ## ToAbiFunctionMulti + 74 | Generates a `AbiFunction` from a `function_proto_multi`. + 75 | + 76 | ### Signature + 77 | + 78 | ```zig + 79 | pub fn toAbiFunctionMulti( + 80 | self: HumanAbi, + 81 | node: Node.Index, + 82 | ) HumanAbiErrors!AbiFunction + 83 | ``` + 84 | + 85 | ## ToAbiFunctionSimple + 86 | Generates a `AbiFunction` from a `function_proto_simple`. + 87 | + 88 | ### Signature + 89 | + 90 | ```zig + 91 | pub fn toAbiFunctionSimple( + 92 | self: HumanAbi, + 93 | node: Node.Index, + 94 | ) HumanAbiErrors!AbiFunction + 95 | ``` + 96 | + 97 | ## ToStructComponents + 98 | Generates a `AbiParameter` as a tuple with the components. + 99 | +100 | It gets generated from a `struct_decl` node. +101 | +102 | ### Signature +103 | +104 | ```zig +105 | pub fn toStructComponents( +106 | self: HumanAbi, +107 | node: Node.Index, +108 | ) HumanAbiErrors![]const AbiParameter +109 | ``` +110 | +111 | ## ToStructComponentsOne +112 | Generates a `AbiParameter` as a tuple with the components. +113 | +114 | It gets generated from a `struct_decl_one` node. +115 | +116 | ### Signature +117 | +118 | ```zig +119 | pub fn toStructComponentsOne(self: HumanAbi, node: Node.Index) HumanAbiErrors![]const AbiParameter +120 | ``` +121 | +122 | ## ToAbiConstructorMulti +123 | Generates a `AbiConstructor` from a `constructor_proto_multi`. +124 | +125 | ### Signature +126 | +127 | ```zig +128 | pub fn toAbiConstructorMulti( +129 | self: HumanAbi, +130 | node: Node.Index, +131 | ) HumanAbiErrors!AbiConstructor +132 | ``` +133 | +134 | ## ToAbiConstructorSimple +135 | Generates a `AbiConstructor` from a `constructor_proto_simple`. +136 | +137 | ### Signature +138 | +139 | ```zig +140 | pub fn toAbiConstructorSimple( +141 | self: HumanAbi, +142 | node: Node.Index, +143 | ) HumanAbiErrors!AbiConstructor +144 | ``` +145 | +146 | ## ToAbiEventMulti +147 | Generates a `AbiEvent` from a `event_proto_multi`. +148 | +149 | ### Signature +150 | +151 | ```zig +152 | pub fn toAbiEventMulti( +153 | self: HumanAbi, +154 | node: Node.Index, +155 | ) HumanAbiErrors!AbiEvent +156 | ``` +157 | +158 | ## ToAbiEventSimple +159 | Generates a `AbiEvent` from a `event_proto_simple`. +160 | +161 | ### Signature +162 | +163 | ```zig +164 | pub fn toAbiEventSimple( +165 | self: HumanAbi, +166 | node: Node.Index, +167 | ) HumanAbiErrors!AbiEvent +168 | ``` +169 | +170 | ## ToAbiErrorMulti +171 | Generates a `AbiError` from a `error_proto_multi`. +172 | +173 | ### Signature +174 | +175 | ```zig +176 | pub fn toAbiErrorMulti(self: HumanAbi, node: Node.Index) HumanAbiErrors!AbiError +177 | ``` +178 | +179 | ## ToAbiErrorSimple +180 | Generates a `AbiError` from a `error_proto_simple`. +181 | +182 | ### Signature +183 | +184 | ```zig +185 | pub fn toAbiErrorSimple( +186 | self: HumanAbi, +187 | node: Node.Index, +188 | ) HumanAbiErrors!AbiError +189 | ``` +190 | +191 | ## ToAbiParameters +192 | Generates a `[]const AbiParameter` from a slice of `var_decl`. +193 | +194 | ### Signature +195 | +196 | ```zig +197 | pub fn toAbiParameters( +198 | self: HumanAbi, +199 | nodes: []const Node.Index, +200 | ) HumanAbiErrors![]const AbiParameter +201 | ``` +202 | +203 | ## ToAbiParametersFromDecl +204 | Generates a `[]const AbiEventParameter` from a slice of `struct_field` or `error_var_decl`. +205 | +206 | ### Signature +207 | +208 | ```zig +209 | pub fn toAbiParametersFromDecl( +210 | self: HumanAbi, +211 | nodes: []const Node.Index, +212 | ) HumanAbiErrors![]const AbiParameter +213 | ``` +214 | +215 | ## ToAbiEventParameters +216 | Generates a `[]const AbiEventParameter` from a slice of `event_var_decl`. +217 | +218 | ### Signature +219 | +220 | ```zig +221 | pub fn toAbiEventParameters( +222 | self: HumanAbi, +223 | nodes: []const Node.Index, +224 | ) HumanAbiErrors![]const AbiEventParameter +225 | ``` +226 | +227 | ## ToAbiParameter +228 | Generates a `AbiParameter` from a `var_decl`. +229 | +230 | ### Signature +231 | +232 | ```zig +233 | pub fn toAbiParameter( +234 | self: HumanAbi, +235 | node: Node.Index, +236 | ) HumanAbiErrors!AbiParameter +237 | ``` +238 | +239 | ## ToAbiComponents +240 | Generates a `[]const AbiParameter` or in other words generates the tuple components. +241 | +242 | It is expecting the node to be a `tuple_type` or a `tuple_type_one`. +243 | +244 | ### Signature +245 | +246 | ```zig +247 | pub fn toAbiComponents( +248 | self: HumanAbi, +249 | node: Node.Index, +250 | ) HumanAbiErrors![]const AbiParameter +251 | ``` +252 | +253 | ## ToAbiEventParameter +254 | Generates a `AbiEventParameter` from a `event_var_decl`. +255 | +256 | ### Signature +257 | +258 | ```zig +259 | pub fn toAbiEventParameter( +260 | self: HumanAbi, +261 | node: Node.Index, +262 | ) HumanAbiErrors!AbiEventParameter +263 | ``` +264 | +265 | ## ToAbiParameterFromDecl +266 | Generates a `AbiParameter` from a `error_var_decl` or a `struct_field`. +267 | +268 | ### Signature +269 | +270 | ```zig +271 | pub fn toAbiParameterFromDecl( +272 | self: HumanAbi, +273 | node: Node.Index, +274 | ) HumanAbiErrors!AbiParameter +275 | ``` +276 | +277 | ## ToAbiFallbackMulti +278 | Generates a `AbiFallback` from a `fallback_proto_multi`. +279 | +280 | ### Signature +281 | +282 | ```zig +283 | pub fn toAbiFallbackMulti( +284 | self: HumanAbi, +285 | node: Node.Index, +286 | ) Allocator.Error!AbiFallback +287 | ``` +288 | +289 | ## ToAbiFallbackSimple +290 | Generates a `AbiFallback` from a `fallback_proto_simple`. +291 | +292 | ### Signature +293 | +294 | ```zig +295 | pub fn toAbiFallbackSimple( +296 | self: HumanAbi, +297 | node: Node.Index, +298 | ) Allocator.Error!AbiFallback +299 | ``` +300 | +301 | ## ToAbiReceive +302 | Generates a `AbiReceive` from a `receive_proto`. +303 | +304 | ### Signature +305 | +306 | ```zig +307 | pub fn toAbiReceive( +308 | self: HumanAbi, +309 | node: Node.Index, +310 | ) (Allocator.Error || error{UnexpectedMutability})!AbiReceive +311 | ``` +312 | +313 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/human-readable/Parser.md: +-------------------------------------------------------------------------------- + 1 | ## ParserErrors + 2 | + 3 | Errors that can happing whilest parsing the source code. + 4 | + 5 | ```zig + 6 | error{ParsingError} || Allocator.Error + 7 | ``` + 8 | + 9 | ## Deinit + 10 | Clears any allocated memory. + 11 | + 12 | ### Signature + 13 | + 14 | ```zig + 15 | pub fn deinit(self: *Parser) void + 16 | ``` + 17 | + 18 | ## ParseSource + 19 | Parses all of the source and build the `Ast`. + 20 | + 21 | ### Signature + 22 | + 23 | ```zig + 24 | pub fn parseSource(self: *Parser) ParserErrors!void + 25 | ``` + 26 | + 27 | ## ParseUnits + 28 | Parsers all of the solidity source unit values. + 29 | + 30 | More info can be found [here](https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.sourceUnit) + 31 | + 32 | ### Signature + 33 | + 34 | ```zig + 35 | pub fn parseUnits(self: *Parser) ParserErrors!Node.Range + 36 | ``` + 37 | + 38 | ## ExpectUnit + 39 | Expects to find a source unit otherwise it will fail. + 40 | + 41 | ### Signature + 42 | + 43 | ```zig + 44 | pub fn expectUnit(self: *Parser) ParserErrors!Node.Index + 45 | ``` + 46 | + 47 | ## ParseUnit + 48 | Parses a single source unit. + 49 | + 50 | More info can be found [here](https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.sourceUnit) + 51 | + 52 | ### Signature + 53 | + 54 | ```zig + 55 | pub fn parseUnit(self: *Parser) ParserErrors!Node.Index + 56 | ``` + 57 | + 58 | ## ParseFunctionProto + 59 | Parses a solidity function accordingly to the language grammar. + 60 | + 61 | ### Signature + 62 | + 63 | ```zig + 64 | pub fn parseFunctionProto(self: *Parser) ParserErrors!Node.Index + 65 | ``` + 66 | + 67 | ## ParseReceiveProto + 68 | Parses a solidity receive function accordingly to the language grammar. + 69 | + 70 | ### Signature + 71 | + 72 | ```zig + 73 | pub fn parseReceiveProto(self: *Parser) ParserErrors!Node.Index + 74 | ``` + 75 | + 76 | ## ParseFallbackProto + 77 | Parses a solidity fallback function accordingly to the language grammar. + 78 | + 79 | ### Signature + 80 | + 81 | ```zig + 82 | pub fn parseFallbackProto(self: *Parser) ParserErrors!Node.Index + 83 | ``` + 84 | + 85 | ## ParseConstructorProto + 86 | Parses a solidity constructor declaration accordingly to the language grammar. + 87 | + 88 | ### Signature + 89 | + 90 | ```zig + 91 | pub fn parseConstructorProto(self: *Parser) ParserErrors!Node.Index + 92 | ``` + 93 | + 94 | ## ParseSpecifiers + 95 | Parses all of the solidity mutability or visibility specifiers. + 96 | + 97 | ### Signature + 98 | + 99 | ```zig +100 | pub fn parseSpecifiers(self: *Parser) ParserErrors!Node.Index +101 | ``` +102 | +103 | ## ParseErrorProto +104 | Parses a solidity error declaration accordingly to the language grammar. +105 | +106 | ### Signature +107 | +108 | ```zig +109 | pub fn parseErrorProto(self: *Parser) ParserErrors!Node.Index +110 | ``` +111 | +112 | ## ParseEventProto +113 | Parses a solidity event declaration accordingly to the language grammar. +114 | +115 | ### Signature +116 | +117 | ```zig +118 | pub fn parseEventProto(self: *Parser) ParserErrors!Node.Index +119 | ``` +120 | +121 | ## ParseEventVarDecls +122 | Parses the possible event declaration parameters according to the language grammar. +123 | +124 | ### Signature +125 | +126 | ```zig +127 | pub fn parseEventVarDecls(self: *Parser) ParserErrors!Span +128 | ``` +129 | +130 | ## ParseErrorVarDecls +131 | Parses the possible error declaration parameters according to the language grammar. +132 | +133 | ### Signature +134 | +135 | ```zig +136 | pub fn parseErrorVarDecls(self: *Parser) ParserErrors!Span +137 | ``` +138 | +139 | ## ParseReturnParams +140 | Parses the possible function declaration parameters according to the language grammar. +141 | +142 | ### Signature +143 | +144 | ```zig +145 | pub fn parseReturnParams(self: *Parser) ParserErrors!Node.Range +146 | ``` +147 | +148 | ## ParseVariableDecls +149 | Parses the possible function declaration parameters according to the language grammar. +150 | +151 | ### Signature +152 | +153 | ```zig +154 | pub fn parseVariableDecls(self: *Parser) ParserErrors!Span +155 | ``` +156 | +157 | ## ExpectErrorVarDecl +158 | Expects to find a `error_var_decl`. Otherwise returns an error. +159 | +160 | ### Signature +161 | +162 | ```zig +163 | pub fn expectErrorVarDecl(self: *Parser) ParserErrors!Node.Index +164 | ``` +165 | +166 | ## ParseErrorVarDecl +167 | Parses the possible error declaration parameter according to the language grammar. +168 | +169 | ### Signature +170 | +171 | ```zig +172 | pub fn parseErrorVarDecl(self: *Parser) ParserErrors!Node.Index +173 | ``` +174 | +175 | ## ExpectEventVarDecl +176 | Expects to find a `event_var_decl`. Otherwise returns an error. +177 | +178 | ### Signature +179 | +180 | ```zig +181 | pub fn expectEventVarDecl(self: *Parser) ParserErrors!Node.Index +182 | ``` +183 | +184 | ## ParseEventVarDecl +185 | Parses the possible event declaration parameter according to the language grammar. +186 | +187 | ### Signature +188 | +189 | ```zig +190 | pub fn parseEventVarDecl(self: *Parser) ParserErrors!Node.Index +191 | ``` +192 | +193 | ## ExpectVarDecl +194 | Expects to find a `var_decl`. Otherwise returns an error. +195 | +196 | ### Signature +197 | +198 | ```zig +199 | pub fn expectVarDecl(self: *Parser) ParserErrors!Node.Index +200 | ``` +201 | +202 | ## ParseVariableDecl +203 | Parses the possible function declaration parameter according to the language grammar. +204 | +205 | ### Signature +206 | +207 | ```zig +208 | pub fn parseVariableDecl(self: *Parser) ParserErrors!Node.Index +209 | ``` +210 | +211 | ## ParseStructDecl +212 | Parses a struct declaration according to the language grammar. +213 | +214 | ### Signature +215 | +216 | ```zig +217 | pub fn parseStructDecl(self: *Parser) ParserErrors!Node.Index +218 | ``` +219 | +220 | ## ParseStructFields +221 | Parses all of the structs fields according to the language grammar. +222 | +223 | ### Signature +224 | +225 | ```zig +226 | pub fn parseStructFields(self: *Parser) ParserErrors!Span +227 | ``` +228 | +229 | ## ExpectStructField +230 | Expects to find a struct parameter or fails. +231 | +232 | ### Signature +233 | +234 | ```zig +235 | pub fn expectStructField(self: *Parser) ParserErrors!Node.Index +236 | ``` +237 | +238 | ## ExpectType +239 | Expects to find either a `elementary_type`, `tuple_type`, `tuple_type_one`, `array_type` or `struct_type` +240 | +241 | ### Signature +242 | +243 | ```zig +244 | pub fn expectType(self: *Parser) ParserErrors!Node.Index +245 | ``` +246 | +247 | ## ParseType +248 | Parses the token into either a `elementary_type`, `tuple_type`, `tuple_type_one`, `array_type` or `struct_type` +249 | +250 | ### Signature +251 | +252 | ```zig +253 | pub fn parseType(self: *Parser) ParserErrors!Node.Index +254 | ``` +255 | +256 | ## ParseTupleType +257 | Parses the tuple type similarly to `parseErrorVarDecls`. +258 | +259 | ### Signature +260 | +261 | ```zig +262 | pub fn parseTupleType(self: *Parser) ParserErrors!Node.Index +263 | ``` +264 | +265 | ## ConsumeElementaryType +266 | Creates a `elementary_type` node based on the solidity type keywords. +267 | +268 | ### Signature +269 | +270 | ```zig +271 | pub fn consumeElementaryType(self: *Parser) Allocator.Error!Node.Index +272 | ``` +273 | +274 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/human-readable/abi_parsing.md: +-------------------------------------------------------------------------------- + 1 | ## AbiParsed + 2 | ### Signature + 3 | + 4 | ```zig + 5 | pub fn AbiParsed(comptime T: type) type + 6 | ``` + 7 | + 8 | ## Deinit + 9 | ### Signature +10 | +11 | ```zig +12 | pub fn deinit(self: @This()) void +13 | ``` +14 | +15 | ## ParseHumanReadable +16 | Main function to use when wanting to use the human readable parser +17 | This function will allocate and use and ArenaAllocator for its allocations +18 | Caller owns the memory and must free the memory. +19 | Use the handy `deinit()` method provided by the return type +20 | +21 | The return value will depend on the abi type selected. +22 | The function will return an error if the provided type doesn't match the +23 | tokens from the provided signature +24 | +25 | ### Signature +26 | +27 | ```zig +28 | pub fn parseHumanReadable( +29 | alloc: Allocator, +30 | source: [:0]const u8, +31 | ) HumanAbi.Errors!AbiParsed(Abi) +32 | ``` +33 | +34 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/human-readable/lexer.md: +-------------------------------------------------------------------------------- + 1 | ## Lexer + 2 | + 3 | Custom Solidity Lexer that is used to generate tokens based + 4 | on the provided solidity signature. This is not a fully + 5 | solidity compatable Lexer. + 6 | + 7 | ### Properties + 8 | + 9 | ```zig +10 | struct { +11 | position: u32 +12 | currentText: [:0]const u8 +13 | } +14 | ``` +15 | +16 | ### Init +17 | ### Signature +18 | +19 | ```zig +20 | pub fn init(text: [:0]const u8) Lexer +21 | ``` +22 | +23 | ### Reset +24 | ### Signature +25 | +26 | ```zig +27 | pub fn reset( +28 | self: *Lexer, +29 | newText: []const u8, +30 | pos: ?u32, +31 | ) void +32 | ``` +33 | +34 | ### TokenSlice +35 | ### Signature +36 | +37 | ```zig +38 | pub fn tokenSlice( +39 | self: *Lexer, +40 | start: usize, +41 | end: usize, +42 | ) []const u8 +43 | ``` +44 | +45 | ### Scan +46 | ### Signature +47 | +48 | ```zig +49 | pub fn scan(self: *Lexer) Token +50 | ``` +51 | +52 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/human-readable/tokens.md: +-------------------------------------------------------------------------------- + 1 | ## Tag + 2 | + 3 | Tokens tags consumedd by the Lexer + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | struct { + 9 | syntax: SoliditySyntax + 10 | location: Location + 11 | } + 12 | ``` + 13 | + 14 | ## Location + 15 | + 16 | ### Properties + 17 | + 18 | ```zig + 19 | struct { + 20 | start: u32 + 21 | end: u32 + 22 | } + 23 | ``` + 24 | + 25 | ### TypesKeyword + 26 | ### Signature + 27 | + 28 | ```zig + 29 | pub fn typesKeyword(identifier: []const u8) ?SoliditySyntax + 30 | ``` + 31 | + 32 | ### Keywords + 33 | ### Signature + 34 | + 35 | ```zig + 36 | pub fn keywords(identifier: []const u8) ?SoliditySyntax + 37 | ``` + 38 | + 39 | ## SoliditySyntax + 40 | + 41 | ### Properties + 42 | + 43 | ```zig + 44 | enum { + 45 | Identifier + 46 | Number + 47 | Public + 48 | External + 49 | View + 50 | Payable + 51 | Pure + 52 | Private + 53 | Internal + 54 | Function + 55 | Event + 56 | Error + 57 | Fallback + 58 | Receive + 59 | Constructor + 60 | Calldata + 61 | Memory + 62 | Storage + 63 | Indexed + 64 | Comma + 65 | SemiColon + 66 | OpenParen + 67 | ClosingParen + 68 | OpenBrace + 69 | ClosingBrace + 70 | OpenBracket + 71 | ClosingBracket + 72 | After + 73 | Alias + 74 | Anonymous + 75 | Apply + 76 | Auto + 77 | Byte + 78 | Case + 79 | Catch + 80 | Constant + 81 | Copyof + 82 | Default + 83 | Defined + 84 | False + 85 | Final + 86 | Immutable + 87 | Implements + 88 | In + 89 | Inline + 90 | Let + 91 | Mapping + 92 | Match + 93 | Mutable + 94 | Null + 95 | Of + 96 | Override + 97 | Partial + 98 | Promise + 99 | Reference +100 | Relocatable +101 | Return +102 | Returns +103 | Sizeof +104 | Static +105 | Struct +106 | Super +107 | Supports +108 | Switch +109 | This +110 | True +111 | Try +112 | Typedef +113 | Typeof +114 | Var +115 | Virtual +116 | Address +117 | Bool +118 | Tuple +119 | String +120 | Bytes +121 | Bytes1 +122 | Bytes2 +123 | Bytes3 +124 | Bytes4 +125 | Bytes5 +126 | Bytes6 +127 | Bytes7 +128 | Bytes8 +129 | Bytes9 +130 | Bytes10 +131 | Bytes11 +132 | Bytes12 +133 | Bytes13 +134 | Bytes14 +135 | Bytes15 +136 | Bytes16 +137 | Bytes17 +138 | Bytes18 +139 | Bytes19 +140 | Bytes20 +141 | Bytes21 +142 | Bytes22 +143 | Bytes23 +144 | Bytes24 +145 | Bytes25 +146 | Bytes26 +147 | Bytes27 +148 | Bytes28 +149 | Bytes29 +150 | Bytes30 +151 | Bytes31 +152 | Bytes32 +153 | Uint +154 | Uint8 +155 | Uint16 +156 | Uint24 +157 | Uint32 +158 | Uint40 +159 | Uint48 +160 | Uint56 +161 | Uint64 +162 | Uint72 +163 | Uint80 +164 | Uint88 +165 | Uint96 +166 | Uint104 +167 | Uint112 +168 | Uint120 +169 | Uint128 +170 | Uint136 +171 | Uint144 +172 | Uint152 +173 | Uint160 +174 | Uint168 +175 | Uint176 +176 | Uint184 +177 | Uint192 +178 | Uint200 +179 | Uint208 +180 | Uint216 +181 | Uint224 +182 | Uint232 +183 | Uint240 +184 | Uint248 +185 | Uint256 +186 | Int +187 | Int8 +188 | Int16 +189 | Int24 +190 | Int32 +191 | Int40 +192 | Int48 +193 | Int56 +194 | Int64 +195 | Int72 +196 | Int80 +197 | Int88 +198 | Int96 +199 | Int104 +200 | Int112 +201 | Int120 +202 | Int128 +203 | Int136 +204 | Int144 +205 | Int152 +206 | Int160 +207 | Int168 +208 | Int176 +209 | Int184 +210 | Int192 +211 | Int200 +212 | Int208 +213 | Int216 +214 | Int224 +215 | Int232 +216 | Int240 +217 | Int248 +218 | Int256 +219 | EndOfFileToken +220 | UnknowToken +221 | } +222 | ``` +223 | +224 | ### LexProtectedKeywords +225 | ### Signature +226 | +227 | ```zig +228 | pub fn lexProtectedKeywords(tok_type: SoliditySyntax) ?[]const u8 +229 | ``` +230 | +231 | ### LexToken +232 | ### Signature +233 | +234 | ```zig +235 | pub fn lexToken(tok_type: SoliditySyntax) ?[]const u8 +236 | ``` +237 | +238 | ## Location +239 | +240 | ### Properties +241 | +242 | ```zig +243 | struct { +244 | start: u32 +245 | end: u32 +246 | } +247 | ``` +248 | +249 | ## SoliditySyntax +250 | +251 | ### Properties +252 | +253 | ```zig +254 | enum { +255 | Identifier +256 | Number +257 | Public +258 | External +259 | View +260 | Payable +261 | Pure +262 | Private +263 | Internal +264 | Function +265 | Event +266 | Error +267 | Fallback +268 | Receive +269 | Constructor +270 | Calldata +271 | Memory +272 | Storage +273 | Indexed +274 | Comma +275 | SemiColon +276 | OpenParen +277 | ClosingParen +278 | OpenBrace +279 | ClosingBrace +280 | OpenBracket +281 | ClosingBracket +282 | After +283 | Alias +284 | Anonymous +285 | Apply +286 | Auto +287 | Byte +288 | Case +289 | Catch +290 | Constant +291 | Copyof +292 | Default +293 | Defined +294 | False +295 | Final +296 | Immutable +297 | Implements +298 | In +299 | Inline +300 | Let +301 | Mapping +302 | Match +303 | Mutable +304 | Null +305 | Of +306 | Override +307 | Partial +308 | Promise +309 | Reference +310 | Relocatable +311 | Return +312 | Returns +313 | Sizeof +314 | Static +315 | Struct +316 | Super +317 | Supports +318 | Switch +319 | This +320 | True +321 | Try +322 | Typedef +323 | Typeof +324 | Var +325 | Virtual +326 | Address +327 | Bool +328 | Tuple +329 | String +330 | Bytes +331 | Bytes1 +332 | Bytes2 +333 | Bytes3 +334 | Bytes4 +335 | Bytes5 +336 | Bytes6 +337 | Bytes7 +338 | Bytes8 +339 | Bytes9 +340 | Bytes10 +341 | Bytes11 +342 | Bytes12 +343 | Bytes13 +344 | Bytes14 +345 | Bytes15 +346 | Bytes16 +347 | Bytes17 +348 | Bytes18 +349 | Bytes19 +350 | Bytes20 +351 | Bytes21 +352 | Bytes22 +353 | Bytes23 +354 | Bytes24 +355 | Bytes25 +356 | Bytes26 +357 | Bytes27 +358 | Bytes28 +359 | Bytes29 +360 | Bytes30 +361 | Bytes31 +362 | Bytes32 +363 | Uint +364 | Uint8 +365 | Uint16 +366 | Uint24 +367 | Uint32 +368 | Uint40 +369 | Uint48 +370 | Uint56 +371 | Uint64 +372 | Uint72 +373 | Uint80 +374 | Uint88 +375 | Uint96 +376 | Uint104 +377 | Uint112 +378 | Uint120 +379 | Uint128 +380 | Uint136 +381 | Uint144 +382 | Uint152 +383 | Uint160 +384 | Uint168 +385 | Uint176 +386 | Uint184 +387 | Uint192 +388 | Uint200 +389 | Uint208 +390 | Uint216 +391 | Uint224 +392 | Uint232 +393 | Uint240 +394 | Uint248 +395 | Uint256 +396 | Int +397 | Int8 +398 | Int16 +399 | Int24 +400 | Int32 +401 | Int40 +402 | Int48 +403 | Int56 +404 | Int64 +405 | Int72 +406 | Int80 +407 | Int88 +408 | Int96 +409 | Int104 +410 | Int112 +411 | Int120 +412 | Int128 +413 | Int136 +414 | Int144 +415 | Int152 +416 | Int160 +417 | Int168 +418 | Int176 +419 | Int184 +420 | Int192 +421 | Int200 +422 | Int208 +423 | Int216 +424 | Int224 +425 | Int232 +426 | Int240 +427 | Int248 +428 | Int256 +429 | EndOfFileToken +430 | UnknowToken +431 | } +432 | ``` +433 | +434 | ### LexProtectedKeywords +435 | ### Signature +436 | +437 | ```zig +438 | pub fn lexProtectedKeywords(tok_type: SoliditySyntax) ?[]const u8 +439 | ``` +440 | +441 | ### LexToken +442 | ### Signature +443 | +444 | ```zig +445 | pub fn lexToken(tok_type: SoliditySyntax) ?[]const u8 +446 | ``` +447 | +448 | + + +-------------------------------------------------------------------------------- + + + +└── docs + └── pages + └── api + └── meta + ├── abi.md + ├── json.md + └── utils.md + + +/docs/pages/api/meta/abi.md: +-------------------------------------------------------------------------------- + 1 | ## AbiEventParametersDataToPrimative + 2 | Sames as `AbiParametersToPrimative` but for event parameter types. + 3 | + 4 | ### Signature + 5 | + 6 | ```zig + 7 | pub fn AbiEventParametersDataToPrimative(comptime paramters: []const AbiEventParameter) type + 8 | ``` + 9 | +10 | ## AbiEventParameterDataToPrimative +11 | Sames as `AbiParameterToPrimative` but for event parameter types. +12 | +13 | ### Signature +14 | +15 | ```zig +16 | pub fn AbiEventParameterDataToPrimative(comptime param: AbiEventParameter) type +17 | ``` +18 | +19 | ## AbiEventParametersToPrimativeType +20 | Convert sets of solidity ABI Event indexed parameters to the representing Zig types. +21 | +22 | This will create a tuple type of the subset of the resulting types +23 | generated by `AbiEventParameterToPrimativeType`. If the paramters length is +24 | O then the resulting type a tuple of just the Hash type. +25 | +26 | ### Signature +27 | +28 | ```zig +29 | pub fn AbiEventParametersToPrimativeType(comptime event_params: []const AbiEventParameter) type +30 | ``` +31 | +32 | ## AbiEventParameterToPrimativeType +33 | Converts the abi event parameters into native zig types +34 | This is intended to be used for log topic data or in +35 | other words were the params are indexed. +36 | +37 | ### Signature +38 | +39 | ```zig +40 | pub fn AbiEventParameterToPrimativeType(comptime param: AbiEventParameter) type +41 | ``` +42 | +43 | ## AbiParametersToPrimative +44 | Convert sets of solidity ABI paramters to the representing Zig types. +45 | +46 | This will create a tuple type of the subset of the resulting types +47 | generated by `AbiParameterToPrimative`. If the paramters length is +48 | O then the resulting type will be a void type. +49 | +50 | ### Signature +51 | +52 | ```zig +53 | pub fn AbiParametersToPrimative(comptime paramters: []const AbiParameter) type +54 | ``` +55 | +56 | ## AbiParameterToPrimative +57 | Convert solidity ABI paramter to the representing Zig types. +58 | +59 | The resulting type will depend on the parameter passed in. +60 | `string, fixed/bytes and addresses` will result in the zig **string** type. +61 | +62 | For the `int/uint` type the resulting type will depend on the values attached to them. +63 | **If the value is not divisable by 8 or higher than 256 compilation will fail.** +64 | For example `ParamType{.int = 120}` will result in the **i120** type. +65 | +66 | If the param is a `dynamicArray` then the resulting type will be +67 | a **slice** of the set of base types set above. +68 | +69 | If the param type is a `fixedArray` then the a **array** is returned +70 | with its size depending on the *size* property on it. +71 | +72 | Finally for tuple type a **struct** will be created where the field names are property names +73 | that the components array field has. If this field is null compilation will fail. +74 | +75 | ### Signature +76 | +77 | ```zig +78 | pub fn AbiParameterToPrimative(comptime param: AbiParameter) type +79 | ``` +80 | +81 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/meta/json.md: +-------------------------------------------------------------------------------- + 1 | ## JsonParse + 2 | Custom jsonParse that is mostly used to enable + 3 | the ability to parse hex string values into native `int` types, + 4 | since parsing hex values is not part of the JSON RFC we need to rely on + 5 | the hability of zig to create a custom jsonParse method for structs. + 6 | + 7 | ### Signature + 8 | + 9 | ```zig +10 | pub fn jsonParse( +11 | comptime T: type, +12 | allocator: Allocator, +13 | source: anytype, +14 | options: ParseOptions, +15 | ) ParseError(@TypeOf(source.*))!T +16 | ``` +17 | +18 | ## JsonParseFromValue +19 | Custom jsonParseFromValue that is mostly used to enable +20 | the ability to parse hex string values into native `int` types, +21 | since parsing hex values is not part of the JSON RFC we need to rely on +22 | the hability of zig to create a custom jsonParseFromValue method for structs. +23 | +24 | ### Signature +25 | +26 | ```zig +27 | pub fn jsonParseFromValue( +28 | comptime T: type, +29 | allocator: Allocator, +30 | source: Value, +31 | options: ParseOptions, +32 | ) ParseFromValueError!T +33 | ``` +34 | +35 | ## JsonStringify +36 | Custom jsonStringify that is mostly used to enable +37 | the ability to parse int values as hex and to parse address with checksum +38 | and to treat array and slices of `u8` as hex encoded strings. This doesn't +39 | apply if the slice is `const`. +40 | +41 | Parsing hex values or dealing with strings like this is not part of the JSON RFC we need to rely on +42 | the hability of zig to create a custom jsonStringify method for structs +43 | +44 | ### Signature +45 | +46 | ```zig +47 | pub fn jsonStringify( +48 | comptime T: type, +49 | self: T, +50 | writer_stream: anytype, +51 | ) @TypeOf(writer_stream.*).Error!void +52 | ``` +53 | +54 | ## InnerParseValueRequest +55 | Inner parser that enables the behaviour described above. +56 | +57 | We don't use the `innerParse` from slice because the slice gets parsed +58 | as a json dynamic `Value`. +59 | +60 | ### Signature +61 | +62 | ```zig +63 | pub fn innerParseValueRequest( +64 | comptime T: type, +65 | allocator: Allocator, +66 | source: Value, +67 | options: ParseOptions, +68 | ) ParseFromValueError!T +69 | ``` +70 | +71 | ## InnerStringify +72 | Inner stringifier that enables the behaviour described above. +73 | +74 | ### Signature +75 | +76 | ```zig +77 | pub fn innerStringify( +78 | value: anytype, +79 | stream_writer: anytype, +80 | ) @TypeOf(stream_writer.*).Error!void +81 | ``` +82 | +83 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/meta/utils.md: +-------------------------------------------------------------------------------- + 1 | ## ConvertToEnum + 2 | Convert the struct fields into to a enum. + 3 | + 4 | ### Signature + 5 | + 6 | ```zig + 7 | pub fn ConvertToEnum(comptime T: type) type + 8 | ``` + 9 | +10 | ## Extract +11 | Type function use to extract enum members from any enum. +12 | +13 | The needle can be just the tagName of a single member or a comma seperated value. +14 | +15 | Compilation will fail if a invalid needle is provided. +16 | +17 | ### Signature +18 | +19 | ```zig +20 | pub fn Extract( +21 | comptime T: type, +22 | comptime needle: []const u8, +23 | ) type +24 | ``` +25 | +26 | ## MergeStructs +27 | Merge structs into a single one +28 | +29 | ### Signature +30 | +31 | ```zig +32 | pub fn MergeStructs( +33 | comptime T: type, +34 | comptime K: type, +35 | ) type +36 | ``` +37 | +38 | ## MergeTupleStructs +39 | Merge tuple structs +40 | +41 | ### Signature +42 | +43 | ```zig +44 | pub fn MergeTupleStructs( +45 | comptime T: type, +46 | comptime K: type, +47 | ) type +48 | ``` +49 | +50 | ## StructToTupleType +51 | Convert a struct into a tuple type. +52 | +53 | ### Signature +54 | +55 | ```zig +56 | pub fn StructToTupleType(comptime T: type) type +57 | ``` +58 | +59 | ## Omit +60 | Omits the selected keys from struct types. +61 | +62 | ### Signature +63 | +64 | ```zig +65 | pub fn Omit( +66 | comptime T: type, +67 | comptime keys: []const []const u8, +68 | ) type +69 | ``` +70 | +71 | + + +-------------------------------------------------------------------------------- + + + +└── docs + └── pages + └── api + └── types + ├── block.md + ├── ethereum.md + ├── explorer.md + ├── log.md + ├── proof.md + ├── syncing.md + ├── transaction.md + └── txpool.md + + +/docs/pages/api/types/block.md: +-------------------------------------------------------------------------------- + 1 | ## BlockTag + 2 | + 3 | Block tag used for RPC requests. + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | enum { + 9 | latest + 10 | earliest + 11 | pending + 12 | safe + 13 | finalized + 14 | } + 15 | ``` + 16 | + 17 | ## BalanceBlockTag + 18 | + 19 | Specific tags used in some RPC requests + 20 | + 21 | ```zig + 22 | Extract(BlockTag, "latest,pending,earliest") + 23 | ``` + 24 | + 25 | ## ProofBlockTag + 26 | + 27 | Specific tags used in some RPC requests + 28 | + 29 | ```zig + 30 | Extract(BlockTag, "latest,earliest") + 31 | ``` + 32 | + 33 | ## BlockRequest + 34 | + 35 | Used in the RPC method requests + 36 | + 37 | ### Properties + 38 | + 39 | ```zig + 40 | struct { + 41 | block_number: ?u64 = null + 42 | tag: ?BlockTag = .latest + 43 | include_transaction_objects: ?bool = false + 44 | } + 45 | ``` + 46 | + 47 | ## BlockHashRequest + 48 | + 49 | Used in the RPC method requests + 50 | + 51 | ### Properties + 52 | + 53 | ```zig + 54 | struct { + 55 | block_hash: Hash + 56 | include_transaction_objects: ?bool = false + 57 | } + 58 | ``` + 59 | + 60 | ## BalanceRequest + 61 | + 62 | Used in the RPC method requests + 63 | + 64 | ### Properties + 65 | + 66 | ```zig + 67 | struct { + 68 | address: Address + 69 | block_number: ?u64 = null + 70 | tag: ?BalanceBlockTag = .latest + 71 | } + 72 | ``` + 73 | + 74 | ## BlockNumberRequest + 75 | + 76 | Used in the RPC method requests + 77 | + 78 | ### Properties + 79 | + 80 | ```zig + 81 | struct { + 82 | block_number: ?u64 = null + 83 | tag: ?BalanceBlockTag = .latest + 84 | } + 85 | ``` + 86 | + 87 | ## Withdrawal + 88 | + 89 | Withdrawal field struct type. + 90 | + 91 | ### Properties + 92 | + 93 | ```zig + 94 | struct { + 95 | index: u64 + 96 | validatorIndex: u64 + 97 | address: Address + 98 | amount: Wei + 99 | } +100 | ``` +101 | +102 | ## LegacyBlock +103 | +104 | The most common block that can be found before the +105 | ethereum merge. Doesn't contain the `withdrawals` or +106 | `withdrawalsRoot` fields. +107 | +108 | ### Properties +109 | +110 | ```zig +111 | struct { +112 | baseFeePerGas: ?Gwei = null +113 | difficulty: u256 +114 | extraData: Hex +115 | gasLimit: Gwei +116 | gasUsed: Gwei +117 | hash: ?Hash +118 | logsBloom: ?Hex +119 | miner: Address +120 | mixHash: ?Hash = null +121 | nonce: ?u64 +122 | number: ?u64 +123 | parentHash: Hash +124 | receiptsRoot: Hash +125 | sealFields: ?[]const Hex = null +126 | sha3Uncles: Hash +127 | size: u64 +128 | stateRoot: Hash +129 | timestamp: u64 +130 | totalDifficulty: ?u256 = null +131 | transactions: ?BlockTransactions = null +132 | transactionsRoot: Hash +133 | uncles: ?[]const Hash = null +134 | } +135 | ``` +136 | +137 | ## ArbitrumBlock +138 | +139 | The most common block that can be found before the +140 | ethereum merge. Doesn't contain the `withdrawals` or +141 | `withdrawalsRoot` fields. +142 | +143 | ### Properties +144 | +145 | ```zig +146 | struct { +147 | baseFeePerGas: ?Gwei = null +148 | difficulty: u256 +149 | extraData: Hex +150 | gasLimit: Gwei +151 | gasUsed: Gwei +152 | hash: ?Hash +153 | logsBloom: ?Hex +154 | miner: Address +155 | mixHash: ?Hash = null +156 | nonce: ?u64 +157 | number: ?u64 +158 | parentHash: Hash +159 | receiptsRoot: Hash +160 | sealFields: ?[]const Hex = null +161 | sha3Uncles: Hash +162 | size: u64 +163 | stateRoot: Hash +164 | timestamp: u64 +165 | totalDifficulty: ?u256 = null +166 | transactions: ?BlockTransactions = null +167 | transactionsRoot: Hash +168 | uncles: ?[]const Hash = null +169 | l1BlockNumber: u64 +170 | sendCount: u64 +171 | sendRoot: Hash +172 | } +173 | ``` +174 | +175 | ## BlockTransactions +176 | +177 | Possible transactions that can be found in the +178 | block struct fields. +179 | +180 | ### Properties +181 | +182 | ```zig +183 | union(enum) { +184 | hashes: []const Hash +185 | objects: []const Transaction +186 | } +187 | ``` +188 | +189 | ## BeaconBlock +190 | +191 | Almost similar to `LegacyBlock` but with +192 | the `withdrawalsRoot` and `withdrawals` fields. +193 | +194 | ### Properties +195 | +196 | ```zig +197 | struct { +198 | baseFeePerGas: ?Gwei +199 | difficulty: u256 +200 | extraData: Hex +201 | gasLimit: Gwei +202 | gasUsed: Gwei +203 | hash: ?Hash +204 | logsBloom: ?Hex +205 | miner: Address +206 | mixHash: ?Hash = null +207 | nonce: ?u64 +208 | number: ?u64 +209 | parentHash: Hash +210 | receiptsRoot: Hash +211 | sealFields: ?[]const Hex = null +212 | sha3Uncles: Hash +213 | size: u64 +214 | stateRoot: Hash +215 | timestamp: u64 +216 | totalDifficulty: ?u256 = null +217 | transactions: ?BlockTransactions = null +218 | transactionsRoot: Hash +219 | uncles: ?[]const Hash = null +220 | withdrawalsRoot: Hash +221 | withdrawals: []const Withdrawal +222 | } +223 | ``` +224 | +225 | ## BlobBlock +226 | +227 | Almost similar to `BeaconBlock` but with this support blob fields +228 | +229 | ### Properties +230 | +231 | ```zig +232 | struct { +233 | baseFeePerGas: ?Gwei +234 | blobGasUsed: Gwei +235 | difficulty: u256 +236 | excessBlobGas: Gwei +237 | extraData: Hex +238 | gasLimit: Gwei +239 | gasUsed: Gwei +240 | hash: ?Hash +241 | logsBloom: ?Hex +242 | miner: Address +243 | mixHash: ?Hash = null +244 | nonce: ?u64 +245 | number: ?u64 +246 | parentBeaconBlockRoot: ?Hash = null +247 | requestsRoot: ?Hash = null +248 | parentHash: Hash +249 | receiptsRoot: Hash +250 | sealFields: ?[]const Hex = null +251 | sha3Uncles: Hash +252 | size: ?u64 = null +253 | stateRoot: Hash +254 | timestamp: u64 +255 | totalDifficulty: ?u256 = null +256 | transactions: ?BlockTransactions = null +257 | transactionsRoot: Hash +258 | uncles: ?[]const Hash = null +259 | withdrawalsRoot: ?Hash = null +260 | withdrawals: ?[]const Withdrawal = null +261 | } +262 | ``` +263 | +264 | ## Block +265 | +266 | Union type of the possible blocks found on the network. +267 | +268 | ### Properties +269 | +270 | ```zig +271 | union(enum) { +272 | beacon: BeaconBlock +273 | legacy: LegacyBlock +274 | cancun: BlobBlock +275 | arbitrum: ArbitrumBlock +276 | } +277 | ``` +278 | +279 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/types/ethereum.md: +-------------------------------------------------------------------------------- + 1 | ## Hex + 2 | + 3 | Ethereum hex string types in zabi. + 4 | + 5 | ```zig + 6 | []u8 + 7 | ``` + 8 | + 9 | ## Gwei + 10 | + 11 | Ethereum gwei type in zabi. + 12 | + 13 | ```zig + 14 | u64 + 15 | ``` + 16 | + 17 | ## Wei + 18 | + 19 | Ethereum wei value in zabi. + 20 | + 21 | ```zig + 22 | u256 + 23 | ``` + 24 | + 25 | ## Hash + 26 | + 27 | Ethereum hash type in zabi. + 28 | + 29 | ```zig + 30 | [32]u8 + 31 | ``` + 32 | + 33 | ## Address + 34 | + 35 | Ethereum address type in zabi. + 36 | + 37 | ```zig + 38 | [20]u8 + 39 | ``` + 40 | + 41 | ## Subscriptions + 42 | + 43 | RPC subscription calls. + 44 | + 45 | ### Properties + 46 | + 47 | ```zig + 48 | enum { + 49 | newHeads + 50 | logs + 51 | newPendingTransactions + 52 | } + 53 | ``` + 54 | + 55 | ## EthereumRpcMethods + 56 | + 57 | Set of public rpc actions. + 58 | + 59 | ### Properties + 60 | + 61 | ```zig + 62 | enum { + 63 | web3_clientVersion + 64 | web3_sha3 + 65 | net_version + 66 | net_listening + 67 | net_peerCount + 68 | eth_chainId + 69 | eth_gasPrice + 70 | eth_accounts + 71 | eth_getBalance + 72 | eth_getBlockByNumber + 73 | eth_getBlockByHash + 74 | eth_blockNumber + 75 | eth_getTransactionCount + 76 | eth_getBlockTransactionCountByHash + 77 | eth_getBlockTransactionCountByNumber + 78 | eth_getUncleCountByBlockHash + 79 | eth_getUncleCountByBlockNumber + 80 | eth_getCode + 81 | eth_getTransactionByHash + 82 | eth_getTransactionByBlockHashAndIndex + 83 | eth_getTransactionByBlockNumberAndIndex + 84 | eth_getTransactionReceipt + 85 | eth_getUncleByBlockHashAndIndex + 86 | eth_getUncleByBlockNumberAndIndex + 87 | eth_newFilter + 88 | eth_newBlockFilter + 89 | eth_newPendingTransactionFilter + 90 | eth_uninstallFilter + 91 | eth_getFilterChanges + 92 | eth_getFilterLogs + 93 | eth_getLogs + 94 | eth_sign + 95 | eth_signTransaction + 96 | eth_sendTransaction + 97 | eth_sendRawTransaction + 98 | eth_call + 99 | eth_estimateGas +100 | eth_maxPriorityFeePerGas +101 | eth_subscribe +102 | eth_unsubscribe +103 | eth_signTypedData_v4 +104 | eth_blobBaseFee +105 | eth_createAccessList +106 | eth_feeHistory +107 | eth_getStorageAt +108 | eth_getProof +109 | eth_protocolVersion +110 | eth_syncing +111 | eth_getRawTransactionByHash +112 | txpool_content +113 | txpool_contentFrom +114 | txpool_inspect +115 | txpool_status +116 | } +117 | ``` +118 | +119 | ## PublicChains +120 | +121 | Enum of know chains. +122 | More will be added in the future. +123 | +124 | ### Properties +125 | +126 | ```zig +127 | enum { +128 | ethereum = 1 +129 | goerli = 5 +130 | op_mainnet = 10 +131 | cronos = 25 +132 | bnb = 56 +133 | ethereum_classic = 61 +134 | op_kovan = 69 +135 | gnosis = 100 +136 | polygon = 137 +137 | fantom = 250 +138 | boba = 288 +139 | op_goerli = 420 +140 | base = 8543 +141 | anvil = 31337 +142 | arbitrum = 42161 +143 | arbitrum_nova = 42170 +144 | celo = 42220 +145 | avalanche = 43114 +146 | zora = 7777777 +147 | sepolia = 11155111 +148 | op_sepolia = 11155420 +149 | } +150 | ``` +151 | +152 | ## RPCResponse +153 | Wrapper around std.json.Parsed(T). Response for any of the RPC clients +154 | +155 | ### Signature +156 | +157 | ```zig +158 | pub fn RPCResponse(comptime T: type) type +159 | ``` +160 | +161 | ## Deinit +162 | ### Signature +163 | +164 | ```zig +165 | pub fn deinit(self: @This()) void +166 | ``` +167 | +168 | ## FromJson +169 | ### Signature +170 | +171 | ```zig +172 | pub fn fromJson(arena: *ArenaAllocator, value: T) @This() +173 | ``` +174 | +175 | ## EthereumRequest +176 | Zig struct representation of a RPC Request +177 | +178 | ### Signature +179 | +180 | ```zig +181 | pub fn EthereumRequest(comptime T: type) type +182 | ``` +183 | +184 | ## JsonParse +185 | ### Signature +186 | +187 | ```zig +188 | pub fn jsonParse(allocator: Allocator, source: anytype, options: ParseOptions) ParseError(@TypeOf(source.*))!@This() +189 | ``` +190 | +191 | ## JsonParseFromValue +192 | ### Signature +193 | +194 | ```zig +195 | pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) ParseFromValueError!@This() +196 | ``` +197 | +198 | ## JsonStringify +199 | ### Signature +200 | +201 | ```zig +202 | pub fn jsonStringify(self: @This(), writer_stream: anytype) @TypeOf(writer_stream.*).Error!void +203 | ``` +204 | +205 | ## EthereumResponse +206 | RPC response from an ethereum node. Can be either a success or error response. +207 | +208 | ### Signature +209 | +210 | ```zig +211 | pub fn EthereumResponse(comptime T: type) type +212 | ``` +213 | +214 | ## JsonParse +215 | ### Signature +216 | +217 | ```zig +218 | pub fn jsonParse(allocator: Allocator, source: anytype, options: ParseOptions) ParseError(@TypeOf(source.*))!@This() +219 | ``` +220 | +221 | ## JsonParseFromValue +222 | ### Signature +223 | +224 | ```zig +225 | pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) ParseFromValueError!@This() +226 | ``` +227 | +228 | ## JsonStringify +229 | ### Signature +230 | +231 | ```zig +232 | pub fn jsonStringify(self: @This(), stream: anytype) @TypeOf(stream.*).Error!void +233 | ``` +234 | +235 | ## EthereumRpcResponse +236 | Zig struct representation of a RPC Response +237 | +238 | ### Signature +239 | +240 | ```zig +241 | pub fn EthereumRpcResponse(comptime T: type) type +242 | ``` +243 | +244 | ## JsonParse +245 | ### Signature +246 | +247 | ```zig +248 | pub fn jsonParse(allocator: Allocator, source: anytype, options: ParseOptions) ParseError(@TypeOf(source.*))!@This() +249 | ``` +250 | +251 | ## JsonParseFromValue +252 | ### Signature +253 | +254 | ```zig +255 | pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) ParseFromValueError!@This() +256 | ``` +257 | +258 | ## JsonStringify +259 | ### Signature +260 | +261 | ```zig +262 | pub fn jsonStringify(self: @This(), writer_stream: anytype) @TypeOf(writer_stream.*).Error!void +263 | ``` +264 | +265 | ## EthereumSubscribeResponse +266 | Zig struct representation of a RPC subscribe response +267 | +268 | ### Signature +269 | +270 | ```zig +271 | pub fn EthereumSubscribeResponse(comptime T: type) type +272 | ``` +273 | +274 | ## JsonParse +275 | ### Signature +276 | +277 | ```zig +278 | pub fn jsonParse(allocator: Allocator, source: anytype, options: ParseOptions) ParseError(@TypeOf(source.*))!@This() +279 | ``` +280 | +281 | ## JsonParseFromValue +282 | ### Signature +283 | +284 | ```zig +285 | pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) ParseFromValueError!@This() +286 | ``` +287 | +288 | ## JsonStringify +289 | ### Signature +290 | +291 | ```zig +292 | pub fn jsonStringify(self: @This(), writer_stream: anytype) @TypeOf(writer_stream.*).Error!void +293 | ``` +294 | +295 | ## JsonParse +296 | ### Signature +297 | +298 | ```zig +299 | pub fn jsonParse(allocator: Allocator, source: anytype, options: ParseOptions) ParseError(@TypeOf(source.*))!@This() +300 | ``` +301 | +302 | ## JsonParseFromValue +303 | ### Signature +304 | +305 | ```zig +306 | pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) ParseFromValueError!@This() +307 | ``` +308 | +309 | ## JsonStringify +310 | ### Signature +311 | +312 | ```zig +313 | pub fn jsonStringify(self: @This(), writer_stream: anytype) @TypeOf(writer_stream.*).Error!void +314 | ``` +315 | +316 | ## ErrorResponse +317 | +318 | Zig struct representation of a RPC error message +319 | +320 | ### Properties +321 | +322 | ```zig +323 | struct { +324 | code: EthereumErrorCodes +325 | message: []const u8 +326 | data: ?[]const u8 = null +327 | } +328 | ``` +329 | +330 | ## ContractErrorResponse +331 | +332 | Zig struct representation of a contract error response +333 | +334 | ### Properties +335 | +336 | ```zig +337 | struct { +338 | code: EthereumErrorCodes +339 | message: []const u8 +340 | data: []const u8 +341 | } +342 | ``` +343 | +344 | ## EthereumErrorCodes +345 | +346 | Ethereum RPC error codes. +347 | https://eips.ethereum.org/EIPS/eip-1474#error-codes +348 | +349 | ### Properties +350 | +351 | ```zig +352 | enum { +353 | ContractErrorCode = 3 +354 | TooManyRequests = 429 +355 | UserRejectedRequest = 4001 +356 | Unauthorized = 4100 +357 | UnsupportedMethod = 4200 +358 | Disconnected = 4900 +359 | ChainDisconnected = 4901 +360 | InvalidInput = -32000 +361 | ResourceNotFound = -32001 +362 | ResourceUnavailable = -32002 +363 | TransactionRejected = -32003 +364 | MethodNotSupported = -32004 +365 | LimitExceeded = -32005 +366 | RpcVersionNotSupported = -32006 +367 | InvalidRequest = -32600 +368 | MethodNotFound = -32601 +369 | InvalidParams = -32602 +370 | InternalError = -32603 +371 | ParseError = -32700 +372 | _ +373 | } +374 | ``` +375 | +376 | ## EthereumZigErrors +377 | +378 | RPC errors in zig format +379 | +380 | ```zig +381 | error{ +382 | EvmFailedToExecute, +383 | TooManyRequests, +384 | InvalidInput, +385 | ResourceNotFound, +386 | ResourceUnavailable, +387 | TransactionRejected, +388 | MethodNotSupported, +389 | LimitExceeded, +390 | RpcVersionNotSupported, +391 | InvalidRequest, +392 | MethodNotFound, +393 | InvalidParams, +394 | InternalError, +395 | ParseError, +396 | UnexpectedRpcErrorCode, +397 | UserRejectedRequest, +398 | Unauthorized, +399 | UnsupportedMethod, +400 | Disconnected, +401 | ChainDisconnected, +402 | } +403 | ``` +404 | +405 | ## EthereumErrorResponse +406 | +407 | Zig struct representation of a RPC error response +408 | +409 | ### Properties +410 | +411 | ```zig +412 | struct { +413 | jsonrpc: []const u8 = "2.0" +414 | id: ?usize = null +415 | @"error": ErrorResponse +416 | } +417 | ``` +418 | +419 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/types/explorer.md: +-------------------------------------------------------------------------------- + 1 | ## ExplorerResponse + 2 | The json response from a etherscan like explorer + 3 | + 4 | ### Signature + 5 | + 6 | ```zig + 7 | pub fn ExplorerResponse(comptime T: type) type + 8 | ``` + 9 | + 10 | ## Deinit + 11 | ### Signature + 12 | + 13 | ```zig + 14 | pub fn deinit(self: @This()) void + 15 | ``` + 16 | + 17 | ## FromJson + 18 | ### Signature + 19 | + 20 | ```zig + 21 | pub fn fromJson(arena: *ArenaAllocator, value: T) @This() + 22 | ``` + 23 | + 24 | ## ExplorerSuccessResponse + 25 | The json success response from a etherscan like explorer + 26 | + 27 | ### Signature + 28 | + 29 | ```zig + 30 | pub fn ExplorerSuccessResponse(comptime T: type) type + 31 | ``` + 32 | + 33 | ## JsonParse + 34 | ### Signature + 35 | + 36 | ```zig + 37 | pub fn jsonParse( + 38 | allocator: Allocator, + 39 | source: anytype, + 40 | options: ParseOptions, + 41 | ) ParseError(@TypeOf(source.*))!@This() + 42 | ``` + 43 | + 44 | ## JsonParseFromValue + 45 | ### Signature + 46 | + 47 | ```zig + 48 | pub fn jsonParseFromValue( + 49 | allocator: Allocator, + 50 | source: Value, + 51 | options: ParseOptions, + 52 | ) ParseFromValueError!@This() + 53 | ``` + 54 | + 55 | ## JsonStringify + 56 | ### Signature + 57 | + 58 | ```zig + 59 | pub fn jsonStringify( + 60 | self: @This(), + 61 | writer_stream: anytype, + 62 | ) @TypeOf(writer_stream.*).Error!void + 63 | ``` + 64 | + 65 | ## ExplorerErrorResponse + 66 | + 67 | The json error response from a etherscan like explorer + 68 | + 69 | ### Properties + 70 | + 71 | ```zig + 72 | struct { + 73 | status: u1 = 0 + 74 | message: []const u8 + 75 | result: []const u8 + 76 | } + 77 | ``` + 78 | + 79 | ## ExplorerRequestResponse + 80 | The response represented as a union of possible responses. + 81 | Returns the `@error` field from json parsing in case the message is `NOK`. + 82 | + 83 | ### Signature + 84 | + 85 | ```zig + 86 | pub fn ExplorerRequestResponse(comptime T: type) type + 87 | ``` + 88 | + 89 | ## EndPoints + 90 | + 91 | Set of predefined block explorer endpoints. + 92 | For now these must have support for TLS v1.3 + 93 | This only supports etherscan like block explorers. + 94 | + 95 | ### Properties + 96 | + 97 | ```zig + 98 | union(enum) { + 99 | /// Assign it null if you would like to set the default endpoint value. +100 | arbitrum: ?[]const u8 +101 | /// Assign it null if you would like to set the default endpoint value. +102 | arbitrum_sepolia: ?[]const u8 +103 | /// Assign it null if you would like to set the default endpoint value. +104 | base: ?[]const u8 +105 | /// Assign it null if you would like to set the default endpoint value. +106 | bsc: ?[]const u8 +107 | /// Currently doesn't support tls v1.3 so it won't work until +108 | /// zig gets support for tls v1.2 +109 | /// Assign it null if you would like to set the default endpoint value. +110 | ethereum: ?[]const u8 +111 | /// Assign it null if you would like to set the default endpoint value. +112 | fantom: ?[]const u8 +113 | /// Assign it null if you would like to set the default endpoint value. +114 | localhost: ?[]const u8 +115 | /// Assign it null if you would like to set the default endpoint value. +116 | moonbeam: ?[]const u8 +117 | /// Assign it null if you would like to set the default endpoint value. +118 | optimism: ?[]const u8 +119 | /// Assign it null if you would like to set the default endpoint value. +120 | polygon: ?[]const u8 +121 | /// Assign it null if you would like to set the default endpoint value. +122 | sepolia: ?[]const u8 +123 | } +124 | ``` +125 | +126 | ### GetEndpoint +127 | Gets the associated endpoint or the default one. +128 | +129 | ### Signature +130 | +131 | ```zig +132 | pub fn getEndpoint(self: @This()) []const u8 +133 | ``` +134 | +135 | ## MultiAddressBalance +136 | +137 | Result from the api call of `getMultiAddressBalance` +138 | +139 | ### Properties +140 | +141 | ```zig +142 | struct { +143 | /// The address of the account. +144 | account: Address +145 | /// The balance of the account. +146 | balance: u256 +147 | } +148 | ``` +149 | +150 | ## TokenExplorerTransaction +151 | +152 | Token transaction represented by a `etherscan` like client. +153 | +154 | ### Properties +155 | +156 | ```zig +157 | struct { +158 | /// The block number where the transaction was mined +159 | blockNumber: u64 +160 | /// The time when the transaction was commited. +161 | timeStamp: u64 +162 | /// The transaction hash +163 | hash: Hash +164 | /// The transaction nonce. +165 | nonce: u64 +166 | /// The blockHash this transaction was mined. +167 | blockHash: Hash +168 | /// The sender of this transaction +169 | from: Address +170 | /// The contract address in case it exists. +171 | contractAddress: Address +172 | /// The target address. +173 | to: Address +174 | /// The value sent. Only used for erc20 tokens. +175 | value: ?u256 = null +176 | /// The token Id. Only used for erc721 and erc1155 tokens. +177 | tokenId: ?u256 = null +178 | /// The token name. +179 | tokenName: []const u8 +180 | /// The token symbol. +181 | tokenSymbol: []const u8 +182 | /// The token decimal. Only used for erc20 and erc721 tokens. +183 | tokenDecimal: ?u8 = null +184 | /// The index of this transaction on the mempool +185 | transactionIndex: usize +186 | /// The gas limit of the transaction +187 | gas: u64 +188 | /// The gas price of this transaction. +189 | gasPrice: u64 +190 | /// The gas used by the transaction. +191 | gasUsed: u64 +192 | /// The cumulative gas used by the transaction. +193 | cumulativeGasUsed: u64 +194 | /// Input field that has been deprecated. +195 | input: []const u8 = "deprecated" +196 | /// The total number of confirmations +197 | confirmations: usize +198 | } +199 | ``` +200 | +201 | ## InternalExplorerTransaction +202 | +203 | Internal transaction represented by a `etherscan` like client. +204 | +205 | ### Properties +206 | +207 | ```zig +208 | struct { +209 | /// The block number where the transaction was mined +210 | blockNumber: u64 +211 | /// The time when the transaction was commited. +212 | timeStamp: u64 +213 | /// The transaction hash +214 | hash: Hash +215 | /// The sender of this transaction +216 | from: Address +217 | /// The target address. +218 | to: ?Address +219 | /// The value sent. +220 | value: u256 +221 | /// The contract address in case it exists. +222 | contractAddress: ?Address +223 | /// The transaction data. +224 | input: ?[]u8 +225 | /// The transaction type. +226 | type: enum { call } +227 | /// The gas limit of the transaction +228 | gas: u64 +229 | /// The gas used by the transaction. +230 | gasUsed: u64 +231 | /// If the transaction failed. Use `@bitCast` to convert to `bool`. +232 | isError: u1 +233 | /// The status of the receipt. Use `@bitCast` to convert to `bool`. +234 | traceId: []const u8 +235 | /// The error code in case it exists. +236 | errCode: ?i64 +237 | } +238 | ``` +239 | +240 | ## ExplorerTransaction +241 | +242 | Transaction represented by a `etherscan` like client. +243 | +244 | ### Properties +245 | +246 | ```zig +247 | struct { +248 | /// The block number where the transaction was mined +249 | blockNumber: u64 +250 | /// The time when the transaction was commited. +251 | timeStamp: u64 +252 | /// The transaction hash +253 | hash: Hash +254 | /// The transaction nonce +255 | nonce: u64 +256 | /// The block hash +257 | blockHash: Hash +258 | /// Index of the transaction in the memory pool +259 | transactionIndex: usize +260 | /// The sender of this transaction +261 | from: Address +262 | /// The target address. +263 | to: ?Address +264 | /// The value sent. +265 | value: u256 +266 | /// The gas limit of the transaction +267 | gas: u64 +268 | /// The gas price of the transaction. +269 | gasPrice: u64 +270 | /// If the transaction failed. Use `@bitCast` to convert to `bool`. +271 | isError: u1 +272 | /// The status of the receipt. Use `@bitCast` to convert to `bool`. +273 | txreceipt_status: u1 +274 | /// The transaction data. +275 | input: ?[]u8 +276 | /// The gas used by the transaction. +277 | gasUsed: u64 +278 | /// The number of confirmations. +279 | confirmations: u64 +280 | /// The methodId of the contract if it interacted with any. +281 | methodId: ?[]u8 +282 | /// The contract method name if the transaction interacted with one. +283 | functionName: ?[]const u8 +284 | /// The contract address in case it exists. +285 | contractAddress: ?Address = null +286 | } +287 | ``` +288 | +289 | ## GetSourceResult +290 | +291 | ### Properties +292 | +293 | ```zig +294 | struct { +295 | /// The contract's source code. +296 | SourceCode: []const u8 +297 | /// The contract's ABI. +298 | ABI: Abi +299 | /// The contract name. +300 | ContractName: []const u8 +301 | /// The compiler version that was used. +302 | CompilerVersion: SemanticVersion +303 | /// The number of optimizations used. +304 | OptimizationUsed: usize +305 | /// The amount of runs of optimizations. +306 | Runs: usize +307 | /// The constructor arguments if any were used. +308 | ConstructorArguments: ?[]const u8 +309 | /// The EVM version used. +310 | EVMVersion: enum { Default } +311 | /// The library used if any. +312 | Library: ?[]const u8 +313 | /// The license type used by the contract. +314 | LicenseType: []const u8 +315 | /// If it's a proxy contract or not. Can be `@bitCast` to bool +316 | Proxy: u1 +317 | /// The implementation if it exists. +318 | Implementation: ?[]const u8 +319 | /// The bzzr swarm source. +320 | SwarmSource: Uri +321 | } +322 | ``` +323 | +324 | ## Erc1155TokenEventRequest +325 | +326 | ### Properties +327 | +328 | ```zig +329 | struct { +330 | /// The target address. +331 | address: Address +332 | /// The target contract address. +333 | contractaddress: Address +334 | /// The start block from where you want to grab the list. +335 | startblock: usize +336 | /// The end block from where you want to grab the list. +337 | endblock: BlockTag +338 | } +339 | ``` +340 | +341 | ## TokenEventRequest +342 | +343 | ### Properties +344 | +345 | ```zig +346 | struct { +347 | /// The target address. +348 | address: Address +349 | /// The target contract address. +350 | contractaddress: Address +351 | /// The start block from where you want to grab the list. +352 | startblock: usize +353 | /// The end block from where you want to grab the list. +354 | endblock: usize +355 | } +356 | ``` +357 | +358 | ## TransactionListRequest +359 | +360 | ### Properties +361 | +362 | ```zig +363 | struct { +364 | /// The target address. +365 | address: Address +366 | /// The start block from where you want to grab the list. +367 | startblock: usize +368 | /// The end block from where you want to grab the list. +369 | endblock: usize +370 | } +371 | ``` +372 | +373 | ## MultiAddressBalanceRequest +374 | +375 | ### Properties +376 | +377 | ```zig +378 | struct { +379 | /// The target addresses. +380 | address: []const Address +381 | /// The block tag to use. +382 | tag: BlockTag +383 | } +384 | ``` +385 | +386 | ## AddressBalanceRequest +387 | +388 | ### Properties +389 | +390 | ```zig +391 | struct { +392 | /// The target address. +393 | address: Address +394 | /// The block tag to use. +395 | tag: BlockTag +396 | } +397 | ``` +398 | +399 | ## RangeRequest +400 | +401 | ### Properties +402 | +403 | ```zig +404 | struct { +405 | /// The start block number range. +406 | startblock: u64 +407 | /// The end block number range. +408 | endblock: u64 +409 | } +410 | ``` +411 | +412 | ## ContractCreationResult +413 | +414 | ### Properties +415 | +416 | ```zig +417 | struct { +418 | /// The contract address +419 | contractAddress: Address +420 | /// The contract creator +421 | contractCreator: Address +422 | /// The creation transaction hash +423 | txHash: Hash +424 | } +425 | ``` +426 | +427 | ## TransactionStatus +428 | +429 | ### Properties +430 | +431 | ```zig +432 | struct { +433 | /// If the transaction reverted. +434 | isError: ?u1 +435 | /// The error message in case it reverted. +436 | errDescription: ?[]const u8 +437 | } +438 | ``` +439 | +440 | ## ReceiptStatus +441 | +442 | ### Properties +443 | +444 | ```zig +445 | struct { +446 | /// The receipt status +447 | status: ?u1 +448 | } +449 | ``` +450 | +451 | ## BlockRewards +452 | +453 | The block reward endpoint response. +454 | +455 | ### Properties +456 | +457 | ```zig +458 | struct { +459 | /// The block number of the reward. +460 | blockNumber: u64 +461 | /// The timestamp of the reward. +462 | timeStamp: u64 +463 | /// The block miner. +464 | blockMiner: Address +465 | /// The reward value. +466 | blockReward: u256 +467 | /// The uncles block rewards. +468 | uncles: []const BlockRewards +469 | /// The reward value included in uncle blocks. +470 | uncleInclusionReward: u256 +471 | } +472 | ``` +473 | +474 | ## LogRequest +475 | +476 | `getLogs` request via a block explorer. +477 | +478 | ### Properties +479 | +480 | ```zig +481 | struct { +482 | /// The address where you want to grab the logs. +483 | address: Address +484 | /// The start block range where you want search from. +485 | fromBlock: u64 +486 | /// The en block range where you want search to. +487 | toBlock: u64 +488 | } +489 | ``` +490 | +491 | ## ExplorerLog +492 | +493 | Zig struct representation of the log explorer response. +494 | +495 | ### Properties +496 | +497 | ```zig +498 | struct { +499 | /// The contract address +500 | address: Address +501 | /// The emitted log topics from the contract call. +502 | topics: []const ?Hash +503 | /// The data sent via the log +504 | data: []u8 +505 | /// The block number this log was emitted. +506 | blockNumber: ?u64 +507 | /// The block hash where this log was emitted. +508 | blockHash: ?Hash +509 | /// The timestamp where this log was emitted. +510 | timeStamp: u64 +511 | /// The gas price of the transaction this log was emitted in. +512 | gasPrice: u64 +513 | /// The gas used by the transaction this log was emitted in. +514 | gasUsed: u64 +515 | /// The log index. +516 | logIndex: ?usize +517 | /// The transaction hash that emitted this log. +518 | transactionHash: ?Hash +519 | /// The transaction index in the memory pool location. +520 | transactionIndex: ?usize +521 | } +522 | ``` +523 | +524 | ## BlockCountdown +525 | +526 | ### Properties +527 | +528 | ```zig +529 | struct { +530 | /// The current block in the node. +531 | CurrentBlock: u64 +532 | /// The target block. +533 | CountdownBlock: u64 +534 | /// The number of blocks remaining between `CurrentBlock` and `CountdownBlock`. +535 | RemainingBlock: u64 +536 | /// The seconds until `CountdownBlock` is reached. +537 | EstimateTimeInSec: f64 +538 | } +539 | ``` +540 | +541 | ## BlocktimeRequest +542 | +543 | ### Properties +544 | +545 | ```zig +546 | struct { +547 | /// Unix timestamp in seconds +548 | timestamp: u64 +549 | /// The tag to choose for finding the closest block based on the timestamp. +550 | closest: enum { +551 | before, +552 | after, +553 | } +554 | } +555 | ``` +556 | +557 | ## TokenBalanceRequest +558 | +559 | ### Properties +560 | +561 | ```zig +562 | struct { +563 | /// The target address. +564 | address: Address +565 | /// The target contract address. +566 | contractaddress: Address +567 | /// The block tag to use to query this information. +568 | tag: BlockTag +569 | } +570 | ``` +571 | +572 | ## EtherPriceResponse +573 | +574 | ### Properties +575 | +576 | ```zig +577 | struct { +578 | /// The ETH-BTC price. +579 | ethbtc: f64 +580 | /// The ETH-BTC price timestamp. +581 | ethbtc_timestamp: u64 +582 | /// The ETH-USD price. +583 | ethusd: f64 +584 | /// The ETH-USD price timestamp. +585 | ethusd_timestamp: u64 +586 | } +587 | ``` +588 | +589 | ## GasOracle +590 | +591 | ### Properties +592 | +593 | ```zig +594 | struct { +595 | /// The last block where the oracle recorded the information. +596 | LastBlock: u64 +597 | /// Safe gas price to used to get transaciton mined. +598 | SafeGasPrice: u64 +599 | /// Proposed gas price. +600 | ProposeGasPrice: u64 +601 | /// Fast gas price. +602 | FastGasPrice: u64 +603 | /// Suggest transacition base fee. +604 | suggestBaseFee: f64 +605 | /// Gas used ratio. +606 | gasUsedRatio: []const f64 +607 | } +608 | ``` +609 | +610 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/types/log.md: +-------------------------------------------------------------------------------- + 1 | ## Log + 2 | + 3 | Zig struct representation of the log RPC response. + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | struct { + 9 | blockHash: ?Hash +10 | address: Address +11 | logIndex: ?usize +12 | data: Hex +13 | removed: bool +14 | topics: []const ?Hash +15 | blockNumber: ?u64 +16 | transactionIndex: ?usize +17 | transactionHash: ?Hash +18 | transactionLogIndex: ?usize = null +19 | blockTimestamp: ?u64 = null +20 | } +21 | ``` +22 | +23 | ## Logs +24 | +25 | Slice of the struct log +26 | +27 | ```zig +28 | []const Log +29 | ``` +30 | +31 | ## LogRequest +32 | +33 | Its default all null so that when it gets stringified +34 | Logs request struct used by the RPC request methods. +35 | we can use `ignore_null_fields` to omit these fields +36 | +37 | ### Properties +38 | +39 | ```zig +40 | struct { +41 | fromBlock: ?u64 = null +42 | toBlock: ?u64 = null +43 | address: ?Address = null +44 | topics: ?[]const ?Hex = null +45 | blockHash: ?Hash = null +46 | } +47 | ``` +48 | +49 | ## LogTagRequest +50 | +51 | Same as `LogRequest` but `fromBlock` and +52 | `toBlock` are tags. +53 | +54 | ### Properties +55 | +56 | ```zig +57 | struct { +58 | fromBlock: ?BalanceBlockTag = null +59 | toBlock: ?BalanceBlockTag = null +60 | address: ?Address = null +61 | topics: ?[]const ?Hex = null +62 | blockHash: ?Hash = null +63 | } +64 | ``` +65 | +66 | ## WatchLogsRequest +67 | +68 | Options for `watchLogs` websocket request. +69 | +70 | ### Properties +71 | +72 | ```zig +73 | struct { +74 | address: Address +75 | topics: ?[]const ?Hex = null +76 | } +77 | ``` +78 | +79 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/types/proof.md: +-------------------------------------------------------------------------------- + 1 | ## ProofRequest + 2 | + 3 | Eth get proof rpc request. + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | struct { + 9 | address: Address +10 | storageKeys: []const Hash +11 | blockNumber: ?u64 = null +12 | } +13 | ``` +14 | +15 | ## ProofResult +16 | +17 | Result of eth_getProof +18 | +19 | ### Properties +20 | +21 | ```zig +22 | struct { +23 | address: Address +24 | balance: Wei +25 | codeHash: Hash +26 | nonce: u64 +27 | storageHash: Hash +28 | /// Array of RLP-serialized MerkleTree-Nodes +29 | accountProof: []const Hex +30 | storageProof: []const StorageProof +31 | } +32 | ``` +33 | +34 | ## StorageProof +35 | +36 | ### Properties +37 | +38 | ```zig +39 | struct { +40 | key: Hash +41 | value: Wei +42 | /// Array of RLP-serialized MerkleTree-Nodes +43 | proof: []const Hex +44 | } +45 | ``` +46 | +47 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/types/syncing.md: +-------------------------------------------------------------------------------- + 1 | ## SyncStatus + 2 | + 3 | Result when calling `eth_syncing` if a node hasn't finished syncing + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | struct { + 9 | startingBlock: u64 +10 | currentBlock: u64 +11 | highestBlock: u64 +12 | syncedAccounts: u64 +13 | syncedAccountsBytes: u64 +14 | syncedBytecodes: u64 +15 | syncedBytecodesBytes: u64 +16 | syncedStorage: u64 +17 | syncedStorageBytes: u64 +18 | healedTrienodes: u64 +19 | healedTrienodeBytes: u64 +20 | healedBytecodes: u64 +21 | healedBytecodesBytes: u64 +22 | healingTrienodes: u64 +23 | healingBytecode: u64 +24 | txIndexFinishedBlocks: u64 +25 | txIndexRemainingBlocks: u64 +26 | } +27 | ``` +28 | +29 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/types/transaction.md: +-------------------------------------------------------------------------------- + 1 | ## BerlinEnvelope + 2 | + 3 | Tuple representing an encoded envelope for the Berlin hardfork. + 4 | + 5 | ```zig + 6 | StructToTupleType(BerlinTransactionEnvelope) + 7 | ``` + 8 | + 9 | ## BerlinEnvelopeSigned + 10 | + 11 | Tuple representing an encoded envelope for the Berlin hardfork with the signature. + 12 | + 13 | ```zig + 14 | StructToTupleType(BerlinTransactionEnvelopeSigned) + 15 | ``` + 16 | + 17 | ## CancunEnvelope + 18 | + 19 | Tuple representing an encoded envelope for the London hardfork. + 20 | + 21 | ```zig + 22 | StructToTupleType(CancunTransactionEnvelope) + 23 | ``` + 24 | + 25 | ## CancunEnvelopeSigned + 26 | + 27 | Tuple representing an encoded envelope for the London hardfork with the signature. + 28 | + 29 | ```zig + 30 | StructToTupleType(CancunTransactionEnvelopeSigned) + 31 | ``` + 32 | + 33 | ## CancunSignedWrapper + 34 | + 35 | Signed cancun transaction converted to wrapper with blobs, commitments and proofs. + 36 | + 37 | ```zig + 38 | Merge(StructToTupleType(CancunTransactionEnvelopeSigned), struct { []const Blob, []const KZGCommitment, []const KZGProof }) + 39 | ``` + 40 | + 41 | ## CancunWrapper + 42 | + 43 | Cancun transaction converted to wrapper with blobs, commitments and proofs. + 44 | + 45 | ```zig + 46 | Merge(StructToTupleType(CancunTransactionEnvelope), struct { []const Blob, []const KZGCommitment, []const KZGProof }) + 47 | ``` + 48 | + 49 | ## Eip7702Envelope + 50 | + 51 | Tuple representing EIP 7702 authorization envelope tuple. + 52 | + 53 | ```zig + 54 | StructToTupleType(Eip7702TransactionEnvelope) + 55 | ``` + 56 | + 57 | ## Eip7702EnvelopeSigned + 58 | + 59 | Tuple representing EIP 7702 authorization envelope tuple with the signature. + 60 | + 61 | ```zig + 62 | StructToTupleType(Eip7702TransactionEnvelopeSigned) + 63 | ``` + 64 | + 65 | ## LegacyEnvelope + 66 | + 67 | Tuple representing an encoded envelope for a legacy transaction. + 68 | + 69 | ```zig + 70 | StructToTupleType(Omit(LegacyTransactionEnvelope, &.{"chainId"})) + 71 | ``` + 72 | + 73 | ## LegacyEnvelopeSigned + 74 | + 75 | Tuple representing an encoded envelope for a legacy transaction with the signature. + 76 | + 77 | ```zig + 78 | StructToTupleType(Omit(LegacyTransactionEnvelopeSigned, &.{"chainId"})) + 79 | ``` + 80 | + 81 | ## LondonEnvelope + 82 | + 83 | Tuple representing an encoded envelope for the London hardfork. + 84 | + 85 | ```zig + 86 | StructToTupleType(LondonTransactionEnvelope) + 87 | ``` + 88 | + 89 | ## LondonEnvelopeSigned + 90 | + 91 | Tuple representing an encoded envelope for the London hardfork with the signature. + 92 | + 93 | ```zig + 94 | StructToTupleType(LondonTransactionEnvelopeSigned) + 95 | ``` + 96 | + 97 | ## TransactionTypes + 98 | + 99 | All of the transaction types. + 100 | + 101 | ### Properties + 102 | + 103 | ```zig + 104 | enum { + 105 | legacy = 0x00 + 106 | berlin = 0x01 + 107 | london = 0x02 + 108 | cancun = 0x03 + 109 | eip7702 = 0x04 + 110 | deposit = 0x7e + 111 | _ + 112 | } + 113 | ``` + 114 | + 115 | ## TransactionEnvelope + 116 | + 117 | The transaction envelope that will be serialized before getting sent to the network. + 118 | + 119 | ### Properties + 120 | + 121 | ```zig + 122 | union(enum) { + 123 | berlin: BerlinTransactionEnvelope + 124 | cancun: CancunTransactionEnvelope + 125 | eip7702: Eip7702TransactionEnvelope + 126 | legacy: LegacyTransactionEnvelope + 127 | london: LondonTransactionEnvelope + 128 | } + 129 | ``` + 130 | + 131 | ## Eip7702TransactionEnvelope + 132 | + 133 | The transaction envelope from eip7702. + 134 | + 135 | ### Properties + 136 | + 137 | ```zig + 138 | struct { + 139 | chainId: u64 + 140 | nonce: u64 + 141 | maxPriorityFeePerGas: u64 + 142 | maxFeePerGas: u64 + 143 | gas: u64 + 144 | to: ?Address = null + 145 | value: Wei + 146 | data: ?Hex = null + 147 | accessList: []const AccessList + 148 | authorizationList: []const AuthorizationPayload + 149 | } + 150 | ``` + 151 | + 152 | ## CancunTransactionEnvelope + 153 | + 154 | The transaction envelope from the Cancun hardfork + 155 | + 156 | ### Properties + 157 | + 158 | ```zig + 159 | struct { + 160 | chainId: usize + 161 | nonce: u64 + 162 | maxPriorityFeePerGas: Gwei + 163 | maxFeePerGas: Gwei + 164 | gas: Gwei + 165 | to: ?Address = null + 166 | value: Wei + 167 | data: ?Hex = null + 168 | accessList: []const AccessList + 169 | maxFeePerBlobGas: Gwei + 170 | blobVersionedHashes: ?[]const Hash = null + 171 | } + 172 | ``` + 173 | + 174 | ## LondonTransactionEnvelope + 175 | + 176 | The transaction envelope from the London hardfork + 177 | + 178 | ### Properties + 179 | + 180 | ```zig + 181 | struct { + 182 | chainId: usize + 183 | nonce: u64 + 184 | maxPriorityFeePerGas: Gwei + 185 | maxFeePerGas: Gwei + 186 | gas: Gwei + 187 | to: ?Address = null + 188 | value: Wei + 189 | data: ?Hex = null + 190 | accessList: []const AccessList + 191 | } + 192 | ``` + 193 | + 194 | ## BerlinTransactionEnvelope + 195 | + 196 | The transaction envelope from the Berlin hardfork + 197 | + 198 | ### Properties + 199 | + 200 | ```zig + 201 | struct { + 202 | chainId: usize + 203 | nonce: u64 + 204 | gas: Gwei + 205 | gasPrice: Gwei + 206 | to: ?Address = null + 207 | value: Wei + 208 | data: ?Hex = null + 209 | accessList: []const AccessList + 210 | } + 211 | ``` + 212 | + 213 | ## LegacyTransactionEnvelope + 214 | + 215 | The transaction envelope from a legacy transaction + 216 | + 217 | ### Properties + 218 | + 219 | ```zig + 220 | struct { + 221 | chainId: usize = 0 + 222 | nonce: u64 + 223 | gas: Gwei + 224 | gasPrice: Gwei + 225 | to: ?Address = null + 226 | value: Wei + 227 | data: ?Hex = null + 228 | } + 229 | ``` + 230 | + 231 | ## AccessList + 232 | + 233 | Struct representing the accessList field. + 234 | + 235 | ### Properties + 236 | + 237 | ```zig + 238 | struct { + 239 | address: Address + 240 | storageKeys: []const Hash + 241 | } + 242 | ``` + 243 | + 244 | ## AuthorizationPayload + 245 | + 246 | EIP7702 authorization payload. + 247 | + 248 | ### Properties + 249 | + 250 | ```zig + 251 | struct { + 252 | chain_id: u64 + 253 | address: Address + 254 | nonce: u64 + 255 | y_parity: u8 + 256 | r: u256 + 257 | s: u256 + 258 | } + 259 | ``` + 260 | + 261 | ## AccessListResult + 262 | + 263 | Struct representing the result of create accessList + 264 | + 265 | ### Properties + 266 | + 267 | ```zig + 268 | struct { + 269 | accessList: []const AccessList + 270 | gasUsed: Gwei + 271 | } + 272 | ``` + 273 | + 274 | ## TransactionEnvelopeSigned + 275 | + 276 | Signed transaction envelope with the signature fields + 277 | + 278 | ### Properties + 279 | + 280 | ```zig + 281 | union(enum) { + 282 | berlin: BerlinTransactionEnvelopeSigned + 283 | cancun: CancunTransactionEnvelopeSigned + 284 | eip7702: Eip7702TransactionEnvelopeSigned + 285 | legacy: LegacyTransactionEnvelopeSigned + 286 | london: LondonTransactionEnvelopeSigned + 287 | } + 288 | ``` + 289 | + 290 | ## Eip7702TransactionEnvelopeSigned + 291 | + 292 | The transaction envelope from eip7702. + 293 | + 294 | ### Properties + 295 | + 296 | ```zig + 297 | struct { + 298 | chainId: u64 + 299 | nonce: u64 + 300 | maxPriorityFeePerGas: u64 + 301 | maxFeePerGas: u64 + 302 | gas: u64 + 303 | to: ?Address = null + 304 | value: Wei + 305 | data: ?Hex = null + 306 | accessList: []const AccessList + 307 | authorizationList: []const AuthorizationPayload + 308 | v: u2 + 309 | r: u256 + 310 | s: u256 + 311 | } + 312 | ``` + 313 | + 314 | ## CancunTransactionEnvelopeSigned + 315 | + 316 | The transaction envelope from the London hardfork with the signature fields + 317 | + 318 | ### Properties + 319 | + 320 | ```zig + 321 | struct { + 322 | chainId: usize + 323 | nonce: u64 + 324 | maxPriorityFeePerGas: Gwei + 325 | maxFeePerGas: Gwei + 326 | gas: Gwei + 327 | to: ?Address = null + 328 | value: Wei + 329 | data: ?Hex = null + 330 | accessList: []const AccessList + 331 | maxFeePerBlobGas: Gwei + 332 | blobVersionedHashes: ?[]const Hash = null + 333 | v: u2 + 334 | r: u256 + 335 | s: u256 + 336 | } + 337 | ``` + 338 | + 339 | ## LondonTransactionEnvelopeSigned + 340 | + 341 | The transaction envelope from the London hardfork with the signature fields + 342 | + 343 | ### Properties + 344 | + 345 | ```zig + 346 | struct { + 347 | chainId: usize + 348 | nonce: u64 + 349 | maxPriorityFeePerGas: Gwei + 350 | maxFeePerGas: Gwei + 351 | gas: Gwei + 352 | to: ?Address = null + 353 | value: Wei + 354 | data: ?Hex = null + 355 | accessList: []const AccessList + 356 | v: u2 + 357 | r: u256 + 358 | s: u256 + 359 | } + 360 | ``` + 361 | + 362 | ## BerlinTransactionEnvelopeSigned + 363 | + 364 | The transaction envelope from the Berlin hardfork with the signature fields + 365 | + 366 | ### Properties + 367 | + 368 | ```zig + 369 | struct { + 370 | chainId: usize + 371 | nonce: u64 + 372 | gas: Gwei + 373 | gasPrice: Gwei + 374 | to: ?Address = null + 375 | value: Wei + 376 | data: ?Hex = null + 377 | accessList: []const AccessList + 378 | v: u2 + 379 | r: u256 + 380 | s: u256 + 381 | } + 382 | ``` + 383 | + 384 | ## LegacyTransactionEnvelopeSigned + 385 | + 386 | The transaction envelope from a legacy transaction with the signature fields + 387 | + 388 | ### Properties + 389 | + 390 | ```zig + 391 | struct { + 392 | chainId: usize = 0 + 393 | nonce: u64 + 394 | gas: Gwei + 395 | gasPrice: Gwei + 396 | to: ?Address = null + 397 | value: Wei + 398 | data: ?Hex = null + 399 | v: usize + 400 | r: ?u256 + 401 | s: ?u256 + 402 | } + 403 | ``` + 404 | + 405 | ## UnpreparedTransactionEnvelope + 406 | + 407 | Same as `Envelope` but were all fields are optionals. + 408 | + 409 | ### Properties + 410 | + 411 | ```zig + 412 | struct { + 413 | type: TransactionTypes + 414 | chainId: ?usize = null + 415 | nonce: ?u64 = null + 416 | maxFeePerBlobGas: ?Gwei = null + 417 | maxPriorityFeePerGas: ?Gwei = null + 418 | maxFeePerGas: ?Gwei = null + 419 | gas: ?Gwei = null + 420 | gasPrice: ?Gwei = null + 421 | to: ?Address = null + 422 | value: ?Wei = null + 423 | data: ?Hex = null + 424 | accessList: ?[]const AccessList = null + 425 | blobVersionedHashes: ?[]const Hash = null + 426 | authList: ?[]const AuthorizationPayload = null + 427 | } + 428 | ``` + 429 | + 430 | ## LondonPendingTransaction + 431 | + 432 | The representation of a London hardfork pending transaction. + 433 | + 434 | ### Properties + 435 | + 436 | ```zig + 437 | struct { + 438 | hash: Hash + 439 | nonce: u64 + 440 | blockHash: ?Hash + 441 | blockNumber: ?u64 + 442 | transactionIndex: ?u64 + 443 | from: Address + 444 | to: ?Address + 445 | value: Wei + 446 | gasPrice: Gwei + 447 | gas: Gwei + 448 | input: Hex + 449 | v: u4 + 450 | /// Represented as values instead of the hash because + 451 | /// a valid signature is not guaranteed to be 32 bits + 452 | r: u256 + 453 | /// Represented as values instead of the hash because + 454 | /// a valid signature is not guaranteed to be 32 bits + 455 | s: u256 + 456 | type: TransactionTypes + 457 | accessList: []const AccessList + 458 | maxPriorityFeePerGas: Gwei + 459 | maxFeePerGas: Gwei + 460 | chainId: usize + 461 | yParity: u1 + 462 | } + 463 | ``` + 464 | + 465 | ## LegacyPendingTransaction + 466 | + 467 | The legacy representation of a pending transaction. + 468 | + 469 | ### Properties + 470 | + 471 | ```zig + 472 | struct { + 473 | hash: Hash + 474 | nonce: u64 + 475 | blockHash: ?Hash + 476 | blockNumber: ?u64 + 477 | transactionIndex: ?u64 + 478 | from: Address + 479 | to: ?Address + 480 | value: Wei + 481 | gasPrice: Gwei + 482 | gas: Gwei + 483 | input: Hex + 484 | v: usize + 485 | /// Represented as values instead of the hash because + 486 | /// a valid signature is not guaranteed to be 32 bits + 487 | r: u256 + 488 | /// Represented as values instead of the hash because + 489 | /// a valid signature is not guaranteed to be 32 bits + 490 | s: u256 + 491 | type: TransactionTypes + 492 | chainId: ?usize = null + 493 | } + 494 | ``` + 495 | + 496 | ## L2Transaction + 497 | + 498 | The Cancun hardfork representation of a transaction. + 499 | + 500 | ### Properties + 501 | + 502 | ```zig + 503 | struct { + 504 | hash: Hash + 505 | nonce: u64 + 506 | blockHash: ?Hash + 507 | blockNumber: ?u64 + 508 | transactionIndex: ?u64 + 509 | from: Address + 510 | to: ?Address + 511 | value: Wei + 512 | gasPrice: Gwei + 513 | gas: Gwei + 514 | input: Hex + 515 | v: usize + 516 | /// Represented as values instead of the hash because + 517 | /// a valid signature is not guaranteed to be 32 bits + 518 | r: u256 + 519 | /// Represented as values instead of the hash because + 520 | /// a valid signature is not guaranteed to be 32 bits + 521 | s: u256 + 522 | sourceHash: ?Hash = null + 523 | isSystemTx: ?bool = null + 524 | index: u64 + 525 | l1BlockNumber: u64 + 526 | l1Timestamp: u64 + 527 | l1TxOrigin: ?Hash + 528 | queueIndex: ?u64 + 529 | queueOrigin: []const u8 + 530 | rawTransaction: Hex + 531 | } + 532 | ``` + 533 | + 534 | ## CancunTransaction + 535 | + 536 | The Cancun hardfork representation of a transaction. + 537 | + 538 | ### Properties + 539 | + 540 | ```zig + 541 | struct { + 542 | hash: Hash + 543 | nonce: u64 + 544 | blockHash: ?Hash + 545 | blockNumber: ?u64 + 546 | transactionIndex: ?u64 + 547 | from: Address + 548 | to: ?Address + 549 | value: Wei + 550 | gasPrice: Gwei + 551 | gas: Gwei + 552 | input: Hex + 553 | v: u4 + 554 | /// Represented as values instead of the hash because + 555 | /// a valid signature is not guaranteed to be 32 bits + 556 | r: u256 + 557 | /// Represented as values instead of the hash because + 558 | /// a valid signature is not guaranteed to be 32 bits + 559 | s: u256 + 560 | sourceHash: ?Hash = null + 561 | isSystemTx: ?bool = null + 562 | type: TransactionTypes + 563 | accessList: []const AccessList + 564 | blobVersionedHashes: []const Hash + 565 | maxFeePerBlobGas: Gwei + 566 | maxPriorityFeePerGas: Gwei + 567 | maxFeePerGas: Gwei + 568 | chainId: usize + 569 | yParity: ?u1 = null + 570 | } + 571 | ``` + 572 | + 573 | ## LondonTransaction + 574 | + 575 | The London hardfork representation of a transaction. + 576 | + 577 | ### Properties + 578 | + 579 | ```zig + 580 | struct { + 581 | hash: Hash + 582 | nonce: u64 + 583 | blockHash: ?Hash + 584 | blockNumber: ?u64 + 585 | transactionIndex: ?u64 + 586 | from: Address + 587 | to: ?Address + 588 | value: Wei + 589 | gasPrice: Gwei + 590 | gas: Gwei + 591 | input: Hex + 592 | v: u4 + 593 | /// Represented as values instead of the hash because + 594 | /// a valid signature is not guaranteed to be 32 bits + 595 | r: u256 + 596 | /// Represented as values instead of the hash because + 597 | /// a valid signature is not guaranteed to be 32 bits + 598 | s: u256 + 599 | sourceHash: ?Hash = null + 600 | isSystemTx: ?bool = null + 601 | type: TransactionTypes + 602 | accessList: []const AccessList + 603 | maxPriorityFeePerGas: Gwei + 604 | maxFeePerGas: Gwei + 605 | chainId: usize + 606 | yParity: ?u1 = null + 607 | } + 608 | ``` + 609 | + 610 | ## BerlinTransaction + 611 | + 612 | The Berlin hardfork representation of a transaction. + 613 | + 614 | ### Properties + 615 | + 616 | ```zig + 617 | struct { + 618 | hash: Hash + 619 | nonce: u64 + 620 | blockHash: ?Hash + 621 | blockNumber: ?u64 + 622 | transactionIndex: ?u64 + 623 | from: Address + 624 | to: ?Address + 625 | value: Wei + 626 | gasPrice: Gwei + 627 | gas: Gwei + 628 | input: Hex + 629 | v: u8 + 630 | /// Represented as values instead of the hash because + 631 | /// a valid signature is not guaranteed to be 32 bits + 632 | r: u256 + 633 | /// Represented as values instead of the hash because + 634 | /// a valid signature is not guaranteed to be 32 bits + 635 | s: u256 + 636 | sourceHash: ?Hash = null + 637 | isSystemTx: ?bool = null + 638 | type: TransactionTypes + 639 | accessList: []const AccessList + 640 | chainId: usize + 641 | yParity: ?u1 = null + 642 | } + 643 | ``` + 644 | + 645 | ## LegacyTransaction + 646 | + 647 | The legacy representation of a transaction. + 648 | + 649 | ### Properties + 650 | + 651 | ```zig + 652 | struct { + 653 | hash: Hash + 654 | nonce: u64 + 655 | blockHash: ?Hash + 656 | blockNumber: ?u64 + 657 | transactionIndex: ?u64 + 658 | from: Address + 659 | to: ?Address + 660 | value: Wei + 661 | gasPrice: Gwei + 662 | gas: Gwei + 663 | input: Hex + 664 | v: usize + 665 | /// Represented as values instead of the hash because + 666 | /// a valid signature is not guaranteed to be 32 bits + 667 | r: u256 + 668 | /// Represented as values instead of the hash because + 669 | /// a valid signature is not guaranteed to be 32 bits + 670 | s: u256 + 671 | sourceHash: ?Hash = null + 672 | isSystemTx: ?bool = null + 673 | type: ?TransactionTypes = null + 674 | chainId: ?usize = null + 675 | } + 676 | ``` + 677 | + 678 | ## Transaction + 679 | + 680 | All transactions objects that one might find whilest interaction + 681 | with the JSON RPC server. + 682 | + 683 | ### Properties + 684 | + 685 | ```zig + 686 | union(enum) { + 687 | /// Legacy type transactions. + 688 | legacy: LegacyTransaction + 689 | /// Berlin hardfork transactions that might have the accessList. + 690 | berlin: BerlinTransaction + 691 | /// London hardfork transaction objects. + 692 | london: LondonTransaction + 693 | /// Cancun hardfork transactions. + 694 | cancun: CancunTransaction + 695 | /// L2 transaction objects + 696 | l2_transaction: L2Transaction + 697 | /// L2 Deposit transaction + 698 | deposit: DepositTransactionSigned + 699 | } + 700 | ``` + 701 | + 702 | ## LegacyReceipt + 703 | + 704 | The london and other hardforks transaction receipt representation + 705 | + 706 | ### Properties + 707 | + 708 | ```zig + 709 | struct { + 710 | transactionHash: Hash + 711 | transactionIndex: u64 + 712 | blockHash: Hash + 713 | blockNumber: ?u64 + 714 | from: Address + 715 | to: ?Address + 716 | cumulativeGasUsed: Gwei + 717 | effectiveGasPrice: Gwei + 718 | gasUsed: Gwei + 719 | contractAddress: ?Address + 720 | logs: Logs + 721 | logsBloom: Hex + 722 | blobGasPrice: ?u64 = null + 723 | type: ?TransactionTypes = null + 724 | root: ?Hex = null + 725 | status: ?bool = null + 726 | deposit_nonce: ?usize = null + 727 | } + 728 | ``` + 729 | + 730 | ## CancunReceipt + 731 | + 732 | Cancun transaction receipt representation + 733 | + 734 | ### Properties + 735 | + 736 | ```zig + 737 | struct { + 738 | transactionHash: Hash + 739 | transactionIndex: u64 + 740 | blockHash: Hash + 741 | blockNumber: ?u64 + 742 | from: Address + 743 | to: ?Address + 744 | cumulativeGasUsed: Gwei + 745 | effectiveGasPrice: Gwei + 746 | blobGasPrice: Gwei + 747 | blobGasUsed: Gwei + 748 | gasUsed: Gwei + 749 | contractAddress: ?Address + 750 | logs: Logs + 751 | logsBloom: Hex + 752 | type: ?TransactionTypes = null + 753 | root: ?Hex = null + 754 | status: ?bool = null + 755 | deposit_nonce: ?usize = null + 756 | } + 757 | ``` + 758 | + 759 | ## OpstackReceipt + 760 | + 761 | L2 transaction receipt representation + 762 | + 763 | ### Properties + 764 | + 765 | ```zig + 766 | struct { + 767 | transactionHash: Hash + 768 | transactionIndex: u64 + 769 | blockHash: Hash + 770 | blockNumber: ?u64 + 771 | from: Address + 772 | to: ?Address + 773 | gasUsed: Gwei + 774 | cumulativeGasUsed: Gwei + 775 | contractAddress: ?Address + 776 | logs: Logs + 777 | status: ?bool = null + 778 | logsBloom: Hex + 779 | type: ?TransactionTypes = null + 780 | effectiveGasPrice: ?Gwei = null + 781 | deposit_nonce: ?usize = null + 782 | l1Fee: Wei + 783 | l1GasPrice: Gwei + 784 | l1GasUsed: Gwei + 785 | l1FeeScalar: ?f64 = null + 786 | root: ?Hex = null + 787 | } + 788 | ``` + 789 | + 790 | ## DepositReceipt + 791 | + 792 | L2 Deposit transaction receipt representation + 793 | + 794 | ### Properties + 795 | + 796 | ```zig + 797 | struct { + 798 | transactionHash: Hash + 799 | transactionIndex: u64 + 800 | blockHash: Hash + 801 | blockNumber: ?u64 + 802 | from: Address + 803 | to: ?Address + 804 | cumulativeGasUsed: Gwei + 805 | gasUsed: Gwei + 806 | contractAddress: ?Address + 807 | logs: Logs + 808 | status: ?bool = null + 809 | logsBloom: Hex + 810 | type: ?TransactionTypes = null + 811 | effectiveGasPrice: ?Gwei = null + 812 | deposit_nonce: ?usize = null + 813 | depositNonce: ?u64 + 814 | depositNonceVersion: ?u64 = null + 815 | root: ?Hex = null + 816 | } + 817 | ``` + 818 | + 819 | ## ArbitrumReceipt + 820 | + 821 | Arbitrum transaction receipt representation + 822 | + 823 | ### Properties + 824 | + 825 | ```zig + 826 | struct { + 827 | transactionHash: Hash + 828 | blockHash: Hash + 829 | blockNumber: ?u64 + 830 | logsBloom: Hex + 831 | l1BlockNumber: Wei + 832 | contractAddress: ?Address + 833 | transactionIndex: u64 + 834 | gasUsedForL1: Gwei + 835 | type: ?TransactionTypes = null + 836 | gasUsed: Gwei + 837 | cumulativeGasUsed: Gwei + 838 | from: Address + 839 | to: ?Address + 840 | effectiveGasPrice: ?Gwei = null + 841 | logs: Logs + 842 | root: ?Hex = null + 843 | status: ?bool = null + 844 | deposit_nonce: ?usize = null + 845 | } + 846 | ``` + 847 | + 848 | ## TransactionReceipt + 849 | + 850 | All possible transaction receipts + 851 | + 852 | ### Properties + 853 | + 854 | ```zig + 855 | union(enum) { + 856 | legacy: LegacyReceipt + 857 | cancun: CancunReceipt + 858 | op_receipt: OpstackReceipt + 859 | arbitrum_receipt: ArbitrumReceipt + 860 | deposit_receipt: DepositReceipt + 861 | } + 862 | ``` + 863 | + 864 | ## EthCall + 865 | + 866 | The representation of an `eth_call` struct. + 867 | + 868 | ### Properties + 869 | + 870 | ```zig + 871 | union(enum) { + 872 | legacy: LegacyEthCall + 873 | london: LondonEthCall + 874 | } + 875 | ``` + 876 | + 877 | ## LondonEthCall + 878 | + 879 | The representation of an London hardfork `eth_call` struct where all fields are optional + 880 | These are optionals so that when we stringify we can + 881 | use the option `ignore_null_fields` + 882 | + 883 | ### Properties + 884 | + 885 | ```zig + 886 | struct { + 887 | from: ?Address = null + 888 | maxPriorityFeePerGas: ?Gwei = null + 889 | maxFeePerGas: ?Gwei = null + 890 | gas: ?Gwei = null + 891 | to: ?Address = null + 892 | value: ?Wei = null + 893 | data: ?Hex = null + 894 | } + 895 | ``` + 896 | + 897 | ## LegacyEthCall + 898 | + 899 | The representation of an `eth_call` struct where all fields are optional + 900 | These are optionals so that when we stringify we can + 901 | use the option `ignore_null_fields` + 902 | + 903 | ### Properties + 904 | + 905 | ```zig + 906 | struct { + 907 | from: ?Address = null + 908 | gasPrice: ?Gwei = null + 909 | gas: ?Gwei = null + 910 | to: ?Address = null + 911 | value: ?Wei = null + 912 | data: ?Hex = null + 913 | } + 914 | ``` + 915 | + 916 | ## EstimateFeeReturn + 917 | + 918 | Return struct for fee estimation calculation. + 919 | + 920 | ### Properties + 921 | + 922 | ```zig + 923 | union(enum) { + 924 | london: struct { + 925 | max_priority_fee: Gwei, + 926 | max_fee_gas: Gwei, + 927 | } + 928 | legacy: struct { + 929 | gas_price: Gwei, + 930 | } + 931 | cancun: struct { + 932 | max_priority_fee: Gwei, + 933 | max_fee_gas: Gwei, + 934 | max_fee_per_blob: Gwei, + 935 | } + 936 | } + 937 | ``` + 938 | + 939 | ## FeeHistory + 940 | + 941 | Provides recent fee market data that consumers can use to determine + 942 | + 943 | ### Properties + 944 | + 945 | ```zig + 946 | struct { + 947 | /// List of each block's base fee + 948 | baseFeePerGas: []const u256 + 949 | /// List of each block's base blob fee + 950 | baseFeePerBlobGas: ?[]const u256 = null + 951 | /// Ratio of gas used out of the total available limit + 952 | gasUsedRatio: []const f64 + 953 | /// Ratio of blob gas used out of the total available limit + 954 | blobGasUsedRatio: ?[]const f64 = null + 955 | /// Block corresponding to first response value + 956 | oldestBlock: u64 + 957 | /// List every txs priority fee per block + 958 | /// Depending on the blockCount or the newestBlock this can be null + 959 | reward: ?[]const []const u256 = null + 960 | } + 961 | ``` + 962 | + 963 | ## DepositTransaction + 964 | + 965 | Op stack deposit transaction representation. + 966 | + 967 | ### Properties + 968 | + 969 | ```zig + 970 | struct { + 971 | sourceHash: Hash + 972 | from: Address + 973 | to: ?Address + 974 | mint: u256 + 975 | value: Wei + 976 | gas: Gwei + 977 | isSystemTx: bool + 978 | data: ?Hex + 979 | } + 980 | ``` + 981 | + 982 | ## DepositTransactionSigned + 983 | + 984 | Op stack deposit transaction representation with the signed parameters. + 985 | + 986 | ### Properties + 987 | + 988 | ```zig + 989 | struct { + 990 | hash: Hash + 991 | nonce: u64 + 992 | blockHash: ?Hash + 993 | blockNumber: ?u64 + 994 | transactionIndex: ?u64 + 995 | from: Address + 996 | to: ?Address + 997 | value: Wei + 998 | gasPrice: Gwei + 999 | gas: Gwei +1000 | input: Hex +1001 | v: usize +1002 | /// Represented as values instead of the hash because +1003 | /// a valid signature is not guaranteed to be 32 bits +1004 | r: u256 +1005 | /// Represented as values instead of the hash because +1006 | /// a valid signature is not guaranteed to be 32 bits +1007 | s: u256 +1008 | type: TransactionTypes +1009 | sourceHash: Hex +1010 | mint: ?u256 = null +1011 | isSystemTx: ?bool = null +1012 | depositReceiptVersion: ?u64 = null +1013 | } +1014 | ``` +1015 | +1016 | ## DepositData +1017 | +1018 | Op stack deposit data. +1019 | +1020 | ### Properties +1021 | +1022 | ```zig +1023 | struct { +1024 | mint: u256 +1025 | value: Wei +1026 | gas: Gwei +1027 | creation: bool +1028 | data: ?Hex +1029 | } +1030 | ``` +1031 | +1032 | ## TransactionDeposited +1033 | +1034 | Op stack return type when decoding a deposit transaction from the contract. +1035 | +1036 | ### Properties +1037 | +1038 | ```zig +1039 | struct { +1040 | from: Address +1041 | to: Address +1042 | version: u256 +1043 | opaqueData: Hex +1044 | logIndex: usize +1045 | blockHash: Hash +1046 | } +1047 | ``` +1048 | +1049 | ## DepositTransactionEnvelope +1050 | +1051 | Op stack deposit envelope to be serialized. +1052 | +1053 | ### Properties +1054 | +1055 | ```zig +1056 | struct { +1057 | gas: ?Gwei = null +1058 | mint: ?Wei = null +1059 | value: ?Wei = null +1060 | creation: bool = false +1061 | data: ?Hex = null +1062 | to: ?Address = null +1063 | } +1064 | ``` +1065 | +1066 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/types/txpool.md: +-------------------------------------------------------------------------------- + 1 | ## TxPoolStatus + 2 | + 3 | Result tx pool status. + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | struct { + 9 | pending: u64 +10 | queued: u64 +11 | } +12 | ``` +13 | +14 | ## TxPoolContent +15 | +16 | Result tx pool content. +17 | +18 | ### Properties +19 | +20 | ```zig +21 | struct { +22 | pending: Subpool +23 | queued: Subpool +24 | } +25 | ``` +26 | +27 | ## TxPoolInspect +28 | +29 | ### Properties +30 | +31 | ```zig +32 | struct { +33 | pending: InspectSubpool +34 | queued: InspectSubpool +35 | } +36 | ``` +37 | +38 | ## Subpool +39 | +40 | Geth mempool subpool type +41 | +42 | ### Properties +43 | +44 | ```zig +45 | struct { +46 | address: AddressHashMap +47 | } +48 | ``` +49 | +50 | ## InspectSubpool +51 | +52 | Geth mempool inspect subpool type +53 | +54 | ### Properties +55 | +56 | ```zig +57 | struct { +58 | address: InspectAddressHashMap +59 | } +60 | ``` +61 | +62 | ## InspectPoolTransactionByNonce +63 | +64 | Geth inspect transaction object dump from mempool by nonce. +65 | +66 | ### Properties +67 | +68 | ```zig +69 | struct { +70 | nonce: InspectPoolPendingTransactionHashMap +71 | } +72 | ``` +73 | +74 | ## PoolTransactionByNonce +75 | +76 | Geth transaction object dump from mempool by nonce. +77 | +78 | ### Properties +79 | +80 | ```zig +81 | struct { +82 | nonce: PoolPendingTransactionHashMap +83 | } +84 | ``` +85 | +86 | + + +-------------------------------------------------------------------------------- + + + +└── docs + └── pages + └── api + └── utils + ├── args.md + ├── env_load.md + ├── generator.md + ├── stack.md + └── utils.md + + +/docs/pages/api/utils/args.md: +-------------------------------------------------------------------------------- + 1 | ## ParseArgs + 2 | Parses console arguments in the style of --foo=bar + 3 | For now not all types are supported but might be in the future + 4 | if the need for them arises. + 5 | + 6 | Allocations are only made for slices and pointer types. + 7 | Slice or arrays that aren't u8 are expected to be comma seperated. + 8 | + 9 | ### Signature +10 | +11 | ```zig +12 | pub fn parseArgs( +13 | comptime T: type, +14 | allocator: Allocator, +15 | args: *ArgIterator, +16 | ) T +17 | ``` +18 | +19 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/utils/env_load.md: +-------------------------------------------------------------------------------- + 1 | ## Token + 2 | + 3 | Token structure produced my the tokenizer. + 4 | + 5 | ### Properties + 6 | + 7 | ```zig + 8 | struct { + 9 | token: Tag + 10 | location: Location + 11 | } + 12 | ``` + 13 | + 14 | ## Location + 15 | + 16 | ### Properties + 17 | + 18 | ```zig + 19 | struct { + 20 | start: usize + 21 | end: usize + 22 | } + 23 | ``` + 24 | + 25 | ## Tag + 26 | + 27 | ### Properties + 28 | + 29 | ```zig + 30 | enum { + 31 | identifier + 32 | value + 33 | value_int + 34 | eof + 35 | invalid + 36 | } + 37 | ``` + 38 | + 39 | ## Location + 40 | + 41 | ### Properties + 42 | + 43 | ```zig + 44 | struct { + 45 | start: usize + 46 | end: usize + 47 | } + 48 | ``` + 49 | + 50 | ## Tag + 51 | + 52 | ### Properties + 53 | + 54 | ```zig + 55 | enum { + 56 | identifier + 57 | value + 58 | value_int + 59 | eof + 60 | invalid + 61 | } + 62 | ``` + 63 | + 64 | ## Offset + 65 | + 66 | Index used to know token starts and ends. + 67 | + 68 | ```zig + 69 | u32 + 70 | ``` + 71 | + 72 | ## TokenIndex + 73 | + 74 | Index used to know token tags. + 75 | + 76 | ```zig + 77 | u32 + 78 | ``` + 79 | + 80 | ## TokenList + 81 | + 82 | MultiArrayList used to generate the neccessary information for the parser to use. + 83 | + 84 | ```zig + 85 | std.MultiArrayList(struct { + 86 | tag: Token.Tag, + 87 | start: Offset, + 88 | }) + 89 | ``` + 90 | + 91 | ## Tokenizer + 92 | + 93 | Tokenizer that will produce lexicar tokens so that the + 94 | parser can consume and load it to the `EnvMap`. + 95 | + 96 | ### Properties + 97 | + 98 | ```zig + 99 | struct { +100 | /// The source that will be used to produce tokens. +101 | buffer: [:0]const u8 +102 | /// Current index into the source +103 | index: usize +104 | } +105 | ``` +106 | +107 | ### Init +108 | Sets the initial state. +109 | +110 | ### Signature +111 | +112 | ```zig +113 | pub fn init(source: [:0]const u8) Tokenizer +114 | ``` +115 | +116 | ### Next +117 | Advances the tokenizer's state and produces a single token. +118 | +119 | ### Signature +120 | +121 | ```zig +122 | pub fn next(self: *Tokenizer) Token +123 | ``` +124 | +125 | ## ParserEnv +126 | +127 | Parses the enviroment variables strings and loads them +128 | into a `EnvMap`. +129 | +130 | ### Properties +131 | +132 | ```zig +133 | struct { +134 | /// Slice of produced token tags from the tokenizer. +135 | token_tags: []const Token.Tag +136 | /// Slice of produced token starts from the tokenizer. +137 | token_starts: []const Offset +138 | /// The current index in any of the previous slices. +139 | token_index: TokenIndex +140 | /// The source that will be used to load values from. +141 | source: [:0]const u8 +142 | /// The enviroment map that will be used to load the variables to. +143 | env_map: *EnvMap +144 | } +145 | ``` +146 | +147 | ### ParseAndLoad +148 | Parses all token tags and loads the all into the `EnvMap`. +149 | +150 | ### Signature +151 | +152 | ```zig +153 | pub fn parseAndLoad(self: *ParserEnv) !void +154 | ``` +155 | +156 | ### ParseAndLoadOne +157 | Parses a single line and load it to memory. +158 | IDENT -> VALUE/VALUE_INT +159 | +160 | ### Signature +161 | +162 | ```zig +163 | pub fn parseAndLoadOne(self: *ParserEnv) (Allocator.Error || error{UnexpectedToken})!void +164 | ``` +165 | +166 | ### ParseIdentifier +167 | Parses the identifier token. +168 | Returns and error if the current token is not a `identifier` one. +169 | +170 | ### Signature +171 | +172 | ```zig +173 | pub fn parseIdentifier(self: *ParserEnv) error{UnexpectedToken}!TokenIndex +174 | ``` +175 | +176 | ### ParseIntValue +177 | Parses the value_int token. +178 | Returns null if the current token is not a `value_int` one. +179 | +180 | ### Signature +181 | +182 | ```zig +183 | pub fn parseIntValue(self: *ParserEnv) ?TokenIndex +184 | ``` +185 | +186 | ### ParseValue +187 | Parses the value or value_int token. +188 | Returns and error if the current token is not a `value` or `value_int` one. +189 | +190 | ### Signature +191 | +192 | ```zig +193 | pub fn parseValue(self: *ParserEnv) error{UnexpectedToken}!TokenIndex +194 | ``` +195 | +196 | ## ParseToEnviromentVariables +197 | Parses and loads all possible enviroment variables from the +198 | provided `source`. +199 | +200 | Can error if the parser encounters unexpected token values. +201 | +202 | ### Signature +203 | +204 | ```zig +205 | pub fn parseToEnviromentVariables( +206 | allocator: Allocator, +207 | source: [:0]const u8, +208 | env_map: *EnvMap, +209 | ) (Allocator.Error || error{UnexpectedToken})!void +210 | ``` +211 | +212 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/utils/generator.md: +-------------------------------------------------------------------------------- + 1 | ## Generated + 2 | Similar to std.json.Parsed(T) + 3 | + 4 | ### Signature + 5 | + 6 | ```zig + 7 | pub fn Generated(comptime T: type) type + 8 | ``` + 9 | +10 | ## Deinit +11 | ### Signature +12 | +13 | ```zig +14 | pub fn deinit(self: @This()) void +15 | ``` +16 | +17 | ## GenerateOptions +18 | +19 | Controls some of the behaviour for the generator. +20 | +21 | More options can be added in the future to alter +22 | further this behaviour. +23 | +24 | ### Properties +25 | +26 | ```zig +27 | struct { +28 | /// Control the size of the slice that you want to create. +29 | slice_size: ?usize = null +30 | /// If the provided type is consider a potential "string" +31 | /// Tell the generator to use only ascii letter bytes and +32 | /// if you want lower or uppercase chars +33 | ascii: struct { +34 | use_on_arrays_and_slices: bool = false, +35 | format_bytes: enum { lowercase, uppercase } = .lowercase, +36 | } = .{} +37 | /// Tell the generator to use the types default values. +38 | use_default_values: bool = false +39 | } +40 | ``` +41 | +42 | ## GenerateRandomData +43 | Generate pseudo random data for the provided type. Creates an +44 | arena for all allocations. Similarly to how std.json works. +45 | +46 | This works on most zig types with a few expections of course. +47 | +48 | ### Signature +49 | +50 | ```zig +51 | pub fn generateRandomData(comptime T: type, allocator: Allocator, seed: u64, opts: GenerateOptions) Allocator.Error!Generated(T) +52 | ``` +53 | +54 | ## GenerateRandomDataLeaky +55 | Generate pseudo random data for provided type. Nothing is freed +56 | from the result so it's best to use something like an arena allocator or similar +57 | to free the memory all at once. +58 | +59 | This is done because we might have +60 | types where there will be deeply nested allocatations that can +61 | be cumbersome to free. +62 | +63 | This works on most zig types with a few expections of course. +64 | +65 | ### Signature +66 | +67 | ```zig +68 | pub fn generateRandomDataLeaky(comptime T: type, allocator: Allocator, seed: u64, opts: GenerateOptions) Allocator.Error!T +69 | ``` +70 | +71 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/utils/stack.md: +-------------------------------------------------------------------------------- + 1 | ## Stack + 2 | Stack implemented using a `ArrayList` and + 3 | with thread safety features added on to it. + 4 | + 5 | If memory is allocated on the stack items, `deinit` + 6 | will not clear all memory. You must clear them one by one. + 7 | + 8 | ### Signature + 9 | + 10 | ```zig + 11 | pub fn Stack(comptime T: type) type + 12 | ``` + 13 | + 14 | ## Error + 15 | + 16 | Set of possible errors while performing stack operations. + 17 | + 18 | ```zig + 19 | Allocator.Error || error{ StackOverflow, StackUnderflow } + 20 | ``` + 21 | + 22 | ## Init + 23 | Starts the stack but doesn't set an initial capacity. + 24 | This is best to use when you would like a dymanic size stack. + 25 | + 26 | ### Signature + 27 | + 28 | ```zig + 29 | pub fn init( + 30 | allocator: Allocator, + 31 | max_size: ?usize, + 32 | ) Self + 33 | ``` + 34 | + 35 | ## InitWithCapacity + 36 | Starts the stack and grows the capacity to the max size. + 37 | This is best to use when you would like a static size stack. + 38 | + 39 | ### Signature + 40 | + 41 | ```zig + 42 | pub fn initWithCapacity( + 43 | allocator: Allocator, + 44 | max_size: usize, + 45 | ) !Self + 46 | ``` + 47 | + 48 | ## Deinit + 49 | Clears the stack. + 50 | + 51 | ### Signature + 52 | + 53 | ```zig + 54 | pub fn deinit(self: *Self) void + 55 | ``` + 56 | + 57 | ## DupUnsafe + 58 | Duplicates an item from the stack. Appends it to the top. + 59 | This is not thread safe. + 60 | + 61 | ### Signature + 62 | + 63 | ```zig + 64 | pub fn dupUnsafe( + 65 | self: *Self, + 66 | position: usize, + 67 | ) Self.Error!void + 68 | ``` + 69 | + 70 | ## PushUnsafe + 71 | Appends an item to the stack. + 72 | This is not thread safe. + 73 | + 74 | ### Signature + 75 | + 76 | ```zig + 77 | pub fn pushUnsafe( + 78 | self: *Self, + 79 | item: T, + 80 | ) (Allocator.Error || error{StackOverflow})!void + 81 | ``` + 82 | + 83 | ## PopUnsafe + 84 | Pops an item off the stack. + 85 | This is not thread safe. + 86 | + 87 | ### Signature + 88 | + 89 | ```zig + 90 | pub fn popUnsafe(self: *Self) ?T + 91 | ``` + 92 | + 93 | ## Push + 94 | Appends an item to the stack. + 95 | This is thread safe and blocks until it can + 96 | append the item. + 97 | + 98 | ### Signature + 99 | +100 | ```zig +101 | pub fn push( +102 | self: *Self, +103 | item: T, +104 | ) void +105 | ``` +106 | +107 | ## Pop +108 | Pops an item off the stack. +109 | This is thread safe and blocks until it can +110 | remove the item. +111 | +112 | ### Signature +113 | +114 | ```zig +115 | pub fn pop(self: *Self) T +116 | ``` +117 | +118 | ## PopOrNull +119 | Pops an item off the stack. Returns null if the stack is empty. +120 | This is thread safe, +121 | +122 | ### Signature +123 | +124 | ```zig +125 | pub fn popOrNull(self: *Self) ?T +126 | ``` +127 | +128 | ## SwapToTopUnsafe +129 | Swaps the top value of the stack with the different position. +130 | This is not thread safe. +131 | +132 | ### Signature +133 | +134 | ```zig +135 | pub fn swapToTopUnsafe( +136 | self: *Self, +137 | position_swap: usize, +138 | ) error{StackUnderflow}!void +139 | ``` +140 | +141 | ## SwapUnsafe +142 | Swap an item from the stack depending on the provided positions. +143 | This is not thread safe. +144 | +145 | ### Signature +146 | +147 | ```zig +148 | pub fn swapUnsafe( +149 | self: *Self, +150 | position: usize, +151 | swap: usize, +152 | ) error{StackUnderflow}!void +153 | ``` +154 | +155 | ## TryPopUnsafe +156 | Pops item from the stack. Returns `StackUnderflow` if it cannot. +157 | This is not thread safe, +158 | +159 | ### Signature +160 | +161 | ```zig +162 | pub fn tryPopUnsafe( +163 | self: *Self, +164 | ) error{StackUnderflow}!T +165 | ``` +166 | +167 | ## TryPop +168 | Pops item from the stack. Returns `StackUnderflow` if it cannot. +169 | This is thread safe, +170 | +171 | ### Signature +172 | +173 | ```zig +174 | pub fn tryPop( +175 | self: *Self, +176 | item: T, +177 | ) error{StackUnderflow}!T +178 | ``` +179 | +180 | ## TryPush +181 | Pushes an item to the stack. +182 | This is thread safe, +183 | +184 | ### Signature +185 | +186 | ```zig +187 | pub fn tryPush( +188 | self: *Self, +189 | item: T, +190 | ) !void +191 | ``` +192 | +193 | ## StackHeight +194 | Returns the current stack size. +195 | +196 | ### Signature +197 | +198 | ```zig +199 | pub fn stackHeight(self: *Self) usize +200 | ``` +201 | +202 | ## AvailableSize +203 | Returns number of items available in the stack +204 | +205 | ### Signature +206 | +207 | ```zig +208 | pub fn availableSize(self: Self) usize +209 | ``` +210 | +211 | ## BoundedStack +212 | Stack implementation based on the `std.BoundedArray`. +213 | +214 | ### Signature +215 | +216 | ```zig +217 | pub fn BoundedStack(comptime size: usize) type +218 | ``` +219 | +220 | ## Error +221 | +222 | Set of possible errors while performing stack operations. +223 | +224 | ```zig +225 | error{ StackOverflow, StackUnderflow } +226 | ``` +227 | +228 | ## SwapToTopUnsafe +229 | Swaps the top value of the stack with the different position. +230 | This is not thread safe. +231 | +232 | ### Signature +233 | +234 | ```zig +235 | pub fn swapToTopUnsafe( +236 | self: *Self, +237 | position_swap: usize, +238 | ) error{StackUnderflow}!void +239 | ``` +240 | +241 | ## DupUnsafe +242 | Duplicates an item from the stack. Appends it to the top. +243 | +244 | This is not thread safe. +245 | +246 | ### Signature +247 | +248 | ```zig +249 | pub fn dupUnsafe( +250 | self: *Self, +251 | position: usize, +252 | ) Self.Error!void +253 | ``` +254 | +255 | ## PushUnsafe +256 | Pops item from the stack. Returns `StackUnderflow` if it cannot. +257 | +258 | This is not thread safe, +259 | +260 | ### Signature +261 | +262 | ```zig +263 | pub fn pushUnsafe( +264 | self: *Self, +265 | item: u256, +266 | ) error{StackOverflow}!void +267 | ``` +268 | +269 | ## AppendAssumeCapacity +270 | Appends item to the inner buffer. Increments the `len` of this array. +271 | +272 | ### Signature +273 | +274 | ```zig +275 | pub fn appendAssumeCapacity( +276 | self: *Self, +277 | item: u256, +278 | ) void +279 | ``` +280 | +281 | ## EnsureUnusedCapacity +282 | Ensures that the stack has enough room to grow. +283 | Otherwise it returns `StackOverflow`. +284 | +285 | ### Signature +286 | +287 | ```zig +288 | pub fn ensureUnusedCapacity( +289 | self: Self, +290 | grow: usize, +291 | ) error{StackOverflow}!void +292 | ``` +293 | +294 | ## PopUnsafe +295 | Pops item from the stack. Returns `null` if it cannot. +296 | This is not thread safe, +297 | +298 | ### Signature +299 | +300 | ```zig +301 | pub fn popUnsafe(self: *Self) ?u256 +302 | ``` +303 | +304 | ## TryPopUnsafe +305 | Pops item from the stack. Returns `StackUnderflow` if it cannot. +306 | This is not thread safe, +307 | +308 | ### Signature +309 | +310 | ```zig +311 | pub fn tryPopUnsafe(self: *Self) error{StackUnderflow}!u256 +312 | ``` +313 | +314 | ## PopOrNull +315 | Pops item from the stack. +316 | Returns null if the `len` is 0. +317 | +318 | ### Signature +319 | +320 | ```zig +321 | pub fn popOrNull(self: *Self) ?u256 +322 | ``` +323 | +324 | ## Pop +325 | Pops item from the stack. +326 | +327 | ### Signature +328 | +329 | ```zig +330 | pub fn pop(self: *Self) u256 +331 | ``` +332 | +333 | ## Peek +334 | Peek the last element of the stack and returns it's pointer. +335 | +336 | Returns null if len is 0; +337 | +338 | ### Signature +339 | +340 | ```zig +341 | pub fn peek(self: *Self) ?*u256 +342 | ``` +343 | +344 | ## TryPeek +345 | Peek the last element of the stack and returns it's pointer. +346 | +347 | Returns `StackUnderflow` if len is 0; +348 | +349 | ### Signature +350 | +351 | ```zig +352 | pub fn tryPeek(self: *Self) error{StackUnderflow}!*u256 +353 | ``` +354 | +355 | ## StackHeight +356 | Returns the current stack size. +357 | +358 | ### Signature +359 | +360 | ```zig +361 | pub fn stackHeight(self: *Self) usize +362 | ``` +363 | +364 | ## AvailableSize +365 | Returns number of items available in the stack +366 | +367 | ### Signature +368 | +369 | ```zig +370 | pub fn availableSize(self: Self) usize +371 | ``` +372 | +373 | + + +-------------------------------------------------------------------------------- +/docs/pages/api/utils/utils.md: +-------------------------------------------------------------------------------- + 1 | ## IsStaticType + 2 | Checks if a given type is static + 3 | + 4 | ### Signature + 5 | + 6 | ```zig + 7 | pub inline fn isStaticType(comptime T: type) bool + 8 | ``` + 9 | + 10 | ## IsDynamicType + 11 | Checks if a given type is static + 12 | + 13 | ### Signature + 14 | + 15 | ```zig + 16 | pub inline fn isDynamicType(comptime T: type) bool + 17 | ``` + 18 | + 19 | ## ToChecksum + 20 | Converts ethereum address to checksum + 21 | + 22 | ### Signature + 23 | + 24 | ```zig + 25 | pub fn toChecksum( + 26 | allocator: Allocator, + 27 | address: []const u8, + 28 | ) (Allocator.Error || error{ Overflow, InvalidCharacter })![]u8 + 29 | ``` + 30 | + 31 | ## IsAddress + 32 | Checks if the given address is a valid ethereum address. + 33 | + 34 | ### Signature + 35 | + 36 | ```zig + 37 | pub fn isAddress(addr: []const u8) bool + 38 | ``` + 39 | + 40 | ## AddressToBytes + 41 | Convert address to its representing bytes + 42 | + 43 | ### Signature + 44 | + 45 | ```zig + 46 | pub fn addressToBytes( + 47 | address: []const u8, + 48 | ) error{ InvalidAddress, NoSpaceLeft, InvalidLength, InvalidCharacter }!Address + 49 | ``` + 50 | + 51 | ## HashToBytes + 52 | Convert a hash to its representing bytes + 53 | + 54 | ### Signature + 55 | + 56 | ```zig + 57 | pub fn hashToBytes( + 58 | hash: []const u8, + 59 | ) error{ InvalidHash, NoSpaceLeft, InvalidLength, InvalidCharacter }!Hash + 60 | ``` + 61 | + 62 | ## IsHexString + 63 | Checks if a given string is a hex string; + 64 | + 65 | ### Signature + 66 | + 67 | ```zig + 68 | pub fn isHexString(value: []const u8) bool + 69 | ``` + 70 | + 71 | ## IsHash + 72 | Checks if the given hash is a valid 32 bytes hash + 73 | + 74 | ### Signature + 75 | + 76 | ```zig + 77 | pub fn isHash(hash: []const u8) bool + 78 | ``` + 79 | + 80 | ## IsHashString + 81 | Check if a string is a hash string + 82 | + 83 | ### Signature + 84 | + 85 | ```zig + 86 | pub fn isHashString(hash: []const u8) bool + 87 | ``` + 88 | + 89 | ## ParseEth + 90 | Convert value into u256 representing ether value + 91 | Ex: 1 * 10 ** 18 = 1 ETH + 92 | + 93 | ### Signature + 94 | + 95 | ```zig + 96 | pub fn parseEth(value: usize) error{Overflow}!u256 + 97 | ``` + 98 | + 99 | ## ParseGwei +100 | Convert value into u64 representing ether value +101 | Ex: 1 * 10 ** 9 = 1 GWEI +102 | +103 | ### Signature +104 | +105 | ```zig +106 | pub fn parseGwei(value: usize) error{Overflow}!u64 +107 | ``` +108 | +109 | ## FormatInt +110 | Finds the size of an int and writes to the buffer accordingly. +111 | +112 | ### Signature +113 | +114 | ```zig +115 | pub inline fn formatInt(int: u256, buffer: *[32]u8) u8 +116 | ``` +117 | +118 | ## ComputeSize +119 | Computes the size of a given int +120 | +121 | ### Signature +122 | +123 | ```zig +124 | pub inline fn computeSize(int: u256) u8 +125 | ``` +126 | +127 | ## BytesToInt +128 | Similar to `parseInt` but handles the hex bytes and not the +129 | hex represented string. +130 | +131 | ### Signature +132 | +133 | ```zig +134 | pub fn bytesToInt(comptime T: type, slice: []const u8) error{Overflow}!T +135 | ``` +136 | +137 | ## CalcultateBlobGasPrice +138 | Calcutates the blob gas price +139 | +140 | ### Signature +141 | +142 | ```zig +143 | pub fn calcultateBlobGasPrice(excess_gas: u64) u128 +144 | ``` +145 | +146 | + + +-------------------------------------------------------------------------------- \ No newline at end of file diff --git a/package.json b/package.json index 3a5eb11..31d1150 100644 --- a/package.json +++ b/package.json @@ -37,8 +37,13 @@ }, "types": "./dist/index.d.ts", "scripts": { - "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json", - "build:clean": "rm -rf dist && rm -rf tsconfig.build.tsbuildinfo", + "build:clean": "rm -rf dist && rm -rf tsconfig.build.tsbuildinfo && rm -rf zig-out && rm -rf .zig-cache", + "build:wasm": "cd src/zig && zig build wasm && cd ../../ && mkdir -p dist/wasm && cp zig-out/dist/wasm/evmstate.wasm dist/wasm/evmstate.wasm && rm -rf zig-out && echo \"WASM build completed\" && echo \"WASM size: $(ls -lh dist/wasm/evmstate.wasm | awk '{print $5}')\" && echo \"WASM path: $(realpath dist/wasm/evmstate.wasm)\"", + "build:zig": "cd src/zig && zig build", + "watch:zig": "zig build test --watch", + "build:ts": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json", + "build": "pnpm build:clean && pnpm build:wasm && pnpm build:ts", + "build:watch": "pnpm build:watch:zig && pnpm build:watch:ts", "changeset": "changeset", "changeset:publish": "pnpm build && changeset publish --access public", "changeset:version": "changeset version && pnpm install --lockfile-only", @@ -47,9 +52,11 @@ "docs:preview": "pnpm build && pnpm --filter @polareth/evmstate-docs preview", "prepare": "node -e \"process.env.GITHUB_ACTIONS !== 'true' && process.env.VERCEL !== '1' && process.exit(1)\" || DEBUG=trace tsx scripts/prepare.ts", "benchmark": "DEBUG=trace pnpm vitest run test/bench/benchmark.test.ts && tsx scripts/summarize-benchmarks.ts", - "test": "pnpm test:unit && pnpm test:staging", + "dev": "run-pty % pnpm test % pnpm watch:zig", + "test": "pnpm test:zig && pnpm test:unit && pnpm test:staging", "test:unit": "DEBUG=trace dotenvx run -f .env.test --quiet -- vitest test/unit", "test:staging": "DEBUG=trace TEST_ENV=staging dotenvx run -f .env.test --quiet -- vitest test/staging", + "test:zig": "cd src/zig && zig build test", "typecheck": "DEBUG=trace dotenvx run -f .env.test --quiet -- vitest test/types.test.ts" }, "dependencies": { @@ -76,6 +83,7 @@ "prettier-plugin-jsdoc": "^1.3.2", "react": "^18.2.0", "react-dom": "^18.2.0", + "run-pty": "^5.0.0", "tinybench": "^4.0.1", "tsc-alias": "^1.8.15", "tsx": "^3.14.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0a73cf3..71316bc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -72,6 +72,9 @@ importers: react-dom: specifier: ^18.2.0 version: 18.3.1(react@18.3.1) + run-pty: + specifier: ^5.0.0 + version: 5.0.0 tinybench: specifier: ^4.0.1 version: 4.0.1 @@ -750,6 +753,39 @@ packages: '@jridgewell/trace-mapping@0.3.25': resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==} + '@lydell/node-pty-darwin-arm64@1.1.0': + resolution: {integrity: sha512-7kFD+owAA61qmhJCtoMbqj3Uvff3YHDiU+4on5F2vQdcMI3MuwGi7dM6MkFG/yuzpw8LF2xULpL71tOPUfxs0w==} + cpu: [arm64] + os: [darwin] + + '@lydell/node-pty-darwin-x64@1.1.0': + resolution: {integrity: sha512-XZdvqj5FjAMjH8bdp0YfaZjur5DrCIDD1VYiE9EkkYVMDQqRUPHYV3U8BVEQVT9hYfjmpr7dNaELF2KyISWSNA==} + cpu: [x64] + os: [darwin] + + '@lydell/node-pty-linux-arm64@1.1.0': + resolution: {integrity: sha512-yyDBmalCfHpLiQMT2zyLcqL2Fay4Xy7rIs8GH4dqKLnEviMvPGOK7LADVkKAsbsyXBSISL3Lt1m1MtxhPH6ckg==} + cpu: [arm64] + os: [linux] + + '@lydell/node-pty-linux-x64@1.1.0': + resolution: {integrity: sha512-NcNqRTD14QT+vXcEuqSSvmWY+0+WUBn2uRE8EN0zKtDpIEr9d+YiFj16Uqds6QfcLCHfZmC+Ls7YzwTaqDnanA==} + cpu: [x64] + os: [linux] + + '@lydell/node-pty-win32-arm64@1.1.0': + resolution: {integrity: sha512-JOMbCou+0fA7d/m97faIIfIU0jOv8sn2OR7tI45u3AmldKoKoLP8zHY6SAvDDnI3fccO1R2HeR1doVjpS7HM0w==} + cpu: [arm64] + os: [win32] + + '@lydell/node-pty-win32-x64@1.1.0': + resolution: {integrity: sha512-3N56BZ+WDFnUMYRtsrr7Ky2mhWGl9xXcyqR6cexfuCqcz9RNWL+KoXRv/nZylY5dYaXkft4JaR1uVu+roiZDAw==} + cpu: [x64] + os: [win32] + + '@lydell/node-pty@1.1.0': + resolution: {integrity: sha512-VDD8LtlMTOrPKWMXUAcB9+LTktzuunqrMwkYR1DMRBkS6LQrCt+0/Ws1o2rMml/n3guePpS7cxhHF7Nm5K4iMw==} + '@manypkg/find-root@1.1.0': resolution: {integrity: sha512-mki5uBvhHzO8kYYix/WRy2WX8S3B5wdVSc9D6KcU5lQNglP2yt58/VfLuAK49glRXChosY8ap2oJ1qgma3GUVA==} @@ -4255,6 +4291,10 @@ packages: run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + run-pty@5.0.0: + resolution: {integrity: sha512-0gk83+2NmrZGGPlJ88lqt0dYHvgyau/JBdRz9OqEbNyIfmbiq9E5sGCsvHdjrLoUJVh09ZX9r5rN587ACoM3vQ==} + hasBin: true + rustbn-wasm@0.4.0: resolution: {integrity: sha512-C2ujvPv05hXC69MD7YwSsoUEsT/X/dKHkkgwN9B0ZTgb0OXDC9yaHhE6Pq+uaRAzMyW0Y97bwc4JO4cqPDzVuQ==} @@ -4539,6 +4579,9 @@ packages: thread-stream@3.1.0: resolution: {integrity: sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==} + tiny-decoders@23.0.0: + resolution: {integrity: sha512-gQB+za3EW9JN1ASDmrVl1a1I6Q/jzg4M75YLI9ToHCdCW4/9KvBTTNH4u3kFbg8e+/8Zn68VRF+ayuiPNqYAmg==} + tiny-jsonc@1.0.2: resolution: {integrity: sha512-f5QDAfLq6zIVSyCZQZhhyl0QS6MvAyTxgz4X4x3+EoCktNWEYJ6PeoEA97fyb98njpBNNi88ybpD7m+BDFXaCw==} @@ -5698,6 +5741,33 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.0 + '@lydell/node-pty-darwin-arm64@1.1.0': + optional: true + + '@lydell/node-pty-darwin-x64@1.1.0': + optional: true + + '@lydell/node-pty-linux-arm64@1.1.0': + optional: true + + '@lydell/node-pty-linux-x64@1.1.0': + optional: true + + '@lydell/node-pty-win32-arm64@1.1.0': + optional: true + + '@lydell/node-pty-win32-x64@1.1.0': + optional: true + + '@lydell/node-pty@1.1.0': + optionalDependencies: + '@lydell/node-pty-darwin-arm64': 1.1.0 + '@lydell/node-pty-darwin-x64': 1.1.0 + '@lydell/node-pty-linux-arm64': 1.1.0 + '@lydell/node-pty-linux-x64': 1.1.0 + '@lydell/node-pty-win32-arm64': 1.1.0 + '@lydell/node-pty-win32-x64': 1.1.0 + '@manypkg/find-root@1.1.0': dependencies: '@babel/runtime': 7.27.1 @@ -10283,6 +10353,11 @@ snapshots: dependencies: queue-microtask: 1.2.3 + run-pty@5.0.0: + dependencies: + '@lydell/node-pty': 1.1.0 + tiny-decoders: 23.0.0 + rustbn-wasm@0.4.0: dependencies: '@scure/base': 1.2.5 @@ -10654,6 +10729,8 @@ snapshots: dependencies: real-require: 0.2.0 + tiny-decoders@23.0.0: {} + tiny-jsonc@1.0.2: {} tinybench@2.9.0: {} diff --git a/src/index.ts b/src/index.ts index 5061f9a..9351623 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,7 +19,6 @@ export type { export { watchState } from "@/lib/watch/index.js"; export type { WatchStateOptions, StateChange } from "@/lib/watch/types.js"; -export type { ExploreStorageConfig } from "@/lib/explore/config.js"; export type { // Solidity type extraction (mapping, array, struct) ExtractMappingKeyType, @@ -49,6 +48,8 @@ export type { // Helpers DeepReadonly, AbiTypeInplace, + // Explore + ExploreStorageConfig, } from "@/lib/explore/types.js"; export { PathSegmentKind } from "@/lib/explore/types.js"; diff --git a/src/lib/explore/index.ts b/src/lib/explore/index.ts index c94201e..b73817f 100644 --- a/src/lib/explore/index.ts +++ b/src/lib/explore/index.ts @@ -1,33 +1,19 @@ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; import { type Abi, type TraceResult } from "tevm"; import { type Address, type ContractFunctionName, type Hex } from "tevm/utils"; import { abi } from "@shazow/whatsabi"; -import { trim } from "viem"; -import { parseConfig } from "@/lib/explore/config.js"; -import { exploreStorage } from "@/lib/explore/explore-storage.js"; -import { extractPotentialKeys } from "@/lib/explore/mapping.js"; -import { type SolcStorageLayout, type SolcStorageLayoutTypes } from "@/lib/solc.js"; +import { parse, stringify } from "@/lib/explore/json.js"; +import { type SolcStorageLayout } from "@/lib/solc.js"; import { TraceStateResult } from "@/lib/trace/result.js"; -import type { - LabeledIntrinsicsState, - LabeledState, - LabeledStorageState, - TraceStateOptions, -} from "@/lib/trace/types.js"; -import { cleanTrace } from "@/lib/trace/utils.js"; +import type { LabeledIntrinsicsState, LabeledState, TraceStateOptions } from "@/lib/trace/types.js"; import { logger } from "@/logger.js"; +import { labelStateDiff as _labelStateDiff } from "@/zig/explore/label-state-diff.js"; +import { initWasm } from "@/zig/wasm-loader.js"; -export const labelStateDiff = < - TAbi extends Abi | readonly unknown[] = Abi, - TFunctionName extends ContractFunctionName = ContractFunctionName, ->({ - stateDiff, - layouts, - uniqueAddresses, - structLogs, - abiFunctions, - options, -}: { +type LabelStateDiffArgs> = { stateDiff: Record< Address, LabeledIntrinsicsState & { storage: Record } @@ -37,136 +23,17 @@ export const labelStateDiff = < structLogs: TraceResult["structLogs"]; abiFunctions: Array; options: TraceStateOptions; -}): TraceStateResult => { - // Extract potential key/index values from the execution trace - // Create a slim version of the trace with deduplicated stack values for efficiency - const dedupedTraceLog = { - // Deduplicate stack values across all operations - uniqueStackValues: [...new Set(structLogs.flatMap((log) => log.stack))], - // Only keep storage-related operations for detailed analysis - relevantOps: structLogs.filter((log) => ["SLOAD", "SSTORE", "SHA3"].includes(log.op)), - }; - - const potentialKeys = extractPotentialKeys(dedupedTraceLog, uniqueAddresses, abiFunctions, options); - logger.log(`Extracted ${potentialKeys.length} unique potential values from the trace`); - - const result = new TraceStateResult(); - // Process each address - for (const address of uniqueAddresses) { - const layout = layouts[address.toLowerCase() as Address]; - const { storage, ...intrinsics } = stateDiff[address]; - - if (!layout) { - const labeledState: LabeledState = { - ...intrinsics, - storage: Object.entries(storage).reduce( - (acc, [slot, { current, next }]) => { - acc[`slot_${slot}`] = { - name: `slot_${slot}`, - trace: [ - // @ts-expect-error - Type boolean is not assignable to false - { - modified: next !== undefined && current !== undefined && next !== current, - ...(current !== undefined ? { current: { hex: current } } : {}), - ...(next !== undefined ? { next: { hex: next } } : {}), - slots: [slot as Hex], - path: [], - fullExpression: `slot_${slot}`, - note: "Could not label this slot access because no layout was found.", - }, - ], - }; - return acc; - }, - {} as Record>, - ), - }; - - result.set(address.toLowerCase() as Address, labeledState); - continue; - } - - // 1. Decode using all known variables with optimized exploration - const { withLabels, unexploredSlots } = exploreStorage( - layout, - storage, - potentialKeys.map((k) => k.hex), - parseConfig(options.config), - ); - - // 2. Process results into named variables - const decoded = withLabels.reduce( - (acc, result) => { - // Retrieve existing entry or create a new one - acc[result.name] = acc[result.name] ?? { - name: result.name, - type: result.type, - kind: result.type.startsWith("mapping") - ? "mapping" - : result.type.endsWith("]") && result.type.match(/\[\d+\]$/) - ? "static_array" - : result.type.endsWith("[]") - ? "dynamic_array" - : result.type.startsWith("struct") - ? "struct" - : result.type === "bytes" || result.type === "string" - ? "bytes" - : "primitive", - trace: [], - }; - - acc[result.name].trace.push( - cleanTrace({ - modified: - result.next !== undefined && - result.current !== undefined && - trim(result.next.hex) !== trim(result.current.hex), - current: result.current, - next: result.next, - slots: result.slots, - path: result.path, - fullExpression: result.fullExpression, - note: result.note, - }), - ); - - return acc; - }, - {} as Record>, - ); - - // 3. Create unknown variables access traces for remaining slots - const unknownAccess = Object.fromEntries( - [...unexploredSlots].map((slot) => { - const current = storage[slot].current; - const next = storage[slot].next; - - return [ - `slot_${slot}`, - { - name: `slot_${slot}`, - trace: [ - cleanTrace({ - modified: next !== undefined && current !== undefined && next !== current, - current: { hex: current }, - next: { hex: next }, - slots: [slot], - path: [], - fullExpression: `slot_${slot}`, - note: "Could not label this slot access.", - }), - ], - }, - ]; - }), - ); - - // Add to TraceStateResult - result.set(address.toLowerCase() as Address, { - ...intrinsics, - storage: { ...decoded, ...unknownAccess }, - }); - } +}; - return result; +export const labelStateDiff = async < + TAbi extends Abi | readonly unknown[] = Abi, + TFunctionName extends ContractFunctionName = ContractFunctionName, +>( + args: LabelStateDiffArgs, +): Promise => { + // Initialize WASM instance with all implementation methods + const wasmModule = await initWasm(); + console.log(wasmModule.exports.add(1, 2)); + + return _labelStateDiff(args); }; diff --git a/src/lib/explore/json.ts b/src/lib/explore/json.ts new file mode 100644 index 0000000..872ffb7 --- /dev/null +++ b/src/lib/explore/json.ts @@ -0,0 +1,8 @@ +export const stringify = (obj: T): string => + JSON.stringify(obj, (_key, value) => (typeof value === "bigint" ? `__bigint__${value.toString()}` : value)); + +export const parse = (jsonString: string): T => { + return JSON.parse(jsonString, (_key, value) => + typeof value === "string" && value.startsWith("__bigint__") ? BigInt(value.replace("__bigint__", "")) : value, + ); +}; diff --git a/src/lib/explore/types.ts b/src/lib/explore/types.ts index 59c6579..8078378 100644 --- a/src/lib/explore/types.ts +++ b/src/lib/explore/types.ts @@ -336,3 +336,28 @@ export type DecodedResult = { path: Array; note?: string; }; + +/* -------------------------------------------------------------------------- */ +/* CONFIG */ +/* -------------------------------------------------------------------------- */ + +export interface ExploreStorageConfig { + /** + * Optional exploration limit for mapping combinations per mapping. + * + * Set to `-1` to disable early termination. + */ + mappingExplorationLimit?: number; + /** + * Optional maximum nesting depth for mappings to prevent excessive recursion and memory usage. + * + * Set to `-1` to disable early termination. + */ + maxMappingDepth?: number; + /** + * Optional early termination threshold - stop processing keys if we've found this many matches. + * + * Set to `-1` to disable early termination. + */ + earlyTerminationThreshold?: number; +} diff --git a/src/lib/react/lib.tsx b/src/lib/react/lib.tsx index 23addaf..3951c5a 100644 --- a/src/lib/react/lib.tsx +++ b/src/lib/react/lib.tsx @@ -1,6 +1,6 @@ import React, { createContext, useContext, useMemo, type ReactNode } from "react"; -import { type ExploreStorageConfig } from "@/lib/explore/config.js"; +import { type ExploreStorageConfig } from "@/lib/explore/types.js"; import { Tracer } from "@/lib/trace/index.js"; import type { TraceStateBaseOptions } from "@/lib/trace/types.js"; diff --git a/src/lib/trace/index.ts b/src/lib/trace/index.ts index 9fc37ab..824954d 100644 --- a/src/lib/trace/index.ts +++ b/src/lib/trace/index.ts @@ -2,8 +2,8 @@ import { type Abi, type AbiFunction, type Address, type ContractFunctionName } f import type { abi } from "@shazow/whatsabi"; import { toFunctionSignature } from "viem"; -import { type ExploreStorageConfig } from "@/lib/explore/config.js"; import { labelStateDiff } from "@/lib/explore/index.js"; +import { type ExploreStorageConfig } from "@/lib/explore/types.js"; import { type SolcStorageLayout } from "@/lib/solc.js"; import { debugTraceTransaction } from "@/lib/trace/debug.js"; import { TraceStateResult } from "@/lib/trace/result.js"; diff --git a/src/lib/trace/types.ts b/src/lib/trace/types.ts index 66e95d4..63278cb 100644 --- a/src/lib/trace/types.ts +++ b/src/lib/trace/types.ts @@ -3,7 +3,6 @@ import { type Common } from "tevm/common"; import { abi } from "@shazow/whatsabi"; import { type AbiStateMutability, type ContractFunctionArgs } from "viem"; -import { type ExploreStorageConfig } from "@/lib/explore/config.js"; import type { DeepReadonly, ParseSolidityType, @@ -12,6 +11,7 @@ import type { VariableExpression, VariablePathSegments, } from "@/lib/explore/types.js"; +import { type ExploreStorageConfig } from "@/lib/explore/types.js"; import { type SolcStorageLayout, type SolcStorageLayoutTypes } from "@/lib/solc.js"; /* -------------------------------------------------------------------------- */ diff --git a/src/lib/watch/index.ts b/src/lib/watch/index.ts index b3be6d5..3d37345 100644 --- a/src/lib/watch/index.ts +++ b/src/lib/watch/index.ts @@ -81,29 +81,32 @@ export const watchState = async { + for (const { txHash, stateDiff, addresses, newAddresses, structLogs } of traces) { const uniqueAddresses = [...new Set([...addresses, ...newAddresses])].map((addr) => addr.toLowerCase()); - if (!uniqueAddresses.includes(address.toLowerCase())) return; + if (!uniqueAddresses.includes(address.toLowerCase())) continue; // TODO: we might want to return the tx params (input) for each tx in debug_traceBlock to extract potential function args; this would avoid including transactions in the block which is solely for this const tx = block.transactions.find((tx) => tx.hash === txHash); - const diff = labelStateDiff({ - stateDiff, - layouts: storageLayout ? { [address.toLowerCase()]: storageLayout as SolcStorageLayout } : {}, - uniqueAddresses: uniqueAddresses as Array
, - structLogs, - abiFunctions, - // @ts-expect-error mismatch data - options: { - from: tx?.from, - to: tx?.to ?? undefined, - data: tx?.input, - value: tx?.value, - }, - }).get(address); + // await because of loading wasm, which will probably be cached for later use + const diff = ( + await labelStateDiff({ + stateDiff, + layouts: storageLayout ? { [address.toLowerCase()]: storageLayout as SolcStorageLayout } : {}, + uniqueAddresses: uniqueAddresses as Array
, + structLogs, + abiFunctions, + // @ts-expect-error mismatch data + options: { + from: tx?.from, + to: tx?.to ?? undefined, + data: tx?.input, + value: tx?.value, + }, + }) + ).get(address); if (diff) onStateChange({ ...diff, txHash: txHash } as unknown as StateChange); - }); + } }, }); diff --git a/src/lib/watch/types.ts b/src/lib/watch/types.ts index f469edf..955f3b6 100644 --- a/src/lib/watch/types.ts +++ b/src/lib/watch/types.ts @@ -1,8 +1,8 @@ import { type Abi, type Address, type Hex } from "tevm"; import { abi } from "@shazow/whatsabi"; -import { type ExploreStorageConfig } from "@/lib/explore/config.js"; import type { DeepReadonly } from "@/lib/explore/types.js"; +import { type ExploreStorageConfig } from "@/lib/explore/types.js"; import { type SolcStorageLayout } from "@/lib/solc.js"; import type { LabeledState, TraceStateBaseOptions } from "@/lib/trace/types.js"; diff --git a/src/lib/explore/config.ts b/src/zig/explore/config.ts similarity index 56% rename from src/lib/explore/config.ts rename to src/zig/explore/config.ts index 6abc7bf..add03f1 100644 --- a/src/lib/explore/config.ts +++ b/src/zig/explore/config.ts @@ -1,3 +1,5 @@ +import type { ExploreStorageConfig } from "@/lib/explore/types.js"; + /** Default exploration limit per mapping to prevent excessive computation */ const DEFAULT_MAPPING_EXPLORATION_LIMIT = 1_000_000; @@ -7,33 +9,6 @@ const DEFAULT_MAX_MAPPING_DEPTH = 5; /** Early pruning threshold - stop processing keys if we've found this many matches */ const DEFAULT_EARLY_TERMINATION_THRESHOLD = 500; -export interface ExploreStorageConfig { - /** - * Optional exploration limit for mapping combinations per mapping. - * - * Set to `-1` to disable early termination. - * - * Default {@link DEFAULT_MAPPING_EXPLORATION_LIMIT} - */ - mappingExplorationLimit?: number; - /** - * Optional maximum nesting depth for mappings to prevent excessive recursion and memory usage. - * - * Set to `-1` to disable early termination. - * - * Default {@link DEFAULT_MAX_MAPPING_DEPTH} - */ - maxMappingDepth?: number; - /** - * Optional early termination threshold - stop processing keys if we've found this many matches. - * - * Set to `-1` to disable early termination. - * - * Default {@link DEFAULT_EARLY_TERMINATION_THRESHOLD} - */ - earlyTerminationThreshold?: number; -} - export const parseConfig = (config?: ExploreStorageConfig): Required => { return { mappingExplorationLimit: diff --git a/src/lib/explore/explore-storage.ts b/src/zig/explore/explore-storage.ts similarity index 99% rename from src/lib/explore/explore-storage.ts rename to src/zig/explore/explore-storage.ts index cb760d4..04dbb54 100644 --- a/src/lib/explore/explore-storage.ts +++ b/src/zig/explore/explore-storage.ts @@ -1,18 +1,18 @@ import type { AbiTypeToPrimitiveType } from "abitype"; import { bytesToString, decodeAbiParameters, keccak256, padHex, toBytes, toHex, type Hex } from "viem"; -import { type ExploreStorageConfig } from "@/lib/explore/config.js"; -import { computeMappingSlot, sortCandidateKeys } from "@/lib/explore/mapping.js"; import { PathSegmentKind, TypePriority, type AbiTypeInplace, type DecodedResult, + type ExploreStorageConfig, type PathSegment, } from "@/lib/explore/types.js"; -import { decodeSlotDiffForPrimitive, max, toHexFullBytes } from "@/lib/explore/utils.js"; import type { SolcStorageLayout, SolcStorageLayoutMappingType } from "@/lib/solc.js"; import { logger } from "@/logger.js"; +import { computeMappingSlot, sortCandidateKeys } from "@/zig/explore/mapping.js"; +import { decodeSlotDiffForPrimitive, max, toHexFullBytes } from "@/zig/explore/utils.js"; /** * Memory-efficient implementation of storage exploration. diff --git a/src/zig/explore/label-state-diff.ts b/src/zig/explore/label-state-diff.ts new file mode 100644 index 0000000..e4de979 --- /dev/null +++ b/src/zig/explore/label-state-diff.ts @@ -0,0 +1,180 @@ +import { type Abi, type TraceResult } from "tevm"; +import { type Address, type ContractFunctionName, type Hex } from "tevm/utils"; +import { abi } from "@shazow/whatsabi"; +import { trim } from "viem"; + +import { type SolcStorageLayout, type SolcStorageLayoutTypes } from "@/lib/solc.js"; +import { TraceStateResult } from "@/lib/trace/result.js"; +import type { + LabeledIntrinsicsState, + LabeledState, + LabeledStorageState, + TraceStateOptions, +} from "@/lib/trace/types.js"; +import { cleanTrace } from "@/lib/trace/utils.js"; +import { logger } from "@/logger.js"; +import { parseConfig } from "@/zig/explore/config.js"; +import { exploreStorage } from "@/zig/explore/explore-storage.js"; +import { extractPotentialKeys } from "@/zig/explore/mapping.js"; + +export type LabelStateDiffArgs< + TAbi extends Abi | readonly unknown[] = Abi | readonly unknown[], + TFunctionName extends ContractFunctionName = ContractFunctionName, +> = { + stateDiff: Record< + Address, + // TODO: intrinsics should be in hex not bigints + LabeledIntrinsicsState & { storage: Record } + >; + layouts: Record; + uniqueAddresses: Array
; + structLogs: TraceResult["structLogs"]; + abiFunctions: Array; + options: TraceStateOptions; +}; + +export const labelStateDiff = < + TAbi extends Abi | readonly unknown[] = Abi, + TFunctionName extends ContractFunctionName = ContractFunctionName, +>({ + stateDiff, + layouts, + uniqueAddresses, + structLogs, + abiFunctions, + options, + // TODO: we can return the result non-decoded so we don't have to parse or we can parse less(?) and keep hex + // then decode in typescript +}: LabelStateDiffArgs): TraceStateResult => { + // Extract potential key/index values from the execution trace + // Create a slim version of the trace with deduplicated stack values for efficiency + const dedupedTraceLog = { + // Deduplicate stack values across all operations + uniqueStackValues: [...new Set(structLogs.flatMap((log) => log.stack))], + // Only keep storage-related operations for detailed analysis + relevantOps: structLogs.filter((log) => ["SLOAD", "SSTORE", "SHA3"].includes(log.op)), + }; + + const potentialKeys = extractPotentialKeys(dedupedTraceLog, uniqueAddresses, abiFunctions, options); + logger.log(`Extracted ${potentialKeys.length} unique potential values from the trace`); + + const result = new TraceStateResult(); + // Process each address + for (const address of uniqueAddresses) { + const layout = layouts[address.toLowerCase() as Address]; + const { storage, ...intrinsics } = stateDiff[address]; + + if (!layout) { + const labeledState: LabeledState = { + ...intrinsics, + storage: Object.entries(storage).reduce( + (acc, [slot, { current, next }]) => { + acc[`slot_${slot}`] = { + name: `slot_${slot}`, + trace: [ + // @ts-expect-error - Type boolean is not assignable to false + { + modified: next !== undefined && current !== undefined && next !== current, + ...(current !== undefined ? { current: { hex: current } } : {}), + ...(next !== undefined ? { next: { hex: next } } : {}), + slots: [slot as Hex], + path: [], + fullExpression: `slot_${slot}`, + note: "Could not label this slot access because no layout was found.", + }, + ], + }; + return acc; + }, + {} as Record>, + ), + }; + + result.set(address.toLowerCase() as Address, labeledState); + continue; + } + + // 1. Decode using all known variables with optimized exploration + const { withLabels, unexploredSlots } = exploreStorage( + layout, + storage, + potentialKeys.map((k) => k.hex), + parseConfig(options.config), + ); + + // 2. Process results into named variables + const decoded = withLabels.reduce( + (acc, result) => { + // Retrieve existing entry or create a new one + acc[result.name] = acc[result.name] ?? { + name: result.name, + type: result.type, + kind: result.type.startsWith("mapping") + ? "mapping" + : result.type.endsWith("]") && result.type.match(/\[\d+\]$/) + ? "static_array" + : result.type.endsWith("[]") + ? "dynamic_array" + : result.type.startsWith("struct") + ? "struct" + : result.type === "bytes" || result.type === "string" + ? "bytes" + : "primitive", + trace: [], + }; + + acc[result.name].trace.push( + cleanTrace({ + modified: + result.next !== undefined && + result.current !== undefined && + trim(result.next.hex) !== trim(result.current.hex), + current: result.current, + next: result.next, + slots: result.slots, + path: result.path, + fullExpression: result.fullExpression, + note: result.note, + }), + ); + + return acc; + }, + {} as Record>, + ); + + // 3. Create unknown variables access traces for remaining slots + const unknownAccess = Object.fromEntries( + [...unexploredSlots].map((slot) => { + const current = storage[slot].current; + const next = storage[slot].next; + + return [ + `slot_${slot}`, + { + name: `slot_${slot}`, + trace: [ + cleanTrace({ + modified: next !== undefined && current !== undefined && next !== current, + current: { hex: current }, + next: { hex: next }, + slots: [slot], + path: [], + fullExpression: `slot_${slot}`, + note: "Could not label this slot access.", + }), + ], + }, + ]; + }), + ); + + // Add to TraceStateResult + result.set(address.toLowerCase() as Address, { + ...intrinsics, + storage: { ...decoded, ...unknownAccess }, + }); + } + + return result; +}; diff --git a/src/lib/explore/mapping.ts b/src/zig/explore/mapping.ts similarity index 100% rename from src/lib/explore/mapping.ts rename to src/zig/explore/mapping.ts diff --git a/src/lib/explore/utils.ts b/src/zig/explore/utils.ts similarity index 100% rename from src/lib/explore/utils.ts rename to src/zig/explore/utils.ts diff --git a/src/zig/lib.zig b/src/zig/lib.zig new file mode 100644 index 0000000..86f4884 --- /dev/null +++ b/src/zig/lib.zig @@ -0,0 +1,23 @@ +const std = @import("std"); + +// Simple function to be exported to WASM +// It takes two 32-bit integers and returns their sum. +export fn add(a: i32, b: i32) i32 { + return a + b; +} + +// Test for the add function +test "add function" { + const expected: i32 = 5; + const actual: i32 = add(2, 3); + try std.testing.expectEqual(expected, actual); + + try std.testing.expectEqual(@as(i32, -1), add(2, -3)); + try std.testing.expectEqual(@as(i32, 0), add(0, 0)); +} + +// Optional: main function for `zig run src/zig/lib.zig` (if you want to test directly) +// For WASM library builds, this isn't strictly necessary if not building an executable. +// pub fn main() !void { +// std.debug.print("Hello from lib.zig main (not used in WASM build)\n", .{}); +// } diff --git a/src/zig/wasm-loader.ts b/src/zig/wasm-loader.ts new file mode 100644 index 0000000..d40012d --- /dev/null +++ b/src/zig/wasm-loader.ts @@ -0,0 +1,76 @@ +import fs from "node:fs/promises"; // Using promises for async file reading +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +// Determine the directory of the current module +const __dirname = dirname(fileURLToPath(import.meta.url)); +// Resolve the path to the WASM file, assuming this loader is in src/lib +// and the wasm file is in dist/wasm/ +const wasmPath = resolve(__dirname, "../../dist/wasm/evmstate.wasm"); + +/** Represents the exports from our WASM module. Update this interface as you add more exported functions from Zig. */ +interface EvmStateWasmExports extends WebAssembly.Exports { + memory: WebAssembly.Memory; + add: (a: number, b: number) => number; + // Add other exported Zig functions here, e.g.: + // keccak256: (input_ptr: number, input_len: number, output_ptr: number) => void; +} + +/** Type for the instantiated WASM instance, providing type safety. */ +interface EvmStateWasmInstance extends WebAssembly.Instance { + exports: EvmStateWasmExports; +} + +let wasmInstance: EvmStateWasmInstance | null = null; + +/** + * Initializes the WebAssembly module. Reads the WASM file, instantiates it, and caches the instance. + * + * @returns {Promise} The WebAssembly instance with typed exports. + * @throws {Error} If the WASM file cannot be read or instantiation fails. + */ +export const initWasm = async (): Promise => { + if (wasmInstance) return wasmInstance; + + try { + const wasmBuffer = await fs.readFile(wasmPath); + const { instance } = await WebAssembly.instantiate(wasmBuffer, { + // Imports can be provided here if your WASM module needs them + // e.g., env: { your_import_function: () => {} } + }); + + console.log("EVMState WASM module initialized successfully."); + console.log("WASM exports:", Object.keys(instance.exports)); + + wasmInstance = instance as EvmStateWasmInstance; + return wasmInstance; + } catch (err) { + console.error("Error loading EVMState WASM module:", err); + // Depending on your error handling strategy, you might want to throw a custom error + // or handle it differently. + throw new Error(`Failed to initialize EVMState WASM: ${err instanceof Error ? err.message : String(err)}`); + } +}; + +/** + * Gets the initialized WASM instance. Throws an error if `initWasm` has not been called successfully first. + * + * @returns {EvmStateWasmInstance} The WebAssembly instance. + */ +export function getWasmInstance(): EvmStateWasmInstance { + if (!wasmInstance) { + throw new Error("WASM module not initialized. Call initWasm() first."); + } + return wasmInstance; +} + +// Example usage (can be removed or adapted for your library's entry point): +// (async () => { +// try { +// const instance = await initWasm(); +// const result = instance.exports.add(5, 7); +// console.log('Result of add(5, 7) from WASM:', result); // Should output 12 +// } catch (error) { +// console.error('Failed to run WASM example:', error); +// } +// })();