chiru-labs / ERC721A

https://ERC721A.org
MIT License
2.51k stars 842 forks source link

Gas optimizations for reverts and transfer events #441

Closed codeislight1 closed 1 year ago

codeislight1 commented 1 year ago

a more efficient approach to save on runtime reverts (30 gas) + deployment cost (7500 gas per revert message) is to revert using assembly and explicitly assign bytes4 error message hash, Win-Win. Also, there are cases where SLOAD is being performed before a revert, which is better to be assigned after, so on reverts doesn't go to waste. a contract was deployed after those changes and the deployment gas cost saving is 82053.

--Code--

cygaar commented 1 year ago

Can you run the gas reporter to see the diff between this version and the old version?

Vectorized commented 1 year ago

Don't merge first... my OCD.

Vectorized commented 1 year ago

Try this first:

    function _revert(bytes4 errorSelector) internal pure {
        assembly {
            mstore(0x00, errorSelector)
            revert(0x00, 0x04)
        }
    }
Vectorized commented 1 year ago

It's ok if the revert is after the SLOAD if it is for readability. Cuz no one will submit a tx that will incur the revert on purpose.

codeislight1 commented 1 year ago

Try this first:

    function _revert(bytes4 errorSelector) internal pure {
        assembly {
            mstore(0x00, errorSelector)
            revert(0x00, 0x04)
        }
    }

i have compared it and found that explicitly defining the error is cheaper than having it in a _revert function, but i believe if it's for readability purpose than it's definitely better.

codeislight1 commented 1 year ago

errorSelector

yeah that's true, it's more about finding the right balance. but in that case, the startTokenId is not being used in the if statements checks, so i thought better to come after it. I will revert that change.

Vectorized commented 1 year ago

I've edited your main branch.

codeislight1 commented 1 year ago

🫡

codeislight1 commented 1 year ago

with the optimizer on with 200 runs, the deployment gas cost saving is 26102 gas.