Skip to content
Home » Answers » Solidity Global Variables

Solidity Global Variables

Solidity global variables

Understanding Solidity Global Variables

In Solidity, global variables play a crucial role in facilitating smart contract development. They are accessible across different functions within a contract and hold essential information about the contract’s state, Ethereum network, and transaction details.

Before understanding the global variables, we need to understand what variables are, what data types Solidity uses, and what type of variables Solidity has. Let’s understand these concepts one by one.

Solidity data types

Like all other programming languages, variables are used to store data in Solidity. In Solidity smart contracts, variables are used to track data like arrays, boolean, strings, addresses, and signed/unsigned integers. Here is the list of data types Solidity offers.

  1. bool: Boolean data type is used to store true or false.
  2. uint: unit data type is used to store the unsigned integers. These are the few unsigned integers: uint8, uint16, uint32, and uni265.
  3. int: int data type is used to store the signed integers, for example, -12, -567, and -10, etc. Just like uint, we also have different variations of the int variables: int8, int16, int32, and int265.
  4. string: String data type is used to store strings in a variable.
  5. address: The address data type is commonly used to store wallet and smart contract addresses.

Different types of Solidity variables

There are three types of variables in Solidity. Let’s learn what they are.

Type of VariablesDescription
Local variablesLocal variables are the variables defined inside of the function. These variables work like temporary variables.
State variablesState variables in Solidity can be accessed or modified by internal or external function calls from within the contract.
Global variablesGlobal variables in Solidity can be accessed by any contract on the network. They are declared outside of a contract.

It is important to understand the difference between all types of variables so that you know how different types of variables work. Before moving forward, let’s look at short coding examples of local and state variables.

🔥 Check this course out: Build a One Piece Personality dApp With Solidity

Local variables example

Here’s an example of local variables in Solidity.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract LocalVariablesExample {
    function exampleFunction() public view returns (uint64) {
		    // Following are all local variables
        uint64 a = 1;
        uint64 b = 2;
        uint64 sum = a + b;
        return sum;
    }
}

State variables example

Here’s an example of state variables in Solidity.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract StateVariablesExample {
				// These two are state variables
		    uint64 public a = 1;
        uint64 public b = 2;

    function exampleFunction() public view returns (uint64) {
		    // Following is the local variable
        uint64 sum = a + b;
        return sum;
    }
}

What are global variables?

Global variables in Solidity are predefined variables that hold specific values or provide information about the current state of the contract or the Ethereum blockchain. Unlike local variables, which are confined to a specific function’s scope, global variables can be accessed from any function within the contract.

Types of Solidity global variables

Solidity offers various global variables, each serving a distinct purpose. Some of the essential global variables include:

  1. Block Variables: These variables provide information about the current block on the Ethereum blockchain. Examples include block.number, block.timestamp, block.difficulty, and block.coinbase.
  2. Transaction Variables: They offer insights into the current transaction’s details, such as msg.sender, msg.value, and msg.data.
  3. Contract Variables: These variables provide information about the current contract itself. Examples include this.balance, which indicates the contract’s Ether balance.
  4. Gas Variables: Solidity also includes global variables related to gas, such as gasleft(), which returns the amount of gas remaining in the current transaction.

🔥 Check this course out: Build a Semi-Fungible ERC404 Tokens’ Marketplace

Accessing global variables

Accessing global variables is straightforward in Solidity. You can directly reference them within any function in your contract. For example, to retrieve the sender’s address, you would use msg.sender. Similarly, to obtain the block number, you would use block.number.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract GlobalVariablesExample {
    function getSender() public view returns (address) {
        return msg.sender;
    }

    function getBlockNumber() public view returns (uint) {
        return block.number;
    }
}

In this example, the getSender function returns the sender’s address, while the getBlockNumber function returns the current block number.

Use cases and examples

Global variables find applications in various scenarios within smart contracts. Let’s explore some common use cases and examples:

  1. Access Control: Global variables like msg.sender are often used for access control mechanisms. By verifying the sender’s address, contracts can restrict certain functions to specific users or roles.
  2. Timestamp Manipulation: block.timestamp enables contracts to incorporate time-dependent logic, such as scheduling future events or implementing time-based restrictions.
  3. Gas Optimization: Understanding gas-related global variables like gasleft() allows developers to optimize contract execution and minimize transaction costs.
  4. Contract Interaction: Global variables like this.balance are useful for managing Ether within a contract, enabling functionalities like sending funds to other contracts or addresses.

Best practices and considerations

While leveraging global variables in Solidity, it’s essential to adhere to best practices and consider potential pitfalls:

ConsiderationsExplanation
SecurityAvoid using global variables for access control as they can be manipulated by attackers. Use role-based access control (RBAC) to improve contract security.
Gas LimitationsAvoid using too many as-related global variables to prevent running out of gas during contract execution. Complex operations or loops can increase transaction costs by consuming significant gas.
Immutable StateAvoid using mutable states derived from immutable global variables like block.number for critical contract logic.
Version CompatibilityCheck the compatibility of global variables’ Solidity version to prevent compilation issues due to updates or deprecation.

🔥 Check this course out: Build Hogwarts Sorting Hat dApp on Polygon

Conclusion

In conclusion, global variables in Solidity are indispensable tools for smart contract development, offering insights into the blockchain’s state and transaction details.

Developers can build robust and efficient smart contracts tailored to diverse use cases by understanding and utilizing these variables effectively.

However, it’s crucial to exercise caution, adhere to best practices, and stay updated with Solidity’s evolving ecosystem to harness the full potential of global variables in smart contract development.

Try it out, ask us questions, and tell us how it went by tagging Metaschool on Social Media.

Follow us on –

🔮Twitter – https://twitter.com/0xmetaschool

🔗LinkedIn – https://www.linkedin.com/company/0xmetaschool/