skka3134

skka3134

email
telegram

智能合約的gas優化,1.拒絕openzeppelin

能不用 openzeppelin 就不用 openzeppelin
比如寫一個訪問控制和所有權轉移
1. 自己寫邏輯

// 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
2. 用 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
可以看到差了 168235gas,如果在主網的話,大概要多花 30 多塊錢,https://www.cryptoneur.xyz/zh/gas-fees-calculator gas 費率計算網站
image

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。