Ethereum: Compilation failed in solidity
Here is an example article:
Ethereum Compilation Error: “Compilation Failed” in Solidity
When developing a new smart contract for the Ethereum blockchain, it is not uncommon to encounter compilation errors. In this article, we will take a look at an error that occurs when compiling Solidity code using Hardhat.
Problem
In your Hardhat project, you have defined a contract called “Marketplace” with several events. However, during compilation, an error occurs that prevents the contract from successfully compiling. The exact error message states that “Compilation Failed.”
Error Message
The error message is very detailed and contains valuable information about the cause of the problem. The exact text of the error message will depend on the version of Solidity you are using. Here is an example output:
Compilation Failed
Compilation Error: Compilation Failed; expected 'contract 2 _events 1', found '_events 0'
Cause of error
This error usually occurs when you define multiple events in your contract without mapping them in any way. The compiler requires that each event has a corresponding function that can handle it.
In your case, you have defined an event called “UserCreated”, but it does not seem to be mapped to a function (e.g. “onCreate”, “onConnected”, etc.). This means that the compiler expects a function to handle this event, and you have not provided one.
How to fix the error
To fix this problem, you need to add a mapping for each event in your contract. For example:
event UserCreated(
string memory _user,
address memory _address
);
You can also use onEvent
instead of an event with no arguments, which will automatically handle the event.
pragma solidity ^0.8.0;
Contract Market {
function createUser(string memory _user, address memory _address) public {
emit UserCreated(_user, _address);
}
}
Alternatively, you can use onEvent
with mapping to map events to their corresponding functions.
pragma solidity ^0.8.0;
Contract Market {
mapping (string memory => event) mapping (address => event) public events;
function createUser(string memory _user, address memory _address) public {
events[User Created](_user, _address);
}
}
Conclusion
In conclusion, the “Compilation failed” error that occurs when compiling Solidity code in the Hardhat project is often caused by missing event mappings. By adding these mappings to your contract, you can resolve the compilation issue and successfully deploy your smart contract to the Ethereum blockchain.
Remember to always check the official Solidity documentation and the Ethereum website for more information on event definitions and mapping concepts.