Skip to content
This repository has been archived by the owner on Feb 28, 2025. It is now read-only.

Some bugs during demo development #66

Merged
merged 4 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- name: Install cargo-llvm-cov
run: curl -LsSf https://github.com/taiki-e/cargo-llvm-cov/releases/latest/download/cargo-llvm-cov-x86_64-unknown-linux-gnu.tar.gz | tar xzf - -C ~/.cargo/bin
- name: Generate code coverage
run: RUST_LOG=xps_gateway=info,registry=info,inbox=info,messaging=info,gateway_types=info cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info
run: RUST_LOG=xps_gateway=info,registry=info,inbox=info,messaging=info,gateway_types=info cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info --exclude registry-localnet
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
Expand Down
33 changes: 33 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
14 changes: 14 additions & 0 deletions bin/registry-localnet/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[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
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 @@
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<()> {

Check warning on line 18 in lib-xps/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

lib-xps/src/lib.rs#L18

Added line #L18 was not covered by tests
crate::util::init_logging();

let server_addr = format!("{}:{}", host, port);
Expand All @@ -26,9 +26,7 @@

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();

Check warning on line 29 in lib-xps/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

lib-xps/src/lib.rs#L29

Added line #L29 was not covered by tests

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
Loading
Loading