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:
Add dependencies:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_bytes = "0.11"
sha2 = "0.9"
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(¶ms).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.