fix examples

This commit is contained in:
Georgios Konstantopoulos 2020-06-02 13:58:48 +03:00
parent e051cffe47
commit 56d22c0360
No known key found for this signature in database
GPG Key ID: FA607837CD26EDBC
9 changed files with 32 additions and 31 deletions

View File

@ -11,9 +11,6 @@ use std::{error::Error, fmt::Debug};
pub use provider::{Provider, ProviderError}; pub use provider::{Provider, ProviderError};
/// An HTTP provider for interacting with an Ethereum-compatible blockchain
pub type HttpProvider = Provider<Http>;
#[async_trait] #[async_trait]
/// Trait which must be implemented by data transports to be used with the Ethereum /// Trait which must be implemented by data transports to be used with the Ethereum
/// JSON-RPC provider. /// JSON-RPC provider.

View File

@ -25,9 +25,10 @@ pub struct Provider<P>(P, Option<Address>);
#[derive(Debug, Error)] #[derive(Debug, Error)]
/// An error thrown when making a call to the provider /// An error thrown when making a call to the provider
pub enum ProviderError { pub enum ProviderError {
#[error(transparent)]
// dyn dispatch the error to avoid generic return types // dyn dispatch the error to avoid generic return types
JsonRpcClientError(#[from] Box<dyn std::error::Error>), #[error(transparent)]
JsonRpcClientError(#[from] Box<dyn std::error::Error + Send + Sync>),
#[error("ens name not found: {0}")] #[error("ens name not found: {0}")]
EnsError(String), EnsError(String),
} }
@ -357,13 +358,12 @@ impl TryFrom<&str> for Provider<HttpProvider> {
mod ens_tests { mod ens_tests {
use super::*; use super::*;
const INFURA: &str = "https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27";
#[tokio::test] #[tokio::test]
// Test vector from: https://docs.ethers.io/ethers.js/v5-beta/api-providers.html#id2 // Test vector from: https://docs.ethers.io/ethers.js/v5-beta/api-providers.html#id2
async fn mainnet_resolve_name() { async fn mainnet_resolve_name() {
let provider = Provider::<HttpProvider>::try_from( let provider = Provider::<HttpProvider>::try_from(INFURA).unwrap();
"https://mainnet.infura.io/v3/9408f47dedf04716a03ef994182cf150",
)
.unwrap();
let addr = provider let addr = provider
.resolve_name("registrar.firefly.eth") .resolve_name("registrar.firefly.eth")
@ -389,10 +389,7 @@ mod ens_tests {
#[tokio::test] #[tokio::test]
// Test vector from: https://docs.ethers.io/ethers.js/v5-beta/api-providers.html#id2 // Test vector from: https://docs.ethers.io/ethers.js/v5-beta/api-providers.html#id2
async fn mainnet_lookup_address() { async fn mainnet_lookup_address() {
let provider = Provider::<HttpProvider>::try_from( let provider = Provider::<HttpProvider>::try_from(INFURA).unwrap();
"https://mainnet.infura.io/v3/9408f47dedf04716a03ef994182cf150",
)
.unwrap();
let name = provider let name = provider
.lookup_address("6fC21092DA55B392b045eD78F4732bff3C580e2c".parse().unwrap()) .lookup_address("6fC21092DA55B392b045eD78F4732bff3C580e2c".parse().unwrap())

View File

@ -30,7 +30,7 @@ pub enum ClientError {
ProviderError(#[from] ProviderError), ProviderError(#[from] ProviderError),
#[error(transparent)] #[error(transparent)]
SignerError(#[from] Box<dyn std::error::Error>), SignerError(#[from] Box<dyn std::error::Error + Send + Sync>),
#[error("ens name not found: {0}")] #[error("ens name not found: {0}")]
EnsError(String), EnsError(String),
@ -123,6 +123,11 @@ where
pub fn signer_unchecked(&self) -> &S { pub fn signer_unchecked(&self) -> &S {
self.signer.as_ref().expect("no signer is configured") self.signer.as_ref().expect("no signer is configured")
} }
pub fn with_signer(mut self, signer: S) -> Self {
self.signer = Some(signer);
self
}
} }
// Abuse Deref to use the Provider's methods without re-writing everything. // Abuse Deref to use the Provider's methods without re-writing everything.

View File

@ -5,7 +5,7 @@ use ethers::{
}; };
use std::convert::TryFrom; use std::convert::TryFrom;
// Generate the contract bindings by providing the ABI // Generate the type-safe contract bindings by providing the ABI
abigen!( abigen!(
SimpleContract, SimpleContract,
r#"[{"inputs":[{"internalType":"string","name":"value","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"author","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","constant": true, "type":"function"},{"inputs":[{"internalType":"string","name":"value","type":"string"}],"name":"setValue","outputs":[],"stateMutability":"nonpayable","type":"function"}]"#, r#"[{"inputs":[{"internalType":"string","name":"value","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"author","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","constant": true, "type":"function"},{"inputs":[{"internalType":"string","name":"value","type":"string"}],"name":"setValue","outputs":[],"stateMutability":"nonpayable","type":"function"}]"#,
@ -28,14 +28,14 @@ async fn main() -> Result<()> {
.spawn(); .spawn();
// 3. instantiate our wallet // 3. instantiate our wallet
let wallet = "380eb0f3d505f087e438eca80bc4df9a7faa24f868e69fc0440261a0fc0567dc" let wallet =
.parse::<MainnetWallet>()?; "380eb0f3d505f087e438eca80bc4df9a7faa24f868e69fc0440261a0fc0567dc".parse::<Wallet>()?;
// 4. connect to the network // 4. connect to the network
let provider = HttpProvider::try_from(url.as_str())?; let provider = Provider::<Http>::try_from(url.as_str())?;
// 5. instantiate the client with the wallet // 5. instantiate the client with the wallet
let client = wallet.connect(&provider); let client = wallet.connect(provider);
// 6. create a factory which will be used to deploy instances of the contract // 6. create a factory which will be used to deploy instances of the contract
let factory = ContractFactory::new(&client, &contract.abi, &contract.bytecode); let factory = ContractFactory::new(&client, &contract.abi, &contract.bytecode);

View File

@ -5,13 +5,14 @@ use std::convert::TryFrom;
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
// connect to the network // connect to the network
let provider = let provider = Provider::<Http>::try_from(
HttpProvider::try_from("https://mainnet.infura.io/v3/9408f47dedf04716a03ef994182cf150")?; "https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27",
)?;
// create a wallet and connect it to the provider // create a wallet and connect it to the provider
let client = "dcf2cbdd171a21c480aa7f53d77f31bb102282b3ff099c78e3118b37348c72f7" let client = "dcf2cbdd171a21c480aa7f53d77f31bb102282b3ff099c78e3118b37348c72f7"
.parse::<MainnetWallet>()? .parse::<Wallet>()?
.connect(&provider); .connect(provider);
// craft the transaction // craft the transaction
let tx = TransactionRequest::new().to("vitalik.eth").value(100_000); let tx = TransactionRequest::new().to("vitalik.eth").value(100_000);

View File

@ -1,11 +1,11 @@
use anyhow::Result; use anyhow::Result;
use ethers::{networks::Any, prelude::*}; use ethers::prelude::*;
use std::convert::TryFrom; use std::convert::TryFrom;
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
// connect to the network // connect to the network
let provider = HttpProvider::<Any>::try_from("http://localhost:8545")?; let provider = Provider::<Http>::try_from("http://localhost:8545")?;
let filter = Filter::new() let filter = Filter::new()
.address_str("f817796F60D268A36a57b8D2dF1B97B14C0D0E1d")? .address_str("f817796F60D268A36a57b8D2dF1B97B14C0D0E1d")?

View File

@ -10,15 +10,16 @@ async fn main() -> Result<()> {
.port(port) .port(port)
.mnemonic("abstract vacuum mammal awkward pudding scene penalty purchase dinner depart evoke puzzle") .mnemonic("abstract vacuum mammal awkward pudding scene penalty purchase dinner depart evoke puzzle")
.spawn(); .spawn();
// this private key belongs to the above mnemonic // this private key belongs to the above mnemonic
let wallet: MainnetWallet = let wallet: Wallet =
"380eb0f3d505f087e438eca80bc4df9a7faa24f868e69fc0440261a0fc0567dc".parse()?; "380eb0f3d505f087e438eca80bc4df9a7faa24f868e69fc0440261a0fc0567dc".parse()?;
// connect to the network // connect to the network
let provider = HttpProvider::try_from(url.as_str())?; let provider = Provider::<Http>::try_from(url.as_str())?;
// connect the wallet to the provider // connect the wallet to the provider
let client = wallet.connect(&provider); let client = wallet.connect(provider);
// craft the transaction // craft the transaction
let tx = TransactionRequest::new() let tx = TransactionRequest::new()

View File

@ -2,7 +2,7 @@ use ethers::prelude::*;
fn main() { fn main() {
let message = "Some data"; let message = "Some data";
let wallet = MainnetWallet::new(&mut rand::thread_rng()); let wallet = Wallet::new(&mut rand::thread_rng());
// sign a message // sign a message
let signature = wallet.sign_message(message); let signature = wallet.sign_message(message);

View File

@ -1,5 +1,5 @@
use anyhow::Result; use anyhow::Result;
use ethers::{networks::Any, prelude::*, utils::GanacheBuilder}; use ethers::{prelude::*, utils::GanacheBuilder};
use std::convert::TryFrom; use std::convert::TryFrom;
#[tokio::main] #[tokio::main]
@ -9,7 +9,7 @@ async fn main() -> Result<()> {
let _ganache = GanacheBuilder::new().port(port).spawn(); let _ganache = GanacheBuilder::new().port(port).spawn();
// connect to the network // connect to the network
let provider = HttpProvider::<Any>::try_from(url.as_str())?; let provider = Provider::<Http>::try_from(url.as_str())?;
let accounts = provider.get_accounts().await?; let accounts = provider.get_accounts().await?;
let from = accounts[0]; let from = accounts[0];