hashgraph / hedera-sdk-rust

The Hedera™ Rust SDK
Apache License 2.0
43 stars 14 forks source link

Support strings in add_bytes32 in ContractFunctionParameters #731

Closed mehcode closed 1 year ago

mehcode commented 1 year ago

Problem

It's very common/recommended to use the bytes32 type when working with strings that are smaller than 32 bytes in Solidity for performance reasons. However, add_bytes32 only takes &[u8; 32] which is frustrating to convert a string to in Rust.

Solution

Define a new private trait IntoBytes32 and change the signature of add_bytes32 to

fn add_bytes32<T: IntoBytes32>

And implement IntoBytes32 for:

Alternatives

No response

mehcode commented 1 year ago

This is from the rust-web3 crate

fn pad_to_bytes32(s: &str) -> Option<[u8; 32]> {
    let s = s.as_bytes();
    let s_len = s.len();

    if s_len > 32 {
        return None;
    }

    let mut result: [u8; 32] = Default::default();

    result[..s_len].clone_from_slice(s);

    Some(result)
}