2

Can I use strings as identifiers in a Solidity mapping?

I want something like this:

contract C {
    mapping(string => mapping(address => uint)) public balances;
    string[] public tokennames; 
    mapping(string => uint) public tokennameIndex;
}

Each string will represent a different token balance. The list of tokens will be maintained (add, edit, remove, reorganize) by an admin account. One alternative for this is to use different contracts for each token, but a 2-D mapping somehow seems easier, given that storage will not be too big. Also it removes the need for a list of contract addresses. Does such an indexing make sense? Thanks!

2 Answers 2

4

At the moment I don't think that you can. From the solidity docs:

Mapping types are declared as mapping(_KeyType => _ValueType). Here _KeyType can be almost any type except for a mapping, a dynamically sized array, a contract, an enum and a struct.

Note that a string is a dynamically-sized array.

You could still achieve the same thing by, for example, using the three-letter token code as the KeyType, rather than the full token name.

4

Strings don't work as mapping keys. Hash the string with keccak256() and use the resulting bytes32 as the mapping key.

As for the approach of using a 2-dimensional array rather than a separate contract instance per token, it's fine, as long as:

  • You don't need to expose some standard interface, like ERC20, which expects each token to have a contract instance
  • You don't need to give different tokens different behaviours

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.