raiden_primitives/
impls.rs1#![warn(clippy::missing_docs_in_private_items)]
2
3use web3::{
4 signing::{
5 keccak256,
6 Signature,
7 },
8 types::{
9 Address,
10 Bytes,
11 U256,
12 },
13};
14
15use crate::traits::{
16 Checksum,
17 Stringify,
18 ToBytes,
19 ToPexAddress,
20};
21
22impl ToBytes for U256 {
23 fn to_bytes(&self) -> Vec<u8> {
24 let mut bytes = [0u8; 32];
25 self.to_big_endian(&mut bytes);
26 bytes.to_vec()
27 }
28}
29
30impl ToBytes for Signature {
31 fn to_bytes(&self) -> Vec<u8> {
32 let rb = self.r.to_fixed_bytes();
33 let sb = self.s.to_fixed_bytes();
34 let sv = self.v.to_be_bytes();
35
36 let mut b = vec![];
37 b.extend(&rb);
38 b.extend(&sb);
39 b.push(sv[sv.len() - 1]);
40 b
41 }
42}
43
44impl Stringify for Signature {
45 fn as_string(&self) -> String {
46 let bytes = self.to_bytes();
47 format!("0x{}", hex::encode(bytes))
48 }
49}
50
51impl Stringify for Bytes {
52 fn as_string(&self) -> String {
53 let bytes = &self.0;
54 format!("0x{}", hex::encode(bytes))
55 }
56}
57
58impl Checksum for Address {
60 fn checksum(&self) -> String {
61 let prefixed_address = format!("{self:x}");
62 let hash = hex::encode(keccak256(prefixed_address.as_bytes()));
63 let hash = hash.as_bytes();
64
65 let addr_hex = hex::encode(self.as_bytes());
66 let addr_hex = addr_hex.as_bytes();
67
68 addr_hex.iter().zip(hash).fold("0x".to_owned(), |mut encoded, (addr, hash)| {
69 encoded.push(if *hash >= 56 {
70 addr.to_ascii_uppercase() as char
71 } else {
72 addr.to_ascii_lowercase() as char
73 });
74 encoded
75 })
76 }
77}
78
79impl Checksum for Option<Address> {
80 fn checksum(&self) -> String {
81 if let Some(address) = self {
82 address.checksum()
83 } else {
84 String::new()
85 }
86 }
87}
88
89impl ToPexAddress for Address {
90 fn pex(&self) -> String {
91 hex::encode(&self.checksum()[..8])
92 }
93}