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';
9import { GAS_LIMITS } from './constants';
12 sendSignedTransaction,
13 waitForTransactionConfirm,
16import * as need from './need';
17import useLifecycle from './useLifecycle';
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 [gasLimit] = useState(initialGasLimit);
65 const [unsignedTransaction, setUnsignedTransaction] = useState();
66 const [signedTransaction, setSignedTransaction] = useState();
67 const [txHash, setTxHash] = useState();
68 const [needFunds, setNeedFunds] = useState();
70 const initializing = nonce === undefined || chainId === undefined;
71 const constructed = !!unsignedTransaction;
72 const isDefaultState = state === STATE.NONE;
73 const signed = state === STATE.SIGNED;
74 const broadcasted = state === STATE.BROADCASTED;
75 const confirmed = state === STATE.CONFIRMED;
76 const completed = state === STATE.COMPLETED;
78 // lock inputs once we're out of the default state
79 const inputsLocked = !isDefaultState;
82 const canSign = !initializing && constructed && isDefaultState;
84 const construct = useCallback(
86 setUnsignedTransaction(await transactionBuilder(...args)),
90 const unconstruct = useCallback(() => setUnsignedTransaction(undefined), [
91 setUnsignedTransaction,
94 const generateAndSign = useCallback(async () => {
98 const txn = await signTransaction({
103 txn: unsignedTransaction,
106 gasPrice: gasPrice.toFixed(0),
110 setSignedTransaction(txn);
111 setState(STATE.SIGNED);
128 const broadcast = useCallback(async () => {
132 const rawTx = hexify(signedTransaction.serialize());
133 const cost = toWei(gasPrice.toFixed(0), 'gwei') * gasLimit;
135 let usedTank = false;
136 // if this ethereum transaction is being executed by a specific point
137 // see if we can use the tank
138 if (Just.hasInstance(pointCursor)) {
139 usedTank = await ensureFundsFor(
145 (address, minBalance, balance) =>
146 setNeedFunds({ address, minBalance, balance }),
147 () => setNeedFunds(undefined)
151 const txHash = await sendSignedTransaction(
154 /* doubtNonceError */ usedTank
157 setState(STATE.BROADCASTED);
160 await waitForTransactionConfirm(_web3, txHash);
162 setState(STATE.CONFIRMED);
176 const reset = useCallback(() => {
177 setUnsignedTransaction(undefined);
178 setTxHash(undefined);
179 setSignedTransaction(undefined);
180 setGasPrice(suggestedGasPrice);
181 setState(STATE.NONE);
183 setNeedFunds(undefined);
184 }, [suggestedGasPrice, setError]);
186 const resetGasPrice = useCallback(() => setGasPrice(suggestedGasPrice), [
195 const [nonce, chainId, estimatedGasPrice] = await Promise.all([
196 _web3.eth.getTransactionCount(_wallet.address),
197 _web3.eth.net.getId(),
198 _web3.eth.getGasPrice(),
203 const gasPrice = parseInt(fromWei(estimatedGasPrice, 'gwei'), 10);
204 setSuggestedGasPrice(gasPrice);
205 setGasPrice(gasPrice);
213 let cancelled = false;
222 console.error(error);
223 // track a user-friendly error
226 'The transaction succeeded but we were unable to refresh chain state. Refresh to continue.'
236 setState(STATE.COMPLETED);
240 return () => (cancelled = true);
241 }, [confirmed, refetch, completed, setError]);
243 const values = useDeepEqualReference({
270 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