Skip to content

Commit

Permalink
bug fixing & QoL improvments
Browse files Browse the repository at this point in the history
- fix bug where we generated two wallets in methods & gateway context
  leading to insufficient funds error
 - add a `registry-localnet` binary that launches an anvil instance with
   the registry already deployed
- generally add some more logging
  • Loading branch information
insipx committed Feb 13, 2024
1 parent 18f851d commit 15f23c3
Show file tree
Hide file tree
Showing 9 changed files with 191 additions and 18 deletions.
35 changes: 35 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ members = [
"messaging",
"inbox",
"registry",
"xps-types",
"xps-types", "bin/registry-localnet",
]

exclude = []
Expand Down
16 changes: 16 additions & 0 deletions bin/registry-localnet/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "registry-localnet"
version = "0.1.0"
edition = "2021"

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

[dependencies]
ethers.workspace = true
anyhow.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
ctrlc = "3.4.2"
lib-didethresolver.workspace = true
hex.workspace = true
97 changes: 97 additions & 0 deletions bin/registry-localnet/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
use anyhow::Error;
use ethers::{
abi::Address,
core::utils::Anvil,
middleware::SignerMiddleware,
providers::{Provider, Ws},
signers::{LocalWallet, Signer as _},
utils::AnvilInstance,
};
use lib_didethresolver::did_registry::DIDRegistry;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Error> {
let running = Arc::new(AtomicBool::new(true));
let r = running.clone();

ctrlc::set_handler(move || {
r.store(false, Ordering::SeqCst);
})
.expect("Error setting Ctrl-C handler");

let anvil = deploy().await?;

println!("Waiting for Ctrl-C...");
while running.load(Ordering::SeqCst) {}
drop(anvil);
println!("Shutting down...");
Ok(())
}

async fn deploy() -> Result<AnvilInstance, Error> {
let anvil = Anvil::new()
.port(8545_u16)
.args(vec![
"--base-fee",
"35",
"--gas-price",
"50",
"--disable-block-gas-limit",
])
.spawn();
let registry_address = deploy_to_anvil(&anvil).await?;
println!(
"Registry deployed at {}, at endpoint {}",
hex::encode(registry_address),
anvil.ws_endpoint()
);

println!("Chain ID: {}", anvil.chain_id());
println!("Endpoint: {}", anvil.endpoint());
println!("WS Endpoint: {}", anvil.ws_endpoint());

println!("\n\n");
println!("Private Keys -------------------------------------");
for key in anvil.keys() {
println!("0x{}", hex::encode(key.to_bytes()));
}
println!("\n\n");
println!("Addresses -------------------------------------");
for address in anvil.addresses() {
println!("0x{}", hex::encode(address));
}

Ok(anvil)
}

async fn deploy_to_anvil(anvil: &AnvilInstance) -> Result<Address, Error> {
println!("Deploying Registry to local anvil");

let wallet: LocalWallet = anvil.keys()[0].clone().into();
let client = client(anvil, wallet).await;

let registry = DIDRegistry::deploy(client.clone(), ())
.unwrap()
.gas_price(100)
.send()
.await
.unwrap();

Ok(registry.address())
}

async fn client(
anvil: &AnvilInstance,
wallet: LocalWallet,
) -> Arc<SignerMiddleware<Provider<Ws>, LocalWallet>> {
let provider = Provider::<Ws>::connect(anvil.ws_endpoint())
.await
.unwrap()
.interval(std::time::Duration::from_millis(10u64));
Arc::new(SignerMiddleware::new(
provider,
wallet.with_chain_id(anvil.chain_id()),
))
}
6 changes: 2 additions & 4 deletions lib-xps/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub use crate::rpc::{XpsClient, XpsMethods, XpsServer};
use crate::types::GatewayContext;

/// Entrypoint for the xps Gateway
pub async fn run(host: String, port: u16) -> Result<()> {
pub async fn run<P: AsRef<str>>(host: String, port: u16, provider: P) -> Result<()> {
crate::util::init_logging();

let server_addr = format!("{}:{}", host, port);
Expand All @@ -26,9 +26,7 @@ pub async fn run(host: String, port: u16) -> Result<()> {

let registry_contract = Address::from_str(DID_ETH_REGISTRY)?;
let conversation_contract = Address::from_str(CONVERSATION)?;
let provider = Provider::<Ws>::connect("wss://ethereum-sepolia.publicnode.com")
.await
.unwrap();
let provider = Provider::<Ws>::connect(provider.as_ref()).await.unwrap();

let context = GatewayContext::new(registry_contract, conversation_contract, provider).await?;
let xps_methods = rpc::XpsMethods::new(&context);
Expand Down
15 changes: 8 additions & 7 deletions lib-xps/src/rpc/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use ethers::{
use jsonrpsee::types::ErrorObjectOwned;
use lib_didethresolver::types::XmtpAttribute;
use messaging::MessagingOperations;
use rand::{rngs::StdRng, SeedableRng};
use std::sync::Arc;
use thiserror::Error;
use xps_types::{
Expand All @@ -31,7 +30,6 @@ pub const DEFAULT_ATTRIBUTE_VALIDITY: u64 = 60 * 60 * 24 * 365;
pub struct XpsMethods<P: Middleware + 'static> {
message_operations: MessagingOperations<GatewaySigner<P>>,
contact_operations: ContactOperations<GatewaySigner<P>>,
pub wallet: LocalWallet,
pub signer: Arc<GatewaySigner<P>>,
}

Expand All @@ -40,7 +38,6 @@ impl<P: Middleware> XpsMethods<P> {
Self {
message_operations: MessagingOperations::new(context.conversation.clone()),
contact_operations: ContactOperations::new(context.registry.clone()),
wallet: LocalWallet::new(&mut StdRng::from_entropy()),
signer: context.signer.clone(),
}
}
Expand Down Expand Up @@ -81,8 +78,10 @@ impl<P: Middleware + 'static> XpsServer for XpsMethods<P> {
signature,
U256::from(DEFAULT_ATTRIBUTE_VALIDITY),
)
.await
.map_err(RpcError::from)?;
.await;

log::debug!("{:?}", result);
let result = result.map_err(RpcError::from)?;

Ok(result)
}
Expand All @@ -104,7 +103,8 @@ impl<P: Middleware + 'static> XpsServer for XpsMethods<P> {
}

async fn wallet_address(&self) -> Result<Address, ErrorObjectOwned> {
Ok(self.wallet.address())
log::debug!("xps_walletAddress called");
Ok(self.signer.signer().address())
}

/// Fetches the current balance of the wallet in Ether.
Expand All @@ -120,11 +120,12 @@ impl<P: Middleware + 'static> XpsServer for XpsMethods<P> {
/// balance could not be fetched or converted.
///
async fn balance(&self) -> Result<WalletBalance, ErrorObjectOwned> {
log::debug!("xps_balance called");
// Fetch the balance in wei (the smallest unit of Ether) from the blockchain.
let wei_balance: U256 = self
.signer
.provider()
.get_balance(self.wallet.address(), None)
.get_balance(self.signer.signer().address(), None)
.await
.map_err::<RpcError<P>, _>(RpcError::from)?;

Expand Down
12 changes: 11 additions & 1 deletion registry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,20 @@ where
.send()
.await?
.await?;

if let Some(ref receipt) = transaction_receipt {
log::debug!(
"Gas Used by transaction {}, Gas used in block {}, effective_price {}",
receipt.gas_used.unwrap_or(0.into()),
receipt.cumulative_gas_used,
receipt.effective_gas_price.unwrap_or(0.into())
);
}

Ok(GrantInstallationResult {
status: Status::Success,
message: "Installation request complete.".to_string(),
transaction: transaction_receipt.unwrap().transaction_hash.to_string(),
transaction: transaction_receipt.map(|r| r.transaction_hash),
})
}

Expand Down
9 changes: 5 additions & 4 deletions xps-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@

pub mod error;

use ethers::types::U256;
use ethers::types::{Address, Bytes as EthersBytes, Signature};
use ethers::types::{H256, U256};
use ethers::utils::format_units;
use std::fmt;

use serde::{Deserialize, Serialize};
use std::fmt::Display;

/// Address of the did:ethr Registry on Sepolia
pub const DID_ETH_REGISTRY: &str = "0xd1D374DDE031075157fDb64536eF5cC13Ae75000";
// Address of the Converstion on Sepolia
// pub const DID_ETH_REGISTRY: &str = "0xd1D374DDE031075157fDb64536eF5cC13Ae75000";
pub const DID_ETH_REGISTRY: &str = "0x5fbdb2315678afecb367f032d93f642f64180aa3";
// Address of the Conversation on Sepolia
pub const CONVERSATION: &str = "0x15aE865d0645816d8EEAB0b7496fdd24227d1801";

/// A message sent to a conversation
Expand Down Expand Up @@ -49,7 +50,7 @@ pub type Bytes = Vec<u8>;
pub struct GrantInstallationResult {
pub status: Status,
pub message: String,
pub transaction: String,
pub transaction: Option<H256>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
Expand Down
17 changes: 16 additions & 1 deletion xps/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@ struct Args {
port: u16,
#[arg(short = 's', long = "host", default_value = "127.0.0.1")]
host: String,
#[arg(
short = 'e',
long = "endpoint",
default_value = "wss://ethereum-sepolia.publicnode.com"
)]
endpoint: String,
}

#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
crate::run(args.host, args.port).await?;
crate::run(args.host, args.port, args.endpoint).await?;
Ok(())
}

Expand Down Expand Up @@ -60,6 +66,15 @@ mod tests {
let args = Args::parse_from(arg_list);
assert_eq!(args.port, 0);
assert_eq!(args.host, "127.0.0.1");
assert_eq!(args.endpoint, "wss://ethereum-sepolia.publicnode.com");
Ok(())
}

#[test]
fn test_endpoint() -> Result<()> {
let arg_list = vec!["xps", "--endpoint", "http://localhost:8545"];
let args = Args::parse_from(arg_list);
assert_eq!(args.endpoint, "http://localhost:8545");
Ok(())
}
}

0 comments on commit 15f23c3

Please sign in to comment.