Skip to content

Commit

Permalink
update content
Browse files Browse the repository at this point in the history
  • Loading branch information
jackleeio authored and 0xn1c0 committed Nov 5, 2024
1 parent e5a1bd3 commit 90f4990
Showing 1 changed file with 11 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@
displayed_sidebar: generalSidebar
---

# Using Assembly for Revert Statements
# Using assembly to revert with an error message

When optimizing gas usage in Ethereum smart contracts, using assembly for revert statements can lead to significant gas savings. While Solidity's `require` and `revert` statements are convenient, implementing the same functionality with assembly can be more gas-efficient.
When optimizing gas usage in smart contracts, using assembly for revert statements can lead to gas savings. While Solidity's `require` and `revert` statements are convenient, implementing the same functionality with assembly can be more gas-efficient.

Solidity charges additional gas for memory expansion and type checking when using standard revert statements. By using assembly, we can bypass these overhead costs while maintaining the same functionality.

**Key Points:**

- Assembly revert statements are more gas-efficient than Solidity's `require` and `revert`
- Gas savings come from avoiding memory expansion costs and compiler type checks
- The same error messages can be preserved while reducing gas costs

### Gas Comparison Example

Expand Down Expand Up @@ -53,6 +48,7 @@ contract AssemblyRevert {
mstore(0x20, 0x13)
// Store the error message
mstore(0x40, 0x63616c6c6572206973206e6f74206f776e657200000000000000000000000000)
// Revert with data (offset, size)
revert(0x00, 0x60)
}
Expand All @@ -64,13 +60,11 @@ contract AssemblyRevert {

### Gas Analysis

| Implementation | Gas Cost* | Gas Saved |
| Implementation | Gas Cost | Gas Saved |
| ----------------- | --------- | --------- |
| Solidity Revert | 24,042 | - |
| Assembly Revert | 23,734 | 308 |

*Gas measured when calling `restrictedAction(2)` with a non-owner address

### Understanding the Assembly Implementation

The assembly revert implementation consists of several key components:
Expand All @@ -91,9 +85,14 @@ revert(0x00, 0x60)
```
The first parameter (0x00) is the memory offset, and the second (0x60) is the size of the data to revert with.

### Best Practices for Implementation

🌟 **Recommendations**:
**Key Points:**

- Assembly revert statements are more gas-efficient than Solidity's `require` and `revert`
- Gas savings come from avoiding memory expansion costs and compiler type checks
- The same error messages can be preserved while reducing gas costs

### Best Practices for Implementation

1. Use assembly revert in frequently called functions where gas optimization is crucial
2. Maintain clear documentation when using assembly code
Expand Down

0 comments on commit 90f4990

Please sign in to comment.