polymesh_api_client/
lockable_signer.rs

1use core::ops::{Deref, DerefMut};
2use std::sync::Arc;
3
4use sp_runtime::MultiSignature;
5use sp_std::prelude::*;
6
7use tokio::sync::{Mutex, OwnedMutexGuard};
8
9use async_trait::async_trait;
10
11#[cfg(not(feature = "std"))]
12use alloc::string::ToString;
13
14use crate::*;
15
16#[derive(Clone)]
17pub struct LockableSigner<S>(Arc<Mutex<S>>);
18
19impl<S: Signer + 'static> LockableSigner<S> {
20  pub fn new(signer: S) -> Self {
21    Self(Arc::new(Mutex::new(signer)))
22  }
23
24  pub async fn lock(&self) -> LockedSigner<S> {
25    LockedSigner(self.0.clone().lock_owned().await)
26  }
27}
28
29pub struct LockedSigner<S>(OwnedMutexGuard<S>);
30
31impl<S> Deref for LockedSigner<S> {
32  type Target = S;
33
34  fn deref(&self) -> &Self::Target {
35    &self.0
36  }
37}
38
39impl<S> DerefMut for LockedSigner<S> {
40  fn deref_mut(&mut self) -> &mut Self::Target {
41    &mut self.0
42  }
43}
44
45#[async_trait]
46impl<S: Signer> Signer for LockedSigner<S> {
47  fn account(&self) -> AccountId {
48    self.0.account()
49  }
50
51  async fn nonce(&self) -> Option<u32> {
52    self.0.nonce().await
53  }
54
55  async fn set_nonce(&mut self, nonce: u32) {
56    self.0.set_nonce(nonce).await
57  }
58
59  async fn sign(&self, msg: &[u8]) -> Result<MultiSignature> {
60    self.0.sign(msg).await
61  }
62}