1import { useCallback, useEffect, useState } from 'react';
2import { Just } from 'folktale/maybe';
3import { toWei, 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';
29 BROADCASTED: 'BROADCASTED',
30 CONFIRMED: 'CONFIRMED',
31 COMPLETED: 'COMPLETED',
35 * manage the state around sending and confirming an ethereum transaction
36 * @param {Transaction Function()} transactionBuilder
37 * @param {Promise<any> Function()} refetch async function called after completion
38 * @param {number} initialGasLimit gas limit
39 * @param {number} initialGasPrice gas price in gwei
41export default function useEthereumTransaction(
44 initialGasLimit = GAS_LIMITS.DEFAULT,
45 initialGasPrice = DEFAULT_GAS_PRICE_GWEI
47 const { wallet, walletType, walletHdPath } = useWallet();
48 const { web3, networkType } = useNetwork();
49 const { pointCursor } = usePointCursor();
51 const _web3 = need.web3(web3);
52 const _wallet = need.wallet(wallet);
54 const [error, _setError] = useState();
55 const setError = useCallback(
64 const [state, setState] = useState(STATE.NONE);
65 const [chainId, setChainId] = useState();
66 const [nonce, setNonce] = useState();
67 const { gasPrice, setGasPrice, resetGasPrice } = useGasPrice(initialGasPrice);
68 const [gasLimit] = useState(initialGasLimit);
69 const [unsignedTransactions, setUnsignedTransactions] = useState();
70 const [signedTransactions, setSignedTransactions] = useState();
71 const [txHashes, setTxHashes] = useState();
72 const [needFunds, setNeedFunds] = useState();
73 const [confirmationProgress, setConfirmationProgress] = useState(0.0);
75 const initializing = nonce === undefined || chainId === undefined;
76 const constructed = !!unsignedTransactions;
77 const isDefaultState = state === STATE.NONE;
78 const signed = state === STATE.SIGNED;
79 const broadcasted = state === STATE.BROADCASTED;
80 const confirmed = state === STATE.CONFIRMED;
81 const completed = state === STATE.COMPLETED;
83 // lock inputs once we're out of the default state
84 const inputsLocked = !isDefaultState;
87 const canSign = !initializing && constructed && isDefaultState;
89 const construct = useCallback(
91 setUnsignedTransactions(await transactionBuilder(...args)),
95 const unconstruct = useCallback(() => setUnsignedTransactions(undefined), [
96 setUnsignedTransactions,
99 const generateAndSign = useCallback(async () => {
103 const utxs = Array.isArray(unsignedTransactions)
104 ? unsignedTransactions
105 : [unsignedTransactions];
107 const txns = await Promise.all(
117 gasPrice: gasPrice.toFixed(0),
123 setSignedTransactions(txns);
124 setState(STATE.SIGNED);
136 unsignedTransactions,
141 const broadcast = useCallback(async () => {
143 setConfirmationProgress(0.0);
146 const rawTxs = signedTransactions.map(stx => hexify(stx.serialize()));
148 const costGwei = toBN(gasLimit)
150 .mul(toBN(rawTxs.length));
151 const cost = toWei(costGwei.toString(), 'gwei');
152 let usedTank = false;
153 // if this ethereum transaction is being executed by a specific point
154 // see if we can use the tank
155 if (Just.hasInstance(pointCursor)) {
156 usedTank = await ensureFundsFor(
162 (address, minBalance, balance) =>
163 setNeedFunds({ address, minBalance, balance }),
164 () => setNeedFunds(undefined)
168 const txHashes = await signedTransactions.reduce(
171 sendSignedTransaction(
174 /* doubtNonceError */ usedTank
175 ).then(hash => [...hashes, hash])
180 setTxHashes(txHashes);
181 setState(STATE.BROADCASTED);
183 await timeout(PROGRESS_ANIMATION_DELAY_MS);
185 setConfirmationProgress(0.2);
188 txHashes.map(txHash => waitForTransactionConfirm(_web3, txHash))
191 setConfirmationProgress(0.9);
193 setState(STATE.CONFIRMED);
207 const reset = useCallback(() => {
208 setTxHashes(undefined);
209 setSignedTransactions(undefined);
211 setChainId(undefined);
213 setState(STATE.NONE);
215 setNeedFunds(undefined);
216 setConfirmationProgress(0.0);
217 }, [resetGasPrice, setError]);
221 // if nonce or chainId is undefined, re-fetch on-chain info
222 if (!(nonce === undefined || chainId === undefined)) {
229 const [nonce, chainId] = await Promise.all([
230 _web3.eth.getTransactionCount(_wallet.address),
231 _web3.eth.net.getId(),
245 return () => (mounted = false);
246 }, [_wallet, _web3, setError, nonce, chainId, networkType, initialGasPrice]);
258 console.error(error);
259 // track a user-friendly error
262 'The transaction succeeded but we were unable to refresh chain state. Refresh to continue.'
272 setConfirmationProgress(1.0);
274 await timeout(PROGRESS_ANIMATION_DELAY_MS);
280 setState(STATE.COMPLETED);
284 return () => (mounted = false);
285 }, [confirmed, refetch, completed, setError]);
287 const values = useDeepEqualReference({
303 confirmationProgress,
314 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