Compiling a Contract
To add a contract and compile it using Hardhat, do the following:
-
In the project directory, create a
contracts
directory.mkdir contracts
-
Create a new file in the
contracts
directory calledHelloWorld.sol
. -
Copy and paste the following code into
HelloWorld.sol
.// SPDX-License-Identifier: MIT pragma solidity >=0.7.3; // Defines a contract named `HelloWorld`. contract HelloWorld { // Event emitted when update function is called event UpdatedMessages(string oldStr, string newStr); // Declares a state variable `message` of type `string`. string public message; // A constructor is a special function that is only executed upon contract creation. constructor(string memory initMessage) { message = initMessage; } // A public function that accepts a string argument and updates the `message` storage variable. function update(string memory newMessage) public { string memory oldMsg = message; message = newMessage; emit UpdatedMessages(oldMsg, newMessage); } }
-
Compile the contract by running the following command.
npx hardhat compile
You should see a message saying
Compiled 1 Solidity file successfully.
The command also creates a directory called
artifacts
that has some JSON files. TheHelloWorld.json
has the contract's code and application binary interface (ABI). These will be used for contract deployment and interaction.