vialabs-stellar-common 0.1.10

Common interfaces, types, and utilities for Stellar contracts in the VIA cross-chain messaging system
Documentation
/// # Utils Module
///
/// This module provides utility functions for contract operations.
use crate::{errors::Error, storage::ZERO_BYTES};
use soroban_sdk::{panic_with_error, xdr::ToXdr, Address, Bytes, Env};

/// Checks if an address is the zero address.
///
/// # Arguments
///
/// * `env` - The Soroban environment
/// * `address` - Address in bytes format to check
///
/// # Returns
///
/// Returns `true` if the address is the zero address, `false` otherwise.
pub fn is_zero_address(env: &Env, address: Bytes) -> bool {
  let zero_bytes = Bytes::from_array(env, &ZERO_BYTES);

  zero_bytes == address
}

/// Extracts raw bytes from an Address (last 32 bytes of XDR representation).
///
/// # Arguments
///
/// * `env` - The Soroban environment
/// * `address` - The address to extract bytes from
///
/// # Returns
///
/// Returns the raw 32-byte public key bytes from the address.
pub fn address_to_raw_bytes(env: &Env, address: Address) -> Bytes {
  let xdr_bytes = address.to_xdr(env);
  let xdr_buffer = xdr_bytes.to_buffer::<1024>();
  let xdr_slice = xdr_buffer.as_slice();

  if xdr_slice.len() < 32 {
    panic_with_error!(env, Error::AddressXDRRepresentationTooShort);
  }

  let start = xdr_slice.len() - 32;
  let raw_bytes = &xdr_slice[start..xdr_slice.len()];

  Bytes::from_slice(env, raw_bytes)
}

/// Validates that an address's XDR representation matches the provided public key bytes.
///
/// # Arguments
///
/// * `env` - The Soroban environment
/// * `signer` - The address to validate
/// * `public_key` - The public key bytes to match against
///
/// # Returns
///
/// Returns `true` if the address's public key matches the provided public key bytes, `false` otherwise.
pub fn validate_address_bytes(env: &Env, signer: Address, public_key: Bytes) -> bool {
  let raw_bytes_from_address = address_to_raw_bytes(env, signer);

  raw_bytes_from_address == public_key
}