试图弄清楚如何从web3智能合约调用中获取返回数据。到目前为止,我已经有了创建合同的ABI和合同地址,这里是代码:
const web3 = new Web3(window.web3.currentProvider);
// Initialize the contract instance
const kittyContract = new web3.eth.Contract(
KittyCoreABI, // import the contracts's ABI and use it here
CONTRACT_ADDRESS,
);
ABI有一个名为getKitty的函数,该函数是:
{
"constant": true,
"inputs": [
{
"name": "_id",
"type": "uint256"
}
],
"name": "getKitty",
"outputs": [
{
"name": "isGestating",
"type": "bool"
},
{
"name": "isReady",
"type": "bool"
},
{
"name": "cooldownIndex",
"type": "uint256"
},
{
"name": "nextActionAt",
"type": "uint256"
},
{
"name": "siringWithId",
"type": "uint256"
},
{
"name": "birthTime",
"type": "uint256"
},
{
"name": "matronId",
"type": "uint256"
},
{
"name": "sireId",
"type": "uint256"
},
{
"name": "generation",
"type": "uint256"
},
{
"name": "genes",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
我正在尝试调用它,现在只是控制台记录输出,例如:
console.log(kittyContract.methods.getKitty(887674))
只是看它返回什么,但是我得到一个像这样的对象
{call: ƒ, send: ƒ, encodeABI: ƒ, estimateGas: ƒ, arguments: Array(1), …}
arguments
:
[887674]
call
:
ƒ ()
encodeABI
:
ƒ ()
estimateGas
:
ƒ ()
send
:
ƒ ()
_ethAccounts
:
Accounts {_requestManager: RequestManager, givenProvider: MetamaskInpageProvider, providers: {…}, _provider: MetamaskInpageProvider, …}
_method
:
{constant: true, inputs: Array(1), name: "getKitty", outputs: Array(10), payable: false, …}
_parent
:
Contract {_requestManager: RequestManager, givenProvider: MetamaskInpageProvider, providers: {…}, _provider: MetamaskInpageProvider, …}
__proto__
:
Object
对于区块链和智能合约来说是全新的,因此感谢您的帮助。谢谢。
答案 0 :(得分:1)
我假设您正在使用web3.js 1.0-beta。
您需要这样的东西:
console.log(await kittyContract.methods.getKitty(887674).send());
或(如果未使用异步/等待):
kittyContract.methods.getKitty(887674).send().then(function (result) {
console.log(result);
});
根据您的设置,您可能需要传递一个发件人地址和/或其他参数,例如:
kittyContract.methods.getKitty(887674).send({ from: ..., ... }).then(...);
答案 1 :(得分:0)
您还需要在最后使用call()函数,还可以使用回调函数。
kittyContract.methods.getKitty(887674).call({from: address}, function(error, result){
console.log(result)
})