Skip to content

Commit 0215d57

Browse files
authored
feat: track nonce (#2306)
1 parent 0fb4291 commit 0215d57

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

crates/chain-connector/src/connector.rs

+23-7
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ pub trait ChainConnector: Send + Sync {
8282
pub struct HttpChainConnector {
8383
client: Arc<jsonrpsee::http_client::HttpClient>,
8484
config: ChainConfig,
85-
tx_nonce_mutex: Arc<Mutex<()>>,
85+
tx_nonce_mutex: Arc<Mutex<Option<U256>>>,
8686
host_id: PeerId,
8787
}
8888

@@ -106,7 +106,7 @@ impl HttpChainConnector {
106106
let connector = Arc::new(Self {
107107
client: Arc::new(HttpClientBuilder::default().build(&config.http_endpoint)?),
108108
config,
109-
tx_nonce_mutex: Arc::new(Default::default()),
109+
tx_nonce_mutex: Arc::new(Mutex::new(None)),
110110
host_id,
111111
});
112112

@@ -458,8 +458,11 @@ impl HttpChainConnector {
458458
let max_fee_per_gas = base_fee + max_priority_fee_per_gas;
459459

460460
// We use this lock no ensure that we don't send two transactions with the same nonce
461-
let _lock = self.tx_nonce_mutex.lock().await;
462-
let nonce = self.get_tx_nonce().await?;
461+
let mut nonce_guard = self.tx_nonce_mutex.lock().await;
462+
let nonce = match *nonce_guard {
463+
None => self.get_tx_nonce().await?,
464+
Some(n) => n,
465+
};
463466

464467
// Create a new transaction
465468
let tx = Transaction::Eip1559 {
@@ -487,12 +490,25 @@ impl HttpChainConnector {
487490
self.config.wallet_key.to_address()
488491
);
489492

490-
let resp: String = process_response(
493+
let result: Result<String> = process_response(
491494
self.client
492495
.request("eth_sendRawTransaction", rpc_params![format!("0x{}", tx)])
493496
.await,
494-
)?;
495-
Ok(resp)
497+
);
498+
499+
match result {
500+
Ok(resp) => {
501+
let new_nonce = nonce + Uint::from(1);
502+
*nonce_guard = Some(new_nonce);
503+
tracing::debug!(target: "chain-connector", "Incrementing nonce. New nonce {new_nonce}");
504+
Ok(resp)
505+
}
506+
Err(err) => {
507+
tracing::warn!(target: "chain-connector", "Failed to send tx: {err}, resetting nonce");
508+
*nonce_guard = None;
509+
Err(err)
510+
}
511+
}
496512
}
497513

498514
pub async fn register_worker(

0 commit comments

Comments
 (0)