0

I have a simple contract with a simple test-function:

pragma solidity ^0.5.0;

contract TestContract{
  uint public a;
  uint public b;

constructor(uint _a, uint _b) public {
  a = _a;
  b = _b;
}

function TestFunc(uint c, uint d) public view returns(bool success){
  if (c == d){
    return false;
  }
  else{
      return true;
  }
}}

I want to deploy this contract on my local instance of Ganache and call the TestFunc function through a javascript file, using web3js functionality. My javascript file is as follows:

const Web3 = require('web3')
const fs = require('fs');

const options = {
    transactionConfirmationBlocks: 1,
}

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"), null, options);

const contract_Abi = [...] //Copied from Truffle's TestContract.json file
bytecode = ... // This is the bytecode (not the deployedBytecode) from the TestContract.json file

const contract = new web3.eth.Contract(contract_Abi);

async function call_TestFunc(){
  accounts = await web3.eth.getAccounts();
  const gas = await contract.deploy({data: bytecode, arguments:[1,1]}).estimateGas();
  const response = await contract.deploy({data:bytecode, arguments: [1,1]}).send({
    from: accounts[0],
    gas: gas + 1
  });
  console.log(response.jsonInterface);
  const txHash = await response.TestFunc.sendTransaction([1,2], {from:accounts[0]});
  console.log(txHash);
}

call_TestFunc();

Now when I run this script, the response.jsonInterface shows the following:

AbiModel {
  abi:
   { methods:
      { a: [Object],
        '0x0dbe671f': [Object],
        'a()': [Object],
        b: [Object],
        '0x4df7e3d0': [Object],
        'b()': [Object],
        contractConstructor: [Object],
        TestFunc: [Object],
        '0x3ff9143f': [Object],

        'TestFunc(uint256,uint256)': [Object] },
     events: {} } }

but when reaching the part where TestFunc is called it gives the following error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sendTransaction' of undefined

How can I call the TestFunc method properly?

0

I think you want this:

const txHash = await response.methods.TestFunc([1, 2]).send({from: accounts[0]});

Perhaps you're mixing up web3.js 0.2.x syntax with web3.js 1.0-beta syntax?

  • Yes, using that (and removing the [] brackets) solved the problem for me. Thank you so much! – Stefan May 23 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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