Blockchain and Web3 course ยท Module 6: Solidity Basics
Solidity - The Language of Automated Mechanisms
In this lesson6
Welcome to the Hall of Mechanisms! Atlas here. Today you'll learn Solidity - the language used to write automated mechanisms (smart contracts) that operate in the Crypt's tunnels.
What is Solidity?
Solidity is a programming language created specifically for Ethereum. It lets you write smart contracts - programs that run on the blockchain.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract HelloKrypta {
string public message = "Welcome to the Crypt!";
function setMessage(string memory newMessage) public {
message = newMessage;
}
}Contract Structure
// 1. License (required since Solidity 0.6.8)
// SPDX-License-Identifier: MIT
// 2. Compiler version
pragma solidity ^0.8.20;
// 3. Imports (optional)
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// 4. Contract definition
contract MyContract {
// 5. State variables
uint256 public myNumber;
address public owner;
// 6. Events
event NumberChanged(uint256 newNumber);
// 7. Modifiers
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
// 8. Constructor
constructor() {
owner = msg.sender;
}
// 9. Functions
function setNumber(uint256 _number) public onlyOwner {
myNumber = _number;
emit NumberChanged(_number);
}
}Data Types
// Value types
bool isActive = true;
uint256 amount = 1000; // unsigned integer (0 to 2^256-1)
int256 temperature = -10; // signed integer
address wallet = 0x123...; // Ethereum address (20 bytes)
bytes32 hash = keccak256(...); // fixed-size bytes
// Reference types
string name = "Atlas";
bytes data = hex"001122";
uint256[] numbers; // dynamic array
uint256[10] fixedArray; // fixed array
mapping(address => uint256) balances;
// Struct
struct User {
string name;
uint256 balance;
bool isActive;
}Visibility
contract Visibility {
uint256 public publicVar; // Accessible everywhere, auto-getter
uint256 private privateVar; // Only in this contract
uint256 internal internalVar; // This contract + inheriting ones
uint256 external externalVar; // Not for variables!
function publicFunc() public {} // Accessible everywhere
function privateFunc() private {} // Only internally
function internalFunc() internal {} // + inheriting contracts
function externalFunc() external {} // Only from outside
}Functions - view, pure, payable
contract Functions {
uint256 public value;
// view - reads state, does not modify
function getValue() public view returns (uint256) {
return value;
}
// pure - does not read or modify state
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
// payable - can receive ETH
function deposit() public payable {
// msg.value contains the sent ETH
}
// regular - can modify state
function setValue(uint256 _value) public {
value = _value;
}
}Summary
- Solidity - the language of smart contracts
- Contract structure
- Data types (value, reference)
- Visibility (public, private, internal, external)
- Functions (view, pure, payable)
Code for this lesson: index.js
// Solidity - syntax basics
// (simulation in JavaScript - real Solidity requires a compiler)
class SolidityContract {
// Data types in Solidity
static TYPES = {
// Integers
uint8: { min: 0, max: 255 },
uint256: { min: 0, max: BigInt("2") ** BigInt("256") - BigInt("1") },
int256: { min: -(BigInt("2") ** BigInt("255")), max: BigInt("2") ** BigInt("255") - BigInt("1") },
// Boolean
bool: [true, false],
// Address (20 bytes)
address: "0x" + "0".repeat(40),
// Bytes
bytes32: "0x" + "0".repeat(64)
};
constructor() {
// State variables (stored in storage)
this.owner = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";
this.balance = BigInt(0);
this.name = "MyToken";
this.isActive = true;
}
}
console.log("=== DATA TYPES IN SOLIDITY ===\n");
console.log("INTEGER TYPES:");
console.log(" uint8: 0 to 255");
console.log(" uint256: 0 to 2^256-1 (default)");
console.log(" int256: -2^255 to 2^255-1");
console.log("\nOTHER TYPES:");
console.log(" bool: true/false");
console.log(" address: 20 bytes (Ethereum address)");
console.log(" bytes32: 32 bytes (hash)");
console.log(" string: dynamic text");
console.log("\n=== CONTRACT EXAMPLE ===");
console.log(`
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleStorage {
// State variables
uint256 public storedNumber;
address public owner;
string public name;
bool public isActive;
// Constructor
constructor(string memory _name) {
owner = msg.sender;
name = _name;
isActive = true;
}
// Function to store a number
function store(uint256 _number) public {
storedNumber = _number;
}
// View function (read-only)
function retrieve() public view returns (uint256) {
return storedNumber;
}
}
`);
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which line of code correctly declares the Solidity version in a smart contract?
2. Which data type in Solidity represents non-negative integers?
These are 2 of 16 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the elements of a basic smart contract in the correct order:
- Code editor
Create an object representing a simple contract with a 'myNumber' field set to 42
- Click in order
Arrange the elements in the correct order to create a function declaration that returns a uint value
- Code editor
Write a setValue function that takes a 'value' parameter and sets the this.storedValue field
- Horizontal ordering
Arrange the function visibilities from most restrictive to most open:
- Code editor
Write an add function that adds two numbers without using object fields
- Vertical ordering
Arrange the code correctly to show the difference between a state variable and a local one:
- Click in order
Arrange the elements in the correct order to create a mapping that stores address balances
- Code editor
Create a 'balances' object and add a balance of 100 for the address '0x123'
- Horizontal ordering
Arrange the steps for adding an element to an array in Solidity:
- Code editor
Create a 'numbers' array, add the numbers 1, 2, 3 to it, and return the array's length
- Vertical ordering
Arrange the declaration of the Person struct correctly:
- Code editor
Create a person object with the fields name: 'Alice' and age: 25
- Click in order
Arrange the elements in the correct order to create a Transfer event declaration
- Code editor
Write a transfer function that 'emits' an event via console.log with information about the transfer
- Vertical ordering
Arrange the declaration of the custom onlyOwner modifier correctly:
- Code editor
Write an onlyOwner function that checks whether caller === owner and throws an error if not
- Click in order
Arrange the elements in the correct order to create a balance validation
- Code editor
Write a withdraw function that checks whether balance >= amount and throws an error if not
- Horizontal ordering
Arrange the steps for defining and using a custom error in Solidity:
- Code editor
Create an InsufficientBalanceError class extending Error and use it in a function
- Vertical ordering
Arrange the contract inheritance example correctly:
- Click in order
Arrange the elements in the correct order to create a constructor that sets the owner
- Horizontal ordering
What does msg.sender represent in a transaction?
- Code editor
Create a SimpleStorage class with a constructor, a state variable, set and get functions, and an event
Tasks after this lesson
- QuestionSolidity Version
- Put in orderContract Structure
- QuestionInteger Types
- Coding taskYour First Smart Contract
- QuestionThe address Type
- Click in orderFunction Declaration
- QuestionFunction Visibility
- Coding taskFunction with Parameters
- QuestionThe view Modifier
- Put in orderVisibility Levels
- QuestionThe pure Modifier
- Coding taskA pure Function
- Put in orderState Variables vs Local Variables
- QuestionThe bool Type
- Click in orderMapping - Basics
- Coding taskMapping in Practice
- QuestionArrays in Solidity
- Put in orderArray Operations
- Coding taskWorking with Arrays
- QuestionStructs
- Put in orderStruct Declaration
- Coding taskCreating a Struct
- QuestionEvents in Solidity
- Click in orderEvent Declaration
- Coding taskEmitting an Event
- QuestionThe payable Modifier
- Put in orderCustom Modifiers
- Coding taskImplementing a Modifier
- QuestionRequire vs Assert
- Click in orderUsing require
- Coding taskError Handling
- QuestionRevert
- Put in orderCustom Errors
- Coding taskCustom error
- QuestionContract Inheritance
- Put in orderInheritance Structure
- QuestionConstructor
- Click in orderImplementing a Constructor
- QuestionString vs bytes
- Put in orderMsg.sender
- Coding taskComplete Smart Contract
- Project to submitProject - Advanced Contract
- ConversationModule Summary