I'm trying to connect a NodeJs server to a solidity contract thats been migrated to a local blockchain and then call the methods on this class via javascript. However, the code returns an error stating that getGreeting()
is not defined.
I'm very new Solidity and JavaScript (background in C and Java) so I feel like I'm overlooking something really simple?
My question is how to get it to work and find the method and return "Hello, World!" to the terminal?
My development environment is:
- Truffle v5.1.10 (core: 5.1.10)
- Solidity - 0.4.25 (solc-js)
- Node v12.14.1
- Web3.js v1.2.1
Below is the code I'm working on:
// import our compiled JSON
const contractJSON = require("./build/contracts/Hello.json");
const contract = require("@truffle/contract");
const Web3 = require('web3');
// create instance of ganache-cli provider
const web3 = new Web3("http://localhost:9545");
var Hello = contract(contractJSON);
Hello.setProvider(web3);
// if contract is deployed return instance of it and store in app variable
let app = Hello.deployed().then((instance) =>{
return instance;
}).catch(function(error) {
return error;
});
// call a method on our contract via javascript
app.getGreeting().then(() => {
console.log(app);
});
For context the Solidity contract is as follows:
pragma solidity >=0.4.0 <0.7.0;
contract Hello {
string greeting;
constructor() public {
greeting = "Hello, World!";
}
function getGreeting() public view returns (string memory) {
return greeting;
}
function setGreeting(string memory _greeting) public {
greeting = _greeting;
}
}
app
is a Promise, and Promises don't have agetGreeting
method. This should work:app.then(instance => instance.getGreeting()).then(...);
– blexapp.then(instance => instance.getGreeting()).then(console.log);
However, i still get the same error...UnhandledPromiseRejectionWarning: TypeError: instance.getGreeting is not a function
– user5770672instance.getGreeting
returns a String, not a function? Try logginginstance.getGreeting
without()
– blexundefined
in the terminal. Any suggestions? I appreciate the help. – user5770672Cannot read property 'getGreeting' of undefined
, and notinstance.getGreeting is not a function
. What happens if you log the instance like this? – blex