Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Solidity inline assembly

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Solidity inline assembly". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Solidity inline assembly.

When developing intelligent contracts with Solidity, assembler can interact with EVM directly, reduce the overhead cost of gas, and control the behavior of intelligent contracts more finely, so it is worth learning and using by Solidity developers.

2. Ethernet virtual machine and stack structure machine

Etherfang virtual machine EVM has its own instruction set, which currently contains 144 opcodes. For more information, please refer to the Geth source code.

These instructions are abstracted from Solidity and can be used inline in Solidity. For example:

Contract Assembler {function do_something_cpu () public {assembly {/ / start writing evm assembler language}

EVM is a stack virtual machine, and the stack data structure allows only two operations: PUSH or POP data. The last data pressed is at the top of the stack, so it will be the first to eject, which is called last-in, first-out (LIFO:Last In, First Out):

The stack virtual machine saves all the operands on the stack. For more information about the stack virtual machine, please refer to the stack machine Foundation.

3. The operation code of the stack structure machine

In order to solve practical problems, stack machines need to implement some additional instructions, such as ADD, SUBSTRACT, and so on. When an instruction is executed, it usually pops one or more values from the stack as parameters, and then pushes the execution result back on the stack. This is often referred to as inverse Polish representation (RPN:Reverse Polish Notation):

A + b / / Standard notation Infixa b add / / inverse Polish notation RPN4, using inline assembly in Solidity contracts

You can embed assembly code snippets in Solidity using assembly {}, which is called inline assembly:

Assembly {/ / some assembly code here}

The code development language within the assembly block is called Yul, and for simplicity we call it assembly or EVM assembly.

Another concern is that there is no communication between assembly code blocks, that is, variables defined in one assembly code block cannot be accessed in another assembly code block. For example:

Assembly {let x: = 2} assembly {let y: = x / / Error}

The above code compiles with the following error:

/ / DeclarationError: identifier not found// let y: = xmax / ^

The following code uses inline assembly code to calculate the sum of the two parameters of the function and returns the result:

Function addition (uint x, uint y) public pure returns (uint) {assembly {let result: = add (x, y) / x + y mstore (0x0, result) / / Save the result return (0x0, 32) / / return 32 bytes from memory}}

Let's rewrite the above code to add some more detailed comments to explain how each instruction works within EVM.

Function addition (uint x, uint y) public pure returns (uint) {assembly {/ / create a new variable result / /-> use the add opcode to calculate the result of the calculation to the variable result let result: = add (x Y) / x + y / / use the mstore opcode / /-> store the value of the result variable in memory / /-> specify the memory address 0x0 mstore (0x0, result) / / store the result in memory / / return 32 bytes of return (0x0, 32)} 5 from memory address 0x, variable definition and assignment in Solidity assembly

In Yul, use the let keyword to define variables. Assign a value to a variable using the: = operator:

Assembly {let x: = 2}

If you do not assign a value to a variable using the: = operator, the variable is automatically initialized to a value of 0:

Assembly {let x / / is automatically initialized to x = 0 x: = 5 / / x now the value is 5}

You can use complex expressions to assign values to variables, such as:

Assembly {let x: = 7 let y: = add (x, 3) let z: = add (keccak256 (0x0, 0x20), div (slength, 32)) let n} 6, the running mechanism of let instructions in Solidity assembly

Inside EVM, the let directive performs the following tasks:

Create a new stack slot

Keep the slot for the variable

Automatically destroy the slot when the end of the code block is reached

Therefore, variables defined in the assembly code block using the let directive are not accessible outside that code block.

7. Notes in Solidity assembly

Comments are written in the same way as Solidity in Yul assembly, using single-line comments / / or multiple-line comments / * /. For example:

Assembly {/ / single line comment / * Multi line comment * /} 8, literals in Solidity assembly

The literal amount is written in the same way as Solidity in the Solidity assembly. However, the literal amount of a string can contain up to 32 characters.

Assembly {let a: = 0x123 / / hexadecimal let b: = 42 / / 10 let c: = "hello world" / / string let d: = "very long string more than 32 bytes" / / very long string, error! 9. Blocks and scope of action in Solidity assembly

In Solidity assembly, the scope of variables follows standard rules. The range of a block is identified by a pair of curly braces.

In the following example, y and z are valid only within the block in which the definition is defined. So the scope of the y variable is scope 1. The scope of the Z variable is scope 2.

Assembly {let x: = 3 / / x is visible everywhere / / Scope 1 {let y: = x / / ok} / / Scope 2 {let z: = Error} / / here will destroy z} / / DeclarationError: identifier not found// let z: = Error / ^

The only exceptions to the scope are functions and for loops, which we will explain below.

10. Use local variables of functions in Solidity assembly

In Solidity assembly, you only need to use the variable name to access the local variable, whether the variable is defined in the assembly block or in the Solidity code, but the variable must be a local variable of the function:

Function assembly_local_var_access () public pure {uint b = 5 Assembly {/ / defined inside an assembly block let x: = add (2,3) let y: = 10z: = add (x, y)} assembly {/ / defined outside an assembly block let x: = add (2,3) let y: = mul (x, b)}} 11, use for loop in Solidity assembly

First take a look at the use of loops in Solidity. The following Solidity function code calculates the multiple of the variable n times, where value and n are the parameters of the function:

Function for_loop_solidity (uint n, uint value) public pure returns (uint) {for (uint I = 0; I)

< n; i++ ) { value = 2 * value; } return value;} 等效的Solidity汇编代码如下: function for_loop_assembly(uint n, uint value) public pure returns (uint) { assembly { for { let i := 0 } lt(i, n) { i := add(i, 1) } { value := mul(2, value) } mstore(0x0, value) return(0x0, 32) } } 类似于其他开发语言中的for循环,在Solidity汇编中,for循环也包含3个元素: 初始化:let i := 0 执行条件:lt(i, n) ,必须是函数风格表达式 迭代后续步骤:add(i, 1) 注意:for循环中变量的作用范围略有不同。在初始化部分定义的变量在循环的其他部分都有效。 12、在Solidity汇编中使用while循环 在Solidity汇编中实际上是没有while循环关键字的,但是可以使用for循环实现同样的功能:只要留空for循环的初始化部分和迭代后续步骤即可。 assembly { let x := 0 let i := 0 for { } lt(i, 0x100) { } { // 等价于:while(i < 0x100) x := add(x, mload(i)) i := add(i, 0x20) }}13、在Solidity汇编中使用if语句 Solidity内联汇编支持使用if语句来设置代码执行的条件,但是没有其他语言中的else部分。 assembly { if slt(x, 0) { x := sub(0, x) } // Ok if eq(value, 0) revert(0, 0) // Error, 需要大括号} if语句强制要求代码块使用大括号,即使需要保护的代码只有一行,也需要使用大括号。这和solidity不同。 如果需要在Solidity内联汇编中检查多种条件,可以考虑使用switch语句。 14、在Solidity汇编中使用switch语句 EVM汇编中也有switch语句,它将一个表达式的值于多个常量进行对比,并选择相应的代码分支来执行。switch语句支持一个默认分支default,当表达式的值不匹配任何其他分支条件时,将执行默认分支的代码。 assembly { let x := 0 switch calldataload(4) case 0 { x := calldataload(0x24) } default { x := calldataload(0x44) } sstore(0, div(x, 2))} switch语句有一些限制: 分支列表不需要大括号,但是分支的代码块需要大括号- 所有的分支条件值必须:1)具有相同的类型 2)具有不同的值- 如果分支条件已经涵盖所有可能的值,那么不允许再出现default条件 assembly { let x := 34 switch lt(x, 30) case true { // do something } case false { // do something els } default { // 不允许 } }15、在Solidity汇编中使用函数 也可以在Solidity内联汇编中定义底层函数。调用这些自定义的函数和使用内置的操作码一样。 下面的汇编函数用来分配指定长度的内存,并返回内存指针pos: assembly { function allocate(length) ->

Pos {pos: = mload (0x40) mstore (0x40, add (pos, length))} let free_memory_pointer: = allocate (64)}

The assembly function runs as follows:

Extract parameters from the stack

Push the result onto the stack

Unlike the Solidity function, you do not need to specify the visibility of the assembly function, such as public or private, because the assembly function is only valid within the assembly code block in which the definition is located.

16. Opcodes in Solidity assembly

EVM opcodes can be divided into the following categories:

Arithmetic and comparison operation

Bit operation

Cryptographic operations, which currently include only keccak256

Environmental operation, which mainly refers to the global information related to the blockchain, such as blockhash or coinbase collection account

Storage, memory, and stack operations

Transaction and contract call operation

Shutdown operation

Log operation

At this point, I believe that you have a deeper understanding of "Solidity inline assembly how to use", might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report