Web3.js 1.2调用智能合约方法,无法返回正确的结果

时间:2019-08-02 04:17:46

标签: geth remix

当我调用已部署的智能合约时,我没有得到正确的结果!

我已经用谷歌搜索,但无法获得任何帮助。

这是我的合同:

pragma solidity >=0.4.22 <0.6.0;
contract LYQFirst{
function userRegister() public payable returns(string memory)
{
    return "Hello World";
}
}

我的web3.js版本是1.2,web3.js代码如下:

    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);
 });

geth包括以下模块及其版本。模块:管理员:1.0调试:1.0 eth:1.0矿工:1.0净:1.0个人:1.0 rpc:1.0 txpool:1.0 web3:1.0。我通过npm install web3安装了web3.js 1.2,以便与geth进行交互。

我从web3代码中得到的结果如下:

{ 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)

1 个答案:

答案 0 :(得分:0)

如果它是来自Javascript的事务(发送而不是调用),则无法获得返回值。交易返回交易收据,这就是您得到的。

如果需要该值,请将其存储在公共存储变量中,并调用它的getter函数。