2021-03-19 15:44:59 +00:00
use crate ::{
2020-12-31 19:08:12 +00:00
base ::{ encode_function_data , AbiError , BaseContract } ,
2020-10-29 07:48:24 +00:00
call ::ContractCall ,
2021-03-19 15:44:59 +00:00
event ::{ EthEvent , Event } ,
EthLogDecode ,
2020-10-29 07:48:24 +00:00
} ;
2020-05-27 08:46:16 +00:00
2020-05-31 16:01:34 +00:00
use ethers_core ::{
2020-10-27 10:57:01 +00:00
abi ::{ Abi , Detokenize , Error , EventExt , Function , Tokenize } ,
2022-09-19 17:51:04 +00:00
types ::{ Address , Filter , Selector , ValueOrArray } ,
2020-05-28 09:04:12 +00:00
} ;
2021-08-09 00:50:38 +00:00
#[ cfg(not(feature = " legacy " )) ]
use ethers_core ::types ::Eip1559TransactionRequest ;
#[ cfg(feature = " legacy " ) ]
use ethers_core ::types ::TransactionRequest ;
2020-12-17 11:26:01 +00:00
use ethers_providers ::Middleware ;
2020-05-26 18:57:59 +00:00
2020-10-27 10:57:01 +00:00
use std ::{ fmt ::Debug , marker ::PhantomData , sync ::Arc } ;
2020-05-26 18:57:59 +00:00
2020-06-10 18:20:47 +00:00
/// A Contract is an abstraction of an executable program on the Ethereum Blockchain.
/// It has code (called byte code) as well as allocated long-term memory
/// (called storage). Every deployed Contract has an address, which is used to connect
/// to it so that it may be sent messages to call its methods.
///
/// A Contract can emit Events, which can be efficiently observed by applications
/// to be notified when a contract has performed specific operation.
///
/// There are two types of methods that can be called on a Contract:
///
/// 1. A Constant method may not add, remove or change any data in the storage,
/// nor log any events, and may only call Constant methods on other contracts.
/// These methods are free (no Ether is required) to call. The result from them
/// may also be returned to the caller. Constant methods are marked as `pure` and
/// `view` in Solidity.
///
/// 2. A Non-Constant method requires a fee (in Ether) to be paid, but may perform
/// any state-changing operation desired, log events, send ether and call Non-Constant
/// methods on other Contracts. These methods cannot return their result to the caller.
/// These methods must be triggered by a transaction, sent by an Externally Owned Account
/// (EOA) either directly or indirectly (i.e. called from another contract), and are
/// required to be mined before the effects are present. Therefore, the duration
/// required for these operations can vary widely, and depend on the transaction
/// gas price, network congestion and miner priority heuristics.
///
/// The Contract API provides simple way to connect to a Contract and call its methods,
/// as functions on a Rust struct, handling all the binary protocol conversion,
/// internal name mangling and topic construction. This allows a Contract object
/// to be used like any standard Rust struct, without having to worry about the
/// low-level details of the Ethereum Virtual Machine or Blockchain.
///
/// The Contract definition (called an Application Binary Interface, or ABI) must
/// be provided to instantiate a contract and the available methods and events will
/// be made available to call by providing their name as a `str` via the [`method`]
/// and [`event`] methods. If non-existing names are given, the function/event call
/// will fail.
///
/// Alternatively, you can _and should_ use the [`abigen`] macro, or the [`Abigen` builder]
/// to generate type-safe bindings to your contracts.
///
/// # Example
///
/// Assuming we already have our contract deployed at `address`, we'll proceed to
/// interact with its methods and retrieve raw logs it has emitted.
///
/// ```no_run
2021-08-28 21:06:29 +00:00
/// use ethers_core::{
2020-06-20 13:55:07 +00:00
/// abi::Abi,
/// types::{Address, H256},
/// };
2021-08-28 21:06:29 +00:00
/// use ethers_contract::Contract;
/// use ethers_providers::{Provider, Http};
/// use ethers_signers::Wallet;
2020-06-10 18:20:47 +00:00
/// use std::convert::TryFrom;
///
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// // this is a fake address used just for this example
/// let address = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee".parse::<Address>()?;
///
/// // (ugly way to write the ABI inline, you can otherwise read it from a file)
/// let abi: Abi = serde_json::from_str(r#"[{"inputs":[{"internalType":"string","name":"value","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"author","type":"address"},{"indexed":true,"internalType":"address","name":"oldAuthor","type":"address"},{"indexed":false,"internalType":"string","name":"oldValue","type":"string"},{"indexed":false,"internalType":"string","name":"newValue","type":"string"}],"name":"ValueChanged","type":"event"},{"inputs":[],"name":"getValue","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastSender","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"value","type":"string"}],"name":"setValue","outputs":[],"stateMutability":"nonpayable","type":"function"}]"#)?;
///
/// // connect to the network
2020-09-24 21:33:09 +00:00
/// let client = Provider::<Http>::try_from("http://localhost:8545").unwrap();
2020-06-10 18:20:47 +00:00
///
/// // create the contract object at the address
2020-06-22 08:44:08 +00:00
/// let contract = Contract::new(address, abi, client);
2020-06-10 18:20:47 +00:00
///
/// // Calling constant methods is done by calling `call()` on the method builder.
/// // (if the function takes no arguments, then you must use `()` as the argument)
/// let init_value: String = contract
/// .method::<_, String>("getValue", ())?
/// .call()
/// .await?;
///
/// // Non-constant methods are executed via the `send()` call on the method builder.
2020-12-17 11:26:01 +00:00
/// let call = contract
/// .method::<_, H256>("setValue", "hi".to_owned())?;
/// let pending_tx = call.send().await?;
2020-06-22 08:44:08 +00:00
///
/// // `await`ing on the pending transaction resolves to a transaction receipt
2020-12-17 11:26:01 +00:00
/// let receipt = pending_tx.confirmations(6).await?;
2020-06-10 18:20:47 +00:00
///
/// # Ok(())
/// # }
/// ```
///
/// # Event Logging
2023-01-04 11:29:10 +00:00
///
2020-06-10 18:20:47 +00:00
/// Querying structured logs requires you to have defined a struct with the expected
/// datatypes and to have implemented `Detokenize` for it. This boilerplate code
/// is generated for you via the [`abigen`] and [`Abigen` builder] utilities.
2023-01-04 11:29:10 +00:00
//
// Ignore because `ethers-contract-derive` macros do not work in doctests in `ethers-contract`.
2021-08-28 21:06:29 +00:00
/// ```ignore
2020-06-10 18:20:47 +00:00
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// use ethers_core::{abi::Abi, types::Address};
2021-03-19 15:44:59 +00:00
/// use ethers_contract::{Contract, EthEvent};
2020-09-24 21:33:09 +00:00
/// use ethers_providers::{Provider, Http, Middleware};
2020-06-10 18:20:47 +00:00
/// use ethers_signers::Wallet;
/// use std::convert::TryFrom;
/// use ethers_core::abi::{Detokenize, Token, InvalidOutputType};
/// # // this is a fake address used just for this example
/// # let address = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee".parse::<Address>()?;
/// # let abi: Abi = serde_json::from_str(r#"[]"#)?;
2020-09-24 21:33:09 +00:00
/// # let client = Provider::<Http>::try_from("http://localhost:8545").unwrap();
2020-06-22 08:44:08 +00:00
/// # let contract = Contract::new(address, abi, client);
2020-06-10 18:20:47 +00:00
///
2021-03-19 15:44:59 +00:00
/// #[derive(Clone, Debug, EthEvent)]
2020-06-10 18:20:47 +00:00
/// struct ValueChanged {
/// old_author: Address,
/// new_author: Address,
/// old_value: String,
/// new_value: String,
/// }
///
/// let logs: Vec<ValueChanged> = contract
2021-03-19 15:44:59 +00:00
/// .event()
2020-06-10 18:20:47 +00:00
/// .from_block(0u64)
/// .query()
/// .await?;
///
/// println!("{:?}", logs);
/// # Ok(())
/// # }
/// ```
///
/// _Disclaimer: these above docs have been adapted from the corresponding [ethers.js page](https://docs.ethers.io/ethers.js/html/api-contract.html)_
///
/// [`abigen`]: macro.abigen.html
2022-11-07 23:43:23 +00:00
/// [`Abigen` builder]: struct.Abigen.html
2020-06-20 13:55:07 +00:00
/// [`event`]: method@crate::Contract::event
/// [`method`]: method@crate::Contract::method
2022-04-27 12:33:22 +00:00
#[ derive(Debug) ]
2020-09-24 21:33:09 +00:00
pub struct Contract < M > {
2022-09-24 00:32:24 +00:00
address : Address ,
2020-10-27 10:57:01 +00:00
base_contract : BaseContract ,
2020-09-24 21:33:09 +00:00
client : Arc < M > ,
2022-09-24 00:32:24 +00:00
}
impl < M > std ::ops ::Deref for Contract < M > {
type Target = BaseContract ;
fn deref ( & self ) -> & Self ::Target {
& self . base_contract
}
2020-05-26 18:57:59 +00:00
}
2022-04-27 12:33:22 +00:00
impl < M > Clone for Contract < M > {
fn clone ( & self ) -> Self {
Contract {
base_contract : self . base_contract . clone ( ) ,
client : self . client . clone ( ) ,
address : self . address ,
}
}
}
2022-09-24 00:32:24 +00:00
impl < M > Contract < M > {
/// Returns the contract's address
pub fn address ( & self ) -> Address {
self . address
}
/// Returns a reference to the contract's ABI
pub fn abi ( & self ) -> & Abi {
& self . base_contract . abi
}
2022-09-24 19:40:08 +00:00
/// Returns a pointer to the contract's client
pub fn client ( & self ) -> Arc < M > {
self . client . clone ( )
2022-09-24 00:32:24 +00:00
}
}
2022-11-22 21:15:36 +00:00
impl < M : Middleware > Contract < M > {
/// Returns an [`Event`](crate::builders::Event) builder for the provided event.
/// This function operates in a static context, then it does not require a `self`
/// to reference to instantiate an [`Event`](crate::builders::Event) builder.
2022-11-23 15:35:38 +00:00
pub fn event_of_type < D : EthEvent > ( client : & Arc < M > ) -> Event < M , D > {
2022-11-22 21:15:36 +00:00
Event {
provider : client ,
filter : Filter ::new ( ) . event ( & D ::abi_signature ( ) ) ,
datatype : PhantomData ,
}
}
}
2020-09-24 21:33:09 +00:00
impl < M : Middleware > Contract < M > {
2020-05-26 18:57:59 +00:00
/// Creates a new contract from the provided client, abi and address
2022-09-24 00:32:24 +00:00
pub fn new (
address : impl Into < Address > ,
abi : impl Into < BaseContract > ,
client : impl Into < Arc < M > > ,
) -> Self {
Self { base_contract : abi . into ( ) , client : client . into ( ) , address : address . into ( ) }
2020-05-26 18:57:59 +00:00
}
2021-03-19 15:44:59 +00:00
/// Returns an [`Event`](crate::builders::Event) builder for the provided event.
pub fn event < D : EthEvent > ( & self ) -> Event < M , D > {
self . event_with_filter ( Filter ::new ( ) . event ( & D ::abi_signature ( ) ) )
}
/// Returns an [`Event`](crate::builders::Event) builder with the provided filter.
pub fn event_with_filter < D : EthLogDecode > ( & self , filter : Filter ) -> Event < M , D > {
Event {
2020-09-24 21:33:09 +00:00
provider : & self . client ,
2021-08-12 16:19:24 +00:00
filter : filter . address ( ValueOrArray ::Value ( self . address ) ) ,
2020-05-26 18:57:59 +00:00
datatype : PhantomData ,
2021-03-19 15:44:59 +00:00
}
}
/// Returns an [`Event`](crate::builders::Event) builder with the provided name.
pub fn event_for_name < D : EthLogDecode > ( & self , name : & str ) -> Result < Event < M , D > , Error > {
// get the event's full name
let event = self . base_contract . abi . event ( name ) ? ;
Ok ( self . event_with_filter ( Filter ::new ( ) . event ( & event . abi_signature ( ) ) ) )
2020-05-26 18:57:59 +00:00
}
/// Returns a transaction builder for the provided function name. If there are
/// multiple functions with the same name due to overloading, consider using
/// the `method_hash` method instead, since this will use the first match.
pub fn method < T : Tokenize , D : Detokenize > (
& self ,
name : & str ,
args : T ,
2020-10-29 07:48:24 +00:00
) -> Result < ContractCall < M , D > , AbiError > {
2020-05-26 18:57:59 +00:00
// get the function
2020-10-27 10:57:01 +00:00
let function = self . base_contract . abi . function ( name ) ? ;
2020-05-26 18:57:59 +00:00
self . method_func ( function , args )
}
/// Returns a transaction builder for the selected function signature. This should be
/// preferred if there are overloaded functions in your smart contract
pub fn method_hash < T : Tokenize , D : Detokenize > (
& self ,
signature : Selector ,
args : T ,
2020-10-29 07:48:24 +00:00
) -> Result < ContractCall < M , D > , AbiError > {
2020-05-26 18:57:59 +00:00
let function = self
2020-10-27 10:57:01 +00:00
. base_contract
2020-05-26 18:57:59 +00:00
. methods
. get ( & signature )
2020-10-27 10:57:01 +00:00
. map ( | ( name , index ) | & self . base_contract . abi . functions [ name ] [ * index ] )
2020-12-31 17:19:14 +00:00
. ok_or_else ( | | Error ::InvalidName ( hex ::encode ( signature ) ) ) ? ;
2020-05-26 18:57:59 +00:00
self . method_func ( function , args )
}
fn method_func < T : Tokenize , D : Detokenize > (
& self ,
function : & Function ,
args : T ,
2020-10-29 07:48:24 +00:00
) -> Result < ContractCall < M , D > , AbiError > {
2020-12-31 19:08:12 +00:00
let data = encode_function_data ( function , args ) ? ;
2020-05-26 18:57:59 +00:00
2021-08-09 00:50:38 +00:00
#[ cfg(feature = " legacy " ) ]
2020-05-26 18:57:59 +00:00
let tx = TransactionRequest {
2022-09-19 17:51:04 +00:00
to : Some ( self . address . into ( ) ) ,
2020-10-29 07:48:24 +00:00
data : Some ( data ) ,
2020-05-26 18:57:59 +00:00
.. Default ::default ( )
} ;
2021-08-09 00:50:38 +00:00
#[ cfg(not(feature = " legacy " )) ]
let tx = Eip1559TransactionRequest {
2022-09-19 17:51:04 +00:00
to : Some ( self . address . into ( ) ) ,
2021-08-09 00:50:38 +00:00
data : Some ( data ) ,
.. Default ::default ( )
} ;
let tx = tx . into ( ) ;
2020-05-26 18:57:59 +00:00
2020-05-27 08:46:16 +00:00
Ok ( ContractCall {
2020-05-26 18:57:59 +00:00
tx ,
2020-06-22 08:44:08 +00:00
client : Arc ::clone ( & self . client ) , // cheap clone behind the Arc
2020-05-26 18:57:59 +00:00
block : None ,
function : function . to_owned ( ) ,
datatype : PhantomData ,
} )
}
2020-06-02 10:36:02 +00:00
/// Returns a new contract instance at `address`.
///
/// Clones `self` internally
2021-12-19 04:28:38 +00:00
#[ must_use ]
2020-06-21 07:17:11 +00:00
pub fn at < T : Into < Address > > ( & self , address : T ) -> Self
where
2020-09-24 21:33:09 +00:00
M : Clone ,
2020-06-21 07:17:11 +00:00
{
2020-06-02 10:36:02 +00:00
let mut this = self . clone ( ) ;
this . address = address . into ( ) ;
this
}
/// Returns a new contract instance using the provided client
///
/// Clones `self` internally
2021-12-19 04:28:38 +00:00
#[ must_use ]
2022-04-21 15:05:23 +00:00
pub fn connect < N > ( & self , client : Arc < N > ) -> Contract < N >
2020-06-21 07:17:11 +00:00
where
2022-04-21 15:05:23 +00:00
N : Clone ,
2020-06-21 07:17:11 +00:00
{
2022-04-21 15:05:23 +00:00
Contract { base_contract : self . base_contract . clone ( ) , client , address : self . address }
2020-06-02 10:36:02 +00:00
}
2021-01-22 09:25:22 +00:00
}