[Ethereum] how to return uint256 from solidity to javascript

javascriptsolidityweb3js

I have a function in Solidity:

address[] contracts;

function getContractsCount() constant returns (uint256) {
      return contracts.length;
}

in Remix it's work perfect. I get 1, it's right, but when I call the function from javascript:

import FactoryContract from '../build/contracts/Factory.json';

const selectContractInstance = (contractBuild) => {
  return new Promise(res => {
    const myContract = contract(contractBuild);
    myContract.setProvider(provider);
    myContract
      .deployed()
      .then(instance => res(instance));
  })
}

var factoryContract = await selectContractInstance(FactoryContract);    

var contractCount = await factoryContract.getContractsCount.call().toNumber();

I get wrong number – 0.

How to return uint from Solidity to JavaScript from contract function

[UPDATE]
———

Solidity Code

address[] public contracts;
 TokenFactory public newContract;

function createContract(uint _totalSupply, string _name, string _symbol, uint _decimal) payable returns(uint256 t) {
  newContract = new TokenFactory(_totalSupply, _name, _symbol, _decimal);
  contracts.push(newContract);
  return (contracts.length);
} //return 1, it's right

function getContractsCount() constant returns (uint256 length) {
  return (contracts.length);
} // after that the function return 0, it's wrong!

JavaScript Code not change

Best Answer

I think the contract address or ABI is not correctly set in your case because I tested and it works perfectly.

Please check if correct contract address and ABI is updated in your javascript file.

[Update]

-----------------------

As you asked, I am attaching my code:

Solidity Code:

pragma solidity ^0.4.0;

contract testContract {
    uint256 num1;

    address[] contracts = [0x36eaf79c12e96a3dc6f53426c, 0xf235aa56dd96bda02acfb361e];

    function getContractsCount() constant returns (uint256) {
          return contracts.length;
    }

}

jQuery code:

$(document).ready(function(){
    function contractInvocation() {
        var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        var abi = <ABI>;
        var testContract = web3.eth.contract(abi);
        var contractInstance = testContract.at('<Contract Address>');
        var y = contractInstance.getContractsCount.call({from:web3.eth.accounts[0]}).c[0];
        console.log(y);
});
Related Topic