use std::fmt;
use bech32::{Bech32, primitives::decode::CheckedHrpstring};
use serde::{Deserialize, Serialize};
use crate::{
domain::{Amount, U256},
error::{Error, ValidationError},
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum AccountPrefix {
#[serde(rename = "thor")]
Thor,
#[serde(rename = "tthor")]
Tthor,
#[serde(rename = "sthor")]
Sthor,
#[serde(rename = "cthor")]
Cthor,
}
impl AccountPrefix {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Thor => "thor",
Self::Tthor => "tthor",
Self::Sthor => "sthor",
Self::Cthor => "cthor",
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "NetworkFields")]
pub struct Network {
chain_id: String,
account_prefix: AccountPrefix,
alias: String,
}
impl Network {
pub fn new(chain_id: &str, account_prefix: AccountPrefix, alias: &str) -> Result<Self, Error> {
if !valid_id(chain_id, 50) || !super::super::valid_label(alias, 64) {
return Err(ValidationError::InvalidThorchainNetwork.into());
}
Ok(Self {
chain_id: chain_id.to_owned(),
account_prefix,
alias: alias.to_owned(),
})
}
#[must_use]
pub fn chain_id(&self) -> &str {
&self.chain_id
}
#[must_use]
pub const fn account_prefix(&self) -> AccountPrefix {
self.account_prefix
}
#[must_use]
pub fn alias(&self) -> &str {
&self.alias
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NetworkFields {
chain_id: String,
account_prefix: AccountPrefix,
alias: String,
}
impl TryFrom<NetworkFields> for Network {
type Error = Error;
fn try_from(v: NetworkFields) -> Result<Self, Error> {
Self::new(&v.chain_id, v.account_prefix, &v.alias)
}
}
fn valid_id(value: &str, cap: usize) -> bool {
!value.is_empty()
&& value.len() <= cap
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Address(String);
impl Address {
pub fn parse(value: &str) -> Result<Self, Error> {
let invalid = || Error::from(ValidationError::InvalidThorchainAddress);
if value.len() > 90 {
return Err(invalid());
}
let checked = CheckedHrpstring::new::<Bech32>(value).map_err(|_| invalid())?;
let prefix = checked.hrp().to_string().to_ascii_lowercase();
if !matches!(prefix.as_str(), "thor" | "tthor" | "sthor" | "cthor") {
return Err(invalid());
}
let bytes: Vec<u8> = checked.byte_iter().collect();
if bytes.len() != 20 {
return Err(invalid());
}
let canonical = bech32::encode::<Bech32>(checked.hrp(), &bytes)
.map_err(|_| invalid())?
.to_ascii_lowercase();
if !canonical.eq_ignore_ascii_case(value) {
return Err(invalid());
}
Ok(Self(canonical))
}
#[must_use]
pub fn prefix(&self) -> AccountPrefix {
if self.0.starts_with("tthor1") {
AccountPrefix::Tthor
} else if self.0.starts_with("sthor1") {
AccountPrefix::Sthor
} else if self.0.starts_with("cthor1") {
AccountPrefix::Cthor
} else {
AccountPrefix::Thor
}
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for Address {
type Error = Error;
fn try_from(v: String) -> Result<Self, Error> {
Self::parse(&v)
}
}
impl From<Address> for String {
fn from(v: Address) -> Self {
v.0
}
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Chain(String);
impl Chain {
pub fn parse(value: &str) -> Result<Self, Error> {
if !(3..=10).contains(&value.len()) || !value.bytes().all(|b| b.is_ascii_alphabetic()) {
return Err(ValidationError::InvalidThorchainAsset.into());
}
Ok(Self(value.to_ascii_uppercase()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for Chain {
type Error = Error;
fn try_from(v: String) -> Result<Self, Error> {
Self::parse(&v)
}
}
impl From<Chain> for String {
fn from(v: Chain) -> Self {
v.0
}
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AssetKind {
LayerOne,
Synthetic,
Trade,
Secured,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Asset {
chain: Chain,
symbol: String,
kind: AssetKind,
}
impl Asset {
pub fn parse(value: &str) -> Result<Self, Error> {
let invalid = || Error::from(ValidationError::InvalidThorchainAsset);
if value.len() > 256 {
return Err(invalid());
}
let (index, delimiter) = value
.char_indices()
.find(|(_, c)| matches!(c, '.' | '/' | '~' | '-'))
.ok_or_else(invalid)?;
let chain = Chain::parse(&value[..index])?;
let symbol = &value[index + 1..];
if symbol.is_empty()
|| !symbol
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_'))
{
return Err(invalid());
}
let kind = match delimiter {
'/' => AssetKind::Synthetic,
'~' => AssetKind::Trade,
'-' => AssetKind::Secured,
_ => AssetKind::LayerOne,
};
if kind != AssetKind::LayerOne && chain.as_str() == "THOR" {
return Err(invalid());
}
Ok(Self {
chain,
symbol: symbol.to_ascii_uppercase(),
kind,
})
}
#[must_use]
pub const fn chain(&self) -> &Chain {
&self.chain
}
#[must_use]
pub fn symbol(&self) -> &str {
&self.symbol
}
#[must_use]
pub const fn kind(&self) -> AssetKind {
self.kind
}
#[must_use]
pub fn is_thor_held(&self) -> bool {
self.chain.as_str() == "THOR" || self.kind != AssetKind::LayerOne
}
}
impl fmt::Display for Asset {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let separator = match self.kind {
AssetKind::LayerOne => '.',
AssetKind::Synthetic => '/',
AssetKind::Trade => '~',
AssetKind::Secured => '-',
};
write!(f, "{}{separator}{}", self.chain.as_str(), self.symbol)
}
}
impl TryFrom<String> for Asset {
type Error = Error;
fn try_from(v: String) -> Result<Self, Error> {
Self::parse(&v)
}
}
impl From<Asset> for String {
fn from(v: Asset) -> Self {
v.to_string()
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "ChainAddressFields")]
pub struct ChainAddress {
chain: Chain,
address: Text,
}
impl ChainAddress {
pub fn new(chain: Chain, address: &str) -> Result<Self, Error> {
if address.is_empty()
|| address.len() > 256
|| !address.bytes().all(|b| b.is_ascii_graphic())
{
return Err(super::invalid_record());
}
let text = if chain.as_str() == "THOR" {
Address::parse(address)?.as_str().to_owned()
} else {
address.to_owned()
};
Ok(Self {
chain,
address: Text::new(&text)?,
})
}
#[must_use]
pub const fn chain(&self) -> &Chain {
&self.chain
}
#[must_use]
pub fn as_str(&self) -> &str {
self.address.as_str()
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ChainAddressFields {
chain: Chain,
address: Text,
}
impl TryFrom<ChainAddressFields> for ChainAddress {
type Error = Error;
fn try_from(v: ChainAddressFields) -> Result<Self, Error> {
Self::new(v.chain, v.address.as_str())
}
}
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Text(String);
impl Text {
pub fn new(value: &str) -> Result<Self, Error> {
if value.len() > 4096 || value.chars().any(char::is_control) {
return Err(super::invalid_record());
}
Ok(Self(value.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for Text {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Text")
.field("bytes", &self.0.len())
.finish()
}
}
impl TryFrom<String> for Text {
type Error = Error;
fn try_from(v: String) -> Result<Self, Error> {
Self::new(&v)
}
}
impl From<Text> for String {
fn from(v: Text) -> Self {
v.0
}
}
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct TransactionMemo(String);
impl TransactionMemo {
pub const MAXIMUM_BYTES: usize = 250;
pub fn new(value: &str) -> Result<Self, Error> {
if value.len() > Self::MAXIMUM_BYTES {
return Err(super::invalid_record());
}
Ok(Self(value.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for TransactionMemo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TransactionMemo")
.field("bytes", &self.0.len())
.finish()
}
}
impl TryFrom<String> for TransactionMemo {
type Error = Error;
fn try_from(value: String) -> Result<Self, Error> {
Self::new(&value)
}
}
impl From<TransactionMemo> for String {
fn from(value: TransactionMemo) -> Self {
value.0
}
}
macro_rules! quantity {
($name:ident, $description:literal) => {
#[doc = $description]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct $name(U256);
impl $name {
#[must_use]
pub const fn new(value: U256) -> Self {
Self(value)
}
pub fn from_decimal(value: &str) -> Result<Self, Error> {
Ok(Self(super::super::amount::parse_uint(value)?))
}
#[must_use]
pub const fn raw(self) -> U256 {
self.0
}
}
impl TryFrom<String> for $name {
type Error = Error;
fn try_from(v: String) -> Result<Self, Error> {
Self::from_decimal(&v)
}
}
impl From<$name> for String {
fn from(v: $name) -> Self {
v.0.to_string()
}
}
};
}
quantity!(
RawQuantity,
"An exact raw quantity; its field defines units, with no inferred decimal precision."
);
quantity!(
ProtocolAmount,
"An exact `THORChain` protocol amount normalized to 1e8 units, not foreign native units."
);
impl ProtocolAmount {
#[must_use]
pub const fn amount(self) -> Amount {
Amount::new(self.0, Some(8))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "u32", into = "u32")]
pub struct CollectionLimit(u32);
impl CollectionLimit {
pub const MAXIMUM: u32 = 100_000;
pub fn new(value: u32) -> Result<Self, Error> {
if value == 0 || value > Self::MAXIMUM {
return Err(super::invalid_record());
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u32 {
self.0
}
}
impl TryFrom<u32> for CollectionLimit {
type Error = Error;
fn try_from(v: u32) -> Result<Self, Error> {
Self::new(v)
}
}
impl From<CollectionLimit> for u32 {
fn from(v: CollectionLimit) -> Self {
v.0
}
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TxidKind {
Hash,
PrefixedHash,
CosmosIndexed,
SolanaSignature,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Txid {
value: String,
kind: TxidKind,
}
impl Txid {
pub fn parse(value: &str) -> Result<Self, Error> {
let invalid = super::invalid_record;
if !value.is_ascii() {
return Err(invalid());
}
let (canonical, kind) = match value.len() {
64 if value.bytes().all(|b| b.is_ascii_hexdigit()) => {
(value.to_ascii_uppercase(), TxidKind::Hash)
}
66 if value[..2].eq_ignore_ascii_case("0x")
&& value[2..].bytes().all(|b| b.is_ascii_hexdigit()) =>
{
(value.to_ascii_uppercase(), TxidKind::PrefixedHash)
}
66..=85
if value.as_bytes()[64] == b'-'
&& value[..64].bytes().all(|b| b.is_ascii_hexdigit())
&& value[65..].bytes().all(|b| b.is_ascii_digit())
&& value[65..].parse::<u64>().is_ok() =>
{
(value.to_ascii_uppercase(), TxidKind::CosmosIndexed)
}
87 | 88 => {
let mut bytes = [0u8; 64];
if bs58::decode(value)
.onto(&mut bytes)
.map_err(|_| invalid())?
!= 64
|| bs58::encode(bytes).into_string() != value
{
return Err(invalid());
}
(value.to_owned(), TxidKind::SolanaSignature)
}
_ => return Err(invalid()),
};
Ok(Self {
value: canonical,
kind,
})
}
#[must_use]
pub const fn kind(&self) -> TxidKind {
self.kind
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.value
}
#[must_use]
pub fn is_blank(&self) -> bool {
matches!(self.kind, TxidKind::Hash | TxidKind::PrefixedHash)
&& self.identity_key().bytes().all(|b| b == b'0')
}
#[must_use]
pub fn same_transaction(&self, other: &Self) -> bool {
self.identity_key() == other.identity_key()
}
pub(crate) fn identity_key(&self) -> String {
match self.kind {
TxidKind::Hash | TxidKind::SolanaSignature => self.value.clone(),
TxidKind::PrefixedHash => self.value[2..].to_owned(),
TxidKind::CosmosIndexed => {
let index = self.value[65..].trim_start_matches('0');
format!(
"{}-{}",
&self.value[..64],
if index.is_empty() { "0" } else { index }
)
}
}
}
}
impl fmt::Display for Txid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.value)
}
}
impl TryFrom<String> for Txid {
type Error = Error;
fn try_from(v: String) -> Result<Self, Error> {
Self::parse(&v)
}
}
impl From<Txid> for String {
fn from(v: Txid) -> Self {
v.value
}
}