Introduction to Solidity
First Solidity Program
Beginner Level
Writing your first Solidity program is a great way to get familiar with the syntax, structure, and workflow of smart contracts on Ethereum. We’ll create a simple contract that stores and retrieves a message.
1. Understanding the Contract
A Solidity contract is similar to a class in object-oriented programming. It contains state variables, functions, and visibility modifiers.
In this example, we will create a contract called HelloWorld that:
- Stores a string message.
- Allows reading and updating the message.
2. The Code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract HelloWorld {
// State variable to store the message
string public message;
// Constructor to initialize the message when deploying the contract
constructor(string memory initMessage) {
message = initMessage;
}
// Function to update the message
function setMessage(string memory newMessage) public {
message = newMessage;
}
// Function to read the current message
function getMessage() public view returns (string memory) {
return message;
}
}
3. Code Explanation
-
pragma solidity ^0.8.20;
Specifies the Solidity compiler version. The ^ symbol ensures compatibility with versions 0.8.20 and above. -
contract HelloWorld { ... }
Defines a smart contract named HelloWorld. -
State Variable:
string public message;
This variable stores the message and is publicly readable. -
Constructor:
constructor(string memory initMessage)initializes the message when the contract is deployed. -
setMessage Function:
Updates the stored message. Marked as public so anyone can call it. -
getMessage Function:
Returns the current message. view means it doesn’t change blockchain state and doesn’t cost gas when called externally.
4. Deploying on Remix IDE
- Open Remix IDE.
- Create a new file named HelloWorld.sol.
- Paste the code above into the editor.
- Go to the Solidity Compiler tab and click Compile HelloWorld.sol.
-
Go to the Deploy & Run Transactions tab:
- Select the HelloWorld contract.
- Enter an initial message (e.g., "Hello, Ethereum!").
- Click Deploy.
-
Interact with the contract:
- Click getMessage to read the message.
- Use setMessage to update it, then call getMessage again to see the change.
5. Key Takeaways
- Solidity contracts are structured with state variables, functions, and optional constructors.
- Public variables automatically generate a getter function.
- View functions read blockchain state without costing gas.
- Remix IDE allows you to compile, deploy, and test smart contracts quickly without setting up a local environment.
Continue Learning
Explore more topics in Solidity or browse other tutorials.