-
Notifications
You must be signed in to change notification settings - Fork 86
/
Factory.sol
103 lines (83 loc) · 2.63 KB
/
Factory.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
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.24;
import "./interfaces/IFactory.sol";
import "./Pool.sol";
contract Factory is IFactory {
mapping(address => mapping(address => address[])) public pools;
Parameters public override parameters;
function sortToken(
address tokenA,
address tokenB
) private pure returns (address, address) {
return tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
}
function getPool(
address tokenA,
address tokenB,
uint32 index
) external view override returns (address) {
require(tokenA != tokenB, "IDENTICAL_ADDRESSES");
require(tokenA != address(0) && tokenB != address(0), "ZERO_ADDRESS");
// Declare token0 and token1
address token0;
address token1;
(token0, token1) = sortToken(tokenA, tokenB);
return pools[token0][token1][index];
}
function createPool(
address tokenA,
address tokenB,
int24 tickLower,
int24 tickUpper,
uint24 fee
) external override returns (address pool) {
// validate token's individuality
require(tokenA != tokenB, "IDENTICAL_ADDRESSES");
// Declare token0 and token1
address token0;
address token1;
// sort token, avoid the mistake of the order
(token0, token1) = sortToken(tokenA, tokenB);
// get current all pools
address[] memory existingPools = pools[token0][token1];
// check if the pool already exists
for (uint256 i = 0; i < existingPools.length; i++) {
IPool currentPool = IPool(existingPools[i]);
if (
currentPool.tickLower() == tickLower &&
currentPool.tickUpper() == tickUpper &&
currentPool.fee() == fee
) {
return existingPools[i];
}
}
// save pool info
parameters = Parameters(
address(this),
token0,
token1,
tickLower,
tickUpper,
fee
);
// generate create2 salt
bytes32 salt = keccak256(
abi.encode(token0, token1, tickLower, tickUpper, fee)
);
// create pool
pool = address(new Pool{salt: salt}());
// save created pool
pools[token0][token1].push(pool);
// delete pool info
delete parameters;
emit PoolCreated(
token0,
token1,
uint32(existingPools.length),
tickLower,
tickUpper,
fee,
pool
);
}
}