众筹智能合约编译报错:ParserError: Expected primary expression
Solidity众筹合约编译错误(ParserError)修复方案
错误原因及修复步骤
变量名不匹配
合约中定义的贡献者数组为address [] public suppliers;,但在contribute和returnFunds函数里使用了未声明的backers变量,这是触发语法错误的核心原因。需将数组变量名统一:要么把suppliers改为backers,要么将函数内的backers替换为suppliers。函数代码块未闭合
returnFunds函数的for循环结束后,缺少闭合整个函数的大括号,导致编译器无法解析代码结构,引发语法错误。可选优化(避免编译器警告)
Solidity 0.8.x版本中now已被标记为过时,建议使用block.timestamp替代,功能完全一致但更符合当前规范。
修正后的完整代码
// SPDX-License-Identifier: MIT pragma solidity ^0.8.8; contract Crowfunding { uint256 public fundingGoal; // 众筹目标金额 uint256 public deadline; // 众筹截止时间 uint256 public amountRaised; // 当前已筹集金额 mapping (address => uint256) public contributions; // 记录每个地址的贡献金额 address[] public backers; // 记录所有贡献者地址 bool public funded; uint256 public fundsReturned; constructor(uint256 _fundingGoal, uint256 _deadline) { fundingGoal = _fundingGoal; deadline = _deadline; } function contribute() public payable { require(msg.value > 0, "You must contribute a positive amount."); require(block.timestamp <= deadline, "The deadline for contributions has passed."); contributions[msg.sender] += msg.value; amountRaised += msg.value; backers.push(msg.sender); } function returnFunds() public { require(block.timestamp > deadline, "The deadline for contributions has not passed yet."); require(fundsReturned == 0, "The funds have already been returned."); for (uint256 i = 0; i < backers.length; i++) { backers[i].transfer(contributions[backers[i]]); } fundsReturned = amountRaised; // 标记退款完成,防止重复执行 } }
内容的提问来源于stack exchange,提问作者Belen Paccioretti
相关产品推荐
相关产品推荐

