Skip to main content

Convert from bytes to other types

Bytes is a contiguous growable array type containing u8s. They may represent various types of data including strings, addresses, or other information. Converting any data type to bytes ensures that the data be consistently handled by the Soroban runtime and interacting systems.

Bytes to Addressโ€‹

When retrieving data stored on the blockchain, addresses might be stored in byte representation for compactness and efficiency. Off-chain systems, such as APIs, databases, or user interfaces, usually expect addresses in a human-readable format. In such cases, you need to convert the bytes to an address format to ensure compatibility.

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

pub fn bytes_to_address(bytes: Bytes) -> Address {
Address::from_string_bytes(&bytes)
}

Bytes to Stringโ€‹

When dealing with binary data, you may need to convert certain portions of the data to a human-readable format like strings for logging, debugging, processing or display.

use soroban_sdk::{String, Bytes, Env, FromVal};

pub fn bytes_to_string(env: &Env, bytes: Bytes) -> String {
String::from_val(env, &bytes.to_val())
}

Bytes to ScValโ€‹

In a Soroban smart contract that interacts with an external oracle service to provide price data in raw byte format, you would need to convert the bytes to ScVal to process and manipulate the data within your contract.

use soroban_sdk::{Bytes, Env, FromVal, Val};

pub fn bytes_to_val(env: &Env, bytes: Bytes) -> Val {
Val::from_val(env, &bytes.to_val())
}