1import { useCallback, useEffect, useState } from 'react';
2import { Just } from 'folktale/maybe';
3import { toBN } from 'web3-utils';
5import { useNetwork } from 'store/network';
6import { useWallet } from 'store/wallet';
7import { usePointCursor } from 'store/pointCursor';
11 DEFAULT_GAS_PRICE_GWEI,
12 PROGRESS_ANIMATION_DELAY_MS,
16 sendSignedTransaction,
17 waitForTransactionConfirm,
20import * as need from 'lib/need';
21import { ensureFundsFor } from 'lib/tank';
22import useDeepEqualReference from 'lib/useDeepEqualReference';
23import useGasPrice from 'lib/useGasPrice';
24import timeout from 'lib/timeout';
25import { safeToWei } from 'lib/lib';
30 BROADCASTED: 'BROADCASTED',
31 CONFIRMED: 'CONFIRMED',
32 COMPLETED: 'COMPLETED',
36 * manage the state around sending and confirming an ethereum transaction
37 * @param {Transaction Function()} transactionBuilder
38 * @param {Promise<any> Function()} refetch async function called after completion
39 * @param {number} initialGasLimit gas limit
40 * @param {number} initialGasPrice gas price in gwei
42export default function useEthereumTransaction(
45 initialGasLimit = GAS_LIMITS.DEFAULT,
46 initialGasPrice = DEFAULT_GAS_PRICE_GWEI
48 const { wallet, walletType, walletHdPath } = useWallet();
49 const { web3, networkType } = useNetwork();
50 const { pointCursor } = usePointCursor();
52 const _web3 = need.web3(web3);
53 const _wallet = need.wallet(wallet);
55 const [error, _setError] = useState();
56 const setError = useCallback(
65 const [state, setState] = useState(STATE.NONE);
66 const [chainId, setChainId] = useState();
67 const [nonce, setNonce] = useState();
68 const { gasPrice, setGasPrice, resetGasPrice } = useGasPrice(initialGasPrice);
69 const [gasLimit] = useState(initialGasLimit);
70 const [unsignedTransactions, setUnsignedTransactions] = useState();
71 const [signedTransactions, setSignedTransactions] = useState();
72 const [txHashes, setTxHashes] = useState();
73 const [needFunds, setNeedFunds] = useState();
74 const [confirmationProgress, setConfirmationProgress] = useState(0.0);
76 const initializing = nonce === undefined || chainId === undefined;
77 const constructed = !!unsignedTransactions;
78 const isDefaultState = state === STATE.NONE;
79 const signed = state === STATE.SIGNED;
80 const broadcasted = state === STATE.BROADCASTED;
81 const confirmed = state === STATE.CONFIRMED;
82 const completed = state === STATE.COMPLETED;
84 // lock inputs once we're out of the default state
85 const inputsLocked = !isDefaultState;
88 const canSign = !initializing && constructed && isDefaultState;
90 const construct = useCallback(
92 setUnsignedTransactions(await transactionBuilder(...args)),
96 const unconstruct = useCallback(() => setUnsignedTransactions(undefined), [
97 setUnsignedTransactions,
100 const generateAndSign = useCallback(async () => {
104 const utxs = Array.isArray(unsignedTransactions)
105 ? unsignedTransactions
106 : [unsignedTransactions];
108 const txns = await Promise.all(
118 gasPrice: gasPrice.toFixed(0),
124 setSignedTransactions(txns);
125 setState(STATE.SIGNED);
137 unsignedTransactions,
142 const broadcast = useCallback(async () => {
144 setConfirmationProgress(0.0);
147 const rawTxs = signedTransactions.map(stx => hexify(stx.serialize()));
149 const costGwei = toBN(gasLimit)
151 .mul(toBN(rawTxs.length));
152 const cost = safeToWei(costGwei, 'gwei');
153 let usedTank = false;
154 // if this ethereum transaction is being executed by a specific point
155 // see if we can use the tank
156 if (Just.hasInstance(pointCursor)) {
157 usedTank = await ensureFundsFor(
164 (address, minBalance, balance) =>
165 setNeedFunds({ address, minBalance, balance }),
166 () => setNeedFunds(undefined)
170 const txHashes = await signedTransactions.reduce(
173 sendSignedTransaction(
176 /* doubtNonceError */ usedTank
177 ).then(hash => [...hashes, hash])
182 setTxHashes(txHashes);
183 setState(STATE.BROADCASTED);
185 await timeout(PROGRESS_ANIMATION_DELAY_MS);
187 setConfirmationProgress(0.2);
190 txHashes.map(txHash => waitForTransactionConfirm(_web3, txHash))
193 setConfirmationProgress(0.9);
195 setState(STATE.CONFIRMED);
210 const reset = useCallback(() => {
211 setTxHashes(undefined);
212 setSignedTransactions(undefined);
214 setChainId(undefined);
216 setState(STATE.NONE);
218 setNeedFunds(undefined);
219 setConfirmationProgress(0.0);
220 }, [resetGasPrice, setError]);
224 // if nonce or chainId is undefined, re-fetch on-chain info
225 if (!(nonce === undefined || chainId === undefined)) {
232 const [nonce, chainId] = await Promise.all([
233 _web3.eth.getTransactionCount(_wallet.address),
234 _web3.eth.net.getId(),
248 return () => (mounted = false);
249 }, [_wallet, _web3, setError, nonce, chainId, networkType, initialGasPrice]);
261 console.error(error);
262 // track a user-friendly error
265 'The transaction succeeded but we were unable to refresh chain state. Refresh to continue.'
275 setConfirmationProgress(1.0);
277 await timeout(PROGRESS_ANIMATION_DELAY_MS);
283 setState(STATE.COMPLETED);
287 return () => (mounted = false);
288 }, [confirmed, refetch, completed, setError]);
290 const values = useDeepEqualReference({
306 confirmationProgress,
316 unsignedTransactions,
319 return { ...values, bind: values };
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list