axiom_codec/utils/
native.rs

1pub use axiom_eth::utils::{encode_addr_to_field, encode_h256_to_hilo};
2use ethers_core::types::{Address, H256, U256};
3
4use crate::{Field, HiLo};
5
6pub fn u256_to_h256(input: &U256) -> H256 {
7    let mut bytes = [0; 32];
8    input.to_big_endian(&mut bytes);
9    H256(bytes)
10}
11
12pub fn decode_hilo_to_h256<F: Field>(fe: HiLo<F>) -> H256 {
13    let mut bytes = [0u8; 32];
14    bytes[..16].copy_from_slice(&fe.lo().to_bytes_le()[..16]);
15    bytes[16..].copy_from_slice(&fe.hi().to_bytes_le()[..16]);
16    bytes.reverse();
17    H256(bytes)
18}
19
20/// Takes U256, converts to bytes32 (big endian) and returns (hash[..16], hash[16..]) represented as big endian numbers in the prime field
21pub fn encode_u256_to_hilo<F: Field>(input: &U256) -> HiLo<F> {
22    let mut bytes = vec![0; 32];
23    input.to_little_endian(&mut bytes);
24    // repr is in little endian
25    let mut repr = [0u8; 32];
26    repr[..16].copy_from_slice(&bytes[16..]);
27    let hi = F::from_bytes_le(&repr);
28    let mut repr = [0u8; 32];
29    repr[..16].copy_from_slice(&bytes[..16]);
30    let lo = F::from_bytes_le(&repr);
31    HiLo::from_lo_hi([lo, hi])
32}
33
34pub fn decode_hilo_to_u256<F: Field>(fe: HiLo<F>) -> U256 {
35    let mut bytes = [0u8; 32];
36    bytes[..16].copy_from_slice(&fe.lo().to_bytes_le()[..16]);
37    bytes[16..].copy_from_slice(&fe.hi().to_bytes_le()[..16]);
38    U256::from_little_endian(&bytes)
39}
40
41pub fn decode_field_to_addr<F: Field>(fe: &F) -> Address {
42    let mut bytes = [0u8; 20];
43    bytes.copy_from_slice(&fe.to_bytes_le()[..20]);
44    bytes.reverse();
45    Address::from_slice(&bytes)
46}