[Ethereum] How to view structs with truffle

soliditystructtruffle

In my contract I have a mapping like this mapping(uint => myStruct)

I have a check function where I give a uint id and I want to get all the info in the struct (there are strings, addresses, uints, …) with a call function in my truffle app.js.

What's the best way to do that? Can I convert every field to a string and send an array of strings? Should I make a separate getter for each field and use as many call functions?

For now I just return struct and I get invalid solidity type!: tuple

Best Answer

You don't need an extra solidity function to get the info from a struct. You can call the struct directly using web3.

It helps if you have a function on the contract to get the amount of tokens otherwise you might be stuck using while instead of for. Lets assume you have a function to give you struct.length

var OwnableList = [];

//to get one struct entry you do this.

function getStructData(tokenId) {

    myContract.Ownables(tokenId, function(error, details) {
        if(details == undefined) {
            return false;
        } else {
            var name = details[0];
            var creator = details[1];
            var currentOwner = details[2];
            var isDestructible = details[3];
            var price = parseInt(details[4]);
            OwnableList.push({name: name, creator: creator, currentOwner: currentOwner, isDestructible: isDestructible, price: price});
    })
    return true;
    }
}

//to get all struct entrys you do this

function dumpStructData() {
    myContract.totalOwnables(function(error, total) {
        for(i=0; i<parseInt(total); i++) {
            getStructData(i);
        }
    }
}

//now you can just read the struct

function showStruct() {
    console.log(JSON.stringify(OwnableList);
}
Related Topic