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!

up vote 4 down vote accepted

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.

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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