From 4731dc93f831f85a5f02f1e9e1abf0143440d592 Mon Sep 17 00:00:00 2001 From: Yaser Martinez Palenzuela Date: Sun, 16 Jan 2022 17:06:22 +0100 Subject: [PATCH] add abigen uniswapv2 example (#798) --- examples/uniswapv2.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 examples/uniswapv2.rs diff --git a/examples/uniswapv2.rs b/examples/uniswapv2.rs new file mode 100644 index 00000000..91ae6b2b --- /dev/null +++ b/examples/uniswapv2.rs @@ -0,0 +1,32 @@ +use anyhow::Result; +use ethers::prelude::*; +use std::sync::Arc; + +// Generate the type-safe contract bindings by providing the ABI +// definition in human readable format +abigen!( + IUniswapV2Pair, + r#"[ + function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) + ]"#, +); + +#[tokio::main] +async fn main() -> Result<()> { + let client = Provider::::try_from( + "https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27", + )?; + let client = Arc::new(client); + + // ETH/USDT pair on Uniswap V2 + let address = "0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852".parse::
()?; + let pair = IUniswapV2Pair::new(address, Arc::clone(&client)); + + // getReserves -> get_reserves + let (reserve0, reserve1, _timestamp) = pair.get_reserves().call().await?; + println!("Reserves (ETH, USDT): ({}, {})", reserve0, reserve1); + + let mid_price = f64::powi(10.0, 18 - 6) * reserve1 as f64 / reserve0 as f64; + println!("ETH/USDT price: {:.2}", mid_price); + Ok(()) +}