2022-08-04 12:07:57 +00:00
|
|
|
use std::convert::TryFrom;
|
|
|
|
|
|
|
|
use crate::errors::ConversionError;
|
|
|
|
use super::caip2::ChainId;
|
2022-04-26 14:12:26 +00:00
|
|
|
|
2022-08-04 12:07:57 +00:00
|
|
|
#[derive(Debug, PartialEq)]
|
2022-04-27 18:14:15 +00:00
|
|
|
pub enum Currency {
|
|
|
|
Ethereum,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Currency {
|
|
|
|
fn code(&self) -> String {
|
|
|
|
match self {
|
|
|
|
Self::Ethereum => "ETH",
|
|
|
|
}.to_string()
|
|
|
|
}
|
2022-04-27 11:05:46 +00:00
|
|
|
|
2022-08-04 15:44:48 +00:00
|
|
|
pub fn field_name(&self) -> String {
|
|
|
|
format!("${}", self.code())
|
|
|
|
}
|
|
|
|
|
2022-08-04 12:07:57 +00:00
|
|
|
/// Returns CAIP-2 chain ID
|
|
|
|
pub fn chain_id(&self) -> ChainId {
|
|
|
|
self.into()
|
2022-04-27 11:05:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn normalize_address(&self, address: &str) -> String {
|
|
|
|
match self {
|
|
|
|
Self::Ethereum => address.to_lowercase(),
|
|
|
|
}
|
|
|
|
}
|
2022-04-27 18:14:15 +00:00
|
|
|
}
|
|
|
|
|
2022-08-04 12:07:57 +00:00
|
|
|
impl From<&Currency> for ChainId {
|
|
|
|
fn from(value: &Currency) -> Self {
|
|
|
|
let (namespace, reference) = match value {
|
|
|
|
Currency::Ethereum => ("eip155", "1"),
|
|
|
|
};
|
|
|
|
Self {
|
|
|
|
namespace: namespace.to_string(),
|
|
|
|
reference: reference.to_string(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TryFrom<&ChainId> for Currency {
|
|
|
|
type Error = ConversionError;
|
|
|
|
|
|
|
|
fn try_from(value: &ChainId) -> Result<Self, Self::Error> {
|
|
|
|
let currency = match value.namespace.as_str() {
|
|
|
|
"eip155" => match value.reference.as_str() {
|
|
|
|
"1" => Self::Ethereum,
|
|
|
|
_ => return Err(ConversionError),
|
|
|
|
},
|
|
|
|
_ => return Err(ConversionError),
|
|
|
|
};
|
|
|
|
Ok(currency)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-27 18:14:15 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
2022-08-04 12:07:57 +00:00
|
|
|
#[test]
|
|
|
|
fn test_chain_id_conversion() {
|
|
|
|
let ethereum = Currency::Ethereum;
|
|
|
|
let ethereum_chain_id = ChainId::from(ðereum);
|
|
|
|
let currency = Currency::try_from(ðereum_chain_id).unwrap();
|
|
|
|
assert_eq!(currency, ethereum);
|
|
|
|
}
|
|
|
|
|
2022-04-27 18:14:15 +00:00
|
|
|
#[test]
|
|
|
|
fn test_get_currency_field_name() {
|
|
|
|
let ethereum = Currency::Ethereum;
|
2022-08-04 15:44:48 +00:00
|
|
|
assert_eq!(ethereum.field_name(), "$ETH");
|
2022-04-27 18:14:15 +00:00
|
|
|
}
|
|
|
|
}
|