0
0
Blockchain / Solidityprogramming~30 mins

Variable packing in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Variable Packing in Solidity
📖 Scenario: You are building a smart contract to store user information efficiently on the Ethereum blockchain. Since storage costs gas, you want to pack multiple small variables into a single storage slot.
🎯 Goal: Create a Solidity contract that uses variable packing to store a user's age, a boolean flag for membership, and a small number representing user level in a single storage slot.
📋 What You'll Learn
Create a contract named UserInfo
Declare three state variables: uint8 age, bool isMember, and uint8 level
Use variable packing by declaring the variables in the correct order
Write a function setUserInfo to set all three variables
Write a function getUserInfo that returns all three variables
💡 Why This Matters
🌍 Real World
Variable packing helps reduce gas costs in Ethereum smart contracts by storing multiple small variables in a single 32-byte storage slot.
💼 Career
Understanding variable packing is important for blockchain developers to write efficient and cost-effective smart contracts.
Progress0 / 4 steps
1
Create the contract and declare packed variables
Create a Solidity contract named UserInfo. Inside it, declare three state variables in this order: uint8 age, bool isMember, and uint8 level. This order helps Solidity pack them into one storage slot.
Blockchain / Solidity
Need a hint?

Declare the variables in the order: uint8 age, then bool isMember, then uint8 level to enable packing.

2
Add a function to set user info
Inside the UserInfo contract, write a public function named setUserInfo that takes three parameters: uint8 _age, bool _isMember, and uint8 _level. Assign these parameters to the state variables age, isMember, and level respectively.
Blockchain / Solidity
Need a hint?

Define a public function setUserInfo with three parameters and assign them to the state variables.

3
Add a function to get user info
Inside the UserInfo contract, write a public view function named getUserInfo that returns three values: uint8 for age, bool for isMember, and uint8 for level. Return the state variables in the order age, isMember, level.
Blockchain / Solidity
Need a hint?

Define a public view function getUserInfo that returns the three state variables in order.

4
Test the contract by setting and getting values
Write a simple test in Solidity by adding a public function named testUserInfo that calls setUserInfo with age = 30, isMember = true, and level = 5, then calls getUserInfo and returns the results.
Blockchain / Solidity
Need a hint?

Create a function testUserInfo that sets values and returns them to verify packing works.