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"
endGenerated Functions
For each ABI function, generates:
- Read functions (
view/pure):fn_name(contract, ...params, opts \\ [])delegates toOnchain.Contract.call/5 - Write functions (
nonpayable/payable):fn_name(contract, ...params, opts)encodes calldata viaOnchain.ABI.encode_call/2and delegates toOnchain.Signer.send_transaction/3 - Bang variants:
fn_name!that raises on error __contract_abi__/0: returns the full parsed ABI map
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.solfile, 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 toFile.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
defmodulewith@enforce_keys,defstruct, andfrom_raw/1for each struct definition - Enum constants: module attributes
@enum_name_variant indexfor each enum variant - NatSpec docs:
@docpulled from/// @noticecomments