1import { useCallback, useEffect, useState } from 'react';
2import { Just } from 'folktale/maybe';
4import { useNetwork } from 'store/network';
5import { useWallet } from 'store/wallet';
10 waitForTransactionConfirm,
13import * as need from './need';
14import { toHex, toWei, fromWei } from 'web3-utils';
19 BROADCASTED: 'BROADCASTED',
20 CONFIRMED: 'CONFIRMED',
24 * manage the state around sending and confirming an ethereum transaction
25 * @param {number} initialGasLimit
27export default function useEthereumTransaction(initialGasLimit = 0) {
28 const { wallet, walletType, walletHdPath } = useWallet();
29 const { web3, networkType } = useNetwork();
30 const _web3 = need.web3(web3);
31 const _wallet = need.wallet(wallet);
33 const [error, _setError] = useState();
34 const setError = useCallback(
43 const [state, setState] = useState(STATE.NONE);
44 const [chainId, setChainId] = useState();
45 const [nonce, setNonce] = useState();
46 const [gasPrice, setGasPrice] = useState(20); // gwei
47 const [gasLimit] = useState(initialGasLimit);
48 const [unsignedTransaction, setUnsignedTransaction] = useState();
49 const [signedTransaction, setSignedTransaction] = useState();
50 const [txHash, setTxHash] = useState();
52 const initializing = nonce === undefined || chainId === undefined;
53 const constructed = !!unsignedTransaction;
54 const signed = state === STATE.SIGNED;
55 const broadcasted = state === STATE.BROADCASTED;
56 const confirmed = state === STATE.CONFIRMED;
58 const inputsLocked = signed || broadcasted || confirmed;
60 const canSign = !initializing && constructed;
62 const construct = useCallback(txn => setUnsignedTransaction(txn), [
63 setUnsignedTransaction,
66 const generateAndSign = useCallback(async () => {
69 // TODO: set varaibles
70 // txn.gas = toHex(gasLimit);
71 // txn.gasPrice = toHex(toWei(gasPrice, 'gwei'));
73 const txn = await signTransaction({
78 txn: unsignedTransaction,
85 setSignedTransaction(txn);
86 setState(STATE.SIGNED);
103 const broadcast = useCallback(async () => {
106 const txHash = await sendSignedTransaction(
109 /* doubtNonceError */ false
112 setState(STATE.BROADCASTED);
115 await waitForTransactionConfirm(_web3, txHash);
117 setState(STATE.CONFIRMED);
121 }, [_web3, setError, signedTransaction]);
123 const reset = useCallback(() => {
124 setState(STATE.NONE);
127 setSignedTransaction(undefined);
134 const [nonce, chainId, estimatedGasPrice] = await Promise.all([
135 _web3.eth.getTransactionCount(_wallet.address),
136 _web3.eth.net.getId(),
137 _web3.eth.getGasPrice(),
142 setGasPrice(fromWei(estimatedGasPrice, 'gwei'));
147 }, [_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