skka3134

skka3134

email
telegram

Gas optimization for smart contracts, 1. Reject openzeppelin.

If you can avoid using OpenZeppelin, then 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 this is on the mainnet, it would cost around more than 30 dollars. You can calculate gas fees on this website: 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.