@@ -178,17 +178,28 @@ where
178178 "Error sending transaction. Checking onchain nonce."
179179 ) ;
180180 let onchain_nonce = self . get_transaction_count ( self . address , block) . await ?;
181+ let onchain_nonce_u64 = onchain_nonce. as_u64 ( ) ;
181182 let internal_nonce = self . nonce . load ( Ordering :: SeqCst ) ;
182- if onchain_nonce != internal_nonce. into ( ) {
183- // try re-submitting the transaction with the correct nonce if there
184- // was a nonce mismatch
183+ // a tx was just sent and an error was returned.
184+ // for this tx to land, it needs to have used `onchain_nonce`
185+ // but since the internal nonce is incremented by 1 after its value is read,
186+ // the nonce used to broadcast the tx was `internal_nonce - 1`.
187+ // so we need to check if the onchain nonce is equal to the last used nonce
188+ let last_used_nonce = internal_nonce. saturating_sub ( 1 ) ;
189+ if onchain_nonce_u64 != last_used_nonce {
185190 self . nonce . store ( onchain_nonce. as_u64 ( ) , Ordering :: SeqCst ) ;
186- tx. set_nonce ( onchain_nonce) ;
191+ // the nonce was just resynced so this counter can be reset
192+ tracing:: debug!( ?nonce, "Resynced internal nonce with onchain nonce" ) ;
193+ self . txs_since_resync . store ( 0 , Ordering :: SeqCst ) ;
194+ // call `nonce.next()` to increment the internal nonce after it's read
195+ let tx_nonce = self . next ( ) ;
196+ tx. set_nonce ( tx_nonce) ;
197+
187198 tracing:: warn!(
188- onchain_nonce=?onchain_nonce . as_u64 ( ) ,
189- ?internal_nonce ,
199+ onchain_nonce=?onchain_nonce_u64 ,
200+ ?last_used_nonce ,
190201 error=?err,
191- "Onchain nonce didn't match internal nonce. Resending transaction with updated nonce."
202+ "Onchain nonce didn't match last used nonce. Resending transaction with updated nonce."
192203 ) ;
193204 self . inner
194205 . send_transaction ( tx, block)
0 commit comments