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';
28import { Transaction } from '@ethereumjs/tx';
33 FAKE_SIGNED: 'FAKE_SIGNED',
34 BROADCASTED: 'BROADCASTED',
35 CONFIRMED: 'CONFIRMED',
36 COMPLETED: 'COMPLETED',
40 * manage the state around sending and confirming an ethereum transaction
41 * @param {Transaction Function()} transactionBuilder
42 * @param {Promise<any> Function()} refetch async function called after completion
43 * @param {number} initialGasLimit gas limit
44 * @param {number} initialGasPrice gas price in gwei
46export default function useEthereumTransaction(
49 initialGasLimit = GAS_LIMITS.DEFAULT,
50 initialGasPrice = DEFAULT_GAS_PRICE_GWEI
52 const { wallet, walletType, walletHdPath } = useWallet();
53 const { web3, networkType } = useNetwork();
54 const { pointCursor } = usePointCursor();
56 signTransaction: wcSign,
57 sendTransaction: wcSend,
58 } = useWalletConnect();
60 const _web3 = need.web3(web3);
61 const _wallet = need.wallet(wallet);
63 const [error, _setError] = useState();
64 const setError = useCallback(
73 const [state, setState] = useState(STATE.NONE);
74 const [chainId, setChainId] = useState();
75 const [nonce, setNonce] = useState();
76 const { gasPrice, setGasPrice, resetGasPrice } = useGasPrice(initialGasPrice);
77 const [gasLimit] = useState(initialGasLimit);
78 const [unsignedTransactions, setUnsignedTransactions] = useState();
79 const [signedTransactions, setSignedTransactions] = useState();
80 const [txHashes, setTxHashes] = useState();
81 const [needFunds, setNeedFunds] = useState();
82 const [confirmationProgress, setConfirmationProgress] = useState(0.0);
84 const [finalCost, setFinalCost] = useState();
86 const initializing = nonce === undefined || chainId === undefined;
87 const constructed = !!unsignedTransactions;
88 const isDefaultState = state === STATE.NONE;
89 const signed = state === STATE.SIGNED || state === STATE.FAKE_SIGNED;
90 const fakeSigned = state === STATE.FAKE_SIGNED;
91 const broadcasted = state === STATE.BROADCASTED;
92 const confirmed = state === STATE.CONFIRMED;
93 const completed = state === STATE.COMPLETED;
95 // lock inputs once we're out of the default state
96 const inputsLocked = !isDefaultState;
99 const canSign = !initializing && constructed && isDefaultState;
101 const construct = useCallback(
103 setUnsignedTransactions(await transactionBuilder(...args)),
107 const unconstruct = useCallback(() => setUnsignedTransactions(undefined), [
108 setUnsignedTransactions,
111 const generateAndSign = useCallback(async () => {
115 const utxs = Array.isArray(unsignedTransactions)
116 ? unsignedTransactions
117 : [unsignedTransactions];
119 // Due to React's Rules of Hooks, optionally inject the
120 // WC transaction signing function
121 // https://reactjs.org/docs/hooks-rules.html
123 walletType === WALLET_TYPES.WALLET_CONNECT ? wcSign : undefined;
125 walletType === WALLET_TYPES.WALLET_CONNECT ? wcSend : undefined;
127 const txns = await Promise.all(
137 gasPrice: gasPrice.toFixed(0),
145 setSignedTransactions(txns);
147 // Per return type of `signTransaction`, tx is either a Transaction or FakeSignedTx.
148 // We check the negation in this case, since TS cannot perform run-time check of type
149 // FakeSignedTx, but it can check for an instance of the ethereumjs/tx class.
150 if (txns.some(tx => !(tx instanceof Transaction))) {
151 setState(STATE.FAKE_SIGNED);
153 setState(STATE.SIGNED);
156 console.error('error signing txs', error);
167 unsignedTransactions,
174 const broadcast = useCallback(async () => {
176 setConfirmationProgress(0.0);
178 setState(STATE.BROADCASTED);
180 const rawTxs = signedTransactions.map(stx => hexify(stx.serialize()));
182 const costGwei = toBN(gasLimit)
184 .mul(toBN(rawTxs.length));
185 const cost = safeToWei(costGwei, 'gwei');
186 let usedTank = false;
187 // if this ethereum transaction is being executed by a specific point
188 // see if we can use the tank
189 if (Just.hasInstance(pointCursor)) {
190 usedTank = await ensureFundsFor(
197 (address, minBalance, balance) =>
198 setNeedFunds({ address, minBalance, balance }),
199 () => setNeedFunds(undefined)
203 const txHashes = await signedTransactions.reduce(
206 sendSignedTransaction(
209 /* doubtNonceError */ usedTank
210 ).then(hash => [...hashes, hash])
215 setTxHashes(txHashes);
217 await timeout(PROGRESS_ANIMATION_DELAY_MS);
219 setConfirmationProgress(0.2);
221 const receipts = await Promise.all(
222 txHashes.map(txHash => waitForTransactionConfirm(_web3, txHash))
230 toBN(receipt.gasUsed)
241 setConfirmationProgress(0.9);
243 setState(STATE.CONFIRMED);
258 const reset = useCallback(() => {
259 setTxHashes(undefined);
260 setSignedTransactions(undefined);
262 setChainId(undefined);
264 setState(STATE.NONE);
266 setNeedFunds(undefined);
267 setConfirmationProgress(0.0);
268 setFinalCost(undefined);
269 }, [resetGasPrice, setError]);
273 // if nonce or chainId is undefined, re-fetch on-chain info
274 if (!(nonce === undefined || chainId === undefined)) {
281 const [nonce, chainId] = await Promise.all([
282 _web3.eth.getTransactionCount(_wallet.address),
283 _web3.eth.net.getId(),
297 return () => (mounted = false);
298 }, [_wallet, _web3, setError, nonce, chainId, networkType, initialGasPrice]);
310 console.error(error);
311 // track a user-friendly error
314 'The transaction succeeded but we were unable to refresh chain state. Refresh to continue.'
324 setConfirmationProgress(1.0);
326 await timeout(PROGRESS_ANIMATION_DELAY_MS);
332 setState(STATE.COMPLETED);
336 return () => (mounted = false);
337 }, [confirmed, refetch, completed, setError]);
339 const values = useDeepEqualReference({
356 confirmationProgress,
366 unsignedTransactions,
370 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