Skip to content

Commit

Permalink
Add a gas optimization tutorial entry, regarding the issue Conflux-Ch…
Browse files Browse the repository at this point in the history
  • Loading branch information
jackleeio committed Mar 14, 2024
1 parent b814dcd commit aea557c
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 31 deletions.
32 changes: 32 additions & 0 deletions docs/general/build/smart-contracts/gas-optimization/constant.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Constant vs Immutable

1. `constant`: Declares a constant that must be initialized at the time of declaration and cannot be altered thereafter.

2. `immutable`: Declares a constant that can be initialized either at the time of declaration or within the constructor, and cannot be altered after deployment.

3. `variable`: Declares a variable that can be assigned and modified at any stage of the contract lifecycle.

The following examples illustrate three variables defined with different modifiers.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract ConstantExample {
uint256 public constant FIXED_VALUE = 100;
}
contract ImmutableExample {
uint256 public immutable SETUP_VALUE = 100;
}
contract VariableExample {
uint256 public dynamicValue = 100;
}
```

Recommendations for gas optimization:

🌟 Using variables consumes more gas, so avoid them if you can.

🌟 For constants that do not require modifications after deployment, **defining them as `immutable` is optimal both functionally and in terms of gas efficiency.**
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
title: Gas Optimization
displayed_sidebar: generalSidebar
---

## Some Tips to Make Gas Fee Lower

### Optimize Data Storage
Use Tight Variable Packing: Group smaller data types together in a single storage slot to take advantage of Solidity's storage packing. For example, use uint8, uint16, or bool together in a struct to fit them into a single 32-byte storage slot.

Minimize State Variables: Only store essential data on-chain. Consider off-chain storage solutions (like IPFS) for larger data, and store hashes on-chain if integrity is needed.

Use bytes32 over string: If possible, use bytes32 for fixed-size strings, as it is more gas-efficient than the dynamically-sized string type.
### Optimize Function Execution
Use view and pure Functions: Mark functions that do not modify state with view (if they read the state) or pure (if they don't read the state) to reduce gas cost when called externally.

Limit Visibility: Use the most restrictive visibility (private or internal) for functions and variables, as operations are cheaper when they are internal to a contract.

Reuse Computed Values: Store computed values in local variables if they are used multiple times within a function to avoid redundant computation costs.
### Efficient Loops and Conditions
Avoid Loops When Possible: Loops can significantly increase gas costs, especially if their iteration count can grow. Consider alternatives like mapping for direct access.

Short-Circuit Evaluation: In if statements and logical expressions, order conditions by likelihood or cost. Solidity evaluates conditions from left to right and stops as soon as the result is determined.
### Use Libraries and Delegate Calls
Libraries for Reusable Code: Deploy reusable code as libraries. Libraries can be deployed once and then used by many contracts, reducing the deployment and execution gas costs.
Delegate Calls: Use delegate calls for modular architecture. This can reduce the amount of bytecode in a contract, lowering deployment and execution costs.
### Efficient Event Logging
Use Events for Data Not Requiring Immediate Retrieval: Instead of storing information that doesn't need to be immediately retrieved in storage variables, emit events. Logs cost significantly less gas than storage.
### Testing and Optimization Tools
Use Gas Reporting Tools: Tools like Hardhat and Truffle can report gas usage for contract functions. Identify high-gas functions for optimization.
Use Remix IDE: It provides detailed gas consumption for transactions and can help identify expensive operations.
### Upgradeable Contracts
Consider Proxy Patterns: Using proxies allows for the logic contract to be upgraded without redeploying the entire contract, saving gas on deploying large contracts.

### More Detailed Tutorial of Gas Optimization
- [Constant VS Immutable](/docs/general/build/smart-contracts/gas-optimization/constant)
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
sidebar_position: 1
title: Smart Contracts Development
displayed_sidebar: generalSidebar
# displayed_sidebar: generalSidebar
---

## Introduction to Smart Contracts Development on Conflux Network
Expand Down
31 changes: 1 addition & 30 deletions docs/general/conflux-basics/gas.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,36 +82,7 @@ There are strategies you can use to reduce the cost:

1.Gas prices go up and down every once in a while based on how congested Conflux is. When gas prices are high, waiting just a few minutes before making a transaction could see a significant drop in what you pay.

2.If you are a smart contract developer, here are some tips to write your smart contracts and make gas bills lower:

### Optimize Data Storage
Use Tight Variable Packing: Group smaller data types together in a single storage slot to take advantage of Solidity's storage packing. For example, use uint8, uint16, or bool together in a struct to fit them into a single 32-byte storage slot.

Minimize State Variables: Only store essential data on-chain. Consider off-chain storage solutions (like IPFS) for larger data, and store hashes on-chain if integrity is needed.

Use bytes32 over string: If possible, use bytes32 for fixed-size strings, as it is more gas-efficient than the dynamically-sized string type.
### Optimize Function Execution
Use view and pure Functions: Mark functions that do not modify state with view (if they read the state) or pure (if they don't read the state) to reduce gas cost when called externally.

Limit Visibility: Use the most restrictive visibility (private or internal) for functions and variables, as operations are cheaper when they are internal to a contract.

Reuse Computed Values: Store computed values in local variables if they are used multiple times within a function to avoid redundant computation costs.
### Efficient Loops and Conditions
Avoid Loops When Possible: Loops can significantly increase gas costs, especially if their iteration count can grow. Consider alternatives like mapping for direct access.

Short-Circuit Evaluation: In if statements and logical expressions, order conditions by likelihood or cost. Solidity evaluates conditions from left to right and stops as soon as the result is determined.
### Use Libraries and Delegate Calls
Libraries for Reusable Code: Deploy reusable code as libraries. Libraries can be deployed once and then used by many contracts, reducing the deployment and execution gas costs.
Delegate Calls: Use delegate calls for modular architecture. This can reduce the amount of bytecode in a contract, lowering deployment and execution costs.
### Efficient Event Logging
Use Events for Data Not Requiring Immediate Retrieval: Instead of storing information that doesn't need to be immediately retrieved in storage variables, emit events. Logs cost significantly less gas than storage.
### Testing and Optimization Tools
Use Gas Reporting Tools: Tools like Hardhat and Truffle can report gas usage for contract functions. Identify high-gas functions for optimization.
Use Remix IDE: It provides detailed gas consumption for transactions and can help identify expensive operations.
### Upgradeable Contracts
Consider Proxy Patterns: Using proxies allows for the logic contract to be upgraded without redeploying the entire contract, saving gas on deploying large contracts.

**A series of tutorials will be added later on how to optimize gas.**
2.If you're a smart contract developer aiming to reduce gas costs, start by optimizing data storage, improving function execution, and utilizing efficient loops, among others. For a deeper dive into these techniques and more, check out our dedicated [Gas Optimization](/docs/general/build/smart-contracts/gas-optimization/) tutorial.

## Further Readings

Expand Down

0 comments on commit aea557c

Please sign in to comment.