From ab897bf901a76fa783908f9ca6dbfc43ad46df5f Mon Sep 17 00:00:00 2001 From: Mohammed Sohail Date: Thu, 21 Mar 2024 16:57:06 +0800 Subject: [PATCH] fix: apply fee after quote. Exclude fees from public liquidity --- .gitignore | 1 + solidity/SwapPool.sol | 21 +++++++++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index e8f80ec..cc41cdf 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ build/ dist/ solidity/*.json solidity/*.bin +.venv \ No newline at end of file diff --git a/solidity/SwapPool.sol b/solidity/SwapPool.sol index 6df6a21..457332e 100644 --- a/solidity/SwapPool.sol +++ b/solidity/SwapPool.sol @@ -137,22 +137,30 @@ contract SwapPool { function withdraw(address _outToken, address _inToken, uint256 _value) public { bool r; bytes memory v; - uint256 netValue; uint256 balance; uint256 fee; + uint256 outValue; + uint256 trueBalance; - fee = getFee(_value); - netValue = _value - fee; - netValue = getQuote(_outToken, _inToken, netValue); + outValue = getQuote(_outToken, _inToken, _value); (r, v) = _outToken.call(abi.encodeWithSignature("balanceOf(address)", this)); require(r, "ERR_TOKEN"); balance = abi.decode(v, (uint256)); - require(balance >= netValue + fee, "ERR_BALANCE"); + + // unwithdrawn fees should remain untouched + trueBalance = balance - fees[_outToken]; + + // deduct the fees from the quoted outValue + fee = getFee(outValue); + outValue -= fee; + + // pool should have enough balance to cover the final outValue (fees already deducted) + require(balance >= outValue, "ERR_BALANCE"); deposit(_inToken, _value); - (r, v) = _outToken.call(abi.encodeWithSignature('transfer(address,uint256)', msg.sender, netValue)); + (r, v) = _outToken.call(abi.encodeWithSignature('transfer(address,uint256)', msg.sender, outValue)); require(r, "ERR_TOKEN"); r = abi.decode(v, (bool)); require(r, "ERR_TRANSFER"); @@ -235,3 +243,4 @@ contract SwapPool { return false; } } +