forked from cryptochou/blur-analysis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GemSwap.sol
507 lines (445 loc) · 17.7 KB
/
GemSwap.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
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/ReentrancyGuard.sol";
import "./markets/MarketRegistry.sol";
import "./SpecialTransferHelper.sol";
import "../../interfaces/markets/tokens/IERC20.sol";
import "../../interfaces/markets/tokens/IERC721.sol";
import "../../interfaces/markets/tokens/IERC1155.sol";
contract GemSwap is SpecialTransferHelper, Ownable, ReentrancyGuard {
struct OpenseaTrades {
uint256 value;
bytes tradeData;
}
struct ERC20Details {
address[] tokenAddrs;
uint256[] amounts;
}
struct ERC1155Details {
address tokenAddr;
uint256[] ids;
uint256[] amounts;
}
struct ConverstionDetails {
bytes conversionData;
}
struct AffiliateDetails {
address affiliate;
bool isActive;
}
struct SponsoredMarket {
uint256 marketId;
bool isActive;
}
address public constant GOV = 0x83d841bC0450D5Ac35DCAd8d05Db53EbA29978c2;
address public guardian;
address public converter;
address public punkProxy;
uint256 public baseFees;
bool public openForTrades;
bool public openForFreeTrades;
MarketRegistry public marketRegistry;
AffiliateDetails[] public affiliates;
SponsoredMarket[] public sponsoredMarkets;
modifier isOpenForTrades() {
require(openForTrades, "trades not allowed");
_;
}
modifier isOpenForFreeTrades() {
require(openForFreeTrades, "free trades not allowed");
_;
}
constructor(address _marketRegistry, address _converter, address _guardian) {
marketRegistry = MarketRegistry(_marketRegistry);
converter = _converter;
guardian = _guardian;
baseFees = 0;
openForTrades = true;
openForFreeTrades = true;
affiliates.push(AffiliateDetails(GOV, true));
}
function setUp() external onlyOwner {
// Create CryptoPunk Proxy
IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).registerProxy();
punkProxy = IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).proxyInfo(address(this));
// approve wrapped mooncats rescue to AcclimatedMoonCats contract
IERC721(0x7C40c393DC0f283F318791d746d894DdD3693572).setApprovalForAll(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, true);
}
// @audit This function is used to approve specific tokens to specific market contracts with high volume.
// This is done in very rare cases for the gas optimization purposes.
function setOneTimeApproval(IERC20 token, address operator, uint256 amount) external onlyOwner {
token.approve(operator, amount);
}
function updateGuardian(address _guardian) external onlyOwner {
guardian = _guardian;
}
function addAffiliate(address _affiliate) external onlyOwner {
affiliates.push(AffiliateDetails(_affiliate, true));
}
function updateAffiliate(uint256 _affiliateIndex, address _affiliate, bool _IsActive) external onlyOwner {
affiliates[_affiliateIndex] = AffiliateDetails(_affiliate, _IsActive);
}
function addSponsoredMarket(uint256 _marketId) external onlyOwner {
sponsoredMarkets.push(SponsoredMarket(_marketId, true));
}
function updateSponsoredMarket(uint256 _marketIndex, uint256 _marketId, bool _isActive) external onlyOwner {
sponsoredMarkets[_marketIndex] = SponsoredMarket(_marketId, _isActive);
}
function setBaseFees(uint256 _baseFees) external onlyOwner {
baseFees = _baseFees;
}
function setOpenForTrades(bool _openForTrades) external onlyOwner {
openForTrades = _openForTrades;
}
function setOpenForFreeTrades(bool _openForFreeTrades) external onlyOwner {
openForFreeTrades = _openForFreeTrades;
}
// @audit we will setup a system that will monitor the contract for any leftover
// assets. In case any asset is leftover, the system should be able to trigger this
// function to close all the trades until the leftover assets are rescued.
function closeAllTrades() external {
require(_msgSender() == guardian);
openForTrades = false;
openForFreeTrades = false;
}
function setConverter(address _converter) external onlyOwner {
converter = _converter;
}
function setMarketRegistry(MarketRegistry _marketRegistry) external onlyOwner {
marketRegistry = _marketRegistry;
}
function _transferEth(address _to, uint256 _amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), _to, _amount, 0, 0, 0, 0)
}
require(callStatus, "_transferEth: Eth transfer failed");
}
function _collectFee(uint256[2] memory feeDetails) internal {
require(feeDetails[1] >= baseFees, "Insufficient fee");
if (feeDetails[1] > 0) {
AffiliateDetails memory affiliateDetails = affiliates[feeDetails[0]];
affiliateDetails.isActive
? _transferEth(affiliateDetails.affiliate, feeDetails[1])
: _transferEth(GOV, feeDetails[1]);
}
}
function _checkCallResult(bool _success) internal pure {
if (!_success) {
// Copy revert reason from call
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
function _transferFromHelper(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details
) internal {
// transfer ERC20 tokens from the sender to this contract
for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i]));
}
// transfer ERC721 tokens from the sender to this contract
for (uint256 i = 0; i < erc721Details.length; i++) {
// accept CryptoPunks
if (erc721Details[i].tokenAddr == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB) {
_acceptCryptoPunk(erc721Details[i]);
}
// accept Mooncat
else if (erc721Details[i].tokenAddr == 0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6) {
_acceptMoonCat(erc721Details[i]);
}
// default
else {
for (uint256 j = 0; j < erc721Details[i].ids.length; j++) {
IERC721(erc721Details[i].tokenAddr).transferFrom(
_msgSender(),
address(this),
erc721Details[i].ids[j]
);
}
}
}
// transfer ERC1155 tokens from the sender to this contract
for (uint256 i = 0; i < erc1155Details.length; i++) {
IERC1155(erc1155Details[i].tokenAddr).safeBatchTransferFrom(
_msgSender(),
address(this),
erc1155Details[i].ids,
erc1155Details[i].amounts,
""
);
}
}
function _conversionHelper(
ConverstionDetails[] memory _converstionDetails
) internal {
for (uint256 i = 0; i < _converstionDetails.length; i++) {
// convert to desired asset
(bool success, ) = converter.delegatecall(_converstionDetails[i].conversionData);
// check if the call passed successfully
_checkCallResult(success);
}
}
function _trade(
MarketRegistry.TradeDetails[] memory _tradeDetails
) internal {
for (uint256 i = 0; i < _tradeDetails.length; i++) {
// get market details
(address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
// market should be active
require(_isActive, "_trade: InActive Market");
// execute trade
if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b || _proxy == 0x7f268357A8c2552623316e2562D90e642bB538E5) {
_proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
} else {
(bool success, ) = _isLib
? _proxy.delegatecall(_tradeDetails[i].tradeData)
: _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// check if the call passed successfully
_checkCallResult(success);
}
}
}
// function _tradeSponsored(
// MarketRegistry.TradeDetails[] memory _tradeDetails,
// uint256 sponsoredMarketId
// ) internal returns (bool isSponsored) {
// for (uint256 i = 0; i < _tradeDetails.length; i++) {
// // check if the trade is for the sponsored market
// if (_tradeDetails[i].marketId == sponsoredMarketId) {
// isSponsored = true;
// }
// // get market details
// (address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
// // market should be active
// require(_isActive, "_trade: InActive Market");
// // execute trade
// if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b) {
// _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// } else {
// (bool success, ) = _isLib
// ? _proxy.delegatecall(_tradeDetails[i].tradeData)
// : _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// // check if the call passed successfully
// _checkCallResult(success);
// }
// }
// }
function _returnDust(address[] memory _tokens) internal {
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
// return remaining tokens (if any)
for (uint256 i = 0; i < _tokens.length; i++) {
if (IERC20(_tokens[i]).balanceOf(address(this)) > 0) {
_tokens[i].call(abi.encodeWithSelector(0xa9059cbb, msg.sender, IERC20(_tokens[i]).balanceOf(address(this))));
}
}
}
function batchBuyFromOpenSea(
OpenseaTrades[] memory openseaTrades
) payable external nonReentrant {
// execute trades
for (uint256 i = 0; i < openseaTrades.length; i++) {
// execute trade
address(0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b).call{value:openseaTrades[i].value}(openseaTrades[i].tradeData);
}
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
}
function batchBuyWithETH(
MarketRegistry.TradeDetails[] memory tradeDetails
) payable external nonReentrant {
// execute trades
_trade(tradeDetails);
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
}
function batchBuyWithERC20s(
ERC20Details memory erc20Details,
MarketRegistry.TradeDetails[] memory tradeDetails,
ConverstionDetails[] memory converstionDetails,
address[] memory dustTokens
) payable external nonReentrant {
// transfer ERC20 tokens from the sender to this contract
for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i]));
}
// Convert any assets if needed
_conversionHelper(converstionDetails);
// execute trades
_trade(tradeDetails);
// return dust tokens (if any)
_returnDust(dustTokens);
}
// swaps any combination of ERC-20/721/1155
// User needs to approve assets before invoking swap
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
function multiAssetSwap(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details,
ConverstionDetails[] memory converstionDetails,
MarketRegistry.TradeDetails[] memory tradeDetails,
address[] memory dustTokens,
uint256[2] memory feeDetails // [affiliateIndex, ETH fee in Wei]
) payable external isOpenForTrades nonReentrant {
// collect fees
_collectFee(feeDetails);
// transfer all tokens
_transferFromHelper(
erc20Details,
erc721Details,
erc1155Details
);
// Convert any assets if needed
_conversionHelper(converstionDetails);
// execute trades
_trade(tradeDetails);
// return dust tokens (if any)
_returnDust(dustTokens);
}
// Utility function that is used for free swaps for sponsored markets
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
// function multiAssetSwapWithoutFee(
// ERC20Details memory erc20Details,
// SpecialTransferHelper.ERC721Details[] memory erc721Details,
// ERC1155Details[] memory erc1155Details,
// ConverstionDetails[] memory converstionDetails,
// MarketRegistry.TradeDetails[] memory tradeDetails,
// address[] memory dustTokens,
// uint256 sponsoredMarketIndex
// ) payable external isOpenForFreeTrades nonReentrant {
// // fetch the marketId of the sponsored market
// SponsoredMarket memory sponsoredMarket = sponsoredMarkets[sponsoredMarketIndex];
// // check if the market is active
// require(sponsoredMarket.isActive, "multiAssetSwapWithoutFee: InActive sponsored market");
//
// // transfer all tokens
// _transferFromHelper(
// erc20Details,
// erc721Details,
// erc1155Details
// );
//
// // Convert any assets if needed
// _conversionHelper(converstionDetails);
//
// // execute trades
// bool isSponsored = _tradeSponsored(tradeDetails, sponsoredMarket.marketId);
//
// // check if the trades include the sponsored market
// require(isSponsored, "multiAssetSwapWithoutFee: trades do not include sponsored market");
//
// // return dust tokens (if any)
// _returnDust(dustTokens);
// }
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) public virtual returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) public virtual returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return 0x150b7a02;
}
// Used by ERC721BasicToken.sol
function onERC721Received(
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return 0xf0b9e5ba;
}
function supportsInterface(bytes4 interfaceId)
external
virtual
view
returns (bool)
{
return interfaceId == this.supportsInterface.selector;
}
receive() external payable {}
// Emergency function: In case any ETH get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueETH(address recipient) onlyOwner external {
_transferEth(recipient, address(this).balance);
}
// Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC20(address asset, address recipient) onlyOwner external {
asset.call(abi.encodeWithSelector(0xa9059cbb, recipient, IERC20(asset).balanceOf(address(this))));
}
// Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external {
for (uint256 i = 0; i < ids.length; i++) {
IERC721(asset).transferFrom(address(this), recipient, ids[i]);
}
}
// Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external {
for (uint256 i = 0; i < ids.length; i++) {
IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], "");
}
}
}