https://github.com/tradmod/smard-contracts
Best Practices & Techniques to make Smart Contracts, "Smard Contracts" (Smart + Hard)
https://github.com/tradmod/smard-contracts
blockchain gas-optimization security smardcontracts smart-contracts solidity solidity-contracts web3security
Last synced: 12 months ago
JSON representation
Best Practices & Techniques to make Smart Contracts, "Smard Contracts" (Smart + Hard)
- Host: GitHub
- URL: https://github.com/tradmod/smard-contracts
- Owner: TradMod
- Created: 2022-10-07T13:19:51.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-10-12T13:36:01.000Z (over 3 years ago)
- Last Synced: 2025-01-17T07:07:07.974Z (about 1 year ago)
- Topics: blockchain, gas-optimization, security, smardcontracts, smart-contracts, solidity, solidity-contracts, web3security
- Language: Solidity
- Homepage:
- Size: 3.91 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Gas Optimizations:
## I. Use `Custom Errors` instead of `Require` Statements
The benefit of using [Custom Errors](https://blog.soliditylang.org/2021/04/21/custom-errors/) is that they significantly reduce gas costs especially deployment costs because unlike `require`, `Custom Errors` do not store a dynamic `string` of Error Message to revert when an operation fails.
**Examlple**: Execution Cost: 232904
```solidity
contract Ownable {
address public owner = msg.sender;
// `require` Not Optimized:
function newOwner(address _newOwner) public {
require(owner == msg.sender, "Only Owner Allowed");
owner = _newOwner;
}
}
```
**Examlple**: Execution Cost: 232904
```solidity
error Only_Owner_Allowed(); //Custom errors are defined using the error statement
contract Ownable_SmardWay {
address public owner = msg.sender;
// `Custom Error` Gas Optimized:
function newOwner_SmardWay(address _newOwner) public {
if(owner != msg.sender) { revert Only_Owner_Allowed(); }
owner = _newOwner;
}
}
```
References: https://tinyurl.com/3yaj4u8n & https://tinyurl.com/2k3wv67m
## II. Use `++i` instead `i++` inside loops
`++i` returns the incremented value, `i++` returns the non-incremented value, which costs a little bit extra gas.
**Examlple**: Execution Cost: 182005
```solidity
contract PrimeCheck {
function primeChecker(uint n) public pure returns (bool) {
for (uint i = 2; i < n; i++) {
if (n % i == 0) {
return true;
}
}
return false;
}
}
```
**Examlple**: Execution Cost: 181573
```solidity
contract PrimeCheck_SmardWay {
function primeChecker_SmardWay(uint n) public pure returns (bool) {
for (uint i = 2; i < n; ++i) {
if (n % i == 0) {
return true;
}
}
return false;
}
}
```
References: https://tinyurl.com/mr4b4jcd & https://tinyurl.com/mr2xtn2r