How to encode structs into bytes?

How do I encode a struct imported from Sway into bytes using Rust SDK?

For example I have a struct defined in Sway


struct TransferParams {
    to: Identity,
    asset_id: ContractId,
    amount: u64,
}

I need to sha256 this struct using Rust so I need the struct encoded as bytes.

Any help? Thanks

I found out that for a simple struct fuels::core::calldata! macro will encode it into bytes.

Care must be taken if the struct contains Bytes and you need to hash it. The hash might be inconsistent between the code you write in Rust SDK and Sway.

tsk I just saw this topic and will try to help you.

To encode a struct in Rust and hash it using SHA256, you first need to serialize the struct into bytes. Here’s a general approach using serde and serde_bytes for serialization:

  1. Add dependencies:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_bytes = "0.11"
sha2 = "0.9"
  1. Implement struct serialization:
use serde::{Serialize};
use sha2::{Sha256, Digest};

#[derive(Serialize)]
struct TransferParams {
    to: String, // Replace with actual type for Identity
    asset_id: String, // Replace with actual type for ContractId
    amount: u64,
}

fn main() {
    let params = TransferParams {
        to: "some_identity".to_string(),
        asset_id: "some_contract_id".to_string(),
        amount: 1000,
    };

    // Serialize struct to bytes
    let bytes = bincode::serialize(&params).expect("Failed to serialize");

    // Hash with SHA256
    let hash = Sha256::digest(&bytes);
    println!("{:x}", hash);
}

This will encode your struct into bytes and compute the SHA256 hash of the serialized data.