dsa-connectors/contracts/avalanche/connectors/paraswap/helpers.sol

72 lines
2.0 KiB
Solidity
Raw Normal View History

2022-03-22 14:55:14 +00:00
//SPDX-License-Identifier: MIT
2021-10-05 21:36:11 +00:00
pragma solidity ^0.7.0;
2021-12-03 12:08:48 +00:00
import {DSMath} from "../../common/math.sol";
import {Basic} from "../../common/basic.sol";
import {TokenInterface} from "../../common/interfaces.sol";
import {AugustusSwapperInterface} from "./interface.sol";
2021-10-05 21:36:11 +00:00
abstract contract Helpers is DSMath, Basic {
struct SwapData {
TokenInterface sellToken;
TokenInterface buyToken;
uint256 _sellAmt;
uint256 _buyAmt;
uint256 unitAmt;
bytes callData;
}
2021-12-03 12:08:48 +00:00
address internal constant paraswap =
0xDEF171Fe48CF0115B1d80b88dc8eAB59176FEe57;
2022-01-08 10:26:23 +00:00
2021-12-03 12:08:48 +00:00
function _swapHelper(SwapData memory swapData, uint256 wavaxAmt)
internal
returns (uint256 buyAmt)
{
2021-10-05 21:36:11 +00:00
TokenInterface buyToken = swapData.buyToken;
2021-12-03 12:08:48 +00:00
(uint256 _buyDec, uint256 _sellDec) = getTokensDec(
buyToken,
swapData.sellToken
);
2021-10-05 21:36:11 +00:00
uint256 _sellAmt18 = convertTo18(_sellDec, swapData._sellAmt);
2021-12-03 12:08:48 +00:00
uint256 _slippageAmt = convert18ToDec(
_buyDec,
wmul(swapData.unitAmt, _sellAmt18)
);
2021-10-05 21:36:11 +00:00
uint256 initalBal = getTokenBal(buyToken);
2021-12-03 12:08:48 +00:00
(bool success, ) = paraswap.call{value: wavaxAmt}(swapData.callData);
2021-10-05 21:36:11 +00:00
if (!success) revert("paraswap-failed");
uint256 finalBal = getTokenBal(buyToken);
buyAmt = sub(finalBal, initalBal);
require(_slippageAmt <= buyAmt, "Too much slippage");
}
2021-12-03 12:08:48 +00:00
function _swap(SwapData memory swapData, uint256 setId)
internal
returns (SwapData memory)
{
2021-10-05 21:36:11 +00:00
TokenInterface _sellAddr = swapData.sellToken;
2021-12-03 12:08:48 +00:00
uint256 avaxAmt;
2021-10-05 21:36:11 +00:00
if (address(_sellAddr) == avaxAddr) {
2021-12-03 12:08:48 +00:00
avaxAmt = swapData._sellAmt;
2021-10-05 21:36:11 +00:00
} else {
2021-12-03 12:08:48 +00:00
address tokenProxy = AugustusSwapperInterface(paraswap)
.getTokenTransferProxy();
2021-10-05 21:36:11 +00:00
approve(TokenInterface(_sellAddr), tokenProxy, swapData._sellAmt);
}
2021-12-03 12:08:48 +00:00
swapData._buyAmt = _swapHelper(swapData, avaxAmt);
2021-10-05 21:36:11 +00:00
setUint(setId, swapData._buyAmt);
return swapData;
}
2021-12-03 12:08:48 +00:00
}