use std::str::FromStr;
use anyhow::anyhow;
use subxt::{ext::sp_core::Pair, tx::PairSigner, PolkadotConfig};
use crate::{AccountId, RawKeyPair};
pub struct KeyPair {
inner: PairSigner<PolkadotConfig, RawKeyPair>,
}
impl Clone for KeyPair {
fn clone(&self) -> Self {
KeyPair::new(self.inner.signer().clone())
}
}
impl FromStr for KeyPair {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
let pair = Pair::from_string(s, None)
.map_err(|e| anyhow!("Can't create pair from seed value: {:?}", e))?;
Ok(KeyPair::new(pair))
}
}
impl KeyPair {
pub fn new(keypair: RawKeyPair) -> Self {
KeyPair {
inner: PairSigner::new(keypair),
}
}
pub fn pair_signer(&self) -> &PairSigner<PolkadotConfig, RawKeyPair> {
&self.inner
}
pub fn raw_key_pair(&self) -> &RawKeyPair {
self.inner.signer()
}
pub fn account_id(&self) -> &AccountId {
self.inner.account_id()
}
}
pub fn keypair_from_string(seed: &str) -> KeyPair {
KeyPair::new(raw_keypair_from_string(seed))
}
pub fn raw_keypair_from_string(seed: &str) -> RawKeyPair {
Pair::from_string(seed, None).expect("Can't create pair from seed value")
}
pub fn account_from_keypair<P>(keypair: &P) -> AccountId
where
P: Pair,
AccountId: From<<P as Pair>::Public>,
{
AccountId::from(keypair.public())
}