Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gas: Conditional flow optimization in Exchange.sol:removeLiquidity() #28

Open
code423n4 opened this issue Jan 21, 2022 · 1 comment
Open
Labels
bug Something isn't working G (Gas Optimization) sponsor confirmed Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")

Comments

@code423n4
Copy link
Contributor

Handle

Dravee

Vulnerability details

Impact

It's possible to save gas by optimizing conditional flows to avoid some unnecessary opcodes

Proof of Concept

In Exchange.sol:removeLiquidity(), the code is as follows:

File: Exchange.sol
225:         if (quoteTokenQtyToReturn > internalBalances.quoteTokenReserveQty) {
226:             internalBalances.quoteTokenReserveQty = 0;
227:         } else {
228:             internalBalances.quoteTokenReserveQty -= quoteTokenQtyToReturn;
229:         }

However, this can be optimized :

  • Strict inequalities (>) are more expensive than non-strict ones (>=). This is due to some supplementary checks (ISZERO, 3 gas)
  • In this case here, if quoteTokenQtyToReturn == internalBalances.quoteTokenReserveQty: internalBalances.quoteTokenReserveQty = 0 should be used
  • Avoiding the else clause would avoid some opcodes (1 SUB = 3 gas, 2 MLOADs = 6 gas...)

The code would become:

File: Exchange.sol
225:         if (quoteTokenQtyToReturn >= internalBalances.quoteTokenReserveQty) {
226:             internalBalances.quoteTokenReserveQty = 0;
227:         } else {
228:             internalBalances.quoteTokenReserveQty -= quoteTokenQtyToReturn;
229:         }

Tools Used

VS Code

Recommended Mitigation Steps

Use the non-strict greater-than operator in this particular case

@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Jan 21, 2022
code423n4 added a commit that referenced this issue Jan 21, 2022
@0xean 0xean added the sponsor confirmed Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity") label Jan 31, 2022
@GalloDaSballo
Copy link
Collaborator

After some back and forth it really seems like >= is more gas efficient (3 gas)
Finding is valid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working G (Gas Optimization) sponsor confirmed Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")
Projects
None yet
Development

No branches or pull requests

3 participants