// SPDX-License-Identifier: MIT pragma solidity 0.8.17; import { LibAsset } from "./LibAsset.sol"; import { LibUtil } from "./LibUtil.sol"; import { InvalidContract, NoSwapFromZeroBalance, InsufficientBalance } from "../Errors/GenericErrors.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library LibSwap { struct SwapData { address callTo; address approveTo; address sendingAssetId; address receivingAssetId; uint256 fromAmount; bytes callData; bool requiresDeposit; } event AssetSwapped( bytes32 transactionId, address dex, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount, uint256 timestamp ); function swap(bytes32 transactionId, SwapData calldata _swap) internal { if (!LibAsset.isContract(_swap.callTo)) revert InvalidContract(); uint256 fromAmount = _swap.fromAmount; if (fromAmount == 0) revert NoSwapFromZeroBalance(); uint256 nativeValue = LibAsset.isNativeAsset(_swap.sendingAssetId) ? _swap.fromAmount : 0; uint256 initialSendingAssetBalance = LibAsset.getOwnBalance( _swap.sendingAssetId ); uint256 initialReceivingAssetBalance = LibAsset.getOwnBalance( _swap.receivingAssetId ); if (nativeValue == 0) { LibAsset.maxApproveERC20( IERC20(_swap.sendingAssetId), _swap.approveTo, _swap.fromAmount ); } if (initialSendingAssetBalance < _swap.fromAmount) { revert InsufficientBalance( _swap.fromAmount, initialSendingAssetBalance ); } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory res) = _swap.callTo.call{ value: nativeValue }(_swap.callData); if (!success) { LibUtil.revertWith(res); } uint256 newBalance = LibAsset.getOwnBalance(_swap.receivingAssetId); emit AssetSwapped( transactionId, _swap.callTo, _swap.sendingAssetId, _swap.receivingAssetId, _swap.fromAmount, newBalance > initialReceivingAssetBalance ? newBalance - initialReceivingAssetBalance : newBalance, block.timestamp ); } }