-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource-code.txt
More file actions
416 lines (345 loc) · 11.8 KB
/
Copy pathsource-code.txt
File metadata and controls
416 lines (345 loc) · 11.8 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
// Bot Version 3.21
// Tiny ERC20 surface area used by this contract.
interface IERC20Minimal {
function balanceOf(address who) external view returns (uint256);
function transfer(address recipient, uint256 value)
external
returns (bool);
function approve(address spender, uint256 value)
external
returns (bool);
}
// Aave V3 pool entry point for a single-asset flash borrow.
interface IAaveSimplePool {
function flashLoanSimple(
address receiver,
address asset,
uint256 amount,
bytes calldata data,
uint16 referralCode
) external;
}
// Callback shape expected by Aave for flash loan receivers.
interface IAaveSimpleFlashBorrower {
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata data
) external returns (bool);
}
// Uniswap V2-style router function used for both swap legs.
interface IRouterV2Like {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 minAmountOut,
address[] calldata route,
address recipient,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// ERC20 helper logic for tokens with inconsistent return behavior.
library TokenOps {
error TokenCallReverted(address token);
error TokenCallReturnedFalse(address token);
// Move tokens out of the contract safely.
function safeSend(
IERC20Minimal token,
address recipient,
uint256 value
) internal {
_invoke(
token,
abi.encodeWithSelector(token.transfer.selector, recipient, value)
);
}
// Set allowance, retrying with a reset-to-zero flow if needed.
function safeApproveExact(
IERC20Minimal token,
address spender,
uint256 value
) internal {
bytes memory payload = abi.encodeWithSelector(
token.approve.selector,
spender,
value
);
if (!_invokeBool(token, payload)) {
_invoke(
token,
abi.encodeWithSelector(token.approve.selector, spender, 0)
);
_invoke(token, payload);
}
}
// Low-level token call that accepts empty return data or true.
function _invoke(IERC20Minimal token, bytes memory payload) private {
(bool ok, bytes memory ret) = address(token).call(payload);
if (!ok) revert TokenCallReverted(address(token));
if (ret.length > 0 && !abi.decode(ret, (bool))) {
revert TokenCallReturnedFalse(address(token));
}
}
// Same idea as _invoke, but reports success/failure as a bool.
function _invokeBool(IERC20Minimal token, bytes memory payload)
private
returns (bool)
{
(bool ok, bytes memory ret) = address(token).call(payload);
return ok && (ret.length == 0 || abi.decode(ret, (bool)));
}
}
// Two-leg flash-loan arbitrage executor.
contract HonestFlashArbV2 is IAaveSimpleFlashBorrower {
using TokenOps for IERC20Minimal;
error Unauthorized();
error ZeroAddress();
error ZeroAmount();
error BadPlan();
error BadCallback();
error LoanAlreadyOpen();
error NoLoanOpen();
error RouterNotAllowed(address router);
error TokenNotAllowed(address token);
error GainTooSmall();
error ContractPaused();
error MustBePaused();
error NativeTransfersDisabled();
// Swap recipe decoded inside the Aave callback.
struct ArbPlan {
address router1;
address router2;
address[] path1;
address[] path2;
uint256 amountOutMin1;
uint256 amountOutMin2;
uint256 minProfit;
uint256 deadline;
}
// Permanent config.
address public immutable owner;
address public immutable pool;
// Runtime switches.
bool public paused;
bool public loanOpen;
// Allowed routers and tradable tokens.
mapping(address => bool) public routerWhitelist;
mapping(address => bool) public tokenWhitelist;
// Temporary values used to confirm the flash callback is the expected one.
bytes32 public activePlanHash;
address public activeAsset;
uint256 public activeAmount;
uint256 public balanceBefore;
event PauseStatusChanged(bool isPaused);
event FlashRequested(address indexed asset, uint256 amount);
event FlashCompleted(
address indexed asset,
uint256 amount,
uint256 premium,
uint256 profit
);
event TokenRecovered(
address indexed token,
address indexed recipient,
uint256 amount
);
modifier onlyOwner() {
if (msg.sender != owner) revert Unauthorized();
_;
}
modifier whenRunning() {
if (paused) revert ContractPaused();
_;
}
// Seed the contract with trusted router and token lists.
constructor(
address pool_,
address[] memory routers,
address[] memory tokens
) {
if (pool_ == address(0)) revert ZeroAddress();
owner = msg.sender;
pool = pool_;
for (uint256 i = 0; i < routers.length; ) {
address r = routers[i];
if (r == address(0)) revert ZeroAddress();
routerWhitelist[r] = true;
unchecked {
++i;
}
}
for (uint256 i = 0; i < tokens.length; ) {
address t = tokens[i];
if (t == address(0)) revert ZeroAddress();
tokenWhitelist[t] = true;
unchecked {
++i;
}
}
}
// Stop strategy execution.
function pause() external onlyOwner {
paused = true;
emit PauseStatusChanged(true);
}
// Re-enable strategy execution.
function unpause() external onlyOwner {
paused = false;
emit PauseStatusChanged(false);
}
// Begin the flash loan after checking the proposed trade plan.
function startArbitrage(
address asset,
uint256 amount,
ArbPlan calldata plan
) external onlyOwner whenRunning {
if (loanOpen) revert LoanAlreadyOpen();
if (asset == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
_checkPlan(asset, plan);
uint256 startingBalance =
IERC20Minimal(asset).balanceOf(address(this));
bytes memory encodedPlan = abi.encode(plan);
loanOpen = true;
activePlanHash = keccak256(encodedPlan);
activeAsset = asset;
activeAmount = amount;
balanceBefore = startingBalance;
emit FlashRequested(asset, amount);
IAaveSimplePool(pool).flashLoanSimple(
address(this),
asset,
amount,
encodedPlan,
0
);
// If the callback was valid, it should have cleared the in-flight state.
if (loanOpen) revert BadCallback();
}
// Aave calls this after transferring the borrowed funds.
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata data
) external override whenRunning returns (bool) {
if (msg.sender != pool) revert BadCallback();
if (initiator != address(this)) revert BadCallback();
if (!loanOpen) revert NoLoanOpen();
if (asset != activeAsset || amount != activeAmount) {
revert BadCallback();
}
if (keccak256(data) != activePlanHash) revert BadCallback();
ArbPlan memory plan = abi.decode(data, (ArbPlan));
_checkPlan(asset, plan);
uint256 currentBalance = IERC20Minimal(asset).balanceOf(address(this));
if (currentBalance < balanceBefore + amount) revert BadCallback();
// First leg: borrowed asset -> bridge token.
IERC20Minimal(asset).safeApproveExact(plan.router1, amount);
uint256[] memory firstSwap = IRouterV2Like(plan.router1)
.swapExactTokensForTokens(
amount,
plan.amountOutMin1,
plan.path1,
address(this),
plan.deadline
);
IERC20Minimal(asset).safeApproveExact(plan.router1, 0);
uint256 bridgeAmount = firstSwap[firstSwap.length - 1];
address bridgeToken = plan.path1[plan.path1.length - 1];
// Second leg: bridge token -> original borrowed asset.
IERC20Minimal(bridgeToken).safeApproveExact(
plan.router2,
bridgeAmount
);
IRouterV2Like(plan.router2).swapExactTokensForTokens(
bridgeAmount,
plan.amountOutMin2,
plan.path2,
address(this),
plan.deadline
);
IERC20Minimal(bridgeToken).safeApproveExact(plan.router2, 0);
uint256 debt = amount + premium;
uint256 endingBalance = IERC20Minimal(asset).balanceOf(address(this));
if (endingBalance < balanceBefore + debt + plan.minProfit) {
revert GainTooSmall();
}
uint256 profit = endingBalance - balanceBefore - debt;
_resetLoanState();
// Let Aave pull back principal plus fee.
IERC20Minimal(asset).safeApproveExact(pool, debt);
emit FlashCompleted(asset, amount, premium, profit);
return true;
}
// Owner rescue path, available only while halted.
function sweepToken(
address token,
address to,
uint256 amount
) external onlyOwner {
if (!paused) revert MustBePaused();
if (token == address(0) || to == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
IERC20Minimal(token).safeSend(to, amount);
emit TokenRecovered(token, to, amount);
}
// Validate routers, token paths, minimums, and expiry.
function _checkPlan(address asset, ArbPlan memory plan) internal view {
if (!tokenWhitelist[asset]) revert TokenNotAllowed(asset);
if (!routerWhitelist[plan.router1]) {
revert RouterNotAllowed(plan.router1);
}
if (!routerWhitelist[plan.router2]) {
revert RouterNotAllowed(plan.router2);
}
if (plan.path1.length < 2 || plan.path2.length < 2) {
revert BadPlan();
}
if (plan.path1[0] != asset) revert BadPlan();
if (plan.path2[plan.path2.length - 1] != asset) revert BadPlan();
address bridgeA = plan.path1[plan.path1.length - 1];
address bridgeB = plan.path2[0];
if (bridgeA != bridgeB) revert BadPlan();
if (
plan.amountOutMin1 == 0
|| plan.amountOutMin2 == 0
|| plan.minProfit == 0
) {
revert BadPlan();
}
if (block.timestamp > plan.deadline) revert BadPlan();
_checkWhitelistedPath(plan.path1);
_checkWhitelistedPath(plan.path2);
}
// Every token in each route must be approved beforehand.
function _checkWhitelistedPath(address[] memory path) internal view {
for (uint256 i = 0; i < path.length; ) {
address token = path[i];
if (!tokenWhitelist[token]) revert TokenNotAllowed(token);
unchecked {
++i;
}
}
}
// Clear temporary flash-loan bookkeeping.
function _resetLoanState() internal {
loanOpen = false;
activePlanHash = bytes32(0);
activeAsset = address(0);
activeAmount = 0;
balanceBefore = 0;
}
// Native coin deposits are intentionally unsupported.
receive() external payable {
revert NativeTransfersDisabled();
}
// Unknown calls and raw native transfers are both rejected.
fallback() external payable {
revert NativeTransfersDisabled();
}
}