Solidity is the popular programming language for building smart contracts on blockchain platforms, mostly Ethereum. In this article, we will learn the fundamentals of Solidity programming language and how to build smart contracts. We will also get to know the different data types of Solidity, understand how smart contracts work and write the first smart contract using Solidity.
Why Solidity?
The main reason behind the creation of the Solidity programming language was to provide a way for developers to write smart contracts on the Ethereum blockchain. Smart contracts are self-executing contracts with the terms of the agreement written directly into code. They are designed to execute the contract terms automatically when certain conditions are met.
Before the creation of Solidity, there were no dedicated programming languages for writing smart contracts on the Ethereum blockchain. Developers were forced to use low-level languages like Serpent and Mutan, which were not well-suited for the task and required a high level of technical expertise.
The developers of Solidity recognized the need for a more user-friendly programming language that could be used to create smart contracts on the Ethereum blockchain. They designed the language to be similar in syntax to popular programming languages, making it easy for developers to learn and use.
The main goal of Solidity was to provide developers with a tool that would enable them to create decentralized applications (dApps) on the Ethereum blockchain with greater ease and efficiency. This would, in turn, help to promote the adoption and growth of the Ethereum ecosystem.
Solidity Programming Language
Solidity is a contract-oriented, high-level programming language for writing smart contracts on the Ethereum blockchain. It was first developed in 2014 by Gavin Wood, Christian Reitwiessner, Alex Beregszaszi, and several other contributors. Solidity is similar in syntax to C++, Python, and JavaScript.
Solidity enables developers to write smart contracts that can be executed on the Ethereum Virtual Machine (EVM), which is responsible for processing and executing the instructions in a contract. These contracts can be used to create decentralized applications (dApps) on the Ethereum blockchain, which can be used for various purposes, such as creating digital assets, financial instruments, and more.
One of the key advantages of Solidity is its support for complex data structures, including arrays and mappings, which makes it possible to create more sophisticated dApps.
Additionally, the language includes built-in support for standard programming concepts, such as inheritance and libraries, which further simplifies the development process.
Solidity is widely used in the blockchain space, it’s the most popular smart contract programming language on the Ethereum blockchain. Many dApps and tokens are built using Solidity.
Smart Contracts
A smart contract is a computer program that is stored on the blockchain and can automatically execute the terms of a contract when certain conditions are met. Smart contracts are self-executing and do not require a third party’s intervention to enforce the contract’s terms. They are designed to be transparent, tamper-proof, and secure.
On the Ethereum blockchain, smart contracts are written in Solidity and are stored on the blockchain as part of a decentralized application. They can be used to create a wide range of decentralized applications, such as digital wallets, decentralized exchanges, and prediction markets.
When a smart contract is deployed on the Ethereum blockchain, it gets its unique address. This address is then used to interact with the contract and execute its functions. The contract’s code and state are stored on the blockchain, making it publicly accessible and transparent.
The key benefit of smart contracts on the Ethereum blockchain is that they allow for trustless and decentralized interactions between parties. Because the contract’s code and state are stored on the blockchain, it is tamper-proof and cannot be modified by any party. This eliminates the need for intermediaries or trusted third parties to enforce the terms of the contract.
Smart contracts can also be used to create decentralized autonomous organizations, which are organizations that code rather than people-run. These organizations can manage assets, make decisions and execute actions without the need for human intervention.
Data Types in Solidity
Solidity supports several data types, including
- Integer types:
- ‘uint’ (unsigned integer): an integer that can only hold non-negative values (0 to 2^256-1). It is the most commonly used integer type in Solidity.
- ‘int’ (signed integer): an integer that can hold negative and positive values (-2^255 to 2^255-1).
- ‘byte’ (8-bit integer): a fixed-size integer that can hold values from -128 to 127.
- ‘bytes’ (dynamic array of bytes): a dynamic array of bytes that can hold any data type.
- Boolean type: ‘bool’
- Address type: ‘address’ (20-byte Ethereum address)
- String type: ‘string’ (dynamic array of bytes)
- Enumeration type: ‘enum’ (the user-defined type with a fixed set of named values)
- Fixed-point types: ‘ufixed’ (unsigned fixed-point decimal) and ‘fixed’ (signed fixed-point decimal)
- Array types: ‘array’ and ‘mapping’
- Tuple type: ‘tuple’: a composite data type that contains a fixed number of ordered elements of different types.
- Struct type: ‘struct’: a composite data type that can hold multiple variables of different types.
However, Solidity’s most commonly used data types are ‘uint’, ‘address’, ‘bool’, and ‘string’. These are the main data types you will see in the examples later.
The ‘address’ type is used to represent Ethereum addresses and is commonly used to manage the access control of smart contracts.
The ‘uint’ type is used to represent non-negative integers and is commonly used to represent various types of values like token balances, timestamps, etc.
The ‘string’ type is used to store text or any other kind of data that is represented as a sequence of bytes.
The ‘bool’ type is used to represent Boolean values and is commonly used in conditional statements, along with various types of access control mechanisms.
Build your first smart contract
Now, we will use some of the data types we talked about earlier to write our first smart contract. The following code may look too complicated to start with, but it will be fully explained, so you don’t need to worry at all.
pragma solidity ^0.8.0; contract SimpleStorage{ address owner; // address: Ethereum address (20 bytes) uint count; // uint: Unsigned integer (256-bit) bool isActive; // bool: Boolean string message; // string: Dynamic array of bytes // constructor: A special function that is executed when the contract is created. constructor() { owner = msg.sender; count = 0; isActive = true; message = “Hello, this is a simple storage contract”; } // A function that allows the owner to update the message function updateMessage(string memory newMessage) public { // Only the contract owner can update the message require(msg.sender == owner); message = newMessage; } // A function that allows anyone to increment the count function incrementCount() public { // increment the count count++; } // A function that allows anyone to check the count function getCount() public view returns (uint) { return count; } // A function that allows anyone to check the message function getMessage() public view returns (string memory) { return message; } // A function that allows the owner to deactivate the contract function deactivate() public { require(msg.sender == owner); isActive = false; } // A function that allows anyone to check the contract status function isActive() public view returns (bool) { return isActive; } } |
The first line of the code, “pragma solidity ^0.8.0;” is called a pragma statement. It’s used to specify the version of the Solidity compiler that should be used to compile the code.
The “^” symbol before the version number indicates that the compiler should use the most recent version that is backwards-compatible with the specified version.
This smart contract defines a contract named SimpleStorage with a state variable ‘count’ of type uint, a state variable ‘isActive’ of type bool, and a state variable ‘message’ of type string. It also has a state variable ‘owner’ of type address to store the address of the contract creator.
The contract has three main functionalities:
- The owner can update the message by calling the ‘updateMessage’ function. The function checks if the message sender is the contract owner by comparing the address to the owner variable. If the sender is the owner, it updates the message.
- The contract allows anyone to increment the count by calling the ‘incrementCount’ function. It just increments the count variable by 1.
- ‘deactivate’ allows the owner to deactivate the contract. It sets the isActive variable to false.
The contract also has three view functions:
- ‘getCount’ returns the current count value.
- ‘getMessage’ returns the current message.
- ‘is_Active’ returns the current status of the contract.
A function marked with the ‘view’ keyword can only access the contract’s storage and perform some calculations. It cannot modify the state of the contract. This is useful when the function only retrieves data from the contract and doesn’t need to modify the state.
The ‘msg.sender’ is a built-in variable that refers to the Ethereum address of the account that sent the current message (transaction) to the contract. It can be used to determine the sender’s identity within a smart contract. In the contract above, as you will be the owner of it, and the tester of it -As it is being tested locally-, the ‘msg.sender’ variable and the ‘owner’ variable of the contract will contain the same address.
The ‘require’ function checks if certain conditions are met before executing the function. It will revert the whole transaction if the condition is not met.
The keyword ‘memory’ is used when passing a variable to a function. It tells the compiler to create a temporary copy of the variable in memory.
Remix Online IDE
Remix is a web-based Integrated Development Environment (IDE) for the Ethereum platform. It is a powerful tool that allows developers to write, test, and deploy smart contracts written in Solidity.
After compiling and deploying the above smart contract on a Remix, here is the output. It is an interactive output, but it will be shown in the following pictures:
This is the initial position right after deploying the smart contract. The orange buttons represent the functions that, when called, make changes in the values of the contract’s variables, therefore, they change the structure of the blockchain, and in case you are on a mainnet, you have to pay a gas fee to execute them. The blue buttons are the view functions, they reflect the values of the different variables, and they make no change in the blockchain.
This is the same position, but after pressing the three blue buttons. Because of the constructor, The ‘getCount’ is showing 0, and The ‘getMessage’ is showing the constructor’s message. and the ‘is_Active’ value is true.
This is the position after clicking the ‘incrementCount’ button thrice. and updating the ‘Message’ to “Hello World!”. Then clicking all the blue buttons to see what happened. The ‘getCount’ is showing 3 now, the ‘getMessage’ is showing “Hello World!”, and the ‘is_Active’ is true, still.
After pressing the ‘deactivate’ button, this is the final position, and then the ‘is_Active’ button to refresh its output. We can see that the ‘is_Active’ value has changed to false. This way, future contract users will know that this contract is deactivated -by the owner- and that it is no longer valid.
Conclusion
In this article, we have learned about Solidity and deployed a simple, smart contract. However, reading about blockchain isn’t enough to be a good developer. Practice makes perfect, so I advise getting your hands dirty and dealing with smart contracts yourself. One free source to learn about blockchain is the cryptozombies website (https://cryptozombies.io/). You can check it out and wait for the next articles.