使用 web3 js 调用智能合约函数

calling a smart contract function with web3 js

试图找出如何从 web3 智能合约调用中获取 return 数据。到目前为止,我已经有了创建合约的 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))

只是想看看它 return 是什么,但我得到了一个像这样的对象:

    {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

对区块链和智能合约完全陌生,因此非常感谢您的帮助。谢谢。

我假设您使用的是 web3.js 1.0-beta。

你需要这样的东西:

console.log(await kittyContract.methods.getKitty(887674).send());

或(如果不使用 async/await):

kittyContract.methods.getKitty(887674).send().then(function (result) {
    console.log(result);
});

根据您的设置,您可能需要传递发件人地址 and/or 其他参数,例如:

kittyContract.methods.getKitty(887674).send({ from: ..., ... }).then(...);

最后还需要有call()函数,也可以使用回调函数。

kittyContract.methods.getKitty(887674).call({from: address}, function(error, result){
console.log(result)
})