ABI Encode
The ABI Encode has 2 types which are encode and encode_packed.
encodewill concatenate all values and add padding to fit into 32 bytes for each values.encode_packedwill concatenate all values in the exact byte representations without padding. (For example,encode_packed("a", "bc") == encode_packed("ab", "c"))
Suppose we have a tuple of values: (target, value, func, data, timestamp) to encode, and their alloy primitives type are (Address, U256, String, Bytes, U256).
Firstly we need to import those types we need from alloy_primitives, stylus_sdk::abi and alloc::string:
注記
This code has yet to be audited. Please use at your own risk.
// Import items from the SDK. The prelude contains common traits and macros.
use stylus_sdk::{alloy_primitives::{U256, Address, FixedBytes}, abi::Bytes, prelude::*};
// Import String from alloc
use alloc::string::String;
Secondly because we will use the method abi_encode_sequence and abi_encode_packed under alloy_sol_types to encode data, we also need to import the types from alloy_sol_types:
// Becauce the naming of alloy_primitives and alloy_sol_types is the same, so we need to re-name the types in alloy_sol_types
use alloy_sol_types::{sol_data::{Address as SOLAddress, String as SOLString, Bytes as SOLBytes, *}, SolType};
encode
Then encode them:
// define sol types tuple
type TxIdHashType = (SOLAddress, Uint<256>, SOLString, SOLBytes, Uint<256>);
// set the tuple
let tx_hash_data = (target, value, func, data, timestamp);
// encode the tuple
let tx_hash_bytes = TxIdHashType::abi_encode_sequence(&tx_hash_data);
encode_packed
There are 2 methods to encode_packed data:
encode_packedthem:
// define sol types tuple
type TxIdHashType = (SOLAddress, Uint<256>, SOLString, SOLBytes, Uint<256>);
// set the tuple
let tx_hash_data = (target, value, func, data, timestamp);
// encode the tuple
let tx_hash_data_encode_packed = TxIdHashType::abi_encode_packed(&tx_hash_data);
- We can also use the following method to
encode_packedthem:
let tx_hash_data_encode_packed = [&target.to_vec(), &value.to_be_bytes_vec(), func.as_bytes(), &data.to_vec(), ×tamp.to_be_bytes_vec()].concat();