Solidity Structs – Accessing Mapping Inside Mapping of Struct in Solidity ^0.5.0

mappingsoliditystructtruffle

I have a contract which looks like this:

contract a {
    struct Str {
        uint256 totalTokens;
        mapping(address => uint256) playerTokens;
    }

    mapping(uint256 => Str) public tokenStores;
}

now assume that we have defined tokenStores as public and a getter method will be automatically allocated, is it possible to access a particular playerTokens
value using a key from javascript? Any workaround possible in Solidity ^0.5.0 ??

Best Answer

You can't do with a getter from public because the compiler doesn't (yet) know how to formulate the function with nested keys. I believe this is possible if you specific you wish to the experimental ABI.

A safer, more conventional workaround is to simple construct your own getter.

contract a { 

  struct Str {
    uint256 totalTokens;
    mapping(address => uint256) playerTokens;
  }

  mapping(uint256 => Str) private tokenStores;  // we'll make the getter manually

  function getPlayerToken(uint256 tokenId, address player) public returns(uint, uint) {
      Str storage t =  tokenStores[tokenId];
      return (t.totalTokens, t.playerTokens[player]);
  }
}

Hope it helps.