[英]Calling a public method in smart contract with Web3.js version: '1.0.0-beta.46'
I started first steps into ethereum blockchain with parity on a private network. 我开始在私有网络上以奇偶校验开始以太坊区块链的第一步。 I was able to configure parity and perform the deployment of smart contract on a dev mode chain on my private network through Parity UI which also is able to call methods of the contract.
通过Parity UI,我可以配置奇偶校验并在我的专用网络上的开发人员模式链上执行智能合约的部署,该UI也可以调用合约的方法。
The problem that I face is related to calling a function in smart contract using Web3.js. 我面临的问题与使用Web3.js在智能合约中调用函数有关。 I was able to connect to the chain using the Web.js Library;
我能够使用Web.js库连接到链。
Web3 = require('web3')
web3 = new Web3('ws://localhost:8546')
mycontract = web3.eth.Contract([{"constant":false,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}],0xEb112542a487941805F7f3a04591F1D6b04D513c)
When I call the method below; 当我调用下面的方法时;
mycontract.methods.greet().call()
It gives me the following output instead of returning the expected string "OK Computer" through a promise object as written in smart contract greet function. 它给了我以下输出,而不是通过智能合约greet函数中编写的promise对象返回期望的字符串“ OK Computer”。
{ [Function: anonymousFunction]
send: { [Function] request: [Function] },
estimateGas: [Function],
encodeABI: [Function] }
Smart Contract code: 智能合约代码:
pragma solidity ^0.4.22;
//Compiler Version: 0.4.22
contract Greeter {
address owner;
constructor() public {
owner = msg.sender;
}
function greet() public returns(string){
return "OK Computer";
}
}
Every transaction or smart contract method call which involves a change on the blockchain state will return a promise . 每个涉及区块链状态变化的交易或智能合约方法调用都将返回一个承诺 。 So you just need to handle the promise accordingly:
因此,您只需要相应地履行承诺即可:
mycontract.methods.greet.call().then(function(resp) {
console.log(resp) // This will output "OK Computer"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.