1import { useCallback, useEffect, useState } from 'react';
3import { useNetwork } from 'store/network';
4import { useWallet } from 'store/wallet';
9 waitForTransactionConfirm,
11import * as need from './need';
12import { fromWei } from 'web3-utils';
17 BROADCASTED: 'BROADCASTED',
18 CONFIRMED: 'CONFIRMED',
22 * manage the state around sending and confirming an ethereum transaction
23 * @param {number} initialGasLimit
25export default function useEthereumTransaction(initialGasLimit = 0) {
26 const { wallet, walletType, walletHdPath } = useWallet();
27 const { web3, networkType } = useNetwork();
28 const _web3 = need.web3(web3);
29 const _wallet = need.wallet(wallet);
31 const [error, _setError] = useState();
32 const setError = useCallback(
41 const [state, setState] = useState(STATE.NONE);
42 const [chainId, setChainId] = useState();
43 const [nonce, setNonce] = useState();
44 const [gasPrice, setGasPrice] = useState(20); // gwei
45 const [gasLimit] = useState(initialGasLimit);
46 const [unsignedTransaction, setUnsignedTransaction] = useState();
47 const [signedTransaction, setSignedTransaction] = useState();
48 const [txHash, setTxHash] = useState();
50 const initializing = nonce === undefined || chainId === undefined;
51 const constructed = !!unsignedTransaction;
52 const signed = state === STATE.SIGNED;
53 const broadcasted = state === STATE.BROADCASTED;
54 const confirmed = state === STATE.CONFIRMED;
56 const inputsLocked = signed || broadcasted || confirmed;
58 const canSign = !initializing && constructed;
60 const construct = useCallback(txn => setUnsignedTransaction(txn), [
61 setUnsignedTransaction,
64 const generateAndSign = useCallback(async () => {
68 const txn = await signTransaction({
73 txn: unsignedTransaction,
76 gasPrice: gasPrice.toFixed(0),
80 setSignedTransaction(txn);
81 setState(STATE.SIGNED);
98 const broadcast = useCallback(async () => {
101 const txHash = await sendSignedTransaction(
104 /* doubtNonceError */ false
107 setState(STATE.BROADCASTED);
110 await waitForTransactionConfirm(_web3, txHash);
112 setState(STATE.CONFIRMED);
116 }, [_web3, setError, signedTransaction]);
118 const reset = useCallback(() => {
119 setState(STATE.NONE);
122 setSignedTransaction(undefined);
129 const [nonce, chainId, estimatedGasPrice] = await Promise.all([
130 _web3.eth.getTransactionCount(_wallet.address),
131 _web3.eth.net.getId(),
132 _web3.eth.getGasPrice(),
137 setGasPrice(parseInt(fromWei(estimatedGasPrice, 'gwei'), 10));
142 }, [_wallet.address, _web3.eth, setError]);
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