skka3134

skka3134

email
telegram

Gas optimization for smart contracts, 1. Reject openzeppelin

If you can avoid using OpenZeppelin, don't use OpenZeppelin.
For example, write an access control and ownership transfer logic.

  1. Write your own logic
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract test {
    address owner;
    uint256 x;
    constructor() {
        owner = msg.sender;
    }
    modifier onlyOwer() {
        require(msg.sender == owner);
        _;
    }
    function setOwner(address owner_)public onlyOwer{
        owner=owner_;
    }
    function add ()public onlyOwer {
        x=x+1;
    }
}

image

  1. Use OpenZeppelin
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
contract test is Ownable {
    uint256 x;
    constructor() {}
    function add ()public onlyOwner  {
        x=x+1;
    }
}

image

You can see a difference of 168,235 gas. If it were on the mainnet, it would cost about more than 30 dollars. You can check the gas fee calculation website at https://www.cryptoneur.xyz/zh/gas-fees-calculator.
image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.