Skip to content

Commit

Permalink
Rust alloy read write storage contract
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcusWentz committed Jul 6, 2024
1 parent 6102661 commit 8267640
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 2 deletions.
15 changes: 15 additions & 0 deletions Contracts/SimpleStorage.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

contract SimpleStorage {
uint256 public storedData; //Do not set 0 manually it wastes gas!

event setEvent();


function set(uint256 x) public {
storedData = x;
emit setEvent();
}

}
4 changes: 2 additions & 2 deletions Contracts/Store.sol
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
pragma solidity 0.8.26;

contract SimpleStorage {

uint256 public storedData; //Do not set 0 manually it wastes gas!

event setEvent();


function set(uint256 x) public {
storedData = x;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"anonymous":false,"inputs":[],"name":"setEvent","type":"event"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"set","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"storedData","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]
91 changes: 91 additions & 0 deletions Scripts/rust/test_alloy_contract_read_write_events/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use std::env;
use url::Url;
use std::time::{SystemTime};

use alloy::{
network::EthereumWallet,
providers::{Provider, ProviderBuilder},
signers::local::PrivateKeySigner,
primitives::U256,
sol,
};
use eyre::Result;

sol!(
#[allow(missing_docs)]
#[sol(rpc)]
SimpleStorage,
"abi/SimpleStorage.json"
);

#[tokio::main]
async fn main() -> Result<()> {

// Pass RPC (Base Sepolia)
let rpc_base_sepolia_infura_https = env::var("baseSepoliaHTTPS").expect("$baseSepoliaHTTPS is not set");

// // Fail RPC (Any network that is not Base Sepolia)
// let rpc_base_sepolia_infura_https = env::var("optimismSepoliaHTTPS").expect("$baseSepoliaHTTPS is not set");

let private_key_wallet_string = env::var("devTestnetPrivateKey").expect("$devTestnetPrivateKey is not set");

let signer: PrivateKeySigner = private_key_wallet_string.parse().expect("should parse private key");
let wallet = EthereumWallet::from(signer.clone());

let rpc_url = Url::parse(&rpc_base_sepolia_infura_https).expect("RPC url string type covert error");

let provider = ProviderBuilder::new()
.with_recommended_fillers()
.wallet(wallet)
.on_http(rpc_url);

// println!("{:?}", provider);

// // https://docs.rs/alloy/latest/alloy/providers/fillers/struct.FillProvider.html

let chain_id_connected = provider.get_chain_id().await?; // println!("{:?}", latest_block);
println!("chainId {:?}", chain_id_connected);

let latest_block = provider.get_block_number().await?;
println!("latestBlock {:?}", latest_block);

let base_sepolia_chain_id = 84532;

if chain_id_connected != base_sepolia_chain_id {
println!("RPC endpoint not connected to Base Sepolia (chainId {}).",base_sepolia_chain_id);
println!("Switch to Base Sepolia then try again.");
return Ok(())
}

let contract = SimpleStorage::new("0xeD62F27e9e886A27510Dc491F5530996719cEd3d".parse()?, provider);

let stored_data_before = contract.storedData().call().await?._0;
println!("stored_data_before {}", stored_data_before);

println!("Set storage to current UNIX time...");

let tv_sec = get_unix_time();

let tx_hash = contract
.set(U256::from(tv_sec))
.send().await?
.watch().await?;

println!("Sent transaction: {tx_hash}");

let stored_data_after = contract.storedData().call().await?._0;
println!("stored_data_after {}", stored_data_after);

Ok(())
}

fn get_unix_time() -> usize {

let now = SystemTime::now(); //Credit: https://stackoverflow.com/questions/55849295/field-tv-sec-doesnt-exist-in-struct-systemtime
let now_str = format!("{:?}",now); //SystemTime { tv_sec: 1657846097, tv_nsec: 129747070 }
let now_str_digits_spaces: String = now_str.chars().filter(|c| c.is_digit(10) || *c == ',').collect(); //"1657846097,129747070"
let now_splitted: Vec<&str> = now_str_digits_spaces.split(",").collect(); //["1657846097", "129747070"]
let tv_sec:usize = now_splitted[0].parse().unwrap(); //1657846097
println!("Unix Time Now: {:?}", tv_sec);
return tv_sec;
}
13 changes: 13 additions & 0 deletions Scripts/rust/test_alloy_contract_write_erc20_weth/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "test_alloy"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tokio = { version = "1", features = ["full"] }
alloy = { version = "0.1.3", features = ["full"] }
eyre = "0.6.8"
url = "2.5.2"
# futures = "0.3.26"

0 comments on commit 8267640

Please sign in to comment.