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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use std::fmt::{Display, Formatter};

use candid::CandidType;
use ex3_serde::bincode;
use ic_stable_structures::{storable::Bound, Storable};
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};

use crate::impl_from_uint_for;

/// Registered coin types for BIP-0044
///   https://github.com/satoshilabs/slips/blob/master/slip-0044.md
#[derive(Clone, CandidType, Hash, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum Chain {
    Bitcoin = 0,
    Ethereum = 60,
    Dfinity = 223,
    BnbChain = 714,
    EX3Layer2 = 87653426,
}

impl Ord for Chain {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let self_int: BigUint = self.clone().into();
        let other_int: BigUint = other.clone().into();
        self_int.cmp(&other_int)
    }
}

impl PartialOrd for Chain {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Display for Chain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Chain::Dfinity => write!(f, "Dfinity"),
            Chain::BnbChain => write!(f, "BnbChain"),
            Chain::Bitcoin => write!(f, "Bitcoin"),
            Chain::Ethereum => write!(f, "Ethereum"),
            Chain::EX3Layer2 => write!(f, "EX3Layer2"),
        }
    }
}

impl From<BigUint> for Chain {
    fn from(chain_id: BigUint) -> Self {
        match chain_id {
            chain_id if chain_id == BigUint::from(Chain::Dfinity) => Chain::Dfinity,
            chain_id if chain_id == BigUint::from(Chain::BnbChain) => Chain::BnbChain,
            chain_id if chain_id == BigUint::from(Chain::Bitcoin) => Chain::Bitcoin,
            chain_id if chain_id == BigUint::from(Chain::Ethereum) => Chain::Ethereum,
            chain_id if chain_id == BigUint::from(Chain::EX3Layer2) => Chain::EX3Layer2,
            _ => panic!("unknown chain id"),
        }
    }
}

impl From<Chain> for BigUint {
    fn from(chain: Chain) -> Self {
        BigUint::from(chain as u128)
    }
}
impl From<&str> for Chain {
    fn from(chain: &str) -> Self {
        let str = chain.to_string().to_lowercase();
        match str.as_str() {
            "dfinity" => Chain::Dfinity,
            "bnbchain" => Chain::BnbChain,
            "bitcoin" => Chain::Bitcoin,
            "ethereum" => Chain::Ethereum,
            "ex3layer2" => Chain::EX3Layer2,
            _ => panic!("unknown chain"),
        }
    }
}

impl Chain {
    pub fn key_format(&self) -> KeyFormat {
        match self {
            Chain::Dfinity => KeyFormat::EcdsaSecp256k1,
            Chain::BnbChain => KeyFormat::EcdsaSecp256k1,
            Chain::Bitcoin => KeyFormat::EcdsaSecp256k1,
            Chain::Ethereum => KeyFormat::EcdsaSecp256k1,
            Chain::EX3Layer2 => KeyFormat::EcdsaSecp256k1,
        }
    }
}

impl_from_uint_for!(Chain, u8, u16, u32, u64, u128);

#[derive(
    Clone, CandidType, Hash, Debug, Ord, PartialOrd, Eq, PartialEq, Deserialize, Serialize,
)]
pub enum KeyFormat {
    EcdsaSecp256k1 = 0,
    Ed25519 = 1,
}

impl Display for KeyFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyFormat::EcdsaSecp256k1 => write!(f, "EcdsaSecp256k1"),
            KeyFormat::Ed25519 => write!(f, "Ed25519"),
        }
    }
}

#[derive(Clone, CandidType, Hash, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct ChainIdentifier {
    pub chain: Chain,
    pub network: u8,
}

impl Ord for ChainIdentifier {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let o1 = self.chain.cmp(&other.chain);
        if o1 != std::cmp::Ordering::Equal {
            return o1;
        }

        self.network.cmp(&other.network)
    }
}

impl PartialOrd for ChainIdentifier {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Storable for ChainIdentifier {
    fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
        bincode::serialize(self).unwrap().into()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        bincode::deserialize(bytes.as_ref()).unwrap()
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: 20,
        is_fixed_size: false,
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_storable_for_chain_identifier() {
        let chain_identifier = ChainIdentifier {
            chain: Chain::EX3Layer2,
            network: u8::MAX,
        };
        let bytes = chain_identifier.to_bytes();
        assert!(bytes.len() <= 20, "bytes.len() = {}", bytes.len());
        let chain_identifier2 = ChainIdentifier::from_bytes(bytes);
        assert_eq!(chain_identifier, chain_identifier2);
    }
}