code-423n4 / 2022-06-putty-findings

5 stars 0 forks source link

Gas Optimizations #220

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Gas Optimization

Check Asset Array Not Empty Before Transfer Can Save More Gas

Permalinks

Description

Transferring assets in and out of Putty always be executed even the asset array is empty. Checking and skip transferring call over empty asset array can help save some gas.

Mitigation

Add a check against asset array and skip the transferring if it is empty. Here is some example:

//PuttyV2.sol:L375-L377
if (order.erc20Assets.length > 0) _transferERC20sIn(order.erc20Assets, msg.sender);
if (order.erc721Assets.length > 0) _transferERC721sIn(order.erc721Assets, msg.sender);
if (order.floorTokens.length > 0) _transferFloorsIn(order.floorTokens, floorAssetTokenIds, msg.sender);

Prefix Incremental and Unchecked Block in For-Loop Can Save More Gas

Permalinks

Description

Prefix incremental ++i uses slightly less gas than postfix incremental i++. And on arithmetic operation that can be guarantee to not overflow/underflow, the unchecked block should be apply for gas optimization opportunity.

Mitigation

Use prefix instead of postfix incremental, and apply the unchecked block over ++i. Here is an example:

//PuttyV2.sol:L610-L614
function _transferERC721sIn(ERC721Asset[] memory assets, address from) internal {
        for (uint256 i = 0; i < assets.length; ) {
            ERC721(assets[i].token).safeTransferFrom(from, address(this), assets[i].tokenId);

            unchecked {
                ++i;
            }
        }
    }