This repository was archived by the owner on Feb 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathOneSplitAudit.sol
385 lines (346 loc) · 14.5 KB
/
OneSplitAudit.sol
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
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./interface/IWETH.sol";
import "./interface/IUniswapV2Exchange.sol";
import "./IOneSplit.sol";
import "./UniversalERC20.sol";
contract IFreeFromUpTo is IERC20 {
function freeFromUpTo(address from, uint256 value) external returns(uint256 freed);
}
interface IReferralGasSponsor {
function makeGasDiscount(
uint256 gasSpent,
uint256 returnAmount,
bytes calldata msgSenderCalldata
) external;
}
library Array {
function first(IERC20[] memory arr) internal pure returns(IERC20) {
return arr[0];
}
function last(IERC20[] memory arr) internal pure returns(IERC20) {
return arr[arr.length - 1];
}
}
//
// Security assumptions:
// 1. It is safe to have infinite approves of any tokens to this smart contract,
// since it could only call `transferFrom()` with first argument equal to msg.sender
// 2. It is safe to call `swap()` with reliable `minReturn` argument,
// if returning amount will not reach `minReturn` value whole swap will be reverted.
// 3. Additionally CHI tokens could be burned from caller in case of FLAG_ENABLE_CHI_BURN (0x10000000000)
// presented in `flags` or from transaction origin in case of FLAG_ENABLE_CHI_BURN_BY_ORIGIN (0x4000000000000000)
// presented in `flags`. Burned amount would refund up to 43% of gas fees.
//
contract OneSplitAudit is IOneSplit, Ownable {
using SafeMath for uint256;
using UniversalERC20 for IERC20;
using Array for IERC20[];
IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
IOneSplitMulti public oneSplitImpl;
event ImplementationUpdated(address indexed newImpl);
event Swapped(
IERC20 indexed fromToken,
IERC20 indexed destToken,
uint256 fromTokenAmount,
uint256 destTokenAmount,
uint256 minReturn,
uint256[] distribution,
uint256[] flags,
address referral,
uint256 feePercent
);
constructor(IOneSplitMulti impl) public {
setNewImpl(impl);
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin, "OneSplit: do not send ETH directly");
}
function setNewImpl(IOneSplitMulti impl) public onlyOwner {
oneSplitImpl = impl;
emit ImplementationUpdated(address(impl));
}
/// @notice Calculate expected returning amount of `destToken`
/// @param fromToken (IERC20) Address of token or `address(0)` for Ether
/// @param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param parts (uint256) Number of pieces source volume could be splitted,
/// works like granularity, higly affects gas usage. Should be called offchain,
/// but could be called onchain if user swaps not his own funds, but this is still considered as not safe.
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See contants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
/// @notice Calculate expected returning amount of `destToken`
/// @param fromToken (IERC20) Address of token or `address(0)` for Ether
/// @param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param parts (uint256) Number of pieces source volume could be splitted,
/// works like granularity, higly affects gas usage. Should be called offchain,
/// but could be called onchain if user swaps not his own funds, but this is still considered as not safe.
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
/// @param destTokenEthPriceTimesGasPrice (uint256) destToken price to ETH multiplied by gas price
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitImpl.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
/// @notice Calculate expected returning amount of first `tokens` element to
/// last `tokens` element through ann the middle tokens with corresponding
/// `parts`, `flags` and `destTokenEthPriceTimesGasPrices` array values of each step
/// @param tokens (IERC20[]) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param parts (uint256[]) Number of pieces source volume could be splitted
/// @param flags (uint256[]) Flags for enabling and disabling some features, default 0
/// @param destTokenEthPriceTimesGasPrices (uint256[]) destToken price to ETH multiplied by gas price
function getExpectedReturnWithGasMulti(
IERC20[] memory tokens,
uint256 amount,
uint256[] memory parts,
uint256[] memory flags,
uint256[] memory destTokenEthPriceTimesGasPrices
)
public
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitImpl.getExpectedReturnWithGasMulti(
tokens,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrices
);
}
/// @notice Swap `amount` of `fromToken` to `destToken`
/// @param fromToken (IERC20) Address of token or `address(0)` for Ether
/// @param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags // See contants in IOneSplit.sol
) public payable returns(uint256) {
return swapWithReferral(
fromToken,
destToken,
amount,
minReturn,
distribution,
flags,
address(0),
0
);
}
/// @notice Swap `amount` of `fromToken` to `destToken`
/// param fromToken (IERC20) Address of token or `address(0)` for Ether
/// param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
/// @param referral (address) Address of referral
/// @param feePercent (uint256) Fees percents normalized to 1e18, limited to 0.03e18 (3%)
function swapWithReferral(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags, // See contants in IOneSplit.sol
address referral,
uint256 feePercent
) public payable returns(uint256) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = fromToken;
tokens[1] = destToken;
uint256[] memory flagsArray = new uint256[](1);
flagsArray[0] = flags;
swapWithReferralMulti(
tokens,
amount,
minReturn,
distribution,
flagsArray,
referral,
feePercent
);
}
/// @notice Swap `amount` of first element of `tokens` to the latest element of `destToken`
/// @param tokens (IERC20[]) Addresses of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256[]) Flags for enabling and disabling some features, default 0
function swapMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags
) public payable returns(uint256) {
swapWithReferralMulti(
tokens,
amount,
minReturn,
distribution,
flags,
address(0),
0
);
}
/// @notice Swap `amount` of first element of `tokens` to the latest element of `destToken`
/// @param tokens (IERC20[]) Addresses of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256[]) Flags for enabling and disabling some features, default 0
/// @param referral (address) Address of referral
/// @param feePercent (uint256) Fees percents normalized to 1e18, limited to 0.03e18 (3%)
function swapWithReferralMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags,
address referral,
uint256 feePercent
) public payable returns(uint256 returnAmount) {
require(tokens.length >= 2 && amount > 0, "OneSplit: swap makes no sense");
require(flags.length == tokens.length - 1, "OneSplit: flags array length is invalid");
require((msg.value != 0) == tokens.first().isETH(), "OneSplit: msg.value should be used only for ETH swap");
require(feePercent <= 0.03e18, "OneSplit: feePercent out of range");
uint256 gasStart = gasleft();
Balances memory beforeBalances = _getFirstAndLastBalances(tokens, true);
// Transfer From
if (amount == uint256(-1)) {
amount = Math.min(
tokens.first().balanceOf(msg.sender),
tokens.first().allowance(msg.sender, address(this))
);
}
tokens.first().universalTransferFromSenderToThis(amount);
uint256 confirmed = tokens.first().universalBalanceOf(address(this)).sub(beforeBalances.ofFromToken);
// Swap
tokens.first().universalApprove(address(oneSplitImpl), confirmed);
oneSplitImpl.swapMulti.value(tokens.first().isETH() ? confirmed : 0)(
tokens,
confirmed,
minReturn,
distribution,
flags
);
Balances memory afterBalances = _getFirstAndLastBalances(tokens, false);
// Return
returnAmount = afterBalances.ofDestToken.sub(beforeBalances.ofDestToken);
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
tokens.last().universalTransfer(referral, returnAmount.mul(feePercent).div(1e18));
tokens.last().universalTransfer(msg.sender, returnAmount.sub(returnAmount.mul(feePercent).div(1e18)));
emit Swapped(
tokens.first(),
tokens.last(),
amount,
returnAmount,
minReturn,
distribution,
flags,
referral,
feePercent
);
// Return remainder
if (afterBalances.ofFromToken > beforeBalances.ofFromToken) {
tokens.first().universalTransfer(msg.sender, afterBalances.ofFromToken.sub(beforeBalances.ofFromToken));
}
if ((flags[0] & (FLAG_ENABLE_CHI_BURN | FLAG_ENABLE_CHI_BURN_BY_ORIGIN)) > 0) {
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
_chiBurnOrSell(
((flags[0] & FLAG_ENABLE_CHI_BURN_BY_ORIGIN) > 0) ? tx.origin : msg.sender,
(gasSpent + 14154) / 41947
);
}
else if ((flags[0] & FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP) > 0) {
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
IReferralGasSponsor(referral).makeGasDiscount(gasSpent, returnAmount, msg.data);
}
}
function claimAsset(IERC20 asset, uint256 amount) public onlyOwner {
asset.universalTransfer(msg.sender, amount);
}
function _chiBurnOrSell(address payable sponsor, uint256 amount) internal {
IUniswapV2Exchange exchange = IUniswapV2Exchange(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2);
(uint256 sellRefund,,) = UniswapV2ExchangeLib.getReturn(exchange, chi, weth, amount);
uint256 burnRefund = amount.mul(18_000).mul(tx.gasprice);
if (sellRefund < burnRefund.add(tx.gasprice.mul(36_000))) {
chi.freeFromUpTo(sponsor, amount);
}
else {
chi.transferFrom(sponsor, address(exchange), amount);
exchange.swap(0, sellRefund, address(this), "");
weth.withdraw(weth.balanceOf(address(this)));
sponsor.transfer(address(this).balance);
}
}
struct Balances {
uint256 ofFromToken;
uint256 ofDestToken;
}
function _getFirstAndLastBalances(IERC20[] memory tokens, bool subValue) internal view returns(Balances memory) {
return Balances({
ofFromToken: tokens.first().universalBalanceOf(address(this)).sub(subValue ? msg.value : 0),
ofDestToken: tokens.last().universalBalanceOf(address(this))
});
}
}