tomusdrw / rust-web3

Ethereum JSON-RPC multi-transport client. Rust implementation of web3 library. ENS address: rust-web3.eth
MIT License
1.45k stars 471 forks source link

Querying deployed contracts on mainnet-fork #580

Open 0xtempest opened 2 years ago

0xtempest commented 2 years ago

I'm running into an issue with trying to query contracts that should already exist on a mainnet-fork version of ganache I'm running.

Using a basic example

`use hex_literal::hex; use web3::{ contract::{Contract, Options}, types::U256, types::H160 };

[tokio::main]

async fn main() -> web3::Result<()> {

pub type Address = H160;

let transport = web3::transports::Http::new("http://localhost:8545")?;
let web3 = web3::Web3::new(transport);

println!("Calling accounts.");
let mut accounts = web3.eth().accounts().await?;
println!("Accounts: {:?}", accounts);
accounts.push("6b175474e89094c44da98b954eedeac495271d0f".parse().unwrap());

println!("Calling balance.");
for account in accounts {
    let balance = web3.eth().balance(account, None).await?;
    println!("Balance of {:?}: {}", account, balance);
}

let dai_address: Address = hex!("6b175474e89094c44da98b954eedeac495271d0f").into();

println!("dai_account: {:?}", dai_address);

let dai_whale_address: Address = hex!("1e3D6eAb4BCF24bcD04721caA11C478a2e59852D").into();

let dai_contract = Contract::from_json(
    web3.eth(),
    dai_address,
    include_bytes!("dai.json"),
);
let result = dai_contract.query("name", (dai_whale_address,), None, Options::default(), None);
`

I'm running into the error of:
no method named `query` found for enum `Result` in the current scope

method not found in Result<web3::contract::Contract, web3::ethabi::Error>

I'm guessing this is because I didn't actually deploy the dai contract, however, I'm running a version of ganache that is forked from eth mainnet, how would I go about querying the contract without actually having to deploy it locally?

How would I do this just having the contract address and abi

dpuyosa commented 2 years ago

Contract::from_json() returns a Result which doesnt have the method query as stated by the error. You are missing a ? or an unwrap

let dai_contract: Contract<Http> = Contract::from_json(
    web3.eth(),
    dai_address,
    include_bytes!("dai.json"),
)?;