Solidity Encode and Decode

--

A smart contract consists of variables that store information and functions that perform actions. Basically, some functions are private and can only be accessed from within the contract, while others are public and can be accessed from outside the contract. (Others are external and internal)

This means that applications and individuals can send data to the contract and retrieve data from it. In order to send data to the contract, it needs to be formatted in a way that the contract can understand.

This involves encoding the data according to the rules set by the Ethereum Virtual Machine (EVM). The EVM determines how the encoding process should be carried out.

This article provides insights into encoding/decoding rules and demonstrates how to use Solidity to encode and decode data that needs to be passed as parameters in a function.

In Solidity, there exists a global variable, is named “abi”, which includes an encoding/decoding method. This enables us to utilize it for encoding/decoding the parameters of any function.

We have an address and uint variables and we try to encode these variables.

function enCode(address _address, uint number) public pure returns(bytes memory){
return (abi.encode(_address, number));
}

We take these variables as a parameter in enCode function and then function returns these variables as bytes thanks to abi.encode.

We can see result in remix.

_address: 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4

_number:19

This is the result.

We can illustrate this result.

We try to decode our result.

 function deCode(bytes memory data) public pure returns(address _address, uint _number){
(_address, _number) = abi.decode(data, (address, uint));
}

We take this result as a parameter in deCode function and then function returns our variables (address and uint) thanks to abi.decode.

Full code

Associate Professor Engin YILMAZ (VeriDelisi)

--

--