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,
17 sendSignedTransaction,
18 waitForTransactionConfirm,
21import * as need from 'lib/need';
22import { ensureFundsFor } from 'lib/tank';
23import useDeepEqualReference from 'lib/useDeepEqualReference';
24import useGasPrice from 'lib/useGasPrice';
25import { timeout } from 'lib/timeout';
26import { safeToWei, safeFromWei } from 'lib/lib';
27import { useWalletConnect } from './useWalletConnect';
32 BROADCASTED: 'BROADCASTED',
33 CONFIRMED: 'CONFIRMED',
34 COMPLETED: 'COMPLETED',
38 * manage the state around sending and confirming an ethereum transaction
39 * @param {Transaction Function()} transactionBuilder
40 * @param {Promise<any> Function()} refetch async function called after completion
41 * @param {number} initialGasLimit gas limit
42 * @param {number} initialGasPrice gas price in gwei
44export default function useEthereumTransaction(
47 initialGasLimit = GAS_LIMITS.DEFAULT,
48 initialGasPrice = DEFAULT_GAS_PRICE_GWEI
50 const { wallet, walletType, walletHdPath } = useWallet();
51 const { web3, networkType } = useNetwork();
52 const { pointCursor } = usePointCursor();
53 const { signTransaction: wcSign } = useWalletConnect();
55 const _web3 = need.web3(web3);
56 const _wallet = need.wallet(wallet);
58 const [error, _setError] = useState();
59 const setError = useCallback(
68 const [state, setState] = useState(STATE.NONE);
69 const [chainId, setChainId] = useState();
70 const [nonce, setNonce] = useState();
71 const { gasPrice, setGasPrice, resetGasPrice } = useGasPrice(initialGasPrice);
72 const [gasLimit] = useState(initialGasLimit);
73 const [unsignedTransactions, setUnsignedTransactions] = useState();
74 const [signedTransactions, setSignedTransactions] = useState();
75 const [txHashes, setTxHashes] = useState();
76 const [needFunds, setNeedFunds] = useState();
77 const [confirmationProgress, setConfirmationProgress] = useState(0.0);
79 const [finalCost, setFinalCost] = useState();
81 const initializing = nonce === undefined || chainId === undefined;
82 const constructed = !!unsignedTransactions;
83 const isDefaultState = state === STATE.NONE;
84 const signed = state === STATE.SIGNED;
85 const broadcasted = state === STATE.BROADCASTED;
86 const confirmed = state === STATE.CONFIRMED;
87 const completed = state === STATE.COMPLETED;
89 // lock inputs once we're out of the default state
90 const inputsLocked = !isDefaultState;
93 const canSign = !initializing && constructed && isDefaultState;
95 const construct = useCallback(
97 setUnsignedTransactions(await transactionBuilder(...args)),
101 const unconstruct = useCallback(() => setUnsignedTransactions(undefined), [
102 setUnsignedTransactions,
105 const generateAndSign = useCallback(async () => {
109 const utxs = Array.isArray(unsignedTransactions)
110 ? unsignedTransactions
111 : [unsignedTransactions];
113 // Due to React's Rules of Hooks, optionally inject the
114 // WC transaction signing function
115 // https://reactjs.org/docs/hooks-rules.html
117 walletType === WALLET_TYPES.WALLET_CONNECT ? wcSign : undefined;
119 const txns = await Promise.all(
129 gasPrice: gasPrice.toFixed(0),
136 setSignedTransactions(txns);
137 setState(STATE.SIGNED);
139 console.error(error);
150 unsignedTransactions,
156 const broadcast = useCallback(async () => {
158 setConfirmationProgress(0.0);
160 setState(STATE.BROADCASTED);
162 const rawTxs = signedTransactions.map(stx => hexify(stx.serialize()));
164 const costGwei = toBN(gasLimit)
166 .mul(toBN(rawTxs.length));
167 const cost = safeToWei(costGwei, 'gwei');
168 let usedTank = false;
169 // if this ethereum transaction is being executed by a specific point
170 // see if we can use the tank
171 if (Just.hasInstance(pointCursor)) {
172 usedTank = await ensureFundsFor(
179 (address, minBalance, balance) =>
180 setNeedFunds({ address, minBalance, balance }),
181 () => setNeedFunds(undefined)
185 const txHashes = await signedTransactions.reduce(
188 sendSignedTransaction(
191 /* doubtNonceError */ usedTank
192 ).then(hash => [...hashes, hash])
197 setTxHashes(txHashes);
199 await timeout(PROGRESS_ANIMATION_DELAY_MS);
201 setConfirmationProgress(0.2);
203 const receipts = await Promise.all(
204 txHashes.map(txHash => waitForTransactionConfirm(_web3, txHash))
212 toBN(receipt.gasUsed)
223 setConfirmationProgress(0.9);
225 setState(STATE.CONFIRMED);
240 const reset = useCallback(() => {
241 setTxHashes(undefined);
242 setSignedTransactions(undefined);
244 setChainId(undefined);
246 setState(STATE.NONE);
248 setNeedFunds(undefined);
249 setConfirmationProgress(0.0);
250 setFinalCost(undefined);
251 }, [resetGasPrice, setError]);
255 // if nonce or chainId is undefined, re-fetch on-chain info
256 if (!(nonce === undefined || chainId === undefined)) {
263 const [nonce, chainId] = await Promise.all([
264 _web3.eth.getTransactionCount(_wallet.address),
265 _web3.eth.net.getId(),
279 return () => (mounted = false);
280 }, [_wallet, _web3, setError, nonce, chainId, networkType, initialGasPrice]);
292 console.error(error);
293 // track a user-friendly error
296 'The transaction succeeded but we were unable to refresh chain state. Refresh to continue.'
306 setConfirmationProgress(1.0);
308 await timeout(PROGRESS_ANIMATION_DELAY_MS);
314 setState(STATE.COMPLETED);
318 return () => (mounted = false);
319 }, [confirmed, refetch, completed, setError]);
321 const values = useDeepEqualReference({
337 confirmationProgress,
347 unsignedTransactions,
351 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