2021-04-09 00:22:17 +00:00
|
|
|
use std::str::FromStr;
|
|
|
|
|
2022-01-26 13:01:05 +00:00
|
|
|
use secp256k1::SecretKey;
|
2021-04-09 00:22:17 +00:00
|
|
|
use web3::{
|
2022-01-26 13:01:05 +00:00
|
|
|
signing::Key,
|
2021-04-09 00:22:17 +00:00
|
|
|
types::Address,
|
|
|
|
};
|
|
|
|
|
2022-08-04 12:07:57 +00:00
|
|
|
use crate::utils::caip2::ChainId;
|
|
|
|
|
2022-01-25 22:17:28 +00:00
|
|
|
#[derive(thiserror::Error, Debug)]
|
|
|
|
pub enum ChainIdError {
|
|
|
|
#[error("unsupported chain")]
|
|
|
|
UnsupportedChain,
|
|
|
|
|
|
|
|
#[error("invalid EIP155 chain ID")]
|
|
|
|
InvalidEip155ChainId(#[from] std::num::ParseIntError),
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses CAIP-2 chain ID
|
2022-08-10 11:14:17 +00:00
|
|
|
pub fn parse_caip2_chain_id(chain_id: &ChainId) -> Result<u32, ChainIdError> {
|
2022-08-30 20:33:45 +00:00
|
|
|
if !chain_id.is_ethereum() {
|
2022-01-25 22:17:28 +00:00
|
|
|
return Err(ChainIdError::UnsupportedChain);
|
|
|
|
};
|
2022-08-04 12:07:57 +00:00
|
|
|
let eth_chain_id: u32 = chain_id.reference.parse()?;
|
2022-01-25 22:17:28 +00:00
|
|
|
Ok(eth_chain_id)
|
|
|
|
}
|
|
|
|
|
2022-01-26 13:01:05 +00:00
|
|
|
pub fn key_to_ethereum_address(private_key: &SecretKey) -> Address {
|
|
|
|
private_key.address()
|
2021-04-09 00:22:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(thiserror::Error, Debug)]
|
|
|
|
#[error("address error")]
|
|
|
|
pub struct AddressError;
|
|
|
|
|
|
|
|
pub fn parse_address(address: &str) -> Result<Address, AddressError> {
|
|
|
|
Address::from_str(address).map_err(|_| AddressError)
|
|
|
|
}
|
|
|
|
|
2022-04-16 21:22:07 +00:00
|
|
|
/// Converts address object to lowercase hex string
|
|
|
|
pub fn address_to_string(address: Address) -> String {
|
|
|
|
format!("{:#x}", address)
|
|
|
|
}
|
|
|
|
|
2022-01-25 22:17:28 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_parse_caip2_chain_id() {
|
2022-08-10 11:14:17 +00:00
|
|
|
let chain_id: ChainId = "eip155:1".parse().unwrap();
|
|
|
|
let result = parse_caip2_chain_id(&chain_id).unwrap();
|
2022-01-25 22:17:28 +00:00
|
|
|
assert_eq!(result, 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_parse_caip2_chain_id_unsupported() {
|
2022-08-10 11:14:17 +00:00
|
|
|
let chain_id: ChainId = "bip122:000000000019d6689c085ae165831e93".parse().unwrap();
|
|
|
|
let error = parse_caip2_chain_id(&chain_id).err().unwrap();
|
2022-01-25 22:17:28 +00:00
|
|
|
assert!(matches!(error, ChainIdError::UnsupportedChain));
|
|
|
|
}
|
|
|
|
}
|