-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathuseConfirmTransaction.ts
More file actions
289 lines (244 loc) · 8.16 KB
/
Copy pathuseConfirmTransaction.ts
File metadata and controls
289 lines (244 loc) · 8.16 KB
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
import { useContext, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import config from 'config';
import { RouteContext } from 'contexts/RouteContext';
import useWalletProvider from 'hooks/useWalletProvider';
import { useUSDamountGetter } from 'hooks/useUSDamountGetter';
import { useGetTokens } from 'hooks/useGetTokens';
import {
setTxDetails,
setSendTx,
setRoute as setRedeemRoute,
setTimestamp,
} from 'store/redeem';
import { setRoute as setAppRoute } from 'store/router';
import { setAmount, setIsTransactionInProgress } from 'store/transferInput';
import { getTransferDetails } from 'telemetry';
import { ERR_USER_REJECTED } from 'telemetry/types';
import { toDecimals } from 'utils/balance';
import { interpretTransferError } from 'utils/errors';
import { addTxToLocalStorage } from 'utils/inProgressTxCache';
import { validate, isTransferValid } from 'utils/transferValidation';
import { SDKv2Signer } from 'routes/sdkv2/signer';
import { TransferWallet } from 'utils/wallet';
import type { RootState } from 'store';
import type { RelayerFee } from 'store/relay';
import type { QuoteResult } from 'routes/operator';
import { clearCache as clearBalanceCache } from 'utils/balanceCache';
type Props = {
quotes: Record<string, QuoteResult | undefined>;
};
type ReturnProps = {
error: string | undefined;
// errorInternal can be a result of custom validation, hence of unknown type.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
errorInternal: any | undefined;
onConfirm: () => void;
};
const useConfirmTransaction = (props: Props): ReturnProps => {
const dispatch = useDispatch();
const [error, setError] = useState<string | undefined>(undefined);
// errorInternal can be a result of custom validation, hence of unknown type.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [errorInternal, setErrorInternal] = useState<any | undefined>(
undefined,
);
const routeContext = useContext(RouteContext);
const { walletProvider } = useWalletProvider();
const transferInput = useSelector((state: RootState) => state.transferInput);
const {
amount,
fromChain: sourceChain,
toChain: destChain,
route,
validations,
} = transferInput;
const { sourceToken, destToken } = useGetTokens();
const wallet = useSelector((state: RootState) => state.wallet);
const { sending: sendingWallet, receiving: receivingWallet } = wallet;
const relay = useSelector((state: RootState) => state.relay);
const { toNativeToken } = relay;
const quoteResult = props.quotes[route ?? ''];
const quote = quoteResult?.success ? quoteResult : undefined;
const receiveNativeAmount = quote?.destinationNativeGas;
const getUSDAmount = useUSDamountGetter();
const onConfirm = async () => {
// Clear previous errors
if (error) {
setError(undefined);
}
if (config.ui.previewMode) {
setError('Connect is in preview mode');
return;
}
// Pre-check of required values
if (
!sourceChain ||
!sourceToken ||
!destChain ||
!destToken ||
!amount ||
!route ||
!quote
) {
return;
}
// Validate all inputs
// The results of this check will be written back to Redux store (see transferInput.validations).
await validate({ transferInput, relay, wallet }, dispatch, () => false);
const valid = isTransferValid(validations);
if (!valid || !route) {
return;
}
const transferDetails = getTransferDetails(
route,
sourceToken,
destToken,
sourceChain,
destChain,
amount,
getUSDAmount,
);
// Handle custom transfer validation (if provided by integrator)
if (config.validateTransfer) {
try {
const { isValid, error } = await config.validateTransfer({
...transferDetails,
fromWalletAddress: sendingWallet.address,
toWalletAddress: receivingWallet.address,
});
if (!isValid) {
setError(error ?? 'Transfer validation failed');
return;
}
} catch (e: unknown) {
setError('Error validating transfer');
setErrorInternal(e);
console.error(e);
return;
}
}
dispatch(setIsTransactionInProgress(true));
try {
config.triggerEvent({
type: 'transfer.initiate',
details: transferDetails,
});
let signer;
if (config.ui.testOptions?.enableHeadlessSigner) {
signer = await SDKv2Signer.fromPrivateKey(sourceChain);
} else {
signer = await SDKv2Signer.fromChain(
sourceChain,
sendingWallet.address,
TransferWallet.SENDING,
walletProvider,
);
}
const [sdkRoute, receipt] = await config.routes.execute(
route,
sourceToken,
amount,
sourceChain,
signer,
destChain,
receivingWallet.address,
destToken,
{ nativeGas: toNativeToken },
);
// Clear cached balances on sending chain
clearBalanceCache(sendingWallet, sourceChain);
const txId =
'originTxs' in receipt
? receipt.originTxs[receipt.originTxs.length - 1].txid
: undefined;
config.triggerEvent({
type: 'transfer.start',
details: { ...transferDetails, txId },
});
if (!txId) throw new Error("Can't find txid in receipt");
let relayerFee: RelayerFee | undefined = undefined;
if (quote.relayFee) {
const { token, amount } = quote.relayFee;
const feeToken = config.tokens.get(token);
const formattedFee = Number.parseFloat(
toDecimals(amount.amount, amount.decimals, 6),
);
relayerFee = {
fee: formattedFee,
token: feeToken?.tuple,
};
}
const txTimestamp = Date.now();
const txDetails = {
sendTx: txId,
sender: sendingWallet.address,
amount,
recipient: receivingWallet.address,
toChain: receipt.to,
fromChain: receipt.from,
receivedToken: destToken.tuple,
token: sourceToken.tuple,
tokenAddress: sourceToken.tuple[1],
tokenKey: sourceToken.key,
tokenDecimals: sourceToken.decimals,
relayerFee,
receiveAmount: quote.destinationToken.amount,
receiveNativeAmount,
eta: quote.eta || 0,
};
// Add the new transaction to local storage
addTxToLocalStorage({
txDetails,
txHash: txId,
timestamp: txTimestamp,
receipt,
route,
});
// Set the start time of the transaction
dispatch(setTimestamp(txTimestamp));
// TODO: SDKV2 set the tx details using on-chain data
// because they might be different than what we have in memory (relayer fee)
// or we may not have all the data (e.g. block)
// TODO: we don't need all of these details
// The SDK should provide a way to get the details from the chain (e.g. route.lookupSourceTxDetails)
dispatch(setTxDetails(txDetails));
// Reset the amount for a successful transaction
dispatch(setAmount(''));
routeContext.setRoute(sdkRoute);
routeContext.setReceipt(receipt);
dispatch(setSendTx(txId));
dispatch(setRedeemRoute(route));
dispatch(setAppRoute('redeem'));
setError(undefined);
} catch (e: unknown) {
const [uiError, transferError] = interpretTransferError(
e,
transferDetails,
);
if (transferError.type === ERR_USER_REJECTED) {
// User intentionally rejected in their wallet. This is not an error in the sense
// that something went wrong.
} else {
console.error('Wormhole Connect: error completing transfer', e);
// Show error in UI
setError(uiError);
setErrorInternal(e);
// Trigger transfer error event to integrator
config.triggerEvent({
type: 'transfer.error',
error: transferError,
details: transferDetails,
});
}
} finally {
dispatch(setIsTransactionInProgress(false));
}
};
return {
onConfirm,
error,
errorInternal,
};
};
export default useConfirmTransaction;