Contract Invocation – Running Contract Function Returns Error ‘invalid opcode’

contract-developmentcontract-invocationtestrpc

Looks like there are a couple of unanswered threads about this already, though mine is a more simple setup so maybe it will be easier to debug.

Running through testrpc I have a deployed contract, it deploys ok. I can access a contract function displayMessage in the callback of deployed contract ok.

However, I wish run the function on another page:

const contract = web3.eth.contract(abi);
const existingContract = contract.at(contractAddress);
existingContract.displayMessage(function(response){
  console.log('displaymsg')
  console.log(response)
})

The callback function in the response var returns: Error: VM Exception while processing transaction: invalid opcode.

Running console.log(existingContract.displayMessage()) returns the same error.

I have tried manually writing out my abi variable as an array:

const abi = [{
  type: 'function',
  name: 'displayMessage',
  inputs: [],
  outputs: [],
  constant: true,
  payable: false
}]

as well as using the dynamic approach (getting from the file) just incase something was wrong there:
const abi = JSON.parse(compiledContract.contracts[':contractName'].interface)

Can anyone advise on why I would be receiving this error & how to proceed?

Edit:

As requested, here is my contract:

pragma solidity ^0.4.0;

contract contractName {
  function displayMessage() constant returns (string){
    return ("{var}");
  }
}

To give a bit more insight, when creating the initial contract, I am replacing {var} with dynamic data:

fs.readFile(__dirname+'/../solc/contract.sol', 'utf8', function(err, data){
  const source = data.replace('\{var\}', data);
  const compiled = solc.compile(source);
  ...

Best Answer

Sorry, I've tried your contract and it work as expected here

$ testrpc              
EthereumJS TestRPC v4.1.3 (ganache-core: 1.1.3)

Contract deployed using remix.ethereum.org connected to testrpc.

query.js
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const contractAddress = "0xeea88acc603d832800e60e11eaae00d3a3197709";
const contractAbi = [{"constant":true,"inputs":[],"name":"displayMessage","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}];

const contract = web3.eth.contract(contractAbi);
const existingContract = contract.at(contractAddress);
existingContract.displayMessage(function(error, response){
  if (error) {
    console.log(`displayerr: ${error}`);
  } else {
    console.log(`displaymsg: ${response}`);
  }
});
contractName.sol
pragma solidity ^0.4.0;

contract contractName {
  function displayMessage() constant returns (string){
    return ("{var}");
  }
}
package.json
{
  "name": "strings",
  "version": "1.0.0",
  "description": "",
  "main": "query.js",
  "license": "ISC",
  "dependencies": {
    "web3": "^0.20.2"
  }
}