Vaibhav Saini

@vaibhavsaini_67863

Serializing string arrays in solidity

TL;DR This GitHub repository is all you need.

Solidity is still in development and that’s why it still lacks in a lot of features that a good programming language should have. One of the features which solidity is missing is that it cannot return or take multi-dimensional arrays as input. Well, that does not seem important but when we talk about strings, we realize that they are just arbitrary-length byte array(i.e. byte[]). So when you create a string array, you are creating a two-dimensional byte array(i.e. byte[][]). This is where we all get stuck. Kinda like a trap…

it’s a trap!

That’s enough of talking, let’s get to work. The easiest and the most efficient way to get over this problem is to serialize the strings in the array(converting the strings in the array into byte form) and send all of them in one go. After we receive the string array in the byte form we can either pass the byte array as input to another solidity function or send it to user-end(node.js api) where we will de-serialize it back to the string array. Let’s see how it works.

Step 1: Serialize & De-serialize using solidity

For serializing/de-serializing in solidity we will use Seriality which can be used to serialize and de-serialize any data type in solidity. Thanks to pouladzade.

serialize.sol

You will get some output like this (for startindex=1, endindex=2).

0x737472696e6731000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007737472696e6732000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007737472696e6733000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007

Now, pass this bytes buffer into getString()and you will get your strings back!

Note: You have to include Seriality files to your project to make the contract working. You can do that from here.

Step 2: De-serialize the byte buffer using javascript

Now, using javascript we can get our string array back.

deserialize.js

Putting the above byte output in the js function we get the following output.

[“string1”, “string2”]

Voila, you successfully got your array back!

easy as that!

This was just about the strings. You can do a lot of stuff using Seriality.

More by Vaibhav Saini

Topics of interest

More Related Stories