-
Notifications
You must be signed in to change notification settings - Fork 0
/
JalaPair.sol
273 lines (241 loc) · 12.5 KB
/
JalaPair.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
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./tokens/JalaERC20.sol";
import "./libraries/Math.sol";
import "./libraries/UQ112x112.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IJalaFactory.sol";
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
interface IJalaCallee {
function JalaCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external;
}
contract JalaPair is JalaERC20 {
error Locked();
error TransferFailed();
error Forbidden();
error Overflow();
error BadDesiredLiquidity();
error InsufficientLiquidityMinted();
error InsufficientLiquidityBurned();
error InsufficientLiquidity();
error InsufficientOutputAmount();
error InvalidTo();
error InsufficientInputAmount();
error InvalidK();
using UQ112x112 for uint224;
uint256 public constant MINIMUM_LIQUIDITY = 10 ** 3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint256 private unlocked = 1;
modifier lock() {
if (unlocked != 1) revert Locked();
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint256 value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
}
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
if (msg.sender != factory) revert Forbidden();
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1) private {
if (balance0 > type(uint112).max || balance1 > type(uint112).max) revert Overflow();
uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/2th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IJalaFactory(factory).feeTo(); // get feeTo address
feeOn = feeTo != address(0);
uint256 _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint256 rootK = Math.sqrt(uint256(_reserve0) * _reserve1);
uint256 rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply * (rootK - rootKLast);
uint256 denominator = rootK + rootKLast;
uint256 liquidity = numerator / denominator;
// distribute LP fee
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint256 liquidity) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0 - _reserve0;
uint256 amount1 = balance1 - _reserve1;
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
if (IJalaFactory(factory).migrators(msg.sender)) {
liquidity = IMigrator(msg.sender).desiredLiquidity();
if (liquidity == 0 || liquidity == type(uint).max) revert BadDesiredLiquidity();
} else {
liquidity = Math.sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
}
} else {
liquidity = Math.min((amount0 * _totalSupply) / _reserve0, (amount1 * _totalSupply) / _reserve1);
}
if (liquidity == 0) revert InsufficientLiquidityMinted();
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// // this low-level function should be called from a contract which performs important safety checks
// function mint(address to) external lock returns (uint liquidity) {
// (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
// uint balance0 = IERC20(token0).balanceOf(address(this));
// uint balance1 = IERC20(token1).balanceOf(address(this));
// uint amount0 = balance0 - _reserve0;
// uint amount1 = balance1 - _reserve1;
// bool feeOn = _mintFee(_reserve0, _reserve1);
// uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
// if (_totalSupply == 0) {
// liquidity = Math.sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
// _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
// } else {
// liquidity = Math.min((amount0 * _totalSupply) / _reserve0, (amount1 * _totalSupply) / _reserve1);
// }
// if (liquidity == 0) revert InsufficientLiquidityMinted();
// _mint(to, liquidity);
// _update(balance0, balance1, _reserve0, _reserve1);
// if (feeOn) kLast = uint(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
// emit Mint(msg.sender, amount0, amount1);
// }
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
uint256 liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = (liquidity * balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = (liquidity * balance1) / _totalSupply; // using balances ensures pro-rata distribution
if (amount0 == 0 || amount1 == 0) revert InsufficientLiquidityBurned();
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external lock {
if (amount0Out == 0 && amount1Out == 0) revert InsufficientOutputAmount();
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
if (amount0Out > _reserve0 || amount1Out > _reserve1) revert InsufficientLiquidity();
uint256 balance0;
uint256 balance1;
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
if (to == _token0 || to == _token1) revert InvalidTo();
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (IJalaFactory(factory).flashOn() && data.length > 0) {
if (amount0Out > 0) {
_safeTransfer(
_token0,
IJalaFactory(factory).feeTo(),
(amount0Out * IJalaFactory(factory).flashFee()) / 10000
);
amount0Out = (amount0Out * (10000 + IJalaFactory(factory).flashFee())) / 10000;
}
if (amount1Out > 0) {
_safeTransfer(
_token1,
IJalaFactory(factory).feeTo(),
(amount1Out * IJalaFactory(factory).flashFee()) / 10000
);
amount1Out = (amount1Out * (10000 + IJalaFactory(factory).flashFee())) / 10000;
}
IJalaCallee(to).JalaCall(msg.sender, amount0Out, amount1Out, data);
}
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
if (amount0In == 0 && amount1In == 0) revert InsufficientInputAmount();
{
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint256 balance0Adjusted = (balance0 * 1000) - (amount0In * 3);
uint256 balance1Adjusted = (balance1 * 1000) - (amount1In * 3);
if (balance0Adjusted * balance1Adjusted < uint256(_reserve0) * uint256(_reserve1) * (1000 ** 2))
revert InvalidK();
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)) - reserve0);
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)) - reserve1);
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}