Unit 5 (1)
Unit 5 (1)
Definition: Solidity is a high-level programming language used for writing smart contracts on
Ethereum and other blockchain platforms.
Why Solidity?: Powers decentralized applications (dApps) and automates transactions.
Key Features: Static typing, inheritance, libraries, user-defined types.
Solidity resembles JavaScript and C++, but it’s designed for Ethereum Virtual Machine (EVM).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract HelloWorld {
string public greeting = "Hello, World!";
Solidity supports standard control flow structures like if , else , for , while , and do while .
contract ControlFlow {
function checkNumber(uint num) public pure returns (string memory) {
if (num > 10) {
return "Greater than 10";
} else if (num == 10) {
return "Equal to 10";
} else {
return "Less than 10";
}
}
}
Solidity supports multiple data types: uint , int , bool , address , and bytes .
contract DataTypes {
uint public number = 42;
bool public isTrue = true;
address public owner = msg.sender;
bytes32 public data = "Hello";
Slide 5: Variables
contract Variables {
uint public stateVariable = 10; // State variable
Slide 6: Operators
contract Operators {
function calculate(uint a, uint b) public pure returns (uint) {
uint sum = a + b;
uint product = a * b;
return sum + product;
}
}
State variables are stored on the blockchain, while local variables are temporary and exist in memory
during function execution.
contract StorageExample {
uint public storedData;
Every transaction costs gas, measured in Ether. Gas is used to pay for computations and storage on
Ethereum.
contract GasExample {
uint public data;
Slide 9: Events
Events allow smart contracts to communicate with external applications through logs.
contract EventExample {
event DataStored(uint data);
Before diving into scenarios and use cases, let’s briefly explain some fundamental concepts, such as
msg.sender , msg.value , tx.gasprice , and block.timestamp , that are frequently used in Solidity smart
contracts.
1. msg.sender :
Refers to the address that initiated the transaction. In the context of a function, msg.sender
represents the caller of the function.
Used to ensure only certain addresses (like the contract owner) can perform specific actions.
Example:
constructor() {
owner = msg.sender; // Sets the owner as the person who deployed the contract
}
2. msg.value :
Represents the amount of Ether (in wei) sent along with the transaction.
Used to transfer Ether or check if the correct amount of Ether has been sent.
Example:
3. tx.gasprice :
Returns the gas price for the current transaction. Useful for calculating how much gas will be
consumed.
Example:
4. block.timestamp :
Returns the current block’s timestamp in seconds since the Unix epoch. Often used in time-
based conditions.
Example:
Here are five common use cases for Solidity smart contracts, each with an example contract demonstrating
how the scenario is implemented.
Use Case: Allow users to deposit and withdraw Ether from a personal wallet.
Concepts Used: msg.sender , msg.value , payable .
Code Example:
contract SimpleWallet {
address public owner;
constructor() {
owner = msg.sender; // The deployer of the contract is the owner
}
Use Case: Create an auction where bids are only accepted within a certain time frame.
Concepts Used: block.timestamp , payable , msg.value .
Code Example:
contract Auction {
address public owner;
uint public highestBid;
address public highestBidder;
uint public auctionEndTime;
constructor(uint _durationMinutes) {
owner = msg.sender;
auctionEndTime = block.timestamp + _durationMinutes * 1 minutes;
}
highestBid = msg.value;
highestBidder = msg.sender;
}
// End the auction and send the highest bid to the owner
function endAuction() public {
require(msg.sender == owner, "Only the owner can end the auction");
require(block.timestamp >= auctionEndTime, "Auction is still ongoing");
payable(owner).transfer(highestBid);
}
}
Use Case: Contributors fund a project, and the funds are only released if a target is met.
Concepts Used: msg.value , block.timestamp , refunding contributions.
Code Example:
contract Crowdfunding {
address public owner;
uint public goal;
uint public deadline;
mapping(address => uint) public contributions;
payable(owner).transfer(address(this).balance);
}
Use Case: Lock tokens for a certain period before they can be claimed.
Concepts Used: block.timestamp , require , locking mechanism.
Code Example:
contract TokenVesting {
address public beneficiary;
uint public releaseTime;
uint public tokenAmount;
Use Case: Allow users to vote on proposals, and only the owner can finalize the result.
Concepts Used: msg.sender , mapping , require .
Code Example:
contract Voting {
address public owner;
mapping(string => uint) public votes;
mapping(address => bool) public hasVoted;
constructor() {
owner = msg.sender;
}
votes[proposal]++;
hasVoted[msg.sender] = true;
}
ERC20 is a standard interface for tokens that allows for transferability and interaction with
decentralized exchanges.
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
constructor() {
balances[msg.sender] = totalSupply;
}
ERC721 is a standard for non-fungible tokens, often used in digital art and collectibles.
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
Solidity enables decentralized applications by providing smart contract functionality on the Ethereum
network.
Key concepts include data types, control flow, events, and standard token interfaces like ERC20 and
ERC721.