Skip to content

Commit

Permalink
Extend the supported input range of trade-by-source-amount (reduce th…
Browse files Browse the repository at this point in the history
…e probability of reverting on overflow)
  • Loading branch information
barak manos committed Jan 18, 2024
1 parent 637a895 commit 7bb6e3b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
14 changes: 13 additions & 1 deletion contracts/carbon/Strategies.sol
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,12 @@ abstract contract Strategies is Initializable {

uint256 temp4 = MathEx.mulDivC(temp1, temp1, factor);
uint256 temp5 = MathEx.mulDivC(temp3, A, factor);
return MathEx.mulDivF(temp2, temp3 / factor, temp4 + temp5);

(bool safe, uint256 sum) = tryAdd(temp4, temp5);
if (safe) {
return MathEx.mulDivF(temp2, temp3 / factor, sum);
}
return temp2 / (A + MathEx.mulDivC(temp1, temp1, temp3));
}

/**
Expand Down Expand Up @@ -972,6 +977,13 @@ abstract contract Strategies is Initializable {
}
}

function tryAdd(uint256 x, uint256 y) private pure returns (bool safe, uint256 sum) {
unchecked {
sum = x + y;
safe = sum >= x;
}
}

function uncheckedInc(uint256 i) private pure returns (uint256 j) {
unchecked {
j = i + 1;
Expand Down
10 changes: 10 additions & 0 deletions test/carbon/accuracy/data/ExtremeSrcTrade.json
Original file line number Diff line number Diff line change
Expand Up @@ -5108,5 +5108,15 @@
"inputAmount": "912345678",
"implReturn": "11263526807791440437174508207861",
"specReturn": "11263526807791494477914130651426"
},
{
"liquidity": "969467735247045389207437",
"lowestRate": "33333333333333.01391180980424255864136284799315035343170166015625",
"highestRate": "198019801980197.408654344705869476683801622129976749420166015625",
"marginalRate": "104452559155538.8882958589671163947507815520699425817338168004935",
"tradeBy": "SourceAmount",
"inputAmount": "15120357940",
"implReturn": "924248818871126217204242",
"specReturn": "924248818871128843570750.388118986304"
}
]

0 comments on commit 7bb6e3b

Please sign in to comment.