Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String array in solidity

I came across quite a common problem that it seems I can't solve elegantly and efficiently in solidity.

I've to pass an arbitrary long array of arbitrary long strings to a solidity contract.

In my mind it should be something like

function setStrings(string [] row)

but it seems it can't be done.

How can I solve this problem?

like image 465
Fabio Avatar asked Mar 10 '17 11:03

Fabio


People also ask

How do you declare a string array in Solidity?

String arrays as parameters aren't supported yet in solidity. Show activity on this post. You can convert the array elements to a byte string and then deserialize that byte string back to the array inside the function.

What is string in Solidity?

Solidity provides a data type named string to declare variables of type String. It also extends support for string literals using single-quotes ' and double-quotes " . A String can also be created using the string constructor.

How do you join strings in Solidity?

concat() Since it's not possible to concatenate the strings with “ + ” or “ append ” in solidity , we will use the memory bytes to concatenate the strings in method 2. A special method called bytes. concat allows us to easily concatenate the strings in solidity.


2 Answers

This is a limitation of Solidity, and the reason is that string is basically an arbitrary-length byte array (i.e. byte[]), and so string[] is a two-dimensional byte array (i.e. byte[][]). According to Solidity references, two-dimensional arrays as parameters are not yet supported.

Can a contract function accept a two-dimensional array?

This is not yet implemented for external calls and dynamic arrays - you can only use one level of dynamic arrays.

One way you can solve this problem is if you know in advanced the max length of all of your strings (which in most cases are possible), then you can do this:

function setStrings(byte[MAX_LENGTH][] row) {...}

like image 154
Dat Nguyen Avatar answered Oct 13 '22 06:10

Dat Nguyen


December 2021 Update

As of Solidity 0.8.0, ABIEncoderV2, which provides native support for dynamic string arrays, is used by default.

pragma solidity ^0.8.0;

contract Test {
    string[] public row;

    function getRow() public view returns (string[] memory) {
        return row;
    }

    function pushToRow(string memory newValue) public {
        row.push(newValue);
    }
}
like image 25
Yulian Avatar answered Oct 13 '22 05:10

Yulian