Macro import

Source
import!() { /* proc-macro */ }
Expand description

The import! macro generates a Rust struct and implementation for interacting with an Ethereum smart contract based on its ABI (Application Binary Interface) and deploys the corresponding contract.

§Parameters

  • abi_path: A string literal specifying the path to the ABI JSON file (e.g., "examples/ERC20.json").
  • contract_name (optional): A string literal specifying the name of the contract source file (e.g., "my_erc20") without the .rs extension. If omitted, defaults to the base name of the ABI file (e.g., "ERC20" for "ERC20.json"). The file must be located in the examples directory or a configured search path.

§Generated Code

The macro generates a struct named after the ABI file’s base name (e.g., ERC20 for "ERC20.json") with:

  • An address field of type ::zink::primitives::address::Address to hold the contract address.
  • An evm field of type ::zint::revm::EVM<'static> to manage the EVM state.
  • A new method that deploys the specified contract and initializes the EVM.
  • Methods for each function in the ABI, which encode parameters, call the contract, and decode the results.

§Example

#[cfg(feature = "abi-import")]
use zink::import;

#[cfg(test)]
mod tests {
    use zink::primitives::address::Address;
    use zint::revm;

    #[test]
    fn test_contract() -> anyhow::Result<()> {
        #[cfg(feature = "abi-import")]
        {
            // Single argument: uses default contract name "ERC20"
            import!("examples/ERC20.json");
            let contract_address = Address::from(revm::CONTRACT);
            let token = ERC20::new(contract_address);
            let decimals = token.decimals()?;
            assert_eq!(decimals, 18);

            // Two arguments: specifies custom contract name "my_erc20"
            import!("examples/ERC20.json", "my_erc20");
            let token = MyERC20::new(contract_address);
            let decimals = token.decimals()?;
            assert_eq!(decimals, 8);
        }
        Ok(())
    }
}

§Requirements

  • The abi-import feature must be enabled (--features abi-import).
  • For wasm32 targets, the wasm-alloc feature must be enabled (--features wasm-alloc) to provide a global allocator (dlmalloc).

§Notes

  • The contract file (defaulting to the ABI base name or specified by contract_name) must exist and be compilable by zint::Contract::search.
  • The EVM state is initialized with a default account (ALICE) and deploys the contract on new.