neutron_sdk/interchain_queries/
helpers.rs

1use crate::errors::error::{NeutronError, NeutronResult};
2use crate::interchain_queries::types::{AddressBytes, MAX_ADDR_LEN};
3use cosmwasm_std::{StdError, Uint128, Uint256};
4
5/// Decodes a bech32 encoded string and converts to base64 encoded bytes
6/// <https://github.com/cosmos/cosmos-sdk/blob/ad9e5620fb3445c716e9de45cfcdb56e8f1745bf/types/bech32/bech32.go#L20>
7pub fn decode_and_convert(encoded: &str) -> NeutronResult<AddressBytes> {
8    let (_hrp, bytes, _variant) = bech32::decode(encoded)?;
9
10    Ok(bech32::convert_bits(&bytes, 5, 8, false)?)
11}
12
13/// Prefixes the address bytes with its length
14pub fn length_prefix<AddrBytes: AsRef<[u8]>>(addr: AddrBytes) -> NeutronResult<Vec<u8>> {
15    let bz_length = addr.as_ref().len();
16
17    if bz_length == 0 {
18        return Ok(vec![]);
19    }
20
21    if bz_length > MAX_ADDR_LEN {
22        return Err(NeutronError::MaxAddrLength {
23            max: MAX_ADDR_LEN,
24            actual: bz_length,
25        });
26    }
27
28    let mut p: Vec<u8> = vec![bz_length as u8];
29    p.extend_from_slice(addr.as_ref());
30
31    Ok(p)
32}
33
34pub fn uint256_to_u128(value: Uint256) -> Result<u128, StdError> {
35    let converted: Uint128 = value
36        .try_into()
37        .map_err(|_| StdError::generic_err("Uint256 value exceeds u128 limits"))?;
38    Ok(converted.u128())
39}