The Wayback Machine - https://web.archive.org/web/20241118115314/https://www.geeksforgeeks.org/solidity-assembly/
Open In App

Solidity – Assembly

Last Updated : 02 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Assembly or Assembler language indicates a low-level programming language that can be converted to machine code by using assembler. Assembly language is tied to either physical or a virtual machine as their implementation is an instruction set, and these instructions tell the CPU to do that fundamental task like adding two numbers.

Solidity has an option to write an assembly language code inside the smart contract’s source code. With the help of Solidity assembly, we can directly interact with the EVM using the opcodes. Assembly provides more control over some logic which cannot be possible using only solidity, like pointing to the specific memory block. One of the main advantages is that it reduces the cost of the gas used to deploy the contract. Solidity has two ways to implement the assembly language: 

Inline Assembly: Inline assembly code can be written inside solidity code for more fine-grain control and especially used for enhancing the language via creating new libraries. Inline assembly can be inserted in between solidity statements in a way that EVM can understand. It can also be used when the optimizer is not able to produce efficient code. Solidity becomes easier when features like assembly local variables, functions calls, switch statements, if statements, loops, etc are used.
Syntax:

assembly{
     // assembly language statements
}

Example: In the below example, a contract with a function is created, where the inline assembly code is located inside the function.

Solidity




// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.4.16 < 0.9.0;
/// @title A contract for demonstrate Inline Assembly
/// @author Jitendra Kumar
/// @notice For now, this contract just show the function execution using inline assembly
 
contract InlineAssembly {
 
    // Defining function
    function add(uint a) public view returns (uint b) {
 
        // Inline assembly code
        assembly {
 
            // Creating a new variable 'c'
            // Calculate the sum of 'a+16'
            // with the 'add' opcode
            // assign the value to the 'c'
            let c := add(a, 16)
 
            // Use 'mstore' opcode to
            // store 'c' in memory
            // at memory address 0x80
            mstore(0x80, c)
            {
 
                // Creating a new variable'
                // Calculate the sum of 'sload(c)+12'
                // means values in variable 'c'
               // with the 'add' opcode
               // assign the value to 'd'
                let d := add(sload(c), 12)
  
                 // assign the value of 'd' to 'b'
                b := d
  
            // 'd' is deallocated now
            }
     
            // Calculate the sum of 'b+c' with the 'add' opcode
            // assign the value to 'b'
            b := add(b, c)
 
        // 'c' is deallocated here
        }
    }
}


             

Output : 

Inline Assembly

Sometimes writing assembly code is more difficult because will not perform checks, that’s why it is better to use only when things are complex and you have an idea about what you are doing.

Standalone Assembly: Standalone assembly is planned for making an intermediate language for the solidity compiler. It was supported for recent compatibility but it is no more documented in the solidity documentation. Programs written in a standalone assembly are readable even if the code is been generated by a solidity compiler. The control flow should be easy, for optimization and formal verification.

Example: In the below example, the contract and a function are created to demonstrate the concept of Standalone assembly. 

Solidity




// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.4.16 < 0.9.0;
/// @title A contract for demonstrate Standalone Assembly
/// @author Jitendra Kumar
/// @notice For now, this contract just show the flow of for loop
 
contract StandaloneAssembly {
 
  // Defining a function
  function add(uint a) public pure returns (uint b) {
 
    // Initializing the variable b
    b = 10;
 
    // Executing for loop till the condition is met
    for (uint n = 0; n < a; n++)
      b = b + a;
  }
}


    

The assembly level code for the above example is :  

mstore(0x40, 0x60) // this line will store the “free memory pointer” 
// dispatch function 
switch div(calldataload(0), exp(2, 226)) 
case 0xb3de649b { 
let (retData) = func(calldataload(4)) 
let retVal := $memAllocate(0x20) 
mstore(retVal, retData) 
return(retVal, 0x20) 
} 
default { revert(0, 0) } 
// allocate memory 
function $memAllocate(size) -> pos { 
pos := mload(0x40) 
mstore(0x40, add(pos, size)) 
} 
// function of the contract 
function addition(a) -> b { 
b := 10 
for { let n := 0 } lt(n, a) { n := add(n, 1) } { 
b := add(a, b) 
} 
} 
} 

Output : 

Standalone Assembly



Previous Article
Next Article

Similar Reads

Solidity - Types
Solidity is a statically typed language, which implies that the type of each of the variables should be specified. Data types allow the compiler to check the correct usage of the variables. The declared types have some default values called Zero-State, for example for bool the default value is False. Likewise other statically typed languages Solidi
4 min read
How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity (Blockchain)?
There are various processes involved in deploying a smart contract using Ganache and Truffle Suite: 1. Install Ganache first. Ganache is a personal blockchain for Ethereum development. You must first download and install it. It is available for download from https://www.trufflesuite.com/ganache, the official website. 2. Install Truffle Suite: The n
4 min read
Solidity - Functions
A function is basically a group of code that can be reused anywhere in the program, which generally saves the excessive use of memory and decreases the runtime of the program. Creating a function reduces the need of writing the same code over and over again. With the help of functions, a program can be divided into many small pieces of code for bet
4 min read
What are Events in Solidity?
Solidity Events are the same as events in any other programming language. An event is an inheritable member of the contract, which stores the arguments passed in the transaction logs when emitted. Generally, events are used to inform the calling application about the current state of the contract, with the help of the logging facility of EVM. Event
2 min read
Solidity - Inheritance
Inheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. Solidity supports inheritance between smart contracts, where multiple contracts can be inherit
6 min read
Solidity - Polymorphism
Polymorphism is the ability to process data in more than one form. Like any other programming language, Solidity also supports polymorphism. Solidity supports two types of polymorphism, Function Polymorphism, and Contract Polymorphism. Function Polymorphism Function Polymorphism is also known as method overloading. In function polymorphism, multipl
3 min read
Solidity - View and Pure Functions
The view functions are read-only function, which ensures that state variables cannot be modified after calling them. If the statements which modify state variables, emitting events, creating other contracts, using selfdestruct method, transferring ethers via calls, Calling a function which is not 'view or pure', using low-level calls, etc are prese
2 min read
Solidity - Encapsulation
Encapsulation is fundamental and one of the most important concepts of object-oriented programming languages. It refers to the mechanism of manipulation of the scope of variables, i.e. it restricts the access of the variable outside the scope. It allows enough constraint access to a method for taking action on it. The scope of the objects can have
3 min read
Solidity - Abstract Contract
Abstract contracts are contracts that have at least one function without its implementation or in the case when you don't provide arguments for all of the base contract constructors. Also in the case when we don't intend to create a contract directly we can consider the contract to be abstract. An instance of an abstract cannot be created. Abstract
3 min read
How to Install Solidity in Windows?
To install solidity on windows ensure that you are using windows 10, as only windows 10 provides built-in Linux Subsystem. With the help of this feature, we can run the Ubuntu terminal on the Windows machine. Below are the steps to setup Solidity on windows: Step 1: Open control panel on your system and toggle to Windows Subsystem for Linux under C
1 min read
Solidity - While, Do-While, and For Loop
Loops are used when we have to perform an action over and over again. While writing a contract there may be a situation when we have to do some action repeatedly, In this situation, loops are implemented to reduce the number of lines of the statements. Solidity supports following loops too ease down the programming pressure. While Loop This is the
3 min read
Solidity - Break and Continue Statements
In any programming language, Control statements are used to change the execution of the program. Solidity allows us to handle loops and switch statements. These statements are usually used when we have to terminate the loop without reaching the bottom or we have to skip some part of the block of code and start the new iteration. Solidity provides t
2 min read
Solidity - Variables
A Variable is basically a placeholder for the data which can be manipulated at runtime. Variables allow users to retrieve and change the stored information. Rules For Naming Variables 1. A variable name should not match with reserved keywords. 2. Variable names must start with a letter or an underscore (_), and may contain letters from "a to z" or
4 min read
Solidity - Error Handling
Solidity has many functions for error handling. Errors can occur at compile time or runtime. Solidity is compiled to byte code and there a syntax error check happens at compile-time, while runtime errors are difficult to catch and occurs mainly while executing the contracts. Some of the runtime errors are out-of-gas error, data type overflow error,
6 min read
Steps to Execute Solidity Smart Contract using Remix IDE
Remix IDE is generally used to compile and run Solidity smart contracts. Below are the steps for the compilation, execution, and debugging of the smart contract. Step 1: Open Remix IDE on any of your browsers, select on New File and click on Solidity to choose the environment. Step 2: Write the Smart contract in the code section, and click the Comp
1 min read
Solidity - Arrays
Arrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the elements in the array and can be accessed using the index
6 min read
Solidity - Enums and Structs
Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. Enums restrict the variable with one of a few predefined values, these values of the enumerated list are called enums. Options are represented with integer values starting fro
3 min read
Introduction to Solidity
Solidity is a brand-new programming language created by Ethereum which is the second-largest market of cryptocurrency by capitalization, released in the year 2015 and led by Christian Reitwiessner. Some key features of solidity are listed below: Solidity is a high-level programming language designed for implementing smart contracts.It is a statical
5 min read
Solidity - Constructors
A constructor is a special method in any object-oriented programming language which gets called whenever an object of a class is initialized. It is totally different in case of Solidity, Solidity provides a constructor declaration inside the smart contract and it invokes only once when the contract is deployed and is used to initialize the contract
4 min read
Solidity - Decision Making Statements
Decision making in programming is used when we have to adopt one out of a given set of paths for program flow. For this purpose, conditional statements are used which allows the program to execute the piece of code when the condition fulfills. Solidity uses control statements to control the flow of execution of the program to advance and branch-bas
4 min read
Solidity - Operators
In any programming language, operators play a vital role i.e. they create a foundation for the programming. Similarly, the functionality of Solidity is also incomplete without the use of operators. Operators allow users to perform different operations on operands. Solidity supports the following types of operators based upon their functionality. Ar
7 min read
Solidity - Mappings
Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type. Mappings are mostly used to associate the unique Ethereum address with the associated val
4 min read
Solidity - Basics of Contracts
Solidity Contracts are like a class in any other object-oriented programming language. They firmly contain data as state variables and functions which can modify these variables. When a function is called on a different instance (contract), the EVM function call happens and the context is switched in such a way that the state variables are inaccess
4 min read
Solidity - Basics of Interface
Interfaces are the same as abstract contracts created by using an interface keyword, also known as a pure abstract contract. Interfaces do not have any definition or any state variables, constructors, or any function with implementation, they only contain function declarations i.e. functions in interfaces do not have any statements. Functions of In
2 min read
Creating a Smart Contract that Returns Address and Balance of Owner using Solidity
Problem: Create a smart contract named MyContract having a state variable as owner. Create a constructor to fetch the address of the owner from msg and hold it into the state variable owner. Also, create a function getBalance() to show the current balance of the owner. Solution: Every smart contract is owned by an address called as owner. A smart c
2 min read
What is Smart Contract in Solidity?
Solidity's code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum. Now let's look at the code example for making smart contract : Example #
4 min read
How Does Solidity Works?
Solidity is a programming language that helps developers create special programs called smart contracts. These contracts are used on the Ethereum blockchain, Which is like a giant computer that runs Decentralized Applications (DApps). In this article, We will explain how Solidity works in a simple way, using Examples to make it easier to understand
6 min read
What is Hashing in Solidity?
A cryptographic hash function is an algorithm that takes an arbitrary amount of data as input and produces the enciphered text of fixed size. Even a slight change in the input gives a completely different output. Solidity provides the following cryptographic functions: Function Properties keccak256(bytes memory) returns (bytes32)Computes the Keccak
2 min read
Solidity - Programming ERC-20 Token
ERC token standard 20 tokens in a smart contract token that follows the Ethereum Request for Comment proposal 20 guidelines. Our program will have the following mandatory functions: function totalSupply() public view returns (uint256);function balanceOf(address tokenOwner) public view returns (uint);function allowance(address tokenOwner, address sp
4 min read
Random Number Generator in Solidity using keccak256
Random numbers are numbers that occur in a sequence with the following two mandatory conditions: The values are uniformly distributed over a set interval.One cannot predict future values based on past outputs.Example: In the below example, we have created a contract with a function that will generate a random number in a specific range. Below is th
3 min read
Article Tags :
three90RightbarBannerImg