1import { useCallback, useEffect, useState } from 'react';
2import { Just } from 'folktale/maybe';
3import { fromWei, toWei } from 'web3-utils';
5import { useNetwork } from 'store/network';
6import { useWallet } from 'store/wallet';
7import { usePointCursor } from 'store/pointCursor';
8import { useSuggestedGasPrice } from 'lib/useSuggestedGasPrice';
10import { GAS_LIMITS } from './constants';
13 sendSignedTransaction,
14 waitForTransactionConfirm,
17import * as need from './need';
18import { ensureFundsFor } from './tank';
19import useDeepEqualReference from './useDeepEqualReference';
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,
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] = useState(initialGasPrice); // gwei
63 const [suggestedGasPrice, setSuggestedGasPrice] = useState(gasPrice); // gwei
64 const { gasPrice: estimatedGasPrice } = useSuggestedGasPrice();
65 const [gasLimit] = useState(initialGasLimit);
66 const [unsignedTransaction, setUnsignedTransaction] = useState();
67 const [signedTransaction, setSignedTransaction] = useState();
68 const [txHash, setTxHash] = useState();
69 const [needFunds, setNeedFunds] = useState();
71 const initializing = nonce === undefined || chainId === undefined;
72 const constructed = !!unsignedTransaction;
73 const isDefaultState = state === STATE.NONE;
74 const signed = state === STATE.SIGNED;
75 const broadcasted = state === STATE.BROADCASTED;
76 const confirmed = state === STATE.CONFIRMED;
77 const completed = state === STATE.COMPLETED;
79 // lock inputs once we're out of the default state
80 const inputsLocked = !isDefaultState;
83 const canSign = !initializing && constructed && isDefaultState;
85 const construct = useCallback(
87 setUnsignedTransaction(await transactionBuilder(...args)),
91 const unconstruct = useCallback(() => setUnsignedTransaction(undefined), [
92 setUnsignedTransaction,
95 const generateAndSign = useCallback(async () => {
99 const txn = await signTransaction({
104 txn: unsignedTransaction,
107 gasPrice: gasPrice.toFixed(0),
111 setSignedTransaction(txn);
112 setState(STATE.SIGNED);
129 const broadcast = useCallback(async () => {
133 const rawTx = hexify(signedTransaction.serialize());
134 const cost = toWei(gasPrice.toFixed(0), 'gwei') * gasLimit;
136 let usedTank = false;
137 // if this ethereum transaction is being executed by a specific point
138 // see if we can use the tank
139 if (Just.hasInstance(pointCursor)) {
140 usedTank = await ensureFundsFor(
146 (address, minBalance, balance) =>
147 setNeedFunds({ address, minBalance, balance }),
148 () => setNeedFunds(undefined)
152 const txHash = await sendSignedTransaction(
155 /* doubtNonceError */ usedTank
158 setState(STATE.BROADCASTED);
161 await waitForTransactionConfirm(_web3, txHash);
163 setState(STATE.CONFIRMED);
177 const reset = useCallback(() => {
178 setTxHash(undefined);
179 setSignedTransaction(undefined);
181 setChainId(undefined);
182 setGasPrice(suggestedGasPrice);
183 setState(STATE.NONE);
185 setNeedFunds(undefined);
186 }, [suggestedGasPrice, setError]);
188 const resetGasPrice = useCallback(() => setGasPrice(suggestedGasPrice), [
194 const gasPrice = parseInt(
195 fromWei(estimatedGasPrice.toString(), 'gwei'),
198 setSuggestedGasPrice(gasPrice);
199 setGasPrice(gasPrice);
200 }, [estimatedGasPrice]);
204 // if nonce or chainId is undefined, re-fetch on-chain info
205 if (!(nonce === undefined || chainId === undefined)) {
212 const [nonce, chainId] = await Promise.all([
213 _web3.eth.getTransactionCount(_wallet.address),
214 _web3.eth.net.getId(),
228 return () => (mounted = false);
249 console.error(error);
250 // track a user-friendly error
253 'The transaction succeeded but we were unable to refresh chain state. Refresh to continue.'
263 setState(STATE.COMPLETED);
267 return () => (mounted = false);
268 }, [confirmed, refetch, completed, setError]);
270 const values = useDeepEqualReference({
297 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