-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathuseApprove.ts
198 lines (177 loc) · 6.16 KB
/
useApprove.ts
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
import { useCallback, useState } from 'react';
import { parseUnits, type Address, type EstimateContractGasParameters, type Hex, formatUnits } from 'viem';
import MAX_UINT256 from '@exactly/lib/esm/fixed-point-math/MAX_UINT256';
import WAD from '@exactly/lib/esm/fixed-point-math/WAD';
import { ERC20, Market } from 'types/contracts';
import { useWeb3 } from './useWeb3';
import { useOperationContext } from 'contexts/OperationContext';
import useAccountData from './useAccountData';
import handleOperationError from 'utils/handleOperationError';
import waitForTransaction from 'utils/waitForTransaction';
import { useTranslation } from 'react-i18next';
import useEstimateGas from './useEstimateGas';
import { gasLimit } from 'utils/gas';
import { track } from 'utils/mixpanel';
function useApprove({
operation,
contract,
spender,
}:
| { operation: 'deposit' | 'depositAtMaturity' | 'repay' | 'repayAtMaturity'; contract?: ERC20; spender?: Address }
| {
operation: 'withdraw' | 'withdrawAtMaturity' | 'borrow' | 'borrowAtMaturity';
contract?: Market;
spender?: Address;
}) {
const { t } = useTranslation();
const { walletAddress, opts } = useWeb3();
const { qty, symbol, setErrorData, setLoadingButton } = useOperationContext();
const [isLoading, setIsLoading] = useState(false);
const { marketAccount } = useAccountData(symbol);
const estimate = useEstimateGas();
const estimateGas = useCallback(async () => {
if (!contract || !spender || !walletAddress || !opts) return;
let params: EstimateContractGasParameters;
switch (operation) {
case 'deposit':
case 'depositAtMaturity':
case 'repay':
case 'repayAtMaturity': {
const { request } = await contract.simulate.approve([spender, MAX_UINT256], opts);
params = request;
break;
}
case 'withdraw':
case 'withdrawAtMaturity':
case 'borrow':
case 'borrowAtMaturity': {
const { request } = await contract.simulate.approve([spender, MAX_UINT256], opts);
params = request;
break;
}
}
if (!params) return;
return estimate(params);
}, [contract, spender, walletAddress, opts, operation, estimate]);
const needsApproval = useCallback(
async (amount: string): Promise<boolean> => {
try {
if (!walletAddress || !marketAccount || !contract || !spender) return true;
const quantity = parseUnits(amount, marketAccount.decimals);
switch (operation) {
case 'deposit':
case 'depositAtMaturity':
case 'repay':
case 'repayAtMaturity':
if (symbol === 'WETH') return false;
break;
case 'borrow':
case 'borrowAtMaturity':
case 'withdraw':
case 'withdrawAtMaturity': {
if (symbol !== 'WETH') return false;
const shares = await contract.read.previewWithdraw([quantity], opts);
const allowance = await contract.read.allowance([walletAddress, spender], opts);
return allowance < shares;
}
}
const allowance = await contract.read.allowance([walletAddress, spender], opts);
return allowance < quantity;
} catch {
return true;
}
},
[operation, walletAddress, marketAccount, contract, spender, symbol, opts],
);
const approve = useCallback(async () => {
if (!contract || !spender || !walletAddress || !marketAccount || !qty || !opts) return;
try {
let quantity = 0n;
switch (operation) {
case 'deposit':
case 'depositAtMaturity':
quantity = parseUnits(qty, marketAccount.decimals);
break;
case 'repay':
case 'repayAtMaturity':
case 'borrow':
case 'borrowAtMaturity':
quantity = (parseUnits(qty, marketAccount.decimals) * 101n) / 100n;
break;
case 'withdraw':
case 'withdrawAtMaturity':
quantity =
((await contract.read.previewWithdraw([parseUnits(qty, marketAccount.decimals)], opts)) * 101n) / 100n;
break;
}
setIsLoading(true);
setLoadingButton({ label: t('Sign the transaction on your wallet') });
const args = [spender, quantity] as const;
let hash: Hex;
switch (operation) {
case 'deposit':
case 'depositAtMaturity':
case 'repay':
case 'repayAtMaturity': {
const gas = await contract.estimateGas.approve(args, opts);
hash = await contract.write.approve(args, {
...opts,
gasLimit: gasLimit(gas),
});
break;
}
case 'withdraw':
case 'withdrawAtMaturity':
case 'borrow':
case 'borrowAtMaturity': {
const gas = await contract.estimateGas.approve(args, opts);
hash = await contract.write.approve(args, {
...opts,
gasLimit: gasLimit(gas),
});
break;
}
}
track('TX Signed', {
operation,
hash,
method: 'approve',
contractName: 'Market',
spender,
amount: formatUnits(quantity, marketAccount.decimals),
usdAmount: formatUnits((quantity * marketAccount.usdPrice) / WAD, marketAccount.decimals),
});
if (!hash) return;
setLoadingButton({ withCircularProgress: true, label: t('Approving {{symbol}}', { symbol }) });
const { status } = await waitForTransaction({ hash });
if (status === 'reverted') throw new Error('Transaction reverted');
track('TX Completed', {
symbol,
amount: formatUnits(quantity, marketAccount.decimals),
usdAmount: formatUnits((quantity * marketAccount.usdPrice) / WAD, marketAccount.decimals),
status,
hash,
operation,
});
} catch (error) {
setErrorData({ status: true, message: handleOperationError(error) });
} finally {
setIsLoading(false);
setLoadingButton({});
}
}, [
contract,
spender,
walletAddress,
marketAccount,
opts,
setLoadingButton,
t,
operation,
qty,
symbol,
setErrorData,
]);
return { approve, needsApproval, estimateGas, isLoading };
}
export default useApprove;