Skip to content

Commit

Permalink
Fix pool swap zero amount result (#1067)
Browse files Browse the repository at this point in the history
* Fix pool swap zero amount result

Signed-off-by: Anthony Fieroni <bvbfan@abv.bg>

* Prevent divide by zero

Signed-off-by: Anthony Fieroni <bvbfan@abv.bg>
  • Loading branch information
bvbfan authored Jan 26, 2022
1 parent cb25b76 commit 4c2044a
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/masternodes/mn_checks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3761,7 +3761,6 @@ std::vector<std::vector<DCT_ID>> CPoolSwap::CalculatePoolPaths(CCustomCSView& vi
// testOnly is only meant for one-off tests per well defined view.
Res CPoolSwap::ExecuteSwap(CCustomCSView& view, std::vector<DCT_ID> poolIDs, bool testOnly) {

CTokenAmount swapAmountResult{{},0};
Res poolResult = Res::Ok();

// No composite swap allowed before Fort Canning
Expand Down Expand Up @@ -3792,6 +3791,9 @@ Res CPoolSwap::ExecuteSwap(CCustomCSView& view, std::vector<DCT_ID> poolIDs, boo
mnview.Flush();
}

// Set amount to be swapped in pool
CTokenAmount swapAmountResult{obj.idTokenFrom, obj.amountFrom};

for (size_t i{0}; i < poolIDs.size(); ++i) {

// Also used to generate pool specific error messages for RPC users
Expand All @@ -3810,17 +3812,11 @@ Res CPoolSwap::ExecuteSwap(CCustomCSView& view, std::vector<DCT_ID> poolIDs, boo
}
}

// Set amount to be swapped in pool
CTokenAmount swapAmount{obj.idTokenFrom, obj.amountFrom};

// If set use amount from previous loop
if (swapAmountResult.nValue != 0) {
swapAmount = swapAmountResult;
}

// Check if last pool swap
bool lastSwap = i + 1 == poolIDs.size();

const auto swapAmount = swapAmountResult;

if (height >= static_cast<uint32_t>(Params().GetConsensus().FortCanningHillHeight) && lastSwap) {
if (obj.idTokenTo == swapAmount.nTokenId) {
return Res::Err("Final swap should have idTokenTo as destination, not source");
Expand Down Expand Up @@ -3900,9 +3896,11 @@ Res CPoolSwap::ExecuteSwap(CCustomCSView& view, std::vector<DCT_ID> poolIDs, boo

// Reject if price paid post-swap above max price provided
if (height >= Params().GetConsensus().FortCanningHeight && obj.maxPrice != POOLPRICE_MAX) {
const CAmount userMaxPrice = obj.maxPrice.integer * COIN + obj.maxPrice.fraction;
if (arith_uint256(obj.amountFrom) * COIN / swapAmountResult.nValue > userMaxPrice) {
return Res::Err("Price is higher than indicated.");
if (swapAmountResult.nValue != 0) {
const auto userMaxPrice = arith_uint256(obj.maxPrice.integer) * COIN + obj.maxPrice.fraction;
if (arith_uint256(obj.amountFrom) * COIN / swapAmountResult.nValue > userMaxPrice) {
return Res::Err("Price is higher than indicated.");
}
}
}

Expand Down

0 comments on commit 4c2044a

Please sign in to comment.