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
use std::str::FromStr;
use cosmwasm_std::Addr;
use subtle_encoding::bech32;
use ethereum_types::H160;
pub fn default_subaccount_id(addr: &Addr) -> String {
address_to_subaccount_id(addr, 0)
}
pub fn address_to_subaccount_id(addr: &Addr, nonce: u32) -> String {
let address_str = bech32_to_hex(addr);
let nonce_str = left_pad_with_zeroes(nonce, 24);
format!("{}{}", address_str, nonce_str)
}
fn left_pad_with_zeroes(input: u32, length: usize) -> String {
let mut padded_input = input.to_string();
while padded_input.len() < length {
padded_input = "0".to_string() + &padded_input;
}
padded_input
}
pub fn bech32_to_hex(addr: &Addr) -> String {
let decoded_bytes = bech32::decode(addr.as_str()).unwrap().1;
let decoded_h160 = H160::from_slice(&decoded_bytes);
let decoded_string = format!("{:?}", decoded_h160);
decoded_string
}
pub fn addr_to_bech32(addr: String) -> String {
let encoded_bytes = H160::from_str(&addr[2..addr.len()]).unwrap();
bech32::encode("inj", encoded_bytes)
}
pub fn subaccount_id_to_ethereum_address(subaccount_id: String) -> String {
subaccount_id[0..subaccount_id.len() - 24].to_string()
}
pub fn subaccount_id_to_injective_address(subaccount_id: String) -> String {
let ethereum_address = subaccount_id_to_ethereum_address(subaccount_id);
addr_to_bech32(ethereum_address)
}
#[cfg(test)]
mod tests {
use crate::{
subaccount::{address_to_subaccount_id, bech32_to_hex, default_subaccount_id},
subaccount_id_to_injective_address,
};
use cosmwasm_std::Addr;
#[test]
fn bech32_to_hex_test() {
let decoded_string = bech32_to_hex(&Addr::unchecked("inj1khsfhyavadcvzug67pufytaz2cq36ljkrsr0nv"));
println!("{}", decoded_string);
assert_eq!(decoded_string, "0xB5e09b93aCEb70C1711aF078922fA256011D7e56".to_lowercase());
}
#[test]
fn address_to_subaccount_id_test() {
let subaccount_id = address_to_subaccount_id(&Addr::unchecked("inj1khsfhyavadcvzug67pufytaz2cq36ljkrsr0nv"), 69);
println!("{}", subaccount_id);
assert_eq!(subaccount_id, "0xb5e09b93aceb70c1711af078922fa256011d7e56000000000000000000000069");
println!("{}", subaccount_id);
assert_eq!(
default_subaccount_id(&Addr::unchecked("inj1khsfhyavadcvzug67pufytaz2cq36ljkrsr0nv")),
"0xb5e09b93aceb70c1711af078922fa256011d7e56000000000000000000000000"
);
}
#[test]
fn subaccount_id_to_address_test() {
let subaccount_id = "0xb5e09b93aceb70c1711af078922fa256011d7e56000000000000000000000000";
let address = subaccount_id_to_injective_address(subaccount_id.to_string());
println!("{}", address);
assert_eq!(address, "inj1khsfhyavadcvzug67pufytaz2cq36ljkrsr0nv");
}
}