cpchain_rust_sdk/
address.rs1use std::fmt::Display;
2
3use serde::{Serialize, Deserialize};
4use web3::types::H160;
5
6use crate::utils::{self, checksum_encode};
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9pub struct Address {
10 pub h160: H160,
11}
12
13impl Address {
14 pub fn new(h160: H160) -> Self {
15 Self { h160 }
16 }
17 pub fn from_str(s: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
18 let data = utils::hex_to_bytes(s)?;
19 Ok(Self {
20 h160: H160::from_slice(data.as_slice()),
21 })
22 }
23 pub fn to_checksum(&self) -> String {
24 checksum_encode(&self.h160)
25 }
26}
27
28impl Display for Address {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.write_str(&self.to_checksum())
31 }
32}
33
34#[cfg(test)]
35mod tests {
36 use crate::address::{checksum_encode, Address};
37
38 #[test]
39 fn test_checksum() {
40 fn it(addr: &str) {
41 let a = Address::from_str(addr).unwrap();
42 let checksum_addr = checksum_encode(&a.h160);
43 assert!(checksum_addr == addr.to_string());
44 }
45 it("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed");
46 it("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359");
47 it("0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB");
48 it("0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb");
49 }
50}