Unlock the Power of Solidity: Exploring the Essential Keywords for Smart Contract Development
Tags: solidity, blockchain
Published: 2023-08-08 23:17:07

Welcome to the exciting world of smart contract development! If you're eager to dive into the realm of blockchain and build decentralized applications, then Solidity is a language you need to familiarize yourself with. As a high-level programming language designed specifically for Ethereum, Solidity empowers developers to create robust and secure smart contracts. To embark on this journey, it's essential to grasp the fundamental building blocks, and that starts with understanding the common keywords in Solidity. In this article, we'll unravel the key words that form the backbone of Solidity programming, equipping you with the knowledge to harness the potential of this powerful language. Today we will be delve a little deep into **solidity** keywords for writing **Smart Contracts**, follow on with this tutorial if you will love to learn more.

## Solidity keywords we will cover
- pragma
- contract
- Data types - address, uint, int, string, bool, byte32
- modifier
- constructor
- event and emit
- struct
- delete
- mapping
- function
- public, external, internal, private
- require
- returns
- return
- view
- pure
- msg
- payable
- memory
- storage
- enum
- interface
- revert
- indexed
- virtual override

Now let's cover them
1) **Pragma:**
The **"pragma"** keyword is used to specify the version of the Solidity compiler that should be used to compile the code. It ensures that the code is compiled with the correct compiler version and prevents compatibility issues.
```solidity
pragma solidity ^0.8.0;
```
_This shows a version of solidity that should for compilers for version 0.8 and upwards_

2) **Contract:**
The **"contract"** keyword is used to define a new smart contract in Solidity. A contract is a fundamental building block of Ethereum-based applications and encapsulates the data and functions necessary for a specific purpose.
```solidity
contract MyContract{
   // Your contract code goes in here
}
```
_This defines a contract **MyContract**._

3) **Data Types:**
Solidity provides various data types, including:
- Address: Represents an Ethereum address and is used for interacting with other contracts or accounts.
- uint: Represents an unsigned integer of various sizes.
- int: Represents a signed integer of various sizes.
- string: Represents a sequence of characters.
- bool: Represents a boolean value (true or false).
- bytes32: Represents a fixed-size array of 32 bytes.
```solidity
address Owner = 0x40b38765696e3d5d8d9d834d8aad4bb6e418e489;
uint unsignedNumber = 1;
int Number = -1;
string name = "Gargamel";
bool Owns = true;
bytes32 Example = 0x4d794e616d650000000000000000000000000000000000000000000000000000;
```


4) **Modifier:**
The **"modifier"** keyword is used to define a function modifier. Modifiers are used to modify the behavior of functions in Solidity contracts. They allow developers to enforce conditions or perform pre- and post-function execution tasks.
```solidity
modifier(){
   //example
   require(true == true);
   _;
}
```
_A modifier must always end with_ `_; `

5) **Constructor:**
The **"constructor"** keyword is used to define the constructor function of a Solidity contract. The constructor is automatically executed when the contract is deployed and allows initialization of contract variables. A constructor only runs once.
```solidity
address owner;
constructor(){
    owner = msg.sender;
}
```
_It gives the owner variable the address that deployed the contract_

6) **Event and Emit:**
The **"event"** keyword is used to define events in Solidity. The **"emit"** keyword is used to trigger or emit an event, signaling a specific occurrence within the contract.
```solidity
   event Article( address author, string title)

   // Inside a function
   // emit the event
   emit Article(msg.sender, _title);
```
7) **Struct:**
The **"struct"** keyword is used to define a user-defined data structure in Solidity. Structs allow developers to create custom composite data types by combining different data types together.
```solidity
    struct Book {
        string title;
        string content;
    }
    Author myBook;
```
_This defines a Book data type with title and content properties. myBook is given the data type of Author_

8) **Mapping:**
The **"mapping"** keyword is used to define a key-value data structure in Solidity. Mappings are used to create associations between keys and values, similar to dictionaries or hash tables in other programming languages. You can only map a data type to a data type.
```solidity
mapping(address => Book) addressBook;
```
_This maps an address to the Book data type and gives it a variable name "addressBook"_

9) **Function:**
The **"function"** keyword is used to define a function within a Solidity contract. Functions contain the executable code that performs specific tasks or operations.
```solidity
function MyFuction(){
   // function logic
}
```
_A function without parameters_

```solidity
function MyFunction(string a, string b){
 // Function logic goes here
}
```
_A function with parameters_

10) **Public, External, Internal, Private:**
These keywords are used to define the visibility and accessibility of variables and functions within a contract. Public variables and functions can be accessed from anywhere, while external functions can be called only externally. Internal variables and functions are accessible within the current contract and its derived contracts, and private variables and functions are only accessible within the current contract.
```solidity
    function publicFunction() public {
        // Public function
    }
    function externalFunction() external {
        // External function
    }
    function internalFunction() internal {
        // Internal function
    }
    function privateFunction() private {
        // Private function
    }
```
11) **Delete:**
The "delete" keyword is used to delete the value of a state variable or reset it to its initial state.
```solidity
function deleteBook() public {
    delete myBook;
}
```
_the deleteBook function is defined as a public function. When this function is called, it will delete the myBook instance by setting all of its fields to their initial default values. For strings, the default value is an empty string._

12) **Require:**
The **"require"** keyword is used to validate a condition within a function. If the condition evaluates to false, the function execution is reverted, and any changes made within the function are discarded.
```solidity
   owner = msg.sender
   require(owner == msg.sender);
```

13) **Returns:**
The **"returns"** keyword is used to specify the return type of a function. It indicates the data type or types that the function will return when invoked.
```solidity
function example() public returns(string){
    string name = "Hello, world";
}
```

14) **Return:**
The **"return"** keyword is used to exit a function and return a value. It transfers the flow of execution back to the calling function and provides the desired value as the result.
```solidity
function example() public returns(string){
    string name = "Hello, world";
    return name;
}
```

15) **View:**
The **"view"** keyword is used to indicate that a function does not modify the contract's state. View functions are read-only and do not consume any gas when called externally.
```solidity
function example() public view returns(string){
    string name = "Hello, world";
    return name;
}
```

16) **Pure:**
The **"pure"** keyword is used to indicate that a function does not read or modify the contract's state. Pure functions are also read-only but are not allowed to access any contract-related information.
```solidity
function Add(uint a, uint b) public pure returns(uint){
    return a + b;
}
```
*This shows a function that adds two numbers together*

17) **msg:**
**"msg"** is a global variable that provides information about the current message or transaction being executed. It contains several properties that can be accessed within a contract's function.
- msg.sender: This property represents the address of the sender of the current message or transaction.
- msg.value: This property represents the amount of Ether (cryptocurrency) sent along with the transaction. It is applicable when the function is meant to receive funds.
- msg.data: This property contains the complete calldata (input data) of the transaction. It is a byte array that represents the function signature and its arguments. You can use it to access the raw data sent to a function in its encoded form.

18) **Payable:**
The **"payable"** keyword is used to mark a function or a contract to be able to receive Ether (the native cryptocurrency of Ethereum) as part of a transaction.
```solidity
address payable buyer;

function receive() public payable{
     // function logic
}
```
_Defines a buyer variable and a receive function that can send and receive ether_

19) **Memory:**
The **"memory"** keyword is used to specify a data location for variables. Variables defined in the memory are temporary and do not persist between function calls.
```solidity
function example() returns(memory string){
    string name = "Hello, world";
    return name;
}
```

20) **Storage:**
The **"storage"** keyword is used to specify a data location for variables. Variables defined in the storage are persistent and stored on the Ethereum blockchain.
```solidity
string name = "Hello, world";
function example() returns(storage string){
    return name;
}
```

21) **Enum:**
The **"enum"** keyword is used to define an enumeration type in Solidity. Enums allow developers to define a set of named constant values, which can be used as discrete options within the contract.
```solidity
   enum isLying{
       Yes,
       No
   }
```
_This defines an enum which has two possible values: `Yes` and `No`_

22) **Interface:**
The "interface" keyword is used to define an interface in Solidity. Interfaces provide a way to define the functions that must be implemented by other contracts.
```solidity
// Interface declaration
interface Token {
    function transfer(address recipient, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}
```
_In this example, we have an interface called `Token`. The interface specifies two functions: `transfer` and `balanceOf`._

_The `transfer` function is defined with the `external` visibility specifier, indicating that it can be called from external contracts. It takes two parameters: `recipient`, which is the address of the recipient of the tokens, and `amount`, which is the number of tokens to transfer. The function returns a boolean value indicating whether the transfer was successful._

_The `balanceOf` function is defined with the `external` visibility specifier as well. It takes one parameter: `account`, which is the address for which the token balance is queried. The function returns the balance of tokens for the specified account as a `uint256` value._

23) **revert:**
The revert keyword is used in Solidity to explicitly trigger an error and revert the execution of a smart contract. It is commonly used to revert changes made to the state of the contract in case of exceptional conditions or invalid inputs.
```solidity
function withdraw(uint amount) public {
    require(amount <= balance, "Insufficient balance");
    // Withdraw the amount
    if (!payable(msg.sender).send(amount)) {
        revert("Failed to send funds");
    }
    balance -= amount;
}
```
_In the above example, if the `amount` to be withdrawn exceeds the available balance, the `require` statement will throw an error. If the `send` function fails to transfer the funds, the `revert` statement is triggered with the error message "Failed to send funds"._

24) **indexed:**
The indexed keyword is used when declaring event parameters in Solidity. It allows efficient filtering and searching of events in the Ethereum blockchain.
```solidity
event Transfer(address indexed from, address indexed to, uint amount);

function transfer(address to, uint amount) public {
    // Transfer logic
    emit Transfer(msg.sender, to, amount);
}
```
_In the above example, the `from` and `to` addresses are declared as `indexed` in the `Transfer` event. This allows efficient filtering of events based on the sender or recipient addresses._

25) **virtual override:**
In Solidity, the `virtual` and `override` keywords are used in the context of function inheritance and overriding.
The virtual keyword is used when declaring a function in a base contract to indicate that the function can be overridden by derived contracts. It allows derived contracts to provide their own implementation of the function.
```solidity
contract Base {
    function getValue() public virtual returns (uint) {
        return 10;
    }
}

contract Derived is Base {
    function getValue() public virtual override returns (uint) {
        return 20;
    }
}
```
_the `getValue` function is declared as `virtual` in the `Base` contract, indicating that it can be overridden. The `Derived` contract then provides its own implementation of the function._

## Conclusion
In conclusion, understanding the essential keywords in Solidity is crucial for anyone venturing into smart contract development. These keywords form the building blocks of Solidity programming and empower developers to create robust and secure smart contracts. By familiarizing yourself with concepts like pragma, contract, data types, modifiers, constructor, events, structs, mappings, functions, visibility specifiers, require, returns, return, view, pure, msg, payable, memory, storage, enum, interface, revert, indexed, and virtual override, you gain the knowledge and tools needed to harness the power of Solidity effectively.