Create Your First Contract
Learn how to create a simple smart contract.
We’re going to use Solidity to write a simple HelloWorld
smart contract. This is our starting point to create more complex logic and functions.
The HelloWorld
contract
This contract aims to store a string variable called message
on the blockchain. The initial value is set to a "Hello, World!"
string, but the contract also provides a public function called setMessage
to allow changing the value of the message
variable. The basic structure of the contract is:
// SPDX-License-Identifier: MITpragma solidity ^0.8.0;contract HelloWorld {}
Line 1: Indicates the license under which the contract is released.
Line 3: Specifies the version of the Solidity compiler to be used. The
^
symbol means it is compatible with version0.8.0
and higher.Line 5: Declares a new smart contract named
HelloWorld
.
Next, the contract needs a state variable named message
. The variable must be accessible to external calls, so it is declared with the public
keyword.
// SPDX-License-Identifier: MITpragma solidity ^0.8.0;contract HelloWorld {string public message;}
Now, the contract needs the constructor (executed only once when the contract is deployed) and the setMessage()
function.
// SPDX-License-Identifier: MITpragma solidity ^0.8.0;contract HelloWorld {string public message;constructor() {message = "Hello, World!";}function setMessage(string memory newMessage) public {message = newMessage;}}
The smart contract is now complete.