Arbitrum Stylus logo

Stylus by Example

ABI Decode

decode cannot be used for encode_packed data because packed encoding omits 32-byte padding. (For more information see ABI Encode.)

Below is an example using decode on data encoded with standard ABI encoding (abi_encode_params):

1// This should always return true
2pub fn encode_and_decode(
3    &self,
4    address: Address,
5    amount: U256,
6) -> Result<bool, DecoderError> {
7    // define Sol types tuple
8    type TxIdHashType = (SOLAddress, Uint<256>);
9
10    // set the tuple
11    let tx_hash_data = (address, amount);
12
13    // encode with standard ABI (padded) encoding
14    let tx_hash_data_encode = TxIdHashType::abi_encode_params(&tx_hash_data);
15
16    // decode back and compare
17    match TxIdHashType::abi_decode_params(&tx_hash_data_encode) {
18        Ok(res) => Ok(res == tx_hash_data),
19        Err(_) => Err(DecoderError::DecodedFailed(DecodedFailed {})),
20    }
21}
1// This should always return true
2pub fn encode_and_decode(
3    &self,
4    address: Address,
5    amount: U256,
6) -> Result<bool, DecoderError> {
7    // define Sol types tuple
8    type TxIdHashType = (SOLAddress, Uint<256>);
9
10    // set the tuple
11    let tx_hash_data = (address, amount);
12
13    // encode with standard ABI (padded) encoding
14    let tx_hash_data_encode = TxIdHashType::abi_encode_params(&tx_hash_data);
15
16    // decode back and compare
17    match TxIdHashType::abi_decode_params(&tx_hash_data_encode) {
18        Ok(res) => Ok(res == tx_hash_data),
19        Err(_) => Err(DecoderError::DecodedFailed(DecodedFailed {})),
20    }
21}

Full Example code:

src/lib.rs

1Loading...
1Loading...

Cargo.toml

1Loading...
1Loading...