blockful-io / swaplace-contracts

Swaplace is an open-source, ownerless and feeless token swap protocol
https://app.swaplace.xyz/
MIT License
33 stars 33 forks source link

refactor: drastically lowering cancelSwap gas consumption #181

Closed 0xneves closed 7 months ago

0xneves commented 8 months ago

Feature Request

Describe the Feature Request

Running a series of optimizations on cancelSwap, I'm requesting this change to optimize the function drastically.

We can lower the gas consumption of cancelSwap which is at '39428' wei by removing the packData and assuming the swap.config equals '0'. This would reduce gas usage, becoming '39351'.

Additionally, we should remove the msg.sender from the event as the caller is known as the msg.sender already, there is no need to emit such event. PS: Line 437 of TestSwaplace.test.ts is lacking an "await" in the beginning, thus the events emitted are not being checked.

This variable is being loaded into memory but some of its fields are not being used in cancelSwap, I'm requesting the removal of the Swap struct to fracture into only swap.owner and swap.expiry (see preferred solution).

Swap memory swap = _swaps[swapId];

Reducing roughly from 39428 into 25555. A difference of 13873. Don't forget to adapt the tests and add the missing await!

Describe Preferred Solution

Before:

  function cancelSwap(uint256 swapId) public {
    Swap memory swap = _swaps[swapId];

    if (swap.owner != msg.sender) revert InvalidAddress(msg.sender);

    (address allowed, uint256 expiry) = parseData(swap.config);

    if (expiry < block.timestamp) revert InvalidExpiry(expiry);

    _swaps[swapId].config = packData(allowed, 0);

    emit SwapCanceled(swapId, msg.sender);
  }

Optimized:

  function cancelSwap(uint256 swapId) public {
    if (_swaps[swapId].owner != msg.sender) revert InvalidAddress(msg.sender);

    (, uint256 expiry) = parseData(_swaps[swapId].config);
    if (expiry < block.timestamp) revert InvalidExpiry(expiry);

    _swaps[swapId].config = 0;

    emit SwapCanceled(swapId);
  }

Related Code

  function cancelSwap(uint256 swapId) public {
    Swap memory swap = _swaps[swapId];

    if (swap.owner != msg.sender) revert InvalidAddress(msg.sender);

    (address allowed, uint256 expiry) = parseData(swap.config);

    if (expiry < block.timestamp) revert InvalidExpiry(expiry);

    _swaps[swapId].config = packData(allowed, 0);

    emit SwapCanceled(swapId, msg.sender);
  }
blackbeard002 commented 7 months ago

Hey @0xneves I'll take this up