In this tutorial, we're going to dive deeper into Solidity, a statically-typed programming language primarily used to write smart contracts on Ethereum-based platforms. Our goal is to understand Solidity's data types and functions, and learn how to use and manipulate them effectively.
By the end of this tutorial, you will be able to:
Prerequisites:
Solidity provides various data types, similar to other programming languages like JavaScript. Here are some of the common data types:
int / uint: These are used for integer values. 'uint' stands for 'unsigned integer', which means it can only hold positive values.
bool: bool data type is used for Boolean values: true or false.
address: This data type is used to store Ethereum addresses.
string: This is used for string values.
bytes1 to bytes32 / bytes: These are used for byte values. bytes1 to bytes32 are fixed-size byte arrays, while bytes is a dynamic byte array.
mapping: This is equivalent to hash tables or dictionaries in other languages. They are used to store key-value pairs.
array: Solidity supports both fixed-size and dynamic arrays.
A function in Solidity is a piece of code that can be reused. It can take some input, perform operations and return some output. Here is the basic syntax:
function functionName(type param1, type param2) public/external/internal/private returns (type) {
// function body
}
Modifiers in Solidity are code that can be used to modify the behavior of functions. They are typically used to check conditions before executing a function. Here is the basic syntax:
modifier modifierName {
// modifier code
_;
}
pragma solidity ^0.8.4;
contract DataTypes {
uint public myUint; // By default, uint is set to 0
bool public myBool; // By default, bool is set to false
address public myAddress; // By default, address is set to 0x0000000000000000000000000000000000000000
function setMyUint(uint _myUint) public {
myUint = _myUint; // Sets the value of myUint to the input value
}
function setMyBool(bool _myBool) public {
myBool = _myBool; // Sets the value of myBool to the input value
}
function setMyAddress(address _myAddress) public {
myAddress = _myAddress; // Sets the value of myAddress to the input address
}
}
pragma solidity ^0.8.4;
contract Functions {
address public owner;
constructor() {
owner = msg.sender; // Set the contract deployer as the owner
}
modifier onlyOwner {
require(msg.sender == owner); // Checks if the function caller is the owner
_;
}
function changeOwner(address _newOwner) public onlyOwner {
owner = _newOwner; // Change the owner to the new owner
}
}
In this tutorial, you have learned about:
Next steps:
Create a simple contract that manages a to-do list. Use an array to store the tasks, and functions to add and remove tasks.
Create a contract that manages a simple voting system. Use a mapping to store the votes, a modifier to ensure only eligible voters can vote, and functions to cast a vote and to get the current vote count.