0

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

0

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.

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];

    }
  • 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 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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