求助:Solidity代码编译报ParserError错误,期望分号';'却得到关键字'contract'
Hey there! Let's break down why you're hitting this error and how to fix it.
The Root Cause
Your code is mixing Solidity contract syntax with JavaScript test code (looks like Mocha/Truffle test syntax), which the Solidity compiler can't parse. When the compiler reads your pragma solidity ^0.5.0; line, it expects either a semicolon to end the line or a valid Solidity contract definition next—but instead it sees contract('Token', ([deployer, receiver]) => { which is JavaScript, not Solidity. That's why it throws the ParserError.
The Fix: Split Your Code into Two Files
You need to separate your Solidity contract and your test code into distinct files, each using their own language's syntax.
1. Create a Solidity Contract File (Token.sol)
This is where you'll define your token contract using valid Solidity syntax:
pragma solidity ^0.5.0; contract Token { // Public state variables for token details string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // Constructor runs when the contract is deployed constructor() public { name = "Arv Token"; symbol = "ARVV"; decimals = 18; // Calculate total supply with 18 decimals (1 token = 1e18 wei) totalSupply = 1000000 * (10 ** uint256(decimals)); } }
2. Create a JavaScript Test File (token.test.js)
Put your test logic here (this works for Truffle or Mocha-based testing environments):
const Token = artifacts.require("Token"); // Helper function to convert token amount to wei (matches 18 decimals) function tokens(n) { return web3.utils.toWei(n.toString(), 'ether'); } contract('Token', ([deployer, receiver]) => { const name = 'Arv Token'; const symbol = 'ARVV'; const decimals = 18; const totalSupply = tokens(1000000); let token; // Deploy a fresh token instance before each test beforeEach(async () => { token = await Token.new(); }); // Example test case to verify token details it('initializes the token with correct values', async () => { const tokenName = await token.name(); assert.equal(tokenName, name, 'Token name matches'); const tokenSymbol = await token.symbol(); assert.equal(tokenSymbol, symbol, 'Token symbol matches'); const tokenDecimals = await token.decimals(); assert.equal(tokenDecimals.toString(), decimals.toString(), 'Decimals match'); const tokenTotalSupply = await token.totalSupply(); assert.equal(tokenTotalSupply.toString(), totalSupply, 'Total supply matches'); }); });
Why This Works
- The Solidity compiler only processes the
.solfile, which now has valid contract syntax—no more parsing errors. - The test file uses JavaScript syntax that your testing framework (like Truffle) understands, allowing you to deploy and test your contract correctly.
内容的提问来源于stack exchange,提问作者Christian

