解析合约逻辑中写的异常信息,其实通过以下两个步骤即可:
- 通过方法'eth_estimateGas'获取合约返回的异常信息。
- 解析上述方法响应返回参数中'data'字段的内容。
难点在于如何解析'data'字段的内容。
其实也不难,你只需要了解一下数据格式:方法'Error(string)'调用的abi-encoded。
以下为官网资料:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract VendingMachine {
address owner;
error Unauthorized();
function buy(uint amount) public payable {
if (amount > msg.value / 2 ether)
revert("Not enough Ether provided.");
// Alternative way to do it:
require(
amount <= msg.value / 2 ether,
"Not enough Ether provided."
);
// Perform the purchase.
}
function withdraw() public {
if (msg.sender != owner)
revert Unauthorized();
payable(msg.sender).transfer(address(this).balance);
}
}
The provided string is abi-encoded as if it were a call to a function Error(string)
. In the above example, revert("Not enough Ether provided.");
returns the following hexadecimal as error return data:
0x08c379a0 // Function selector for Error(string)
0x0000000000000000000000000000000000000000000000000000000000000020 // Data offset
0x000000000000000000000000000000000000000000000000000000000000001a // String length
0x4e6f7420656e6f7567682045746865722070726f76696465642e000000000000 // String data