-
Notifications
You must be signed in to change notification settings - Fork 33
/
TSwapPool.sol
468 lines (429 loc) · 17.7 KB
/
TSwapPool.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
/**
* /-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\
* | |
* \ _____ ____ /
* -|_ _| / ___|_ ____ _ _ __ -
* / | |____\___ \ \ /\ / / _` | '_ \ \
* | | |_____|__) \ V V / (_| | |_) | |
* \ |_| |____/ \_/\_/ \__,_| .__/ /
* - |_| -
* / \
* | |
* \-/|\-/|\-/|\-/|\-/|\-/|\-/|\-/|\-/|\-/
*/
// SPDX-License-Identifier: GNU General Public License v3.0
pragma solidity 0.8.20;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract TSwapPool is ERC20 {
error TSwapPool__DeadlineHasPassed(uint64 deadline);
error TSwapPool__MaxPoolTokenDepositTooHigh(
uint256 maximumPoolTokensToDeposit,
uint256 poolTokensToDeposit
);
error TSwapPool__MinLiquidityTokensToMintTooLow(
uint256 minimumLiquidityTokensToMint,
uint256 liquidityTokensToMint
);
error TSwapPool__WethDepositAmountTooLow(
uint256 minimumWethDeposit,
uint256 wethToDeposit
);
error TSwapPool__InvalidToken();
error TSwapPool__OutputTooLow(uint256 actual, uint256 min);
error TSwapPool__MustBeMoreThanZero();
using SafeERC20 for IERC20;
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
IERC20 private immutable i_wethToken;
IERC20 private immutable i_poolToken;
uint256 private constant MINIMUM_WETH_LIQUIDITY = 1_000_000_000;
uint256 private swap_count = 0;
uint256 private constant SWAP_COUNT_MAX = 10;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event LiquidityAdded(
address indexed liquidityProvider,
uint256 wethDeposited,
uint256 poolTokensDeposited
);
event LiquidityRemoved(
address indexed liquidityProvider,
uint256 wethWithdrawn,
uint256 poolTokensWithdrawn
);
event Swap(
address indexed swapper,
IERC20 tokenIn,
uint256 amountTokenIn,
IERC20 tokenOut,
uint256 amountTokenOut
);
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
modifier revertIfDeadlinePassed(uint64 deadline) {
if (deadline < uint64(block.timestamp)) {
revert TSwapPool__DeadlineHasPassed(deadline);
}
_;
}
modifier revertIfZero(uint256 amount) {
if (amount == 0) {
revert TSwapPool__MustBeMoreThanZero();
}
_;
}
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
constructor(
address poolToken,
address wethToken,
string memory liquidityTokenName,
string memory liquidityTokenSymbol
) ERC20(liquidityTokenName, liquidityTokenSymbol) {
i_wethToken = IERC20(wethToken);
i_poolToken = IERC20(poolToken);
}
/*//////////////////////////////////////////////////////////////
ADD AND REMOVE LIQUIDITY
//////////////////////////////////////////////////////////////*/
/// @notice Adds liquidity to the pool
/// @dev The invariant of this function is that the ratio of WETH, PoolTokens, and LiquidityTokens is the same
/// before and after the transaction
/// @param wethToDeposit Amount of WETH the user is going to deposit
/// @param minimumLiquidityTokensToMint We derive the amount of liquidity tokens to mint from the amount of WETH the
/// user is going to deposit, but set a minimum so they know approx what they will accept
/// @param maximumPoolTokensToDeposit The maximum amount of pool tokens the user is willing to deposit, again it's
/// derived from the amount of WETH the user is going to deposit
/// @param deadline The deadline for the transaction to be completed by
function deposit(
uint256 wethToDeposit,
uint256 minimumLiquidityTokensToMint,
uint256 maximumPoolTokensToDeposit,
uint64 deadline
)
external
revertIfZero(wethToDeposit)
returns (uint256 liquidityTokensToMint)
{
if (wethToDeposit < MINIMUM_WETH_LIQUIDITY) {
revert TSwapPool__WethDepositAmountTooLow(
MINIMUM_WETH_LIQUIDITY,
wethToDeposit
);
}
if (totalLiquidityTokenSupply() > 0) {
uint256 wethReserves = i_wethToken.balanceOf(address(this));
uint256 poolTokenReserves = i_poolToken.balanceOf(address(this));
// Our invariant says weth, poolTokens, and liquidity tokens must always have the same ratio after the
// initial deposit
// poolTokens / constant(k) = weth
// weth / constant(k) = liquidityTokens
// aka...
// weth / poolTokens = constant(k)
// To make sure this holds, we can make sure the new balance will match the old balance
// (wethReserves + wethToDeposit) / (poolTokenReserves + poolTokensToDeposit) = constant(k)
// (wethReserves + wethToDeposit) / (poolTokenReserves + poolTokensToDeposit) =
// (wethReserves / poolTokenReserves)
//
// So we can do some elementary math now to figure out poolTokensToDeposit...
// (wethReserves + wethToDeposit) = (poolTokenReserves + poolTokensToDeposit) * (wethReserves / poolTokenReserves)
// wethReserves + wethToDeposit = poolTokenReserves * (wethReserves / poolTokenReserves) + poolTokensToDeposit * (wethReserves / poolTokenReserves)
// wethReserves + wethToDeposit = wethReserves + poolTokensToDeposit * (wethReserves / poolTokenReserves)
// wethToDeposit / (wethReserves / poolTokenReserves) = poolTokensToDeposit
// (wethToDeposit * poolTokenReserves) / wethReserves = poolTokensToDeposit
uint256 poolTokensToDeposit = getPoolTokensToDepositBasedOnWeth(
wethToDeposit
);
if (maximumPoolTokensToDeposit < poolTokensToDeposit) {
revert TSwapPool__MaxPoolTokenDepositTooHigh(
maximumPoolTokensToDeposit,
poolTokensToDeposit
);
}
// We do the same thing for liquidity tokens. Similar math.
liquidityTokensToMint =
(wethToDeposit * totalLiquidityTokenSupply()) /
wethReserves;
if (liquidityTokensToMint < minimumLiquidityTokensToMint) {
revert TSwapPool__MinLiquidityTokensToMintTooLow(
minimumLiquidityTokensToMint,
liquidityTokensToMint
);
}
_addLiquidityMintAndTransfer(
wethToDeposit,
poolTokensToDeposit,
liquidityTokensToMint
);
} else {
// This will be the "initial" funding of the protocol. We are starting from blank here!
// We just have them send the tokens in, and we mint liquidity tokens based on the weth
_addLiquidityMintAndTransfer(
wethToDeposit,
maximumPoolTokensToDeposit,
wethToDeposit
);
liquidityTokensToMint = wethToDeposit;
}
}
/// @dev This is a sensitive function, and should only be called by addLiquidity
/// @param wethToDeposit The amount of WETH the user is going to deposit
/// @param poolTokensToDeposit The amount of pool tokens the user is going to deposit
/// @param liquidityTokensToMint The amount of liquidity tokens the user is going to mint
function _addLiquidityMintAndTransfer(
uint256 wethToDeposit,
uint256 poolTokensToDeposit,
uint256 liquidityTokensToMint
) private {
_mint(msg.sender, liquidityTokensToMint);
emit LiquidityAdded(msg.sender, poolTokensToDeposit, wethToDeposit);
// Interactions
i_wethToken.safeTransferFrom(msg.sender, address(this), wethToDeposit);
i_poolToken.safeTransferFrom(
msg.sender,
address(this),
poolTokensToDeposit
);
}
/// @notice Removes liquidity from the pool
/// @param liquidityTokensToBurn The number of liquidity tokens the user wants to burn
/// @param minWethToWithdraw The minimum amount of WETH the user wants to withdraw
/// @param minPoolTokensToWithdraw The minimum amount of pool tokens the user wants to withdraw
/// @param deadline The deadline for the transaction to be completed by
function withdraw(
uint256 liquidityTokensToBurn,
uint256 minWethToWithdraw,
uint256 minPoolTokensToWithdraw,
uint64 deadline
)
external
revertIfDeadlinePassed(deadline)
revertIfZero(liquidityTokensToBurn)
revertIfZero(minWethToWithdraw)
revertIfZero(minPoolTokensToWithdraw)
{
// We do the same math as above
uint256 wethToWithdraw = (liquidityTokensToBurn *
i_wethToken.balanceOf(address(this))) / totalLiquidityTokenSupply();
uint256 poolTokensToWithdraw = (liquidityTokensToBurn *
i_poolToken.balanceOf(address(this))) / totalLiquidityTokenSupply();
if (wethToWithdraw < minWethToWithdraw) {
revert TSwapPool__OutputTooLow(wethToWithdraw, minWethToWithdraw);
}
if (poolTokensToWithdraw < minPoolTokensToWithdraw) {
revert TSwapPool__OutputTooLow(
poolTokensToWithdraw,
minPoolTokensToWithdraw
);
}
_burn(msg.sender, liquidityTokensToBurn);
emit LiquidityRemoved(msg.sender, wethToWithdraw, poolTokensToWithdraw);
i_wethToken.safeTransfer(msg.sender, wethToWithdraw);
i_poolToken.safeTransfer(msg.sender, poolTokensToWithdraw);
}
/*//////////////////////////////////////////////////////////////
GET PRICING
//////////////////////////////////////////////////////////////*/
function getOutputAmountBasedOnInput(
uint256 inputAmount,
uint256 inputReserves,
uint256 outputReserves
)
public
pure
revertIfZero(inputAmount)
revertIfZero(outputReserves)
returns (uint256 outputAmount)
{
// x * y = k
// numberOfWeth * numberOfPoolTokens = constant k
// k must not change during a transaction (invariant)
// with this math, we want to figure out how many PoolTokens to deposit
// since weth * poolTokens = k, we can rearrange to get:
// (currentWeth + wethToDeposit) * (currentPoolTokens + poolTokensToDeposit) = k
// **************************
// ****** MATH TIME!!! ******
// **************************
// FOIL it (or ChatGPT): https://en.wikipedia.org/wiki/FOIL_method
// (totalWethOfPool * totalPoolTokensOfPool) + (totalWethOfPool * poolTokensToDeposit) + (wethToDeposit *
// totalPoolTokensOfPool) + (wethToDeposit * poolTokensToDeposit) = k
// (totalWethOfPool * totalPoolTokensOfPool) + (wethToDeposit * totalPoolTokensOfPool) = k - (totalWethOfPool *
// poolTokensToDeposit) - (wethToDeposit * poolTokensToDeposit)
uint256 inputAmountMinusFee = inputAmount * 997;
uint256 numerator = inputAmountMinusFee * outputReserves;
uint256 denominator = (inputReserves * 1000) + inputAmountMinusFee;
return numerator / denominator;
}
function getInputAmountBasedOnOutput(
uint256 outputAmount,
uint256 inputReserves,
uint256 outputReserves
)
public
pure
revertIfZero(outputAmount)
revertIfZero(outputReserves)
returns (uint256 inputAmount)
{
return
((inputReserves * outputAmount) * 10000) /
((outputReserves - outputAmount) * 997);
}
function swapExactInput(
IERC20 inputToken,
uint256 inputAmount,
IERC20 outputToken,
uint256 minOutputAmount,
uint64 deadline
)
public
revertIfZero(inputAmount)
revertIfDeadlinePassed(deadline)
returns (uint256 output)
{
uint256 inputReserves = inputToken.balanceOf(address(this));
uint256 outputReserves = outputToken.balanceOf(address(this));
uint256 outputAmount = getOutputAmountBasedOnInput(
inputAmount,
inputReserves,
outputReserves
);
if (outputAmount < minOutputAmount) {
revert TSwapPool__OutputTooLow(outputAmount, minOutputAmount);
}
_swap(inputToken, inputAmount, outputToken, outputAmount);
}
/*
* @notice figures out how much you need to input based on how much
* output you want to receive.
*
* Example: You say "I want 10 output WETH, and my input is DAI"
* The function will figure out how much DAI you need to input to get 10 WETH
* And then execute the swap
* @param inputToken ERC20 token to pull from caller
* @param outputToken ERC20 token to send to caller
* @param outputAmount The exact amount of tokens to send to caller
*/
function swapExactOutput(
IERC20 inputToken,
IERC20 outputToken,
uint256 outputAmount,
uint64 deadline
)
public
revertIfZero(outputAmount)
revertIfDeadlinePassed(deadline)
returns (uint256 inputAmount)
{
uint256 inputReserves = inputToken.balanceOf(address(this));
uint256 outputReserves = outputToken.balanceOf(address(this));
inputAmount = getInputAmountBasedOnOutput(
outputAmount,
inputReserves,
outputReserves
);
_swap(inputToken, inputAmount, outputToken, outputAmount);
}
/**
* @notice wrapper function to facilitate users selling pool tokens in exchange of WETH
* @param poolTokenAmount amount of pool tokens to sell
* @return wethAmount amount of WETH received by caller
*/
function sellPoolTokens(
uint256 poolTokenAmount
) external returns (uint256 wethAmount) {
return
swapExactOutput(
i_poolToken,
i_wethToken,
poolTokenAmount,
uint64(block.timestamp)
);
}
/**
* @notice Swaps a given amount of input for a given amount of output tokens.
* @dev Every 10 swaps, we give the caller an extra token as an extra incentive to keep trading on T-Swap.
* @param inputToken ERC20 token to pull from caller
* @param inputAmount Amount of tokens to pull from caller
* @param outputToken ERC20 token to send to caller
* @param outputAmount Amount of tokens to send to caller
*/
function _swap(
IERC20 inputToken,
uint256 inputAmount,
IERC20 outputToken,
uint256 outputAmount
) private {
if (
_isUnknown(inputToken) ||
_isUnknown(outputToken) ||
inputToken == outputToken
) {
revert TSwapPool__InvalidToken();
}
swap_count++;
if (swap_count >= SWAP_COUNT_MAX) {
swap_count = 0;
outputToken.safeTransfer(msg.sender, 1_000_000_000_000_000_000);
}
emit Swap(
msg.sender,
inputToken,
inputAmount,
outputToken,
outputAmount
);
inputToken.safeTransferFrom(msg.sender, address(this), inputAmount);
outputToken.safeTransfer(msg.sender, outputAmount);
}
function _isUnknown(IERC20 token) private view returns (bool) {
if (token != i_wethToken && token != i_poolToken) {
return true;
}
return false;
}
/*//////////////////////////////////////////////////////////////
EXTERNAL AND PUBLIC VIEW AND PURE
//////////////////////////////////////////////////////////////*/
function getPoolTokensToDepositBasedOnWeth(
uint256 wethToDeposit
) public view returns (uint256) {
uint256 poolTokenReserves = i_poolToken.balanceOf(address(this));
uint256 wethReserves = i_wethToken.balanceOf(address(this));
return (wethToDeposit * poolTokenReserves) / wethReserves;
}
/// @notice a more verbose way of getting the total supply of liquidity tokens
function totalLiquidityTokenSupply() public view returns (uint256) {
return totalSupply();
}
function getPoolToken() external view returns (address) {
return address(i_poolToken);
}
function getWeth() external view returns (address) {
return address(i_wethToken);
}
function getMinimumWethDepositAmount() external pure returns (uint256) {
return MINIMUM_WETH_LIQUIDITY;
}
function getPriceOfOneWethInPoolTokens() external view returns (uint256) {
return
getOutputAmountBasedOnInput(
1e18,
i_wethToken.balanceOf(address(this)),
i_poolToken.balanceOf(address(this))
);
}
function getPriceOfOnePoolTokenInWeth() external view returns (uint256) {
return
getOutputAmountBasedOnInput(
1e18,
i_poolToken.balanceOf(address(this)),
i_wethToken.balanceOf(address(this))
);
}
}