-
Notifications
You must be signed in to change notification settings - Fork 2
/
MonoPool.sol
612 lines (490 loc) · 22.5 KB
/
MonoPool.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
import { SafeCastLib } from "solady/utils/SafeCastLib.sol";
import { ERC20 } from "solady/tokens/ERC20.sol";
import { Pool } from "./libs/PoolLib.sol";
import { Accounter } from "./libs/AccounterLib.sol";
import { Token } from "./libs/TokenLib.sol";
import { BPS } from "./libs/SwapLib.sol";
import { Ops } from "./Ops.sol";
import { ReentrancyGuard } from "./utils/ReentrancyGuard.sol";
import { DecoderLib } from "./encoder/DecoderLib.sol";
// Unit for the protocol fees base (divider for the value)
uint256 constant PROTOCOL_FEES = 10_000;
/// @title MonoPool
/// @notice Same as the original MegaTokenPool, but with a single ERC_20 base token (useful for project that want a pool
/// for their internal swap)
/// @author KONFeature <https://github.com/KONFeature>
/// @author Inspired from (https://github.com/Philogy/singleton-swapper/blob/main/src/MegaPool.sol) by Phylogy
contract MonoPool is ReentrancyGuard {
using SafeTransferLib for address;
using SafeCastLib for uint256;
using DecoderLib for uint256;
/* -------------------------------------------------------------------------- */
/* Constant's */
/* -------------------------------------------------------------------------- */
/// @dev The max swap fee (5%)
uint256 private constant MAX_PROTOCOL_FEE = 500;
/// @dev The token state to handle reserves & protocol fees
struct TokenState {
uint256 totalReserves;
uint256 protocolFees;
}
/* -------------------------------------------------------------------------- */
/* Custom error's */
/* -------------------------------------------------------------------------- */
error InvalidOp(uint256 op);
error LeftOverDelta();
error InvalidGive();
error NegativeSend();
error NegativeReceive();
error AmountOutsideBounds();
error NotFeeReceiver();
error Swap0Amount();
error InvalidAddress();
/// @dev 'bytes4(keccak256("Swap0Amount()"))'
uint256 private constant _SWAP_0_AMOUNT_SELECTOR = 0x5509f2e4;
/* -------------------------------------------------------------------------- */
/* Event's */
/* -------------------------------------------------------------------------- */
/// @dev Event emitted after a swap
event Swap(bool zeroForOne, uint256 amountIn);
/// @dev Event emitted after a liquidity update (addition or suppression)
event LiquidityUpdate(address indexed provider, int256 amount0, int256 amount1);
/// @dev Event emitted after a protocol fee update
event ProtocolFeeUpdate(address feesColector, uint256 protocolFee);
/* -------------------------------------------------------------------------- */
/* Storage */
/* -------------------------------------------------------------------------- */
// slither-disable-start naming-convention
/// @dev The token's we will use for the pool
Token private immutable TOKEN_0;
Token private immutable TOKEN_1;
/// @dev The fee that will be taken from each swaps
uint256 private immutable FEE_BPS;
// slither-disable-end naming-convention
/// @dev The fee that will be taken from each swaps
uint256 private protocolFee;
/// @dev The receiver for the swap fees
address private feeReceiver;
/// @dev The pool managed by this contract
Pool private pool;
/// @dev The current token state's
TokenState private token0State;
TokenState private token1State;
/* -------------------------------------------------------------------------- */
/* Constructor */
/* -------------------------------------------------------------------------- */
constructor(address token0, address token1, uint256 feeBps, address _feeReceiver, uint256 _protocolFee) payable {
require(feeBps < BPS);
require(_protocolFee < MAX_PROTOCOL_FEE);
// We can only have one 0 address (representing native pool)
require(token0 != address(0) || token1 != address(0));
// If no fees receiver passed, pass 0 arguments
if (_feeReceiver == address(0)) {
require(_protocolFee == 0);
}
// Save base pool info's
FEE_BPS = feeBps;
TOKEN_0 = Token.wrap(token0);
TOKEN_1 = Token.wrap(token1);
// Save info's about protocol receiver
feeReceiver = _feeReceiver;
protocolFee = _protocolFee;
}
/* -------------------------------------------------------------------------- */
/* External write method's */
/* -------------------------------------------------------------------------- */
/// @notice Update the fee receiver and the fee amount
/// @dev Only the current fee receiver can update the fee receiver and the amount
/// @dev The protocol can decide to stop receiving fees, by doing so he need to send the 0 address & 0 protocol fees
/// @param _feeReceiver The new fee receiver
/// @param _protocolFee The new fee amount per thousand
function updateFeeReceiver(address _feeReceiver, uint256 _protocolFee) external {
if (feeReceiver != msg.sender) revert NotFeeReceiver();
require(_protocolFee < MAX_PROTOCOL_FEE);
if (_feeReceiver == address(0)) {
require(_protocolFee == 0);
}
feeReceiver = _feeReceiver;
protocolFee = _protocolFee;
// Emit event
emit ProtocolFeeUpdate(_feeReceiver, _protocolFee);
}
/**
* @notice Execute a program of operations on pools. The `program` is a serialized list of operations, encoded in a
* specific format.
* @dev This function uses a non-ABI encoding to ensure a custom set of operations, each taking on a different
* amount of data while keeping calldata size minimal. It is not reentrant.
* @param program Serialized list of operations, with each operation consisting of an 8-bit operation specifier and
* parameters. The structure is as follows:
* For every operation:
* 1 byte: 8-bit operation (4-bits operation id and 4-bits flags)
* n bytes: opcode data
* Refer to the function documentation for details on individual operations.
*/
function execute(bytes calldata program) external payable nonReentrant {
(uint256 ptr, uint256 endPtr) = _getPc(program);
// Initialize the accounter
Accounter memory accounter = Accounter(0, 0);
// Interpret each operations
uint256 op;
while (ptr < endPtr) {
unchecked {
(ptr, op) = ptr.readUint8();
ptr = _interpretOp(accounter, ptr, op);
}
}
// If there are any leftover deltas, revert
if (accounter.token0Change != 0 || accounter.token1Change != 0) revert LeftOverDelta();
}
/* -------------------------------------------------------------------------- */
/* Internal write method's */
/* -------------------------------------------------------------------------- */
/// @notice Interpret an `op` from a programm encoded in a `ptr`, saving accounting changes in the `accounter`
function _interpretOp(Accounter memory accounter, uint256 ptr, uint256 op) internal returns (uint256) {
// Extract the operation
uint256 mop = op & Ops.MASK_OP;
if (mop == Ops.SWAP) {
return _swap(accounter, ptr, op);
}
// Send & Receive ALL op's
if (mop == Ops.RECEIVE_ALL) {
return _receiveAll(accounter, ptr, op);
}
if (mop == Ops.SEND_ALL) {
return _sendAll(accounter, ptr, op);
}
// Send & Receive op's
if (mop == Ops.RECEIVE) {
return _receive(accounter, ptr);
}
if (mop == Ops.SEND) {
return _send(accounter, ptr);
}
// Permit helper's
if (mop == Ops.PERMIT_WITHDRAW_VIA_SIG) {
return _permitViaSig(ptr);
}
// Add & Remove liquidity op's
if (mop == Ops.ADD_LIQ) {
return _addLiquidity(accounter, ptr);
}
if (mop == Ops.RM_LIQ) {
return _removeLiquidity(accounter, ptr);
}
// Claim fees op's
if (mop == Ops.CLAIM_ALL_FEES) {
return _claimFees(accounter, ptr);
}
// Revert cause of an invalid OP
revert InvalidOp(op);
}
/// @notice Perform a swap operation
function _swap(Accounter memory accounter, uint256 ptr, uint256 op) internal returns (uint256) {
uint256 amount;
bool zeroForOne = (op & Ops.SWAP_DIR) != 0;
(ptr, amount) = ptr.readUint128();
// If we got a swap fee, deduce it from the amount to swap
uint256 swapFee;
unchecked {
swapFee = (amount * protocolFee) / PROTOCOL_FEES;
// Decrease the amount of the fees we will take
amount = amount - swapFee;
}
// Get the deltas
int256 delta0;
int256 delta1;
// Perform the swap and compute the delta
(delta0, delta1) = pool.swap(zeroForOne, amount, FEE_BPS);
// If we got either of one to 0, revert cause of swapping 0 amount
assembly {
if or(iszero(delta0), iszero(delta1)) {
mstore(0x00, _SWAP_0_AMOUNT_SELECTOR)
revert(0x1c, 0x04)
}
}
// Emit the swap event
emit Swap(zeroForOne, amount);
// Then register the changes (depending on the direction, add the swap fees)
// We can perform all of this stuff in an uncheck block since all the value has been checked before
// If he swap fee cause an overflow, it would be triggered before with the swap amount directly
unchecked {
if (zeroForOne && swapFee > 0) {
accounter.accountChange(delta0 + swapFee.toInt256(), delta1);
// Save protocol fee
token0State.protocolFees = token0State.protocolFees + swapFee;
} else if (swapFee > 0) {
accounter.accountChange(delta0, delta1 + swapFee.toInt256());
// Save protocol fee
token1State.protocolFees = token1State.protocolFees + swapFee;
} else {
accounter.accountChange(delta0, delta1);
}
}
return ptr;
}
/* -------------------------------------------------------------------------- */
/* Token sending / pulling op's */
/* -------------------------------------------------------------------------- */
/// @notice Perform the receive operation
function _receive(Accounter memory accounter, uint256 ptr) internal returns (uint256) {
// Get the right token depending on the input
Token token;
TokenState storage tokenState;
(ptr, token, tokenState,) = _getTokenFromBoolInPtr(ptr);
// Get the amount
uint256 amount;
(ptr, amount) = ptr.readUint128();
// Perform the transfer
token.transferFromSender(address(this), amount);
// Mark the reception state
_accountReceived(accounter, tokenState, token);
return ptr;
}
/// @notice Perform the send operation
function _send(Accounter memory accounter, uint256 ptr) internal returns (uint256) {
// Get address & token state
Token token;
TokenState storage tokenState;
bool isToken0;
(ptr, token, tokenState, isToken0) = _getTokenFromBoolInPtr(ptr);
// Get receiver & amount
address to;
uint256 amount;
(ptr, to) = ptr.readAddress();
(ptr, amount) = ptr.readUint128();
// Register the account changes
// We can perform all of this stuff in an uncheck block since the value came from a uint128 (readUint128()), and
// used in uint256 computation
unchecked {
accounter.accountChange(isToken0, amount.toInt256());
tokenState.totalReserves -= amount;
}
// Simply transfer the tokens
token.transfer(to, amount);
return ptr;
}
/* -------------------------------------------------------------------------- */
/* Token sending / pulling ALL op's */
/* -------------------------------------------------------------------------- */
/// @notice Perform the send all operation
function _sendAll(Accounter memory accounter, uint256 ptr, uint256 op) internal returns (uint256) {
// Get the right token depending on the input
Token token;
TokenState storage tokenState;
bool isToken0;
(ptr, token, tokenState, isToken0) = _getTokenFromBoolInPtr(ptr);
// Get the delta for the current accounting
int256 delta = accounter.resetChange(isToken0);
if (delta > 0) revert NegativeSend();
// Get the limits
uint256 minSend = 0;
uint256 maxSend = type(uint128).max;
if (op & Ops.ALL_MIN_BOUND != 0) (ptr, minSend) = ptr.readUint128();
if (op & Ops.ALL_MAX_BOUND != 0) (ptr, maxSend) = ptr.readUint128();
uint256 amount = uint256(-delta);
if (amount < minSend || amount > maxSend) revert AmountOutsideBounds();
// Get the recipient of the transfer
address to;
(ptr, to) = ptr.readAddress();
// Decrease the total reserve
// Can be done in an unchecked block since the amount will be checked on transfer below
unchecked {
tokenState.totalReserves -= amount;
}
// Simply transfer the tokens
token.transfer(to, amount);
return ptr;
}
/// @notice Perform the receive all operation
function _receiveAll(Accounter memory accounter, uint256 ptr, uint256 op) internal returns (uint256) {
// Get the right token depending on the input
Token token;
TokenState storage tokenState;
bool isToken0;
(ptr, token, tokenState, isToken0) = _getTokenFromBoolInPtr(ptr);
// Get the limits
uint256 minReceive = 0;
uint256 maxReceive = type(uint128).max;
if (op & Ops.ALL_MIN_BOUND != 0) (ptr, minReceive) = ptr.readUint128();
if (op & Ops.ALL_MAX_BOUND != 0) (ptr, maxReceive) = ptr.readUint128();
// Get the delta for the current accounting
int256 delta = accounter.getChange(isToken0);
if (delta < 0) revert NegativeReceive();
// Get the amount to receive
uint256 amount = uint256(delta);
if (amount < minReceive || amount > maxReceive) revert AmountOutsideBounds();
// Perform the transfer
token.transferFromSender(address(this), amount);
// Mark the reception state
_accountReceived(accounter, tokenState, token);
return ptr;
}
/// @dev Function called after we received token from an account, update our total reserve and the account changes
function _accountReceived(Accounter memory accounter, TokenState storage tokenState, Token token) internal {
uint256 reserves = tokenState.totalReserves;
uint256 directBalance = token.selfBalance();
uint256 totalReceived = directBalance - reserves;
// Register the change for either token 0 or 1 (based on the equality check)
accounter.accountChange(token == TOKEN_0, -totalReceived.toInt256());
// Increase the total reservices for this token state
tokenState.totalReserves = directBalance;
}
/* -------------------------------------------------------------------------- */
/* Liquidity specific op's */
/* -------------------------------------------------------------------------- */
/// @notice Perform the add liquidity operation
function _addLiquidity(Accounter memory accounter, uint256 ptr) internal returns (uint256) {
uint256 maxAmount0;
uint256 maxAmount1;
(ptr, maxAmount0) = ptr.readUint128();
(ptr, maxAmount1) = ptr.readUint128();
// Add the liquidity to the pool
(int256 delta0, int256 delta1) = pool.addLiquidity(msg.sender, maxAmount0, maxAmount1);
// Register the account changes
accounter.accountChange(delta0, delta1);
// Send the event
emit LiquidityUpdate(msg.sender, delta0, delta1);
return ptr;
}
/// @notice Perform the remove liquidity operation
function _removeLiquidity(Accounter memory accounter, uint256 ptr) internal returns (uint256) {
uint256 liq;
(ptr, liq) = ptr.readUint256();
// Remove the liquidity from the pool
(int256 delta0, int256 delta1) = pool.removeLiquidity(msg.sender, liq);
// Register the account changes
accounter.accountChange(delta0, delta1);
// Send the event
emit LiquidityUpdate(msg.sender, delta0, delta1);
return ptr;
}
/// @notice Perform the claim fees operation
function _claimFees(Accounter memory accounter, uint256 ptr) internal returns (uint256) {
// Ensure the sender of the message is the fee receiver
if (feeReceiver != msg.sender) revert NotFeeReceiver();
// Then check each tokens he has to claims
uint256 protocolFees0 = token0State.protocolFees;
uint256 protocolFees1 = token1State.protocolFees;
// Update the state only if he got something to claim
if (protocolFees0 > 0) {
accounter.accountChange(true, -(protocolFees0.toInt256()));
token0State.protocolFees = 0;
}
if (protocolFees1 > 0) {
accounter.accountChange(false, -(protocolFees1.toInt256()));
token1State.protocolFees = 0;
}
return ptr;
}
/* -------------------------------------------------------------------------- */
/* Token helper op's */
/* -------------------------------------------------------------------------- */
/// @notice Perform the permit operation
function _permitViaSig(uint256 ptr) internal returns (uint256) {
Token token;
TokenState storage tokenState;
uint256 amount;
uint256 deadline;
uint256 v;
bytes32 r;
bytes32 s;
(ptr, token, tokenState,) = _getTokenFromBoolInPtr(ptr);
(ptr, amount) = ptr.readUint128();
(ptr, deadline) = ptr.readUint48();
(ptr, v) = ptr.readUint8();
(ptr, r) = ptr.readBytes32();
(ptr, s) = ptr.readBytes32();
// Perform the permit operation
token.permit(msg.sender, address(this), amount, deadline, uint8(v), r, s);
return ptr;
}
/* -------------------------------------------------------------------------- */
/* Internal pure helper method's */
/* -------------------------------------------------------------------------- */
function _getPc(bytes calldata program) internal pure returns (uint256 ptr, uint256 endPtr) {
assembly ("memory-safe") {
ptr := program.offset
endPtr := add(ptr, program.length)
}
}
function _getTokenFromBoolInPtr(uint256 ptr)
internal
view
returns (uint256, Token token, TokenState storage tokenState, bool isToken0)
{
(ptr, isToken0) = ptr.readBool();
// Get the right token & state depending on the bool
if (isToken0) {
token = TOKEN_0;
tokenState = token0State;
} else {
token = TOKEN_1;
tokenState = token1State;
}
return (ptr, token, tokenState, isToken0);
}
/* -------------------------------------------------------------------------- */
/* External view method's */
/* -------------------------------------------------------------------------- */
/// @notice Get the current tokens
function getTokens() external view returns (Token token0, Token token1) {
return (TOKEN_0, TOKEN_1);
}
/// @notice Get the current pool
/// @return totalLiquidity
/// @return reserve0
/// @return reserve1
function getPoolState() external view returns (uint256, uint256, uint256) {
return (pool.totalLiquidity, pool.reserves0, pool.reserves1);
}
/// @notice Get the current pool position of the given `liquidityProvider`
/// @return position
function getPosition(address liquidityProvider) external view returns (uint256) {
return pool.positions[liquidityProvider];
}
/// @notice Get the current token states
/// @return totalReserves0
/// @return totalReserves1
function getReserves() external view returns (uint256, uint256) {
return (token0State.totalReserves, token1State.totalReserves);
}
/// @notice Get the current protocol fees
/// @return protocolFees0
/// @return protocolFees1
function getProtocolFees() external view returns (uint256, uint256) {
return (token0State.protocolFees, token1State.protocolFees);
}
/// @notice Get the current fees
/// @return feeBps
/// @return protocolFee
function getFees() external view returns (uint256, uint256) {
return (FEE_BPS, protocolFee);
}
/// @dev Returns the `amountOut` of token that will be received in exchange of `inAmount` in the direction
/// `zeroForOne`.
function estimateSwap(
uint256 inAmount,
bool zeroForOne
)
external
view
returns (uint256 outAmount, uint256 feeAmount, uint256 lpFee)
{
// Compute the liquidity providers fee
lpFee = inAmount * FEE_BPS / BPS;
// Deduce the swap fee from the protocol
feeAmount = (inAmount * protocolFee) / PROTOCOL_FEES;
inAmount -= feeAmount;
// Get our pour reservices
uint256 reserves0 = pool.reserves0;
uint256 reserves1 = pool.reserves1;
if (zeroForOne) {
outAmount = reserves1 - (reserves0 * reserves1) / (reserves0 + inAmount * (BPS - FEE_BPS) / BPS);
} else {
outAmount = reserves0 - (reserves0 * reserves1) / (reserves1 + inAmount * (BPS - FEE_BPS) / BPS);
}
}
}