-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSweepBatchSwap.sol
More file actions
389 lines (322 loc) · 12.9 KB
/
SweepBatchSwap.sol
File metadata and controls
389 lines (322 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
/// @title SweepBatchSwap
/// @author Sweep Team
/// @notice Batch multiple ERC20 token swaps into a single transaction
/// @dev Supports 1inch, Uniswap, 0x, and generic DEX calldata
contract SweepBatchSwap is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
using Address for address;
// ============================================================
// CONSTANTS
// ============================================================
/// @notice Native ETH address placeholder
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Maximum basis points (100%)
uint256 public constant MAX_BPS = 10_000;
/// @notice Maximum fee (5%)
uint256 public constant MAX_FEE_BPS = 500;
// ============================================================
// STATE VARIABLES
// ============================================================
/// @notice Protocol fee in basis points
uint256 public feeBps;
/// @notice Fee collector address
address public feeCollector;
/// @notice Approved DEX routers
mapping(address => bool) public approvedRouters;
/// @notice Paused state
bool public paused;
// ============================================================
// STRUCTS
// ============================================================
/// @notice Single swap parameters
struct SwapParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 minAmountOut;
address router;
bytes routerData;
}
/// @notice Batch swap parameters
struct BatchSwapParams {
SwapParams[] swaps;
address outputToken;
address recipient;
uint256 deadline;
}
// ============================================================
// EVENTS
// ============================================================
event SwapExecuted(
address indexed user,
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut,
address router
);
event BatchSwapExecuted(
address indexed user,
uint256 swapCount,
address outputToken,
uint256 totalOutput,
uint256 feeAmount
);
event RouterApproved(address indexed router, bool approved);
event FeeUpdated(uint256 oldFee, uint256 newFee);
event FeeCollectorUpdated(address indexed oldCollector, address indexed newCollector);
event TokensRescued(address indexed token, address indexed to, uint256 amount);
event Paused(bool isPaused);
// ============================================================
// ERRORS
// ============================================================
error InvalidRouter();
error RouterNotApproved();
error SwapFailed();
error InsufficientOutput();
error DeadlineExpired();
error InvalidParams();
error ContractPaused();
error FeeTooHigh();
error ZeroAddress();
error ZeroAmount();
error TransferFailed();
// ============================================================
// MODIFIERS
// ============================================================
modifier whenNotPaused() {
if (paused) revert ContractPaused();
_;
}
modifier validDeadline(uint256 deadline) {
if (block.timestamp > deadline) revert DeadlineExpired();
_;
}
// ============================================================
// CONSTRUCTOR
// ============================================================
constructor(address _feeCollector, uint256 _feeBps) Ownable(msg.sender) {
if (_feeCollector == address(0)) revert ZeroAddress();
if (_feeBps > MAX_FEE_BPS) revert FeeTooHigh();
feeCollector = _feeCollector;
feeBps = _feeBps;
}
// ============================================================
// EXTERNAL FUNCTIONS
// ============================================================
/// @notice Execute a batch of swaps
/// @param params Batch swap parameters
/// @return totalOutput Total amount of output token received
function batchSwap(BatchSwapParams calldata params)
external
payable
nonReentrant
whenNotPaused
validDeadline(params.deadline)
returns (uint256 totalOutput)
{
if (params.swaps.length == 0) revert InvalidParams();
if (params.recipient == address(0)) revert ZeroAddress();
uint256 swapCount = params.swaps.length;
// Execute each swap
for (uint256 i = 0; i < swapCount;) {
SwapParams calldata swap = params.swaps[i];
uint256 amountOut = _executeSwap(swap);
emit SwapExecuted(
msg.sender,
swap.tokenIn,
swap.tokenOut,
swap.amountIn,
amountOut,
swap.router
);
unchecked {
++i;
}
}
// Calculate total output
totalOutput = _getBalance(params.outputToken);
// Take fee
uint256 feeAmount = 0;
if (feeBps > 0 && totalOutput > 0) {
feeAmount = (totalOutput * feeBps) / MAX_BPS;
totalOutput -= feeAmount;
_transfer(params.outputToken, feeCollector, feeAmount);
}
// Transfer output to recipient
if (totalOutput > 0) {
_transfer(params.outputToken, params.recipient, totalOutput);
}
emit BatchSwapExecuted(msg.sender, swapCount, params.outputToken, totalOutput, feeAmount);
}
/// @notice Execute a single swap
/// @param swap Swap parameters
/// @return amountOut Amount of output token received
function singleSwap(SwapParams calldata swap)
external
payable
nonReentrant
whenNotPaused
returns (uint256 amountOut)
{
amountOut = _executeSwap(swap);
// Take fee
uint256 feeAmount = 0;
if (feeBps > 0 && amountOut > 0) {
feeAmount = (amountOut * feeBps) / MAX_BPS;
amountOut -= feeAmount;
_transfer(swap.tokenOut, feeCollector, feeAmount);
}
// Transfer to sender
_transfer(swap.tokenOut, msg.sender, amountOut);
emit SwapExecuted(msg.sender, swap.tokenIn, swap.tokenOut, swap.amountIn, amountOut, swap.router);
}
// ============================================================
// INTERNAL FUNCTIONS
// ============================================================
/// @notice Execute a single swap internally
/// @param swap Swap parameters
/// @return amountOut Amount received
function _executeSwap(SwapParams calldata swap) internal returns (uint256 amountOut) {
if (!approvedRouters[swap.router]) revert RouterNotApproved();
if (swap.amountIn == 0) revert ZeroAmount();
uint256 balanceBefore = _getBalance(swap.tokenOut);
// Handle token input
if (swap.tokenIn == ETH_ADDRESS) {
// ETH swap - value should be sent with tx
} else {
// ERC20 swap - transfer tokens from user
IERC20(swap.tokenIn).safeTransferFrom(msg.sender, address(this), swap.amountIn);
// Approve router if needed
_approveIfNeeded(swap.tokenIn, swap.router, swap.amountIn);
}
// Execute swap on router
uint256 value = swap.tokenIn == ETH_ADDRESS ? swap.amountIn : 0;
// Execute the swap call
(bool success,) = swap.router.call{value: value}(swap.routerData);
if (!success) revert SwapFailed();
// Calculate amount out
uint256 balanceAfter = _getBalance(swap.tokenOut);
amountOut = balanceAfter - balanceBefore;
if (amountOut < swap.minAmountOut) revert InsufficientOutput();
}
/// @notice Approve token for router if needed
/// @param token Token address
/// @param spender Spender address
/// @param amount Amount to approve
function _approveIfNeeded(address token, address spender, uint256 amount) internal {
uint256 currentAllowance = IERC20(token).allowance(address(this), spender);
if (currentAllowance < amount) {
// Reset allowance first (for tokens like USDT)
if (currentAllowance > 0) {
IERC20(token).forceApprove(spender, 0);
}
IERC20(token).forceApprove(spender, type(uint256).max);
}
}
/// @notice Get balance of token or ETH
/// @param token Token address (ETH_ADDRESS for native)
/// @return balance Current balance
function _getBalance(address token) internal view returns (uint256 balance) {
if (token == ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = IERC20(token).balanceOf(address(this));
}
}
/// @notice Transfer token or ETH
/// @param token Token address (ETH_ADDRESS for native)
/// @param to Recipient
/// @param amount Amount to transfer
function _transfer(address token, address to, uint256 amount) internal {
if (amount == 0) return;
if (token == ETH_ADDRESS) {
(bool success,) = to.call{value: amount}("");
if (!success) revert TransferFailed();
} else {
IERC20(token).safeTransfer(to, amount);
}
}
// ============================================================
// ADMIN FUNCTIONS
// ============================================================
/// @notice Approve or revoke a router
/// @param router Router address
/// @param approved Approval status
function setRouterApproval(address router, bool approved) external onlyOwner {
if (router == address(0)) revert ZeroAddress();
approvedRouters[router] = approved;
emit RouterApproved(router, approved);
}
/// @notice Batch approve routers
/// @param routers Array of router addresses
/// @param approved Approval status
function setRouterApprovalBatch(address[] calldata routers, bool approved) external onlyOwner {
for (uint256 i = 0; i < routers.length;) {
if (routers[i] == address(0)) revert ZeroAddress();
approvedRouters[routers[i]] = approved;
emit RouterApproved(routers[i], approved);
unchecked {
++i;
}
}
}
/// @notice Update protocol fee
/// @param newFeeBps New fee in basis points
function setFee(uint256 newFeeBps) external onlyOwner {
if (newFeeBps > MAX_FEE_BPS) revert FeeTooHigh();
uint256 oldFee = feeBps;
feeBps = newFeeBps;
emit FeeUpdated(oldFee, newFeeBps);
}
/// @notice Update fee collector
/// @param newFeeCollector New fee collector address
function setFeeCollector(address newFeeCollector) external onlyOwner {
if (newFeeCollector == address(0)) revert ZeroAddress();
address oldCollector = feeCollector;
feeCollector = newFeeCollector;
emit FeeCollectorUpdated(oldCollector, newFeeCollector);
}
/// @notice Pause/unpause the contract
/// @param _paused New paused state
function setPaused(bool _paused) external onlyOwner {
paused = _paused;
emit Paused(_paused);
}
/// @notice Rescue stuck tokens
/// @param token Token address (ETH_ADDRESS for native)
/// @param to Recipient
/// @param amount Amount to rescue
function rescueTokens(address token, address to, uint256 amount) external onlyOwner {
if (to == address(0)) revert ZeroAddress();
_transfer(token, to, amount);
emit TokensRescued(token, to, amount);
}
// ============================================================
// VIEW FUNCTIONS
// ============================================================
/// @notice Check if a router is approved
/// @param router Router address
/// @return approved Approval status
function isRouterApproved(address router) external view returns (bool) {
return approvedRouters[router];
}
/// @notice Calculate fee for an amount
/// @param amount Input amount
/// @return fee Fee amount
function calculateFee(uint256 amount) external view returns (uint256 fee) {
return (amount * feeBps) / MAX_BPS;
}
// ============================================================
// RECEIVE FUNCTION
// ============================================================
/// @notice Receive ETH
receive() external payable {}
}