rust-web3 icon indicating copy to clipboard operation
rust-web3 copied to clipboard

Generate structs from contract interfaces

Open tomusdrw opened this issue 8 years ago • 6 comments
trafficstars

Example:

#[cfg(test)]
mod tests {
  use api;
  use helpers::tests::TestTransport;
  use types::U256;

  contract! {
    contract Token {
        event Transfer(address indexed from, address indexed to, uint256 value);
        event Approval(address indexed owner, address indexed spender, uint256 value);

        function balanceOf(address _owner) constant returns (uint256 balance);
        function transfer(address _to, uint256 _value) returns (bool success);
        function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
        function approve(address _spender, uint256 _value) returns (bool success);
        function allowance(address _owner, address _spender) constant returns (uint256 remaining);
    }
  }

  #[test]
  fn should_call_token_contract {
    // given
    let transport = helpers::tests::TestTransport::default();
    let eth = api::Eth::new(transport);
    let token = Token::at(1.into(), eth);

    // when
    let balance = token.balanceOf(5.into());

    // then
    assert_eq!(balance, U256::from(10));

  }
}

tomusdrw avatar Jan 10 '17 09:01 tomusdrw

This would be seriously awesome :) IMO this would be more easily accomplished if we mangled the solidity syntax a bit so all input/output types are just Rust-named. Then the types can just be used directly via IntoTokens/FromTokens and we don't have to maintain any kind of mapping from uint256 -> U256 or address -> Address, etc.

rphmeier avatar Jan 19 '17 14:01 rphmeier

It also might make sense to generate modules from such a macro to encapsulate the events as tuple-structs.

rphmeier avatar Jan 19 '17 14:01 rphmeier

Partially addressable by ethabi_derive. Should add examples how to use it (after ethabi_derive supports async calls/transacts)

tomusdrw avatar Feb 07 '18 10:02 tomusdrw

We should rather use ethabi_derive and make it more ergonomic to call using web3, see #120

tomusdrw avatar May 27 '20 12:05 tomusdrw

I'm working on something similar here - solidity-bindgen

It's not yet well documented, or in any sort of publishable state but you can do something like solidity_bindgen::contract_abis!("../contracts/build/abis"); where the path given is a relative path to a directory containing abis. It will spit out structs for each contract with an async method for each function with named, strongly-typed parameters and return values.

If you want good IDE support, you can use cargo-expand to spit out a file since rust-analyzer doesn't autocomplete well for proc-macro yet.

That3Percent avatar Jun 16 '20 22:06 That3Percent

@That3Percent cool stuff! Keep us informed on the progress. Would be cool if it supported an API that would allow easy integration with web3.

tomusdrw avatar Jun 18 '20 09:06 tomusdrw