Onchain.Contract.Generator (onchain_evm v0.4.0)

Copy Markdown View Source

Compile-time contract codegen macro.

Reads a Solidity ABI (from .sol source, ABI JSON string, or ABI JSON file) at compile time via Onchain.Solidity, then generates typed Elixir functions for every contract function found in the ABI.

Usage

defmodule MyApp.ERC20 do
  use Onchain.Contract.Generator,
    abi_json: File.read!("priv/abis/erc20.json")
end

defmodule MyApp.Pool do
  use Onchain.Contract.Generator,
    sol: File.read!("priv/contracts/IPool.sol")
end

defmodule MyApp.UiPool do
  use Onchain.Contract.Generator,
    sol_file: "priv/contracts/real/aave/IUiPoolDataProviderV3.sol"
end

Generated Functions

For each ABI function, generates:

Address Validation

Parameters with Solidity type address are validated via Onchain.Address.validate/1 before being passed to the ABI encoder.

Overload Disambiguation

When multiple Solidity functions share the same name but differ in parameter count, generated Elixir function names are suffixed with input type names to avoid arity collisions. For example, transfer(address,uint256) and transfer(address,address,uint256) become transfer/3 and transfer_address/4 (suffixed with the disambiguating extra param type).

Options

Provide one of the following source options. If multiple are given, the first match in this order is used (the rest are ignored):

  • :sol — raw Solidity source code as a string (e.g., File.read!("priv/contracts/IPool.sol"))
  • :sol_file — path to a .sol file, resolved relative to the calling module's source directory
  • :abi_json — ABI as a JSON string (e.g., File.read!("priv/abis/erc20.json"))
  • :abi_file — path to an ABI JSON file, passed as-is to File.read/1 (use an absolute path or a path relative to the project root / CWD)

Additional options (only valid with :sol_file):

  • :remappings — a list of Foundry-style remapping strings (e.g., ["@aave/core-v3/=lib/aave-v3-core/"])
  • :root_contract — name of the contract or interface to extract when the file contains multiple definitions (e.g., "IPoolV3")

.sol Extras

When using sol: source:

  • Struct modules: nested defmodule with @enforce_keys, defstruct, and from_raw/1 for each struct definition
  • Enum constants: module attributes @enum_name_variant index for each enum variant
  • NatSpec docs: @doc pulled from /// @notice comments