Solidity Exercise - ABI Decode

Posted by Bourne's Blog - A Full-stack & Web3 Developer on May 10, 2024

ABI Decode

Let’s see the requirement first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;

contract Decoder {
    /* This exercise assumes you know how abi decoding works.
        1. In the `decodeData` function below, write the logic that decodes a `bytes` data, based on the function parameters
        2. Return the decoded data
    */
    bytes public encoded;

    function decodeData(
        bytes memory _data
    ) public pure returns (string memory, uint256) {}
}

Problem Analysis

This problem require us to family the usage of abi.decode, which receive two parameters, first is the encoded data, sencond is the format of the original data.

Coding

1
2
3
4
5
    function decodeData(
        bytes memory _data
    ) public pure returns (string memory, uint256) {
        return abi.decode(_data, (string, uint256));
    }

Test

1
2
3
4
5
6
7
8
9
10
11
➜  Decoder git:(main) ✗ forge test -vvv
[⠊] Compiling...
[⠘] Compiling 19 files with Solc 0.8.25
[⠃] Solc 0.8.25 finished in 763.68ms
Compiler run successful!

Ran 1 test for test/Decoder.t.sol:DecoderTest
[PASS] testDecodedData() (gas: 19759)
Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 5.17ms (460.83µs CPU time)

Ran 1 test suite in 164.58ms (5.17ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)

Great, decode executes perfectly.

Reference: Solidity Exercise - ABI Decode