Solidity (an object-oriented programming language) lets us write assembly language code in a smart contract’s source code. We may utilize Solidity assembly to connect with the Ethereum Virtual Machine (EVM) using the opcodes directly. Assembly language provides more control over some logic that Solidity alone cannot provide.
Between solidity statements, the inline assembly can be introduced in a fashion that the EVM understands. When the optimizer is unable to create efficient code, inline assembly can also be employed. Solidity becomes easier when local assembly variables, functions calls, switch statements, if statements, loops, and other features are used.
assembly{}
In the example below, a contract is constructed with a function, and the inline assembly code is inserted within the function.
// Solidity program to demonstrate// Inline Assemblypragma solidity ^0.5.0;// Creating a contractcontract InlineAssembly {// Defining functionfunction add(uint a) public view returns (uint b) {// Inline assembly codeassembly {// 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 0x80mstore(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}}}
Note: Please read through the inline comments as they explain what is happening line by line in the code widget.
Since assembly code does not do checks, it might be more difficult to write. As a result, it’s best to use it only when things are complicated, and you know what you’re doing.
Standalone assembly is intended to be used as an intermediate language for the Solidity compiler. Even though the code is produced by a Solidity compiler, programs written in the standalone assembly are readable. For optimization and formal verification, the control flow should be simple.
A contract and a function are generated in the example below to explain the notion of standalone assembly.
// Solidity program to demonstrate// Standalone Assemblypragma solidity ^0.5.0;// Creating a contractcontract StandaloneAssembly {// Defining a functionfunction add(uint a) public view returns (uint b) {// Initializing the variable bb = 10;// Executing for loop till the condition is metfor (uint n = 0; n < a; n++)b = b + a;}}
Note: For code explanation, please read the inline comments.