0

I am trying to retrieve the price of four contracts all using the same ABI. I have made the array 'Contract' so I can loop through them and apply the same method of "Price":

var Contract = [];

Contract.push(TheContractName.at("0x23db685b4f40fc3565ecba26751570e60eed82fd"));
Contract.push(TheContractName.at("0xeefc6f5b60ce3481add637dc661d1f82f4041b56"));
Contract.push(TheContractName.at("0xc7138f91b01660206447e756ccca7ac54a15c4cf"));
Contract.push(TheContractName.at("0xf0a9d6b665e2ce6975cffe4f3b4ffd5abafe5933"));

Then I made a loop to fetch the results through Web3.js:

Contract.forEach(function(Price) {
    console.log(Price);
});

However, this just gives me the results of the original array.

I have used this function to retrieve successfully the price when there is no array involved:

Contract.Price(function(error, result) {
     console.log("Price " + result / 1000000000000000000 + " Ether");
});

If I can retrieve the results, I will then make a new array for the values returned, and append the data-* fields in the HTML. With this you can then sort the appended divs with the data-* tag values.

1 Answer 1

1

You're pushing contracts into an array, but then you're just printing them out instead of calling a method on them. Try this:

var contracts = [];

contracts.push(TheContractName.at("0x23db685b4f40fc3565ecba26751570e60eed82fd"));
contracts.push(TheContractName.at("0xeefc6f5b60ce3481add637dc661d1f82f4041b56"));
contracts.push(TheContractName.at("0xc7138f91b01660206447e756ccca7ac54a15c4cf"));
contracts.push(TheContractName.at("0xf0a9d6b665e2ce6975cffe4f3b4ffd5abafe5933"));

contracts.forEach(function (contract) {
    contract.Price(function (error, result) {
        console.log("Price " + result / 10**18 + " ether");
    });
});
2
  • This is works, wow. I spent about 8 hours trying to figure that out. I guess the call and response syntax confused me. The good news is I learned the new ways of doing loops in ES 5 and on. I'm curious about the use of 10**18, while it is more convenient and easy to read, won't this cost more CPU cycles? I wrote the long form as it is just basic division. Commented Jan 23, 2018 at 16:54
  • 1
    Something like web3.fromWei(result, 'ether').toString() would be even better. Yes, both take a few more CPU cycles, but that's right after doing a network call. An extremely premature optimization. :-)
    – user19510
    Commented Jan 23, 2018 at 17:00

Your Answer

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

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