#Create Asset from string

1 messages · Page 1 of 1 (latest)

tame tartan
#

In rest.rs I have

fn native_asset_contract_address(e: &Env) -> Address {
    let env = Env::default();
    let native_asset = Asset::Native;
    let contract_id_preimage = ContractIdPreimage::Asset(native_asset);
    let bytes = Bytes::from_slice(&e, &contract_id_preimage.to_xdr().unwrap());
    let native_asset_address = Address::from_contract_id(&e.crypto().sha256(&bytes));
    native_asset_address
}
.
.
.
// Set the native token address
let native_address =native_asset_contract_address(&e);
let expected_address_string="CDF3YSDVBXV3QU2QSOZ55L4IVR7UZ74HIJKXNJMN4K5MOVFM3NDBNMLY";
assert_eq!(native_address, expected_address_string);

And I get this error

  --> src/test.rs:49:5
   |
49 |     assert_eq!(native_address, expected_address_string);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |     |
   |     expected `Address`, found `&str`
   |     expected because this is `soroban_sdk::Address`

It's obvious because they are not the same.... But, how can I build an Address object with the string of the address? Thanks!

jaunty sierra
#
        let my_str = "";
        if let Strkey::Contract(array) =
            stellar_strkey::Strkey::from_string(my_str).expect("Not a key")
        {
            let contract_id = BytesN::from_array(&env, &array.0);
            let asset_address = Address::from_contract_id(&contract_id);
        }

Maybe something like that

tame tartan
#

Yes! This works! At least inside test.rs

fn native_asset_contract_address(e: &Env) -> Address {
    let native_asset = Asset::Native;
    let contract_id_preimage = ContractIdPreimage::Asset(native_asset);
    let bytes = Bytes::from_slice(&e, &contract_id_preimage.to_xdr().unwrap());
    let native_asset_address = Address::from_contract_id(&e.crypto().sha256(&bytes));
    native_asset_address
}

.
.
.
// Set the native token address
let native_address =native_asset_contract_address(&e);    
let expected_address_string = "CDF3YSDVBXV3QU2QSOZ55L4IVR7UZ74HIJKXNJMN4K5MOVFM3NDBNMLY";
let Strkey::Contract(array) = Strkey::from_string(expected_address_string).unwrap() else { panic!("Failed to convert address") };
let contract_id = BytesN::from_array(&e, &array.0);
let expected_asset_address = Address::from_contract_id(&contract_id);
assert_eq!(native_address, expected_asset_address);
#

Thanks @jaunty sierra !

buoyant plume
#

Please comment on that issue if it would support your workflow, or if modifications would be needed to it to support your workflow.