1import { useCallback, useEffect, useState } from 'react';
2import { Just } from 'folktale/maybe';
3import { toWei } from 'web3-utils';
5import { useNetwork } from 'store/network';
6import { useWallet } from 'store/wallet';
7import { usePointCursor } from 'store/pointCursor';
9import { GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } from './constants';
12 sendSignedTransaction,
13 waitForTransactionConfirm,
16import * as need from 'lib/need';
17import { ensureFundsFor } from 'lib/tank';
18import useDeepEqualReference from './useDeepEqualReference';
19import useGasPrice from './useGasPrice';
24 BROADCASTED: 'BROADCASTED',
25 CONFIRMED: 'CONFIRMED',
26 COMPLETED: 'COMPLETED',
30 * manage the state around sending and confirming an ethereum transaction
31 * @param {Transaction Function()} transactionBuilder
32 * @param {Promise<any> Function()} refetch async function called after completion
33 * @param {number} initialGasLimit gas limit
34 * @param {number} initialGasPrice gas price in gwei
36export default function useEthereumTransaction(
39 initialGasLimit = GAS_LIMITS.DEFAULT,
40 initialGasPrice = DEFAULT_GAS_PRICE_GWEI
42 const { wallet, walletType, walletHdPath } = useWallet();
43 const { web3, networkType } = useNetwork();
44 const { pointCursor } = usePointCursor();
46 const _web3 = need.web3(web3);
47 const _wallet = need.wallet(wallet);
49 const [error, _setError] = useState();
50 const setError = useCallback(
59 const [state, setState] = useState(STATE.NONE);
60 const [chainId, setChainId] = useState();
61 const [nonce, setNonce] = useState();
62 const { gasPrice, setGasPrice, resetGasPrice } = useGasPrice(initialGasPrice);
63 const [gasLimit] = useState(initialGasLimit);
64 const [unsignedTransaction, setUnsignedTransaction] = useState();
65 const [signedTransaction, setSignedTransaction] = useState();
66 const [txHash, setTxHash] = useState();
67 const [needFunds, setNeedFunds] = useState();
69 const initializing = nonce === undefined || chainId === undefined;
70 const constructed = !!unsignedTransaction;
71 const isDefaultState = state === STATE.NONE;
72 const signed = state === STATE.SIGNED;
73 const broadcasted = state === STATE.BROADCASTED;
74 const confirmed = state === STATE.CONFIRMED;
75 const completed = state === STATE.COMPLETED;
77 // lock inputs once we're out of the default state
78 const inputsLocked = !isDefaultState;
81 const canSign = !initializing && constructed && isDefaultState;
83 const construct = useCallback(
85 setUnsignedTransaction(await transactionBuilder(...args)),
89 const unconstruct = useCallback(() => setUnsignedTransaction(undefined), [
90 setUnsignedTransaction,
93 const generateAndSign = useCallback(async () => {
97 const txn = await signTransaction({
102 txn: unsignedTransaction,
105 gasPrice: gasPrice.toFixed(0),
109 setSignedTransaction(txn);
110 setState(STATE.SIGNED);
127 const broadcast = useCallback(async () => {
131 const rawTx = hexify(signedTransaction.serialize());
132 const cost = toWei(gasPrice.toFixed(0), 'gwei') * gasLimit;
134 let usedTank = false;
135 // if this ethereum transaction is being executed by a specific point
136 // see if we can use the tank
137 if (Just.hasInstance(pointCursor)) {
138 usedTank = await ensureFundsFor(
144 (address, minBalance, balance) =>
145 setNeedFunds({ address, minBalance, balance }),
146 () => setNeedFunds(undefined)
150 const txHash = await sendSignedTransaction(
153 /* doubtNonceError */ usedTank
156 setState(STATE.BROADCASTED);
159 await waitForTransactionConfirm(_web3, txHash);
161 setState(STATE.CONFIRMED);
175 const reset = useCallback(() => {
176 setTxHash(undefined);
177 setSignedTransaction(undefined);
179 setChainId(undefined);
181 setState(STATE.NONE);
183 setNeedFunds(undefined);
184 }, [resetGasPrice, setError]);
188 // if nonce or chainId is undefined, re-fetch on-chain info
189 if (!(nonce === undefined || chainId === undefined)) {
196 const [nonce, chainId] = await Promise.all([
197 _web3.eth.getTransactionCount(_wallet.address),
198 _web3.eth.net.getId(),
212 return () => (mounted = false);
213 }, [_wallet, _web3, setError, nonce, chainId, networkType, initialGasPrice]);
225 console.error(error);
226 // track a user-friendly error
229 'The transaction succeeded but we were unable to refresh chain state. Refresh to continue.'
239 setState(STATE.COMPLETED);
243 return () => (mounted = false);
244 }, [confirmed, refetch, completed, setError]);
246 const values = useDeepEqualReference({
273 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