1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use candid::{CandidType, Deserialize};
use serde::Serialize;
use ex3_error::OtherError;
use ex3_serde::bincode::{deserialize, serialize};
use crate::Chain;
#[derive(CandidType, Debug, Clone, Hash, Deserialize, Serialize, PartialEq, Eq)]
pub enum TokenType {
Bitcoin,
EVM(EVMTokenType),
Dfinity(DfinityTokenType),
}
#[derive(CandidType, Debug, Clone, Hash, Deserialize, Serialize, PartialEq, Eq)]
pub enum EVMTokenType {
Native,
ERC20,
ERC721,
}
#[derive(CandidType, Debug, Clone, Hash, Deserialize, Serialize, PartialEq, Eq)]
pub enum DfinityTokenType {
ICP,
Cycles,
DFT,
ICRC1,
}
#[derive(CandidType, Debug, Clone, Hash, PartialEq, Eq)]
pub struct CryptoAsset {
pub chain: Chain,
pub token_type: TokenType,
pub token_id: Option<String>,
}
impl CryptoAsset {
pub fn encode(&self) -> Vec<u8> {
serialize(&(&self.chain, &self.token_type, &self.token_id)).unwrap()
}
}
impl TryFrom<&[u8]> for CryptoAsset {
type Error = OtherError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let (chain, token_type, token_id) = deserialize(value).map_err(|e| {
OtherError::new(format!(
"Failed to deserialize CryptoAsset from bytes: {:?}",
e
))
})?;
Ok(CryptoAsset {
chain,
token_type,
token_id,
})
}
}
impl std::fmt::Display for CryptoAsset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let token_type = match &self.token_type {
TokenType::Bitcoin => "Bitcoin",
TokenType::EVM(token_type) => match token_type {
EVMTokenType::Native => "Native",
EVMTokenType::ERC20 => "ERC20",
EVMTokenType::ERC721 => "ERC721",
},
TokenType::Dfinity(token_type) => match token_type {
DfinityTokenType::ICP => "ICP",
DfinityTokenType::Cycles => "Cycles",
DfinityTokenType::DFT => "DFT",
DfinityTokenType::ICRC1 => "ICRC1",
},
};
write!(
f,
"{}{}{}",
self.chain.to_chain_id(),
token_type,
self.token_id.as_ref().unwrap_or(&"".to_string())
)
}
}