1

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 ??

2 Answers 2

1

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.

3
  • How would you add a Str struct to tokenStores?
    – Fly
    Sep 17, 2021 at 23:56
  • ??? tokenStore is a mapping of structs (Str). They could contain a struct. You declare the struct in the usual way and then cast a member as that type. struct A { ... } struct B { A aStruct; } mapping(address = B) private bMap; Sep 18, 2021 at 0:15
  • bMap is a mapping of B structs. B structs contain an A struct. Sep 18, 2021 at 0:16
0

You can have a function like this in smart contract to return values from mapping. You can call this function from your javascript code using web3 to get what you need.

function getPlayerTokens(uint _tokenStoresId, address playerAdd)
        public
        view 
        returns(uint)
    {
        Str storage s = tokenStores[_tokenStoresId];
        return s.playerTokens[playerAdd];

    }
1
  • yes this is a seperate function, which is pretty straightforward. But I want to know if it is possible to access from the automated getter function itself
    – Kombo
    Jan 18, 2019 at 13:07

Your Answer

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

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