Skip to main content

Convert an address to other types

The Address is an opaque type that could represent an "account" on the Stellar network (i.e., a keypair), or a "contract." From Soroban's point of view, it doesn't really matter which it is. The "account" variety of these addresses are typically displayed as a G... public address, and the "contract" variety is typically displayed as a C... address. An address may also be displayed in other formats such as a 32 byte array, a string, or an ScVal type. The Soroban SDKs provide methods that easily convert an address to any of these types.

Address to bytesNโ€‹

Bytes are a more compact and efficient way to store data in terms of storage optimization and data transmission. In situations where you need to store or transmit an address in a fixed-size, such as for cryptographic operations or data serialization, you need to convert the address to a bytesN format

use soroban_sdk::{Address, BytesN, Env, FromVal};

pub fn address_to_bytes32(env: &Env, address: Address) -> BytesN<32> {
let address_to_bytes: BytesN<32> = BytesN::from_val(env, &address.to_val());
address_to_bytes
}

Address to Stringโ€‹

When transferring data between different systems or over a network, using text-based formats like JSON and XML string formats are often required. Storing addresses as strings in databases can simplify database schema design and queries. Strings are easier to manipulate and are more compatible with user interfaces and APIs.

use soroban_sdk::{Address, String, Env};

pub fn address_to_string(address: Address) -> String {
address.to_string()
}

Address to ScVal

Addresses are often passed as function parameters in Soroban smart contracts. These addresses must be in ScVal format because the Soroban virtual machine processes data in this format. Similarly, if a smart contract function returns an address, it will be returned as an ScVal. Converting to and from ScVal ensures that you can properly handle these return values.

use soroban_sdk::{Address, Val};

pub fn address_to_sc_val(address: Address) -> Val {
address.to_val()
}