Hi guys, going through the Solidity tutorials by
@KenK and I like what I've seen up to now. Structured contract programming and easy calls from Javascript in the DApp.
A question with regard to that: is there an easy way to get the data stored in structs and mappings through the Javascript API?
For example the first contract in
this chapter with one function added:
contract Test{
struct coinWallet {
uint redCoin;
uint greenCoin;
}
coinWallet myWallet;
function Test(){
myWallet.redCoin = 500;
myWallet.greenCoin = 250;
}
function GetRed() returns (uint redAmount){
return myWallet.redCoin;
}
}
Using
var MyContract = web3.eth.contract(...)
with the ABI allows calling the functions of contracts easily: in this case I can call
myContract.GetRed()
.
What I'm looking for is a way to do something like this:
var cw = myContract.myWallet;
var total = cw.redCoin + cw.greenCoin;
Ideally also working with mappings. My thinking is that this would be possible without a transaction, as it's only accessing the contract's storage, which is public.
Is there a way to do this? If not, is it planned?
Comments
Alternatively you can use the accessors that are automatically generated for public variables: https://github.com/ethereum/wiki/wiki/Solidity-Features#state-variable-accessors
Getters for struct types (or mappings to struct types) just return multiple values (all except mappings).
mapping
isn't supported yet as calling it from Javascript in AlethZero results in:TypeError: undefined is not an object (evaluating 'value.indexOf')
But that's something that could be worked around.
the checkGoalReached function in the crowdfunding example might be helpful?
Thanks!
function allWallets(address) returns (uint, uint, string)
I modified your code a little bit.
I deleted "coinWallet public myWallet;"
and add "coinWallet myWallet = allWallets[tx.origin];" inside the Test() function. Now we can access the my wallet data this way;
var myWallet = test.allWallets[myAddr];
should be
var myWallet = test.allWallets(myAddr);
The only thing left to wish for is calling properties of the struct in the mapping by their name instead of their index [0], [1], (..).
E.g. instead of this: I would like to do something like this: But accessing the mapping contents like that without having to add additional functions to the contract is already a step forward.
@KenK eagerly awaiting the next JS part of your tutorials where this will be explained (even though I already have my answer).