首页 文章

使用web3 js调用智能合约功能

提问于
浏览
1

试图弄清楚如何从web3智能合约电话获取返回数据 . 到目前为止,我有ABI和 Contract 地址在这里创建 Contract 是代码:

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

区块链和智能合约是全新的,所以任何帮助都表示赞赏 . 谢谢 .

1 回答

  • 1

    我假设你正在使用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);
    });
    

    根据您的设置,您可能需要传递一个来自地址和/或其他参数,例如:

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

相关问题