Skip to content

Commit

Permalink
correct some typos
Browse files Browse the repository at this point in the history
  • Loading branch information
musitdev committed Jun 30, 2024
1 parent 63b2e39 commit e2f5ee4
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 56 deletions.
82 changes: 41 additions & 41 deletions protocol-units/settlement/mcr/client/src/eth_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::send_eth_tx::InsufficentFunds;
use crate::send_eth_tx::InsufficientFunds;
use crate::send_eth_tx::SendTxErrorRule;
use crate::send_eth_tx::UnderPriced;
use crate::send_eth_tx::VerifyRule;
Expand Down Expand Up @@ -34,14 +34,14 @@ use tokio_stream::StreamExt;
#[derive(Error, Debug)]
pub enum McrEthConnectorError {
#[error(
"MCR Settlement Tx fail because gas estimation is to high. Estimated gas:{0} gas limit:{1}"
"MCR Settlement Tx fails because gas estimation is too high. Estimated gas:{0} gas limit:{1}"
)]
GasLimitExceed(u128, u128),
#[error("MCR Settlement Tx fail because account funds are insufficient. error:{0}")]
#[error("MCR Settlement Tx fails because account funds are insufficient. error:{0}")]
InsufficientFunds(String),
#[error("MCR Settlement Tx send fail because :{0}")]
#[error("MCR Settlement Tx send failed because :{0}")]
SendTxError(#[from] alloy_contract::Error),
#[error("MCR Settlement Tx send fail during its execution :{0}")]
#[error("MCR Settlement Tx send failed during its execution :{0}")]
RpcTxExecution(String),
#[error("MCR Settlement BlockAccepted event notification error :{0}")]
EventNotificationError(#[from] alloy_sol_types::Error),
Expand All @@ -58,8 +58,8 @@ sol!(
);

// When created, kill the pid when dropped.
// Use to kill Anvil process when Suzuka Node end.
// TODO should be removed by new config.
// Use to kill Anvil process when Suzuka Node ends.
// TODO should be removed by the new config.
struct AnvilKillAtDrop {
pid: u32,
}
Expand Down Expand Up @@ -149,7 +149,7 @@ impl<P> Client<P> {
let ws_provider = ProviderBuilder::new().on_ws(ws).await?;

let rule1: Box<dyn VerifyRule> = Box::new(SendTxErrorRule::<UnderPriced>::new());
let rule2: Box<dyn VerifyRule> = Box::new(SendTxErrorRule::<InsufficentFunds>::new());
let rule2: Box<dyn VerifyRule> = Box::new(SendTxErrorRule::<InsufficientFunds>::new());
let send_tx_error_rules = vec![rule1, rule2];

Ok(Client {
Expand Down Expand Up @@ -177,7 +177,7 @@ where
let contract = MCR::new(self.contract_address, &self.rpc_provider);

let eth_block_commitment = MCR::BlockCommitment {
// currently, to simplify the api, we'll say 0 is uncommitted all other numbers are legitimate heights
// Currently, to simplify the API, we'll say 0 is uncommitted all other numbers are legitimate heights
height: U256::from(block_commitment.height),
commitment: alloy_primitives::FixedBytes(block_commitment.commitment.0),
blockId: alloy_primitives::FixedBytes(block_commitment.block_id.0),
Expand All @@ -204,7 +204,7 @@ where
.into_iter()
.map(|block_commitment| {
Ok(MCR::BlockCommitment {
// currently, to simplify the api, we'll say 0 is uncommitted all other numbers are legitimate heights
// Currently, to simplify the API, we'll say 0 is uncommitted all other numbers are legitimate heights
height: U256::from(block_commitment.height),
commitment: alloy_primitives::FixedBytes(block_commitment.commitment.0),
blockId: alloy_primitives::FixedBytes(block_commitment.block_id.0),
Expand All @@ -224,7 +224,7 @@ where
}

async fn stream_block_commitments(&self) -> Result<CommitmentStream, anyhow::Error> {
//register to contract BlockCommitmentSubmitted event
// Register to contract BlockCommitmentSubmitted event

let contract = MCR::new(self.contract_address, &self.ws_provider);
let event_filter = contract.BlockAccepted_filter().watch().await?;
Expand Down Expand Up @@ -280,30 +280,30 @@ pub struct AnvilAddressEntry {
pub private_key: String,
}

/// Read the Anvil config file keys and return all address/private key.
/// Read the Anvil config file keys and return all address/private keys.
pub fn read_anvil_json_file_addresses<P: AsRef<Path>>(
anvil_conf_path: P,
) -> Result<Vec<AnvilAddressEntry>, anyhow::Error> {
let file_content = fs::read_to_string(anvil_conf_path)?;

let json_value: JsonValue = serde_json::from_str(&file_content)?;

// Extract the available_accounts and private_keys fields
// Extract the available_accounts and private_keys fields.
let available_accounts_iter = json_value["available_accounts"]
.as_array()
.expect("available_accounts should be an array")
.expect("Available_accounts should be an array")
.iter()
.map(|v| {
let s = v.as_str().expect("available_accounts elements should be strings");
let s = v.as_str().expect("Available_accounts elements should be strings");
s.to_owned()
});

let private_keys_iter = json_value["private_keys"]
.as_array()
.expect("private_keys should be an array")
.expect("Private_keys should be an array")
.iter()
.map(|v| {
let s = v.as_str().expect("private_keys elements should be strings");
let s = v.as_str().expect("Private_keys elements should be strings");
s.to_owned()
});

Expand All @@ -330,36 +330,36 @@ mod tests {
use std::env;
use std::fs;

// Define 2 validators (signer1 and signer2) with each a little more than 50% of stake.
// After genesis ceremony, 2 validator send the commitment for height 1.
// Validator2 send a commitment for height 2 to trigger next epoch and fire event.
// Wait the commitment accepted event.
// Define 2 validators (signer1 and signer2) with each a little more than 50% of the stake.
// After the genesis ceremony, 2 validators send the commitment for height 1.
// Validator2 sends a commitment for height 2 to trigger the next epoch and fire event.
// Wait for the commitment accepted event.
#[tokio::test]
async fn test_send_commitment() -> Result<(), anyhow::Error> {
//Activate to debug the test.
// use tracing_subscriber::EnvFilter;
// Activate to debug the test.
// Use tracing_subscriber::EnvFilter;

// tracing_subscriber::fmt()
// .with_env_filter(
// EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
// )
// .init();

// Inititalize Test variables
// Initialize Test variables
let rpc_port = env::var("MCR_ANVIL_PORT").unwrap();
let rpc_url = format!("http://localhost:{rpc_port}");
let ws_url = format!("ws://localhost:{rpc_port}");

let anvil_conf_file = env::var("ANVIL_JSON_PATH").context(
"ANVIL_JSON_PATH env var is not defined. It should point to the anvil json file",
"ANVIL_JSON_PATH env var is not defined. It should point to the anvil JSON file",
)?;
let anvil_addresses = crate::eth::utils::read_anvil_json_file_addresses(&anvil_conf_file)?;

//Do SC ceremony init stake calls.
// Do SC ceremony init stake calls.
do_genesis_ceremonial(&anvil_addresses, &rpc_url).await?;

let mcr_address = read_mcr_sc_adress()?;
//Define Signers. Ceremony define 2 signers with half stake each.
// Define Signers. The ceremony defines 2 signers with half stake each.
let signer1: LocalWallet = anvil_addresses[1].private_key.parse()?;
let signer1_addr = signer1.address();

Expand All @@ -370,26 +370,26 @@ mod tests {
..Default::default()
};

//Build client 1 and send first commitment.
// Build client 1 and send the first commitment.
let config1 =
Config { signer_private_key: Some(signer1_addr.to_string()), ..config.clone() };
let client1 = Client::build_with_config(config1).await.unwrap();

let mut client1_stream = client1.stream_block_commitments().await.unwrap();

//client post a new commitment
// Client posts a new commitment
let commitment =
BlockCommitment { height: 1, block_id: Id([2; 32]), commitment: Commitment([3; 32]) };

let res = client1.post_block_commitment(commitment.clone()).await;
assert!(res.is_ok());

//no notification quorum is not reach
// No notification quorum is not reached
let res =
tokio::time::timeout(tokio::time::Duration::from_secs(5), client1_stream.next()).await;
assert!(res.is_err());

//Build client 2 and send the second commitment.
// Build client 2 and send the second commitment.
let config2 = Config {
signer_private_key: Some(anvil_addresses[2].private_key.clone()),
..config.clone()
Expand All @@ -398,18 +398,18 @@ mod tests {

let mut client2_stream = client2.stream_block_commitments().await.unwrap();

//client post a new commitment
// Client posts a new commitment
let res = client2.post_block_commitment(commitment).await;
assert!(res.is_ok());

// now we move to block 2 and make some commitment just to trigger the epochRollover
// Now we move to block 2 and make some commitments just to trigger the epochRollover
let commitment2 =
BlockCommitment { height: 2, block_id: Id([4; 32]), commitment: Commitment([5; 32]) };

let res = client2.post_block_commitment(commitment2.clone()).await;
assert!(res.is_ok());

//validate that the accept commitment stream get the event.
// Validate that the accept commitment stream gets the event.
let event =
tokio::time::timeout(tokio::time::Duration::from_secs(5), client1_stream.next())
.await
Expand All @@ -427,13 +427,13 @@ mod tests {
assert_eq!(event.commitment.0[0], 3);
assert_eq!(event.block_id.0[0], 2);

//test post batch commitment
// post the complementary batch on height 2 and one on height 3
// Test post batch commitment
// Post the complementary batch on height 2 and one on height 3
let commitment3 =
BlockCommitment { height: 3, block_id: Id([6; 32]), commitment: Commitment([7; 32]) };
let res = client1.post_block_commitment_batch(vec![commitment2, commitment3]).await;
assert!(res.is_ok());
//validate that the accept commitment stream get the event.
// Validate that the accepted commitment stream gets the event.
let event =
tokio::time::timeout(tokio::time::Duration::from_secs(5), client1_stream.next())
.await
Expand All @@ -451,7 +451,7 @@ mod tests {
assert_eq!(event.commitment.0[0], 5);
assert_eq!(event.block_id.0[0], 4);

//test get_commitment_at_height
// Test get_commitment_at_height
let commitment = client1.get_commitment_at_height(1).await?;
assert!(commitment.is_some());
let commitment = commitment.unwrap();
Expand All @@ -471,13 +471,13 @@ mod tests {
}

// Do the Genesis ceremony in Rust because if node by forge script,
// it's never done from Rust call.
// It's never done from Rust's call.
async fn do_genesis_ceremonial(
anvil_addresses: &[AnvilAddressEntry],
rpc_url: &str,
) -> Result<(), anyhow::Error> {
let mcr_address = read_mcr_sc_adress()?;
//Define Signer. Signer1 is the MCRSettelement client
// Define Signer. Signer1 is the MCRSettelement client
let signer1: LocalWallet = anvil_addresses[1].private_key.parse()?;
let signer1_addr: Address = anvil_addresses[1].address.parse()?;
let signer1_rpc_provider = ProviderBuilder::new()
Expand All @@ -503,7 +503,7 @@ mod tests {
.on_http(rpc_url.parse()?);
let signer2_contract = MCR::new(mcr_address, &signer2_rpc_provider);

//init staking
// Init staking.
// Build a transaction to set the values.
stake_genesis(
&signer2_rpc_provider,
Expand Down
30 changes: 15 additions & 15 deletions protocol-units/settlement/mcr/client/src/send_eth_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use alloy_provider::Provider;
use alloy_transport::{Transport, TransportError};
use std::marker::PhantomData;

// Define a rule to verify the error generated when a tx is send to determine if:
// * the Tx must me resend with more gas: return Ok(true)
// * a specific error must be return: return Err(McrEthConnectorError::xxx);
// Define a rule to verify the error generated when a tx is sent to determine if:
// * the Tx must be resend with more gas: return Ok(true)
// * a specific error must be returned: return Err(McrEthConnectorError::xxx);
// * the rule doesn't apply: return Ok(false)
pub trait VerifyRule: Sync + Send {
fn verify(&self, error: &alloy_contract::Error) -> Result<bool, McrEthConnectorError>;
Expand All @@ -26,7 +26,7 @@ impl<Kind> SendTxErrorRule<Kind> {

// Define the current 2 errors managed.
pub struct UnderPriced;
pub struct InsufficentFunds;
pub struct InsufficientFunds;

impl VerifyRule for SendTxErrorRule<UnderPriced> {
fn verify(&self, error: &alloy_contract::Error) -> Result<bool, McrEthConnectorError> {
Expand All @@ -43,7 +43,7 @@ impl VerifyRule for SendTxErrorRule<UnderPriced> {
}
}
impl VerifyRule for SendTxErrorRule<InsufficentFunds> {
impl VerifyRule for SendTxErrorRule<InsufficientFunds> {
fn verify(&self, error: &alloy_contract::Error) -> Result<bool, McrEthConnectorError> {
let alloy_contract::Error::TransportError(TransportError::ErrorResp(payload)) = error
else {
Expand All @@ -68,34 +68,34 @@ pub async fn send_tx<
nb_retry: u32,
gas_limit: u128,
) -> Result<(), anyhow::Error> {
//validate gaz price.
// Validate gas price.
let mut estimate_gas = base_call_builder.estimate_gas().await?;
// Add 20% because initial gas estimate are too low.
// Add 20% because initial gas estimates are too low.
estimate_gas += (estimate_gas * 20) / 100;

// Sending Tx automatically can lead to errors that depend on the state for Eth.
// It's convenient to manage some of them automatically to avoid to fail commitment Tx.
// I define a first one but other should be added depending on the test with mainnet.
// It's convenient to manage some of them automatically to avoid failing commitment Tx.
// I define a first one but another should be added depending on the test with mainnet.
for _ in 0..nb_retry {
let call_builder = base_call_builder.clone().gas(estimate_gas);

//detect if the gas price doesn't execeed the limit.
// Detect if the gas price doesn't exceed the limit.
let gas_price = call_builder.provider.get_gas_price().await?;
let tx_fee_wei = estimate_gas * gas_price;
if tx_fee_wei > gas_limit {
return Err(McrEthConnectorError::GasLimitExceed(tx_fee_wei, gas_limit as u128).into());
}

//send the Tx and detect send error.
// Send the Tx and detect send error.
let pending_tx = match call_builder.send().await {
Ok(pending_tx) => pending_tx,
Err(err) => {
//apply defined rules.
// Apply defined rules.
for rule in send_tx_error_rules {
// Verify all rules. If one rule return true or an error stop verification.
// Verify all rules. If one rule returns true or an error stop verification.
// If true retry with more gas else return the error.
if rule.verify(&err)? {
//increase gas of 10% and retry
// Increase gas by 10% and retry
estimate_gas += (estimate_gas * 10) / 100;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
continue;
Expand All @@ -107,7 +107,7 @@ pub async fn send_tx<
};

match pending_tx.get_receipt().await {
// Tx execution fail
// Tx execution fails
Ok(tx_receipt) if !tx_receipt.status() => {
tracing::debug!(
"tx_receipt.gas_used: {} / estimate_gas: {estimate_gas}",
Expand Down

0 comments on commit e2f5ee4

Please sign in to comment.