Converting "fuel..." addresses to Bits256?

Both AssetId and ContractId are roughly typed like so in Sway:

struct AssetId {
    value: b256
}

In the Rust SDK, to convert a hex-like string (either a ContractId or AssetId) to Bits256 is straightforward:

let contr: ContractId = instance.contract_id().into();
let bits: Bits256 = Bits256::from_hex_str(contr.to_string().as_str()).unwrap();
println!("Bits: {:?}", bits); 

and this works fine, but how about if you have a Bech32-like address where the “string” is actually something like fuel15ckkwj6uepv5u2nxpl5sft56unp82s0cean8m6s476dmeu5pdejssxt753?

as an example:

let bech = Bech32ContractId { 
    hrp: "fuel", 
    hash: "a62d674b5cc8594e2a660fe904ae9ae4c27541f8cf667dea15f69bbcf2816e65"
};

let str_out = bech.to_string(); // fuel15ckkwj6uepv5u2nxpl5sft56unp82s0cean8m6s476dmeu5pdejssxt753

// Converting from contr to Bits256 is via ContractId like so:
let contr: ContractId = bech.into();
let bits = Bits256::from_hex_str(contr.to_string().as_str()).unwrap();

// But how to go from a raw string (fuel15ckkwj6uepv5u2nxpl5sft56unp82s0cean8m6s476dmeu5pdejssxt753)
// to Bits256?

I agree, can we just abandon the bech32 address?

There is little to 0 benefit from having it, and it’s just causing type-casting pains

This is a common ‘Cosmos ecosystem trap’ where having a bech32 address looks cool because you have some relationship between chain ↔ user with the address but in reality there are hundreds of chains and it’s just a pain to manage one wallet (seed phrase) with many different bech32 addresses

You can convert ContractId directly into [u8, 32] :

    let contract_id = ContractId::default();
    let _b256 = Bits256(contract_id.into());

for Bech32ContractId you can convert it first to ContractId and then to [u8, 32]

    let bech_contract_id = Bech32ContractId::default();
    let contract_id2: ContractId = bech_contract_id.into();
    let _b256 = Bits256(contract_id2.into());

got it! Thanks so much

2 Likes

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.