Lampros Tech

A Beginner’s Guide to Solidity

Ever wanted to write a Smart Contract on Ethereum and didn’t know which language to use? It’s SOLIDITY! It’s a solid programming language where your Ethereum Smart Contracts are built and executed. Let’s dive in to understand what makes Solidity stand out. We’ll also explore why it’s a great choice for developing and integrating Smart Contracts in the Ethereum blockchain.

Solidity is scripted on Remix IDE, for the Ethereum blockchain. Its prime application is to deal with Smart Contracts on Ether’s blockchain platform.

So, whilst exploring Solidity, this is what we’ll cover in this post:

What Is Solidity?

Solidity is a high-level, object-oriented programming language made by Ethereum, to create and implement Smart Contracts on the blockchain. 

Proposed by Gavin Wood. Christian Reitwiessner with his team, brought this to life. The computing language had its first global release in August 2014. It is one of the 4 languages that perform in the Ethereum Virtual Machine (EVM).

Solidity is very different from its sister languages that run on the EVM. Besides Vyper and LLL, Solidity mainly focuses on building, integrating, and implementing Smart Contracts. Vyper and LLL function similarly but have fundamental differences.

Ethereum logo in gold

Creation: Ethereum, Solidity, and the EVM.

Ethereum’s construction is such that almost any High-Level Programming language can run in the EVM. 

The most common languages in the EVM are C++, Python, Go, JavaScript Ruby, Java, and Rust.

Programmers need not follow a particular programming language in the EVM. But, to create and execute Smart Contracts, they have to use either Solidity or LLL, or Viper (formerly known as Serpent). 

THE EVM: Ethereum Virtual Machine

The Ethereum Virtual Machine is an online machine. It tells the state of each block on the Ethereum blockchain. It also executes particular instructions (opcodes). 

Like many virtual machines, this too serves as an execution platform for the written code. The EVM is specific to Solidity and handles all data on Ethereum alone.

Ethereum’s distributed ledger records all transactions while creating interaction guidelines for users on the blockchain. 

Blocks of a blockchain connected in a virtual space

Considering Ethereum is a massive platform of blocks and blockchains holding on to information on transactions; Smart Contracts can provide an extra layer of functionality.

A vital second layer that tells what happens to the blockchain when the addition of a new block occurs. This layer is Ethereum’s “distributed state machine”.

Ethereum was created to ensure certain functionalities that were absent in the blockchain industry. It has its own language - Solidity that is written on Remix IDE, compiled at the Byte code, and executed in the Ethereum Virtual Machine

Features of Solidity

The 3 main features of Solidity are that it is a Statically Typed, Compiled, and Object-Oriented programming language that compiles on the EVM.

Compiled Language

A compiled language is a language that uses a compiler as a key to ensuring the code works. Upon compilation, the code written by the programmer is now ready to run.

Solidity is a compiled language because the code is written in Remix IDE and later compiles into the bytecode in the Solidity Compiler. It uses the Ethereum Virtual Machine (EVM) to execute the code.

Statically-Typed

A statically typed language is a character of a language in which declaration and determination of values to many variables and variable types happen at the time of compilation.

The compilation event is when all variables receive their values.

code with import and class command line

Object-Oriented

An object-oriented programming (often called as OOP) language adopts the concept of Objects. The coding is such that, these “objects” preserve the data and codes. Data constitutes all the attributes and variables of the program while the code has syntaxes and procedures.

In addition, objects are different parts of a particular program, containing metadata in a class. They are easy to understand and reuse for different purposes.

Furthermore, we write, compile, and organize the code as if all programs written are objects in real life that can interact with other objects.

Solidity has 3 distinct features - to store data and metadata of the program in 'objects', to be compiled, and to assign values to variables during compilation.

Working of Solidity

The Remix IDE is the interface used to write code and generate Smart Contracts. Remix handles creating, utilizing, and monitoring Smart Contracts for Ethereum.

While Remix takes responsibility to create the code/ contract, the Solidity Compiler handles the compiling. Byte code and other tools necessary for deployment and executing Smart Contracts are the outputs of compilation.

In addition to the Remix IDE and the Solidity Compiler, Solidity also uses the EVM to execute itself. The EVM functions as a runtime environment for Smart Contracts in the ETH blockchain.

Being a statically typed language, the variables receive their values just before compilation and not before. In addition, each variable type is specified. Once you state the data types of the variables, the compiler checks the correct use of each variable.

Solidity works with 4 main tools - the Remix IDE, the Solidity Compiler, the Byte code, and the Ethereum Virtual Machine.

Learning Solidity

Solidity, the language for Smart Contracts, runs on 4 main components – The Pragma, The Import, The Contract, and finally The Comment.

1. Pragma

The code with the compiling instructions. As an evolving programming language, the pragma command states which version of the Solidity compiler is responsible to compile the code.

An example of a standard Solidity pragma code is:

  1. pragma solidity ^0.4.0;
  2. pragma solidity ^0.8.16;

In both instances, you state the Remix IDE to compile the code and run for bugs, errors, or warnings.

In (1) we state that the code compilation occurs in a version of 0.4.0 and above. Conversely, in (2) we’ve stated the code compilation occurs on version 0.8.16 and above. [And since there is no version after 0.8.16, the compiler version will be 0.8.16 only.]

Other different ways of writing the pragma code are:

  1. pragma solidity >=0.4.5; this means only version 0.4.5, 0.4.6, or 1.0.0 can compile, but not by versions 0.4.4 or lower.
  1. pragma solidity 0.6.0 || 0.6.3 – 0.6.5; this particular code syntax restricts the versions to 0.6.0, 0.6.3, 0.6.4 and 0.6.5.

Version 0.6.1, 0.6.2, and 0.6.6 cannot participate in compiling the code, at all!

  1. pragma solidity >0.7.2 <=0.7.6; this compiles Solidity codes on versions between 0.7.3, 0.7.4, 0.7.5 and 0.7.6. It cannot perform compilation on version 0.7.2 or 0.7.7
  1. pragma solidity 0.4.*; this code permits compilation on a version that’s 0.4.0 and above.
  1. pragma solidity -0.4.2; this permits the codes to compile at versions ranging from 0.4.2 and 0.(4+1).0 [version 0.5.0]

🚨NOTE: The pragma director does not work for versions before or below 0.4.0. Any code compiled in a version less than 0.4.0 need not have the pragma command.

2. Contract

A contract in Solidity is a group of command lines that contains a cohort of data and code. The code consists of commands on its functions, while the data consists of information about its state. 

This metadata resides on specific addresses on the ETH blockchain. This functions as a library – a reservoir of information and code lines.

The 3 properties of Contracts are:

  1. Functions – A reusable piece of code within or outside the Smart Contract. These can modify the state variables of the contract; which in turn changes the state of the contract in a cascade pattern.
  1. Constructor – A specific function that is recalled whenever the object gets a particular class. In Solidity, the declaration of the constructor happens inside the Smart Contract and deploys only when the contract is executed. The compiler releases a default constructor if a defined constructor is absent.
  1. State Variables – Variables that are different for each contract. These variables are necessary to store the state of the contract.

3. Import

The command to import local and external files to Solidity. The command will be different when you are importing a local file into Solidity compared to while importing an external file.

Supposed we have a local file “example.sol”, our command for the import will be as follows:

pragma solidity ^0.8.15;
contract MyContract{
import "example.sol"
}

Consequently, when you are importing an external file from GitHub, make sure you copy the URL of the website, link to the file as it is, and paste it within the inverted commas.

The syntax while importing a GitHub file would be:

pragma solidity ^0.8.14;
contract MyContract{
import "https://github.com/solidity-external-tests/dappsys-monolithic/blob/master/token.sol";
}

4. Comments

A comment is a note added to the source code, to keep track of what’s happening or what’s coded, and for what purposes. A programmer or a developer who has access to the source codes; now knows the instances under which a particular command was written.

The comment syntax in Solidity is very similar to how it’s present in C or C++. So, the 2 common methods are:

  1. The double-forward slash – The text starting after the // and end of the line is a comment. 
  2. The slash-asterisk – The comment that starts with a /* and ends with */ is considered a comment. This syntax is used if the comment runs for many lines of code.

These 2 common syntaxes are used in Solidity and the compiler ignores the comment while compiling the codes.

As a beginner in Solidity, some of the key components of Solidity are - Pragma, Import, Contract, and Comment. pragma is the directory command that dictates the version of the Solidity compiler to be used. Import functions to import internal and external files. The contract is a specialized cohort of data and code. The comment feature is similar to C++ to add notes in the program.

Data types in Solidity

Some of the many native data types in Solidity are as follows:

  1. boolean – a 2-value system. It gives responses in binary True/False.
  1. int – a 256-bit integer that’s signed and works with bitwise. The values of this data can be negative too.
  1. uint – a data that’s a 256-bit unsigned integer. Works in unsigned arithmetic and bitwise operations.
  1. address – the data code that identifies the account. Very similar to a 160-bit hash.
  1. string32 – An ASCII string with a maximum length of 32 bytes or 256 bits that terminates with a 0.

Variables in Solidity:

We are aware that a variable is a string of characters of an unassigned value. In programming, the variables get their values either towards the end of the compilation of the code.

In Solidity, variables are of certain types and they follow a set of rules.

Variable Nomenclature in Solidity

  1. The variable name and the reserved keyword cannot be similar for nomenclature.
  1. Variable names in Solidity must start with an underscore ( _ ). The variable can contain letters, numbers, and certain special characters.
  1. The variable name is case specific.

Declaration of Variables

The declaration of variables is when a variable is assigned a value. But for that to happen in Solidity, the code must specify the data type first and then input the access modifier also.

<type> <access modifier> <variable name>

Types of Variables in Solidity

As a statically typed language, Solidity assigns values during the time of compilation. But did you know that different variables have different outputs? And Solidity supports many variables. Your 3 Solidity variables based on function are:

  1. State Variables – As discussed previously, state variables are always reserved in the contract reservoir.
  1. Local Variable – These are the variables that are present only for a particular function and until it’s executed by the EVM. These variables store values that are used and then discarded.
  1. Global Variables – A cohort of special variables that are used universally and provide data on transactions and properties of the blockchain. 

Variables based on sizes are also of 3 types:

Fixed-size types

As the name suggests, these variables carry a fixed length of bits or bytes in their value/memory when called during compilation.

Some of the fixed-size types in Solidity are:

  • bool isReady; – A statement that either gives a True or False value.
  • uint a; – A statement that gets a particular value when called/compiled.
  • address recipient; – Gives the location of data in the blockchain system
  • bytes32 data; A program line that can hold arbitrary binary data up to 32 bytes. Very useful to represent strings, when you know in advance that you won’t have a string value with more than 32 bytes.

Variable-sized types

These are a group of variables that have a varied amount of bits or bytes in their value. A random true value assigns at the time of compilation.

  • string name; -Unsure what value a variable might have? Use a string. A string carries alphabets, numbers, or other characters of an unassigned length.
  • bytes _data – As seen above, bytes32 could have only 32 bytes of data in storage. A bytes command is a general version of the same. This command can contain a value with unlimited bytes and contain binary data.
  • uint[] amounts; – Use this command line if you need to declare an array function in your code. In Solidity, the arrays have to have a common type. Either has an array of bytes32 or boolean but both are not possible at the same time.
  • mapping(uint => string); – They are similar to an array with a key function being. They have keys with an associated value. We declare a mapping keyword and define a key. We also have to define the type of value mapped by each key. End the command line by defining the name of the mapping command.

User-defined types

Similar to C, C++, and Java (considering the EVM is made of them), Solidity too supports user-defined variables.

Each variable here innately is session specific and expires automatically once the code has run. 

In Solidity, Enums contain user-defined data types. These are used for specific code lines that have constant values – a collection of predefined values. This makes the designing of a Smart Contract easier in Solidity, compared to other languages.

An example of different variable types in Solidity

Libraries in Solidity 

Stuck with your Solidity Smart Contract? Don’t know where to go? Come on over to Solidity Libraries!

A row full of books in a library

A library in Solidity is a paradise for basically a cheat code you can avail. A developer scans through the Smart Contract library in Solidity for codes and reuses them in other Smart Contracts that they create.

A Solidity library can be available after its deployment in the blockchain. To create other effective Smart Contracts, the specific address and properties/ methods assigned helps guide the developer.

So, you know how to operate around and work effectively in a Library, but how many libraries do you go to?

Well, fret not, here’s a small list of libraries present inside Solidity:

  1. Modular network. This library hosts other modular utilities such as BasicMath, ArrayUtils, Vesting, Token, and much more!
  2. OpenZeppelin. A library for general masses. Some consider this library to be the parent library in Solidity for the vast functionalities and codes it can provide to us. Some of the other libraries within OpenZeppelin are SafeERC20, Roles, SafeMath, Arrays, and Address.
  3. dapp-bin. A library by Ethereum exclusive to IterableMapping, StringUtils, and DoublyLinkedList.

Now, let’s have a closer look at OpenZeppelin.

What Is It?

OpenZepplin is a free, open platform to avail of Smart Contracts for Solidity, mostly used for building dApps. OpenZeppelin believes in striving towards an open economy and protecting it. 

It’s every developer’s first choice for 1 simple fact – it provides reliability, security, and risk management for projects built on Ethereum.

The library conducts security audits of your code, on-demand and takes necessary precautions to avoid an insecure dApp malfunctioning.

It also provides notes and recommendations on different ways to emit the weakness to make your dApp or Smart Contract efficient.

How to Use It?

Developers usually write their code in Solidity and create reusable chic contracts within the library – yes, you can create ERC – 20 – related OpenZeppelin contracts too.

OpenZeppelin Defender is a useful web application by OpenZeppelin. It aids in strengthening and sets the Smart Contract on an auto-pilot mode. The Defender is useful to collaborate with your teams and coders. It brings a structure and defines the workflow, using the contract in the first person.

In addition, it also provides access to an amazing UI experience and the infrastructure needed for casting your transactions and making automated scripts.

Get the Best of It! OpenZeppelin Use Cases

After installing OpenZeppelin, you can use its approved contracts in several Ethereum applications. Several uses of OpenZeppelin are:

Access Restriction: One of OpenZeppelin’s primary use cases is access control. You can choose who has access to specific system resources and features using this contract. You can limit operations like voting, minting, and sending to particular entities with the use of this functionality.

Ownership: Another OpenZeppelin contract called “Ownable” allows you to specify who owns what in a given contract. Put another way, implementing this contract would aid certain entities in acquiring particular capabilities.

Calculations: The OpenZeppelin contract “SafeMath” helps perform exact calculations. When writing Solidity code, this library is extremely helpful for preventing operation overrun. The circumstance arises when the value of a certain arithmetic operation is outside the permitted range.

Tokens: OpenZeppelin built the infrastructure necessary for developers to generate tradable tokens and disperse them to the users of your network. You may keep an eye on the prices, determine how token transfers should be made, confirm purchases, and more with this contract.

Ether tokens on a tray

Payments: Are you creating a dApp with a variety of beneficiaries? You can distribute the proceeds from your dApp purchases to other recipients using the OpenZeppelin “paymentSplitter” contract.

Gas Station Network: This agreement with Gas Station Network enables you to create dApps in which you will make payments on behalf of your users. Users don’t need to have ETH on hand, this way you will pay for them instead.

Uses & Applications

Solidity is a vast, upcoming, growing language of Ethereum, by Ethereum for Ethereum.

This language allows developers to create dApps and Smart Contracts. 

As an evolving language, the applications are limitless. Each version of the language brings more features to the IDE. Thus, allowing developers to create an epic contract. 

Solidity does this while not compromising on UI, UX, or tools and libraries for developers. Forever ready to help a fellow blockchain developer to learn while on the run.

So, Solidity, being at the base or foundation of all things Ethereum, let’s, without further ado, look into the various uses and applications!

On Smart Contracts

So, you know that a Smart Contract is a program that functions like a container with codes and data. Also, understand that some of these contracts are reusable in other contracts.

And of course, to run the code written in the contract, it complies and deploys on the Ethereum Virtual Machine.

Solidity helps with all of that – from using the language to create the contract and reusing it on other applications to deploying it safely on the EVM.

Furthermore, it also helps in creating the contract such that all the information – data and metadata is stored carefully in the Ethereum blockchain. It records all the transactions that have occurred. It’s smart enough to know what to do when – as it is being written.

Other Applications: dApps | NFTs | DeFi 

The language of Ethereum also functions to create dApps, and NFTs; and functions in maintaining a decentralized financial system in the economy.

An NFT with diverse nodes

Having a decentralized app is the hot feature of Web3. Handling your data ensures that it neither gets tampered with nor gets misused for fake news or spam.

Expert developers in the industry interpret a free world of dApps with a decentralized ID to rule the web side-by-side.

NFTs are easy to create and easier to mint thanks to Ethereum’s programming language that’s being the talk of the article! Making Smart Contracts is cool but imagine building your NFT made by Solidity and minting it from a contract built on Solidity! Yeah, that’s some Solidity-Inception right there!

Geek references apart, Solidity can take transactions happening to the NFTs too. Making it a useful language for NFT records.

Having created Smart Contracts, the next best thing one can do is all the financial transactions are secure in an open space – thus the need for DeFi & Solidity in DeFi.

DeFi amongst cryptocurrencies

Contracts by Solidity run in Ethereum, a blockchain program; i.e, there is a record of all transactions in the blockchain as per the contract and is not manipulative at any point in time.

This provides free access to the truth and decentralized finance for all web3 users.

Summary

In summation? Solidity is vital for the functioning of Ethereum and working with Ethereum. This computer language is new, growing, and evolving and allows developers to learn thanks to the libraries present.

The language structure of Solidity reflects its features of being a compiled, statically typed, object-oriented script; thus providing a great user/ developer experience.

Nonetheless, Solidity, as a language has certain rules and conditions to follow. And so, the different data and variable types aid the developer in the cruise through and creating a beautiful Smart Contract that deploys on Ethereum.

Speaking of Smart Contracts, a recyclable tool that has a snippet of Solidity – it functions to create, mint, and record NFT transactions. It also provides a safe platform to host DeFi services and has dApps for all of Web3.

The Ethereum Blockchain is an important tool to handle all Smart Contracts, but we’re merely starting our journey with Web3. Advancements in blockchain technology can change the web for the better.

FAQs

  1. What version to use?

    The Solidity version 0.8.15

  2. Can Solidity be used on Solana?

    Not currently. Solana is a blockchain platform that has a VM similar to the EVM. The EVM is the only tool that can run the Solidity program.

  3. Can Solidity be used on Windows?

    Yes! You can use wite in Solidity without much pressure on installing an IDE. One can use the Remix IDE by Ethereum online and write your code.

  4. What is the purpose of Solidity?

    To create Smart Contracts and build dApps on Ethereum

  5. What is a Solidity map used for?

    A map in Solidity is similar to a directory. It permits you to save the information that you later want to receive in a function.