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
use std::fmt::{Display, Formatter};

use candid::CandidType;
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};

use crate::impl_from_uint_for_enum;

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

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 == Chain::Dfinity.into() => Chain::Dfinity,
            chain_id if chain_id == Chain::BnbChain.into() => Chain::BnbChain,
            chain_id if chain_id == Chain::Bitcoin.into() => Chain::Bitcoin,
            chain_id if chain_id == Chain::Ethereum.into() => Chain::Ethereum,
            chain_id if chain_id == Chain::EX3Layer2.into() => Chain::EX3Layer2,
            _ => panic!("unknown chain id"),
        }
    }
}

impl Into<BigUint> for Chain {
    fn into(self) -> BigUint {
        BigUint::from(self as u128)
    }
}

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_enum!(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"),
        }
    }
}