0

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";
    }
}
Hassaan
  • 3
  • 1
  • 2

1 Answers1

1

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

Gabriel G.
  • 141
  • 6
  • Thanks for the response; the original point was also related to the behavior of the web3.js API that instead of the expected Promise object it returns the object as per the original post; still following your suggestion the output yielded for the statement `mycontract.methods.greet().call().then(function(res) { console.log(res) })`is **TypeError: mycontract.methods.myFunction(...).call(...).then is not a function** – Hassaan Feb 28 '19 at 11:09
  • Following the [web3 documentation](https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-call) I tried locally and the following _mycontract.methods.greet.call().then(console.log);_ prints "Ok Computer" – Gabriel G. Feb 28 '19 at 12:34
  • The address of the contract is supposed to be a string, that I totally overlooked while reading the documentation. Once wrapped in quotes it worked as per your suggestion. – Hassaan Apr 18 '19 at 12:03