【问题标题】:Fallback function not being called when function does not exist in contract合约中不存在函数时不调用后备函数
【发布时间】:2020-01-07 08:28:57
【问题描述】:

我创建了一个带有后备功能的智能合约,当在不存在的合约上调用方法时,我希望调用该功能。但是,我没有调用回退函数,而是得到错误:lotteryContract.methods.getPlayers() is not a function。

为什么不调用回退函数?

这是存在于 lotteryContract 中的后备函数:

function () external payable {
    .... delegates call to another contract ...

}

这里是测试(getPlayers() 在 lotteryContract 中不存在):

beforeEach(async () => {
    accounts = await web3.eth.getAccounts(); // unlocked accounts 
    created automatically for us with ganache

    // use accounts[0] to deploy lottery contract to the test network
    lotteryContract = await new 
         web3.eth.Contract(JSON.parse(compiledLottery.interface))
        .deploy({data: compiledLottery.bytecode})
        .send({gas: '1000000', from: accounts[0]});
    });

describe('Upgrading a Lottery Contract', () => {

it('allows one account to enter', async () => {

        const players = await 
        lotteryContract.methods.getPlayers().call({
        from: accounts[0]
        });

 })
}

我认为我可能错误地调用了 lotteryContract 上的方法(具有回退功能)?

【问题讨论】:

  • 您的 ABI 中有 getPlayers() 吗?您应该在 ABI 中而不是在合同本身中拥有它
  • 为什么它需要在 ABI 中?是不是应该在合约不识别函数调用的基础上调用fallback函数?这就是后备功能的重点吗?
  • 您的后备功能是正确的。您从 web3 收到错误,因为您尝试调用不在 ABI lotteryContract.methods 中的函数。
  • 有没有办法在这种情况下调用回退函数?
  • 您可以将getPlayers() 方法添加到您的compiledLottery.interface

标签: mocha.js ethereum solidity web3


【解决方案1】:

您尝试做的事情是不可能的。 lotteryContract.methods 填充了 ABI 中存在的函数,因此您尝试调用的方法 getPlayers() 不存在,因此代码在调用智能合约之前失败并出现 javascript 异常。

【讨论】:

    【解决方案2】:

    如果要触发fallback函数,最简单的方法是使用sendTransaction。

    const receipt = await web3.eth.sendTransaction({
        from: accounts[0],
        to: lotteryContract.options.address,
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2021-10-17
      • 2021-12-25
      • 2021-12-13
      • 2017-08-07
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多