You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Solidity代码编译报错:Expected ';' but got 'constructor'求助

解决Solidity编译错误:ParserError: Expected ';' but got 'constructor'

这个错误是因为代码中使用了HTML转义字符(&lt;代替<,&gt;代替>),Solidity编译器无法识别这些字符,导致语法解析失败,进而在constructor关键字处提示缺少分号。

修正步骤:

  1. 将代码中所有的&lt;替换为<,&gt;替换为>
  2. 额外注意:constructor中的哈希合并逻辑存在索引错误,原代码中hashes[offset + 1]应为hashes[offset + i],否则会导致Merkle树构建错误

修正后的完整代码:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Tree {
   bytes32[] hashes;
   string[4] transactions = [
       "first transaction",
       "second transaction",
       "third transaction",
       "fourth transaction"
   ];

   constructor() {
       for (uint i = 0; i < transactions.length; i++) {
           hashes.push(makeHash(transactions[i]));
       }

       uint count = transactions.length;
       uint offset = 0;

       while (count > 0) {
           // 只处理偶数对,所以循环条件是i < count - 1
           for (uint i = 0; i < count - 1; i += 2) {
               hashes.push(
                   keccak256(
                       abi.encodePacked(
                           hashes[offset + i],
                           hashes[offset + i + 1]
                       )
                   )
               );
           }
           offset += count;
           count = count / 2;
       }
   }

   function verify(
       string memory transaction,
       uint index,
       bytes32 root,
       bytes32[] memory proof
   ) public pure returns (bool) {
       bytes32 hash = makeHash(transaction);
       for (uint i = 0; i < proof.length; i++) {
           bytes32 element = proof[i];
           if (index % 2 == 0) {
               hash = keccak256(abi.encodePacked(hash, element));
           } else {
               hash = keccak256(abi.encodePacked(element, hash));
           }
           index = index / 2;
       }
       return root == hash;
   }

   function encode(string memory input) public pure returns (bytes memory) {
       return abi.encodePacked(input);
   }

   function makeHash(string memory input) public pure returns (bytes32) {
       return keccak256(encode(input));
   }
}

内容的提问来源于stack exchange,提问作者mbidnyj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:06:25