【问题标题】:Solidity: Is it possible to combine event emit and require?Solidity:是否可以将事件发射和要求结合起来?
【发布时间】:2021-01-13 05:18:41
【问题描述】:

如果用户没有发送足够多的 Eth,我希望 UI 知道并回复消息。

此函数验证 msg.value,但在这种情况下我想触发和事件(UI 可以响应)。

function doSomething() external payable {
  require(
      msg.value == price,
      'Please send the correct amount of ETH'
  );
  //Do something
}

这是正确的做法吗?

有没有办法将 require() 与发送事件结合起来?

function doSomething() external payable {
 if (msg.value < amount){
   emit NotEnoughEth('Please make sure to send correct amount');
   revert();
 }

  //Do something
}

【问题讨论】:

    标签: blockchain ethereum solidity ether


    【解决方案1】:
    emit NotEnoughEth('Please make sure to send correct amount');
    

    你不能这样做。 为了能够发出types.Log,您需要您的evm.Call() 在不执行还原的情况下执行。您所指的 EVM 中有 2 条指令:makeLog (https://github.com/ethereum/go-ethereum/blob/2aaff0ad76991be8851ae30454d2e2e967704102/core/vm/instructions.go#L828) 这是创建事件日志的指令。和opRevert (https://github.com/ethereum/go-ethereum/blob/2aaff0ad76991be8851ae30454d2e2e967704102/core/vm/instructions.go#L806) ,所以如果你做revert,你的Call() 会返回一个错误,并且所有在ethereum State 数据库上的交易结果都将被revert 并且什么都不会被保存。由于存储被取消,你的日志无法保存在区块链上。

    这是检查错误并恢复到以前保存的状态(又名快照)的代码:

        if err != nil {
            evm.StateDB.RevertToSnapshot(snapshot)
            if err != ErrExecutionReverted {
                gas = 0
            }
            // TODO: consider clearing up unused snapshots:
            //} else {
            //  evm.StateDB.DiscardSnapshot(snapshot)
        }
        return ret, gas, err
    }
    

    https://github.com/ethereum/go-ethereum/blob/2aaff0ad76991be8851ae30454d2e2e967704102/core/vm/evm.go#L280

    即使 opRevert() 指令没有显式返回错误,跳转表也被配置为始终为 opRevert 返回错误:

    instructionSet[REVERT] = &operation{
        execute:    opRevert,
        dynamicGas: gasRevert,
        minStack:   minStack(2, 0),
        maxStack:   maxStack(2, 0),
        memorySize: memoryRevert,
        reverts:    true,
        returns:    true,
    }
    

    https://github.com/ethereum/go-ethereum/blob/2aaff0ad76991be8851ae30454d2e2e967704102/core/vm/jump_table.go#L155

    解释器将自行发出errExecutionReverted

        case operation.reverts:
            return res, ErrExecutionReverted
    

    https://github.com/ethereum/go-ethereum/blob/2aaff0ad76991be8851ae30454d2e2e967704102/core/vm/interpreter.go#L297

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-18
      • 2020-05-26
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多