Solidity代码编译报错:Expected ';' but got 'constructor'求助
解决Solidity编译错误:ParserError: Expected ';' but got 'constructor'
这个错误是因为代码中使用了HTML转义字符(<代替<,>代替>),Solidity编译器无法识别这些字符,导致语法解析失败,进而在constructor关键字处提示缺少分号。
修正步骤:
- 将代码中所有的
<替换为<,>替换为> - 额外注意: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
相关产品推荐
相关产品推荐

