ethereumsmartcontractsweb3jsparity-io

Calling a public method in smart contract with Web3.js version: '1.0.0-beta.46'


I started first steps into ethereum blockchain with parity on a private network. I was able to configure parity and perform the deployment of smart contract on a dev mode chain on my private network through Parity UI which also is able to call methods of the contract.

The problem that I face is related to calling a function in smart contract using Web3.js. I was able to connect to the chain using the Web.js Library;

Web3 = require('web3')

web3 = new Web3('ws://localhost:8546')

mycontract = web3.eth.Contract([{"constant":false,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}],0xEb112542a487941805F7f3a04591F1D6b04D513c)

When I call the method below;

mycontract.methods.greet().call()

It gives me the following output instead of returning the expected string "OK Computer" through a promise object as written in smart contract greet function.

{ [Function: anonymousFunction]
  send: { [Function] request: [Function] },
  estimateGas: [Function],
  encodeABI: [Function] }

Smart Contract code:

pragma solidity ^0.4.22;
//Compiler Version: 0.4.22
contract Greeter {
    address owner;

    constructor() public { 
        owner = msg.sender; 
    }    
    function greet() public returns(string){
        return "OK Computer";
    }
}

Solution

  • Every transaction or smart contract method call which involves a change on the blockchain state will return a promise. So you just need to handle the promise accordingly:

    mycontract.methods.greet.call().then(function(resp) {
       console.log(resp) // This will output "OK Computer"
    }
    

    More in web docs