Contract.methods.call() 返回错误 Web3-js

问题描述 投票:0回答:1

我正在使用 web3 CDN,并且我已经部署了具有两个变量的合同。示例:

pragma solidity ^0.5.0;

contract Sweet() {
    address public owner;
    uint256 sweets;
    uint256 shops;
    constructor(uint256 _sweets, uint256 _shops){
       owner = msg.sender;
       sweets = _sweet;
       shops = _shops;
    }

    function setSweetAndShop(uint256 _sweets, uint256 _shops) public {
       sweets = _sweets;
       shops = _shops;
    }
}

部署此示例代码后,混音中一切正常。之后,我创建了一个示例 DAPP。

async function change(){
var web3 = await new Web3(window.ethereum);
var account = await web3.eth.getAccounts();
var abi = [];
var contract = "0x000000000.........";
var token = new web3.eth.Contract(abi, contract);
try{
token.methods.setSweetAndShop(10, 20).call({
   from: account[0], 
   gas: 800000
})
.then(function(error, result) {
    if (!error){
            console.log(result);
        }else{
            console.log(error); //  This part is returning an error g{} , no data inside.
        }
    })
}catch(error){
    console.log(error)
}
}
javascript web3js
1个回答
0
投票

TL;博士 你的方法必须返回一些“可调用”的东西

与将交易广播到区块链的

MethodObject.send(options)
相反,
MethodObject.call(options)
函数不会在区块链中运行任何交易,它用于模拟RPC_NODE内部的EVM方法调用并获取函数的响应,调用无法更改智能合约状态

智能合约中的方法会改变状态并且不会返回任何内容,正如我们可以假设的那样,通过说模拟它并不禁止我们改变状态的EVM方法,但实际上它不会改变状态,但可用于预先确定一些突变,例如PancakeRouter中有一个方法

call
,它使用当前流动性状态变化模拟来预先确定交换的估计输出。
即使从逻辑上讲,调用不进行更改且不返回任何内容的方法也是不合逻辑的。

因此,您需要添加一个 return 语句以获得有用的方法并避免错误。

© www.soinside.com 2019 - 2024. All rights reserved.