abigen!() { /* proc-macro */ }
Available on crate feature abigen only.
Expand description

Proc macro to generate type-safe bindings to a contract(s). This macro accepts one or more Ethereum contract ABI or a path. Note that relative paths are rooted in the crate’s root CARGO_MANIFEST_DIR. Environment variable interpolation is supported via $ prefix, like "$CARGO_MANIFEST_DIR/contracts/c.json"

Examples

// ABI Path
abigen!(MyContract, "MyContract.json");

// HTTP(S) source
abigen!(MyContract, "https://my.domain.local/path/to/contract.json");

// Etherscan.io
abigen!(MyContract, "etherscan:0x0001020304050607080910111213141516171819");
abigen!(MyContract, "https://etherscan.io/address/0x0001020304050607080910111213141516171819");

// npmjs
abigen!(MyContract, "npm:@org/package@1.0.0/path/to/contract.json");

Note that Etherscan rate-limits requests to their API, to avoid this an ETHERSCAN_API_KEY environment variable can be set. If it is, it will use that API key when retrieving the contract ABI.

Currently, the proc macro accepts additional parameters to configure some aspects of the code generation. Specifically it accepts:

  • methods: A list of mappings from method signatures to method names allowing methods names to be explicitely set for contract methods. This also provides a workaround for generating code for contracts with multiple methods with the same name.
  • event_derives: A list of additional derives that should be added to contract event structs and enums.

Example

abigen!(
    MyContract,
    "path/to/MyContract.json",
    methods {
        myMethod(uint256,bool) as my_renamed_method;
    },
    event_derives (serde::Deserialize, serde::Serialize),
);

Aliases for overloaded functions with no aliases provided in the method section are derived automatically.

abigen! supports multiple abigen definitions separated by a semicolon ; This is useful if the contracts use ABIEncoderV2 structs. In which case abigen! bundles all type duplicates so that all rust contracts also use the same rust types.

Example Multiple contracts

abigen!(
    MyContract,
    "path/to/MyContract.json",
    methods {
        myMethod(uint256,bool) as my_renamed_method;
    },
    event_derives (serde::Deserialize, serde::Serialize);

    MyOtherContract,
    "path/to/MyOtherContract.json",
    event_derives (serde::Deserialize, serde::Serialize);
);