0
0
Blockchain / Solidityprogramming~30 mins

Constants and immutables in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Constants and Immutables in Solidity
📖 Scenario: You are creating a simple smart contract for a blockchain-based voting system. You want to set some fixed values that never change after deployment, such as the election name and the maximum number of votes per person.
🎯 Goal: Build a Solidity contract that uses constant and immutable variables to store fixed data and demonstrate how to read them.
📋 What You'll Learn
Create a constant string variable called ELECTION_NAME with the value "Blockchain Election 2024".
Create an immutable unsigned integer variable called maxVotesPerPerson set via the constructor with the value 3.
Write a public function getElectionInfo that returns both ELECTION_NAME and maxVotesPerPerson.
Deploy the contract and print the election info.
💡 Why This Matters
🌍 Real World
Constants and immutables help save gas and ensure important values do not change after deployment in blockchain smart contracts.
💼 Career
Understanding these keywords is essential for blockchain developers to write efficient and secure smart contracts.
Progress0 / 4 steps
1
Create the contract and constant variable
Create a Solidity contract named Voting. Inside it, declare a public constant string variable called ELECTION_NAME and set it to "Blockchain Election 2024".
Blockchain / Solidity
Need a hint?

Use string public constant ELECTION_NAME = "Blockchain Election 2024"; inside the contract.

2
Add an immutable variable set by constructor
Inside the Voting contract, declare a public immutable uint variable called maxVotesPerPerson. Add a constructor that sets maxVotesPerPerson to 3.
Blockchain / Solidity
Need a hint?

Use constructor() { maxVotesPerPerson = 3; } to set the immutable variable.

3
Create a function to return election info
Add a public view function called getElectionInfo that returns (string memory, uint). It should return ELECTION_NAME and maxVotesPerPerson.
Blockchain / Solidity
Need a hint?

Return both variables as a tuple: return (ELECTION_NAME, maxVotesPerPerson);

4
Print the election info
Write a script or test code that calls getElectionInfo and prints the election name and max votes per person in the format: Election: Blockchain Election 2024, Max Votes: 3.
Blockchain / Solidity
Need a hint?

Solidity contracts do not print directly. Imagine calling getElectionInfo and displaying the returned values as shown.