Skip to content

Commit 27ffc63

Browse files
committed
fix: storage for nonces in near client
1 parent c7cc976 commit 27ffc63

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

src/client/near.rs

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ use std::str::FromStr;
3838
use std::sync::atomic::{AtomicU64, Ordering};
3939
use std::sync::Arc;
4040
use std::time::Duration;
41-
use tokio::sync::RwLock;
41+
use tokio::sync::Mutex;
4242

4343
#[cfg(feature = "advanced")]
4444
use super::TransactionOutcome;
@@ -52,7 +52,7 @@ pub struct NearClient {
5252
client: JsonRpcClient,
5353
pub engine_account_id: AccountId,
5454
signer_key_path: Option<String>,
55-
access_key_nonces: Arc<RwLock<HashMap<(AccountId, PublicKey), AtomicU64>>>,
55+
access_key_nonces: Arc<Mutex<HashMap<(AccountId, PublicKey), AtomicU64>>>,
5656
}
5757

5858
impl NearClient {
@@ -74,7 +74,7 @@ impl NearClient {
7474
client,
7575
engine_account_id: engine_account_id.parse().unwrap(),
7676
signer_key_path,
77-
access_key_nonces: Arc::new(RwLock::new(HashMap::new())),
77+
access_key_nonces: Arc::new(Mutex::new(HashMap::new())),
7878
}
7979
}
8080

@@ -477,31 +477,26 @@ impl NearClient {
477477
}
478478

479479
pub async fn get_nonce(&self, signer: &InMemorySigner) -> anyhow::Result<(CryptoHash, u64)> {
480-
let nonces = self.access_key_nonces.read().await;
480+
let mut nonces = self.access_key_nonces.lock().await;
481481
let cache_key = (signer.account_id.clone(), signer.secret_key.public_key());
482482

483483
if let Some(nonce) = nonces.get(&cache_key) {
484484
let nonce = nonce.fetch_add(1, Ordering::SeqCst);
485-
drop(nonces);
486485
// Fetch latest block_hash since the previous one is now invalid for new transactions:
487486
let block = self.view_block(Some(Finality::Final.into())).await?;
488487

489488
Ok((block.header.hash, nonce + 1))
490489
} else {
491-
drop(nonces);
492490
let (block_hash, nonce) = self.get_nonce_block_hash(&cache_key).await?;
493491
// case where multiple writers end up at the same lock acquisition point and tries
494492
// to overwrite the cached value that a previous writer already wrote.
495-
let nonce = self
496-
.access_key_nonces
497-
.write()
498-
.await
493+
let nonce = nonces
499494
.entry(cache_key)
500-
.or_insert_with(|| AtomicU64::new(nonce + 1))
501-
.fetch_max(nonce + 1, Ordering::SeqCst)
502-
.max(nonce + 1);
495+
.or_insert_with(|| AtomicU64::new(nonce))
496+
.fetch_add(1, Ordering::SeqCst);
497+
drop(nonces);
503498

504-
Ok((block_hash, nonce))
499+
Ok((block_hash, nonce + 1))
505500
}
506501
}
507502

0 commit comments

Comments
 (0)