Solidity彩票合约数组值无法读取,调用交易触发回滚求助
问题分析与修复方案
核心问题1:数组越界触发交易回滚
你的participate函数中,for循环条件写成了i <= participantList.length,但Solidity数组的有效索引范围是0到length-1。当i等于participantList.length时,访问participantList[i]会触发数组越界异常,直接导致交易回滚。
核心问题2:逻辑错误导致重复添加或异常
就算修复了循环条件,当前逻辑依然存在问题:遍历数组时,只要遇到一个地址不等于msg.sender的参与者,就会立即插入新记录,这会导致同一用户多次参与时,重复添加多条记录,而非累加彩票数量。
修复后的代码
//SPDX-License-Identifier:MIT pragma solidity ^0.8.7; contract Lottery{ struct Participant{ address participantAddr; uint noOfLotts; } address public manager; Participant [] public participantList; constructor(){ manager = msg.sender; } function participate () external payable{ require(msg.value == 2 ether,"The amount must be equal to 2 Ethers"); bool isExisting = false; // 遍历数组查找已存在的参与者 for(uint i = 0; i < participantList.length; i++){ if(participantList[i].participantAddr == msg.sender){ participantList[i].noOfLotts++; isExisting = true; break; // 找到后立即跳出循环,减少不必要的遍历 } } // 未找到则添加新参与者 if(!isExisting){ participantList.push(Participant(msg.sender,1)); } } }
修复说明
- 将循环条件改为
i < participantList.length,彻底避免数组越界问题 - 新增
isExisting标记位,先完整遍历数组确认用户是否已存在 - 找到用户则累加彩票数,未找到再插入新记录,确保逻辑符合需求
内容的提问来源于stack exchange,提问作者VIVEK T
相关产品推荐
相关产品推荐

