'Web3.js 1.2 invocation smart contract method and can not return correct result
When I invoke the smart contract deployed, I don't get the correct result!
I have googled, but can not fine any help.
Here is my contract:
pragma solidity >=0.4.22 <0.6.0;
contract LYQFirst{
function userRegister() public payable returns(string memory)
{
return "Hello World";
}
}
and my web3.js version is 1.2 and the web3.js code is as follows:
var Web3 = require('web3');
if (typeof web3 !== 'undefined') {
console.log("Hello World");
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider ("http://localhost:8545"));
}
var contract1 = new web3.eth.Contract([
{
"constant": false,
"inputs": [],
"name": "userRegister",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": true,
"stateMutability": "payable",
"type": "function"
}
],"0xd62f32665ac53749ded4a38d984d70f180d2908a");
contract1.methods.userRegister().send
({from: "0x18244fbf3b47175cd6b4a1183a476c9e70cb7368",gas:200000}).then (function(error,result){
console.log(error);
console.log("result="+result);
});
The geth including followings modules and their versions.
modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0.
I installed web3.js 1.2 by npm install web3
for interacting with geth.
The result I got from web3 code is as following:
{ blockHash:
'0x4865c3845d88d7022962833b663ed298f1a0e5b2e7e4905c7b0c968972790174',
blockNumber: 3186,
contractAddress: null,
cumulativeGasUsed: 21847,
from: '0x18244fbf3b47175cd6b4a1183a476c9e70cb7368',
gasUsed: 21847,
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
root:
'0x0141214730cebc516bf7036c8b36a24af0a29dbc11ef8ef9daf05448bb84eec5',
to: '0xd62f32665ac53749ded4a38d984d70f180d2908a',
transactionHash:
'0x804d4751eb7ab6b5f31f709dafc98bfa0b7433758ac9b0d58348b34173f832b8',
transactionIndex: 0,
events: {} }
result=undefined
<<< Process finished (PID=9824). (Exit code 0)
Solution 1:[1]
You cannot get return value if it's a transaction (send, not call) from Javascript. Transactions return transaction receipt, and that's what you got.
If you need the value, store it an a public storage variable and call it's getter function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ferit |