Solidity Variables. A Beginner’s Guide

Solidity Variables at blockchaindoyen.com
Getting your Trinity Audio player ready...

Solidity Variables. A Beginner’s Guide

Solidity Variables at blockchaindoyen.com

Introduction

Welcome to this article which explains how to use Solidity Variables. Solidity is a high-level programming language used to write smart contracts on the Ethereum blockchain. Variables are a fundamental aspect of any programming language, and Solidity is no exception. In this guide, we will explore Solidity variables, their types, and built-in variables and functions.

Note: To avoid verbosity we have used the words “Var” and “Variable” interchangeably in this article.

Rules for Naming Solidity Variables

Solidity variables can be named using a combination of letters, numbers, and underscores. However, the variable’s name must start with a letter, and it cannot be a reserved keyword. Let’s look at an example of Solidity code syntax for naming variables:

uint256 myVariable;

address public myAddress;

string private myString;

Declaration of  Solidity Variables

In Solidity, developers must declare variables before they can use them in their code. The declaration specifies the data type and the variable’s name. Solidity supports several data types, including integers, booleans, strings, and addresses. Here’s an example of Solidity code syntax for declaring variables:

uint256 myVariable = 10;

bool myBoolean = true;

string myString = "Hello, World!";

address myAddress = 0x1234567890123456789012345678901234567890;

Types of Solidity Variables

Solidity variables can be classified into three types:

  1. State variables
  2. Local variables
  3. Global variables
  4. Built-in variables (and Functions)

State Variables

State variables are permanently stored in the contract’s storage and define the state of the contract. These variables have a contract-wide scope and are accessible to all functions within the contract. They are stored in the contract’s storage and retain their values between function calls. Here’s an example of Solidity code syntax for declaring and using state variables in a Solidity program:

contract MyContract {


uint256 public myNumber;


string public myString;


address public myAddress;

}

Local Variables

Local variables are variables that exist within the scope of a function and other functions of that contract can not access them. They are temporary and cease to exist once the function execution completes, which means they are not a part of the contract’s storage.

Here’s an example of Solidity code syntax for declaring and using local variables in a Solidity program:

function myFunction() public returns (uint256) {

uint256 myNumber = 10;

return myNumber;

}

Global Variables

Global variables have a contract-wide scope and the other functions of that contract can access them. They are user-defined and can hold values that are persistent throughout the contract’s execution. Here’s an example of Solidity code syntax for declaring and using global variables in a Solidity program:

pragma solidity ^0.8.0;

contract MyContract {
uint256 public myGlobalVariable; // Declaration of a global variable

function setGlobalVariable(uint256 newValue) public {
myGlobalVariable = newValue; // Updating the value of the global variable
}
}

In this example, myGlobalVariable is a global variable defined within the MyContract contract. It is declared as public, which allows other contracts or external entities to read its value. The function setGlobalVariable is used to update the value of the global variable.

Built-in Variables and Functions in Solidity

These variables have a contract-wide scope and are available for use without requiring explicit declaration. They provide access to specific functionalities and blockchain-related information. This language has several built-in vars and functions that we can use in smart contracts. Here’s an example of Solidity code syntax for declaring and using built-in vars and functions in a smart contract program:

pragma solidity ^0.8.0;

contract MyContract {
function getBlockTimestamp() public view returns (uint256) {
return block.timestamp; // Using the built-in variable block.timestamp
}
}

In this example, the function getBlockTimestamp retrieves the value of the built-in variable block.timestamp, which represents the current timestamp of the mined block containing the transaction.

Important Built-in Variables and Functions in Solidity

The following built-in vars and functions provide access to various blockchain-related information and metadata within Solidity contracts.

1.blockhash(uint blockNumber) returns (bytes32): Returns the hash of the specified block number.

Example

function getBlockHash(uint blockNumber) public view returns (bytes32) {

return blockhash(blockNumber);

}

2.block.coinbase (address payable): Returns the current block's miner address.

Exampl

function getCoinbase() public view returns (address payable) {


return block.coinbase;

}

3.block.difficulty (uint): The current block’s difficulty value.

Example 

function getDifficulty() public view returns (uint) {  

return block.difficulty; 

4.block.gaslimit (uint): Returns the gas limit of the current block.

Example

function getGasLimit() public view returns (uint) {

return block.gaslimit;

5.block.number (uint): Returns the current block’s number.

Example

function getBlockNumber() public view returns (uint) {


return block.number;

6.block.timestamp (uint):- The current block’s timestamp.

Example

function getTimestamp() public view returns (uint) {

return block.timestamp;

7.gasleft() returns (uint256): Amount of gas left for the execution of the current contract.

Example

function getGasLeft() public view returns (uint256) {


return gasleft();

}  

8.msg.data (bytes calldata): Returns complete calldata.

Example

function getData() public view returns (bytes calldata) {


return msg.data;

9.msg.sender (address payable): Returns the address of the message sender.

Example

function getSender() public view returns (address payable) {


return msg.sender;

10.msg.sig (bytes4): Returns the first four bytes of the calldata (function identifier).

Example

function getSig() public view returns (bytes4) {


return msg.sig;

11.msg.value (uint): Returns the number of wei sent with the message.

Example 

function getValue() public payable returns (uint) {

return msg.value;

12.now (uint): Returns the current timestamp.

Example 

function getNow() public view returns (uint) {

return now;

}

13.tx.gasprice (uint): Returns the gas price of the current transaction.

Example 

function getGasPrice() public view returns (uint) {
return tx.gasprice;
}

14.tx.origin (address payable): Returns the address of the transaction sender (external caller).

Example

function getOrigin() public view returns (address payable) {
return tx.origin;

Difference Between Global and Built-in Variables in Solidity

Just to quench the curiosity upfront, we would like to reveal that the global vars and built-in vars are not the same in this language. 

As we mentioned earlier, global means something that exists within the scope of a contract and the different functions of that contract can access them. They can hold values that are persistent throughout the contract’s execution and can maintain the state of the contract.

On the contrary, Solidity incorporates built-in vars that serve distinct functions and provide information related to the blockchain, transactions, and processed messages. These variables are part of the language and are available for use without requiring explicit declaration.

While users can define global variables within a contract, predefined built-in variables provide access to important blockchain-related information and functionalities.

In summary, global variables define variables within a contract’s scope, while the language provides built-in variables as predefined variables to access specific functionalities and blockchain-related information.

Variable Visibility Modifiers in Solidity 

By now we have learned that variable visibility in Solidity refers to the accessibility or scope of a variable within a smart contract. It allows us to determine where and how we can access and manipulate the variable.

Solidity, further, provides visibility modifiers to control access to state variables within a contract. The visibility modifiers include public, private, and internal. These modifiers specify who can access the state variable and from where. Here is the detail about each visibility modifier.

  • Public: Users can access and modify public variables from anywhere, both within and outside the contract. Contracts or external accounts can access them since they are part of the contract’s interface.
  • Private: The contract restricts access to private variables, making them only accessible within the contract. Other contracts or external accounts cannot access or modify them.
  • Internal: The contract and any derived contracts can access internal variables. These variables are not visible outside the contract hierarchy, providing a means to share data among related contracts.

By specifying the appropriate visibility modifier, developers can control the accessibility of state variables and enforce encapsulation. This allows for better security, data integrity, and code organization within smart contracts. It is important to carefully consider the visibility of variables to ensure the desired behavior and prevent unauthorized access to sensitive data.

The Visibility Modifier Is Only Applicable to State Variables

The variable visibility modifiers in Solidity (internal, private, and public) do not apply to local, global, or built-in variables.

The visibility modifiers in Solidity serve a specific purpose for state variables, which developers define within a contract. Developers use these modifiers to control the accessibility of state variables within the contract and its derived contracts.

In contrast, local variables are declared within functions, and their scope is limited to the specific function in which developers declare them. These variables are independent of visibility modifiers since developers can only access them within the function where they declare them.

Global variables, including those declared outside any function in a contract, have a wider scope and are accessible throughout the contract without the need for visibility modifiers. Any function within the contract can access and modify them.

Built-in variables, being predefined by Solidity, have their own predetermined rules for accessibility and are not influenced by visibility modifiers. These variables provide specific functionalities and information within the context of Solidity programming.

Therefore, the visibility modifiers (internal, private, and public) are only applicable to state variables in Solidity and do not apply to local, global, or built-in variables.

Conclusion

Variables are an essential part of writing smart contracts on the Ethereum blockchain. In this guide, we explored the different types of Solidity variables, and their uses, and provided examples of Solidity code syntax for each type of variable and important built-in variables and functions. To learn more about Solidity, check out the official Solidity documentation.

Related Tutorials

What Is a Solidity Smart Contract? A Beginner’s Guide

Solidity Tutorial. A Comprehensive Guide

Solidity Data Types. A Beginner’s Guide

Solidity Functions. A Beginner’s Guide

References

Solidity documentation

Solidity tutorial

 

Leave a Reply

Your email address will not be published. Required fields are marked *