Solidity 常见错误的触发可能: VM Exception while processing transaction: reverted with panic code 0x32 (Array accessed at an out-of-bounds or negative index)
常见错误的可能分析:
Error: VM Exception while processing transaction: reverted with panic code 0x32 (Array accessed at an out-of-bounds or negative index)
初步分析
这个错误翻译过来大概是: 发出去的交易出现了 VM 级别的异常:做了 reverted,错误代码是 0x32(使用了错误的索引访问了数组)
第一步排查
这时候需要仔细查看使用的数据结构是否符合自己的预期。比如如下两种结构是不同的
# 1
mapping(address => mapping(uint256 => UserInfo)) public userInfo;
# 2
mapping(address => UserInfo[]) public userInfo;
在第一种结构里,可以使用 userInfo[msg.sender][0];
这种数据来访问,因为使用的是 mapping 结构。
但是在第二种结构里,缺不可以这么访问,当访问 userInfo[msg.sender]
是没有问题的。但是这时候内部是空数据,此时再访问 [0]
是不对的,这会触发当前错误
第二部排查
如果已经确定数据结构是正确的,并且访问也是正确的,需要查看是否使用的错误。比如
# 1
user[count] = msg.sender;
# 2
user.push(msg.sender);
这里第一种访问是会报当前错误,可以改写为第二种方式。