0
0
Blockchain / Solidityprogramming~30 mins

View and pure functions in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
View and Pure Functions in Solidity
📖 Scenario: You are creating a simple smart contract for a blockchain application. This contract stores a number and allows users to read it without changing the blockchain state. You will learn how to write view and pure functions, which do not modify the blockchain data.
🎯 Goal: Build a Solidity contract named NumberStore that stores a number and includes two functions: one view function to read the stored number, and one pure function to add two numbers without changing the contract state.
📋 What You'll Learn
Create a state variable called storedNumber of type uint.
Write a view function named getStoredNumber that returns the value of storedNumber.
Write a pure function named addNumbers that takes two uint parameters and returns their sum.
Deploy the contract and print the results of calling both functions.
💡 Why This Matters
🌍 Real World
View and pure functions are essential in blockchain smart contracts to read data efficiently and perform calculations without changing the blockchain state, saving gas fees.
💼 Career
Understanding these functions is crucial for blockchain developers to write optimized and secure smart contracts.
Progress0 / 4 steps
1
DATA SETUP: Create the contract and state variable
Create a Solidity contract named NumberStore and inside it declare a uint state variable called storedNumber initialized to 42.
Blockchain / Solidity
Need a hint?

Use contract NumberStore {} to start and declare uint storedNumber = 42; inside.

2
CONFIGURATION: Add a view function to read the stored number
Inside the NumberStore contract, write a view function named getStoredNumber that returns the storedNumber variable.
Blockchain / Solidity
Need a hint?

Use function getStoredNumber() public view returns (uint) and return storedNumber.

3
CORE LOGIC: Add a pure function to add two numbers
Inside the NumberStore contract, write a pure function named addNumbers that takes two uint parameters called a and b, and returns their sum.
Blockchain / Solidity
Need a hint?

Define function addNumbers(uint a, uint b) public pure returns (uint) and return a + b.

4
OUTPUT: Print the results of calling the functions
Write a simple test in Solidity that calls getStoredNumber and addNumbers with 5 and 7, then returns their results. Use public functions to expose these calls.
Blockchain / Solidity
Need a hint?

Create two public functions that call getStoredNumber() and addNumbers(5, 7) and return their results.