-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathremove-liquidity.tsx
180 lines (169 loc) · 5.33 KB
/
remove-liquidity.tsx
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
import {
useSwapCanisterBalances,
useSwapCanisterController,
useSwapCanisterLiquidityPosition,
useSwapCanisterLists,
} from '@/hooks';
import { selectPlugState, useAppSelector } from '@/store';
import {
Liquidity,
Pair,
toBigNumber,
toExponential,
} from '@psychedelic/sonic-js';
import { ChangeEvent, useEffect, useMemo, useState } from 'react';
/**
* Remove Liquidity Section React Component
* Example of a component that removes liquidity
*/
export const RemoveLiquiditySection = () => {
const { pairList, tokenList } = useSwapCanisterLists();
const { principal } = useAppSelector(selectPlugState);
const { updateLpList } = useSwapCanisterLiquidityPosition();
const { updateBalanceList } = useSwapCanisterBalances();
const controller = useSwapCanisterController();
// Create states remove liquidity
const [selectedToken, setSelectedToken] = useState<Pair.Metadata>();
const [amount, setAmount] = useState<string>('0');
const [isRemoveRunning, setIsRemoveRunning] = useState<boolean>(false);
const [[token0Amount, token1Amount], setTokenAmounts] = useState<
[string, string]
>(['', '']);
/**
* Create a flat list state from PairsList to help on data
* manipulation.
*/
const flatPairList = useMemo(() => {
if (!pairList) return [];
return Object.values(pairList).reduce((list, paired) => {
for (const pair of Object.values(paired)) {
const [token0] = pair.id.split(':');
if (token0 === pair.token0) {
list = [...list, pair];
}
}
return list;
}, [] as Pair.Metadata[]);
}, [pairList]);
/**
* Update token amounts state when LP amount changes
*/
useEffect(() => {
if (selectedToken && tokenList) {
// Get amounts by Liquidity calculation
const amounts = Liquidity.getTokenBalances({
decimals0: tokenList[selectedToken.token0].decimals,
decimals1: tokenList[selectedToken.token1].decimals,
lpBalance: toBigNumber(amount)
.removeDecimals(Liquidity.PAIR_DECIMALS)
.toString(),
reserve0: selectedToken.reserve0,
reserve1: selectedToken.reserve1,
totalSupply: selectedToken.totalSupply,
});
setTokenAmounts([
amounts.balance0.toString(),
amounts.balance1.toString(),
]);
} else {
setTokenAmounts(['', '']);
}
}, [amount, selectedToken, tokenList]);
// If there is no principal we can't remove liquidity
if (!principal) {
return (
<section>
<h1>Remove Liquidity</h1>
<span>Connect to plug to remove liquidity</span>
</section>
);
}
// Await fetching tokenList and pairList
if (!tokenList || !pairList) {
return (
<section>
<h1>Remove Liquidity</h1>
<span>Loading...</span>
</section>
);
}
// Create a handler for selecting token
const handleTokenSelect = (e: ChangeEvent<HTMLSelectElement>) => {
setSelectedToken(
flatPairList.find((pair) => pair.id === e.currentTarget.value)
);
};
// Create a handler for changing token amount
const handleAmountChange = (e: ChangeEvent<HTMLInputElement>) => {
setAmount(e.currentTarget.value);
};
/**
* Create a handler for remove LP using the controller and
* managing app states.
*/
const handleRemove = () => {
if (!controller || !selectedToken) return;
setIsRemoveRunning(true);
controller
.removeLiquidity({
token0: selectedToken.token0,
token1: selectedToken.token1,
amount: amount,
})
.then(() => Promise.resolve(updateLpList()))
.then(() => Promise.resolve(updateBalanceList()))
.catch((error) => alert(`Remove LP failed: ${error}`))
.finally(() => setIsRemoveRunning(false));
};
return (
<section>
<h1>Remove Liquidity</h1>
{isRemoveRunning ? (
<span>Loading...</span>
) : (
<>
<div>
Pair:
<select
name="from"
onChange={handleTokenSelect}
value={selectedToken?.id || ''}
>
<option value="" style={{ display: 'none' }}></option>
{flatPairList.map((pair) => {
return (
<option value={pair.id} key={pair.id}>
{tokenList[pair.token0].symbol}/
{tokenList[pair.token1].symbol}
</option>
);
})}
</select>
<input
type="number"
min={0}
step={toExponential(-Liquidity.PAIR_DECIMALS).toNumber()}
value={amount}
onChange={handleAmountChange}
/>
<button onClick={handleRemove}>Remove</button>
</div>
{selectedToken && (
<>
<span>
<b>{tokenList[selectedToken.token0].symbol} received: </b>
{token0Amount}
</span>
<span>
<b>{tokenList[selectedToken.token1].symbol} received: </b>
{token1Amount}
</span>
</>
)}
</>
)}
</section>
);
};