Skip to content

Commit

Permalink
update general/conflux-basics/gas.md, regarding the issue #451 (#453)
Browse files Browse the repository at this point in the history
* update general/conflux-basics gas.md

* update general/conflux-basics/gas.md, regarding the issue #451

* Add a gas optimization tutorial entry, regarding the issue #454

* Update docs/general/build/smart-contracts/introduction-to-smart-contracts.md

Co-authored-by: darwintree <[email protected]>

---------

Co-authored-by: darwintree <[email protected]>
  • Loading branch information
jackleeio and darwintree authored Mar 14, 2024
1 parent 351bd25 commit 0698cd5
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 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)
10 changes: 10 additions & 0 deletions docs/general/conflux-basics/gas.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ gasFee is the total gas fee paid for a transaction. It is calculated as ```gasFe

Suppose there is a regular transfer of 1 CFX, the gas limit can be set to 21,000. If the gasPrice is set to 1GDrip, then the total cost of the transaction is ```1 + 21000 * 0.000000001 = 1.000021 CFX```, where 1 CFX is transferred to the recipient's account, and 0.000021 CFX is the reward for the miner.


### gasUsed

The actual gas consumed during transaction execution.
Expand All @@ -74,6 +75,15 @@ Suppose the gas limit for a regular CFX transfer is set to 100k and the actual e

If the gas limit setting of the transaction is not that high, take the same example as above but set the gas limit to 25000, which is 4000 more than the actual amount used, the exceeding part is not more than a quarter of the gas limit. This part will be returned fully, and the final amount of fees charged will still be ```0.000021 CFX```.


## How to pay less gasFee?

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'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

- [Ethereum Developer Documentation: Gas and Fees](https://ethereum.org/en/developers/docs/gas/)
Expand Down

0 comments on commit 0698cd5

Please sign in to comment.