1import { Common, Chain, Hardfork } from '@ethereumjs/common';
3 FeeMarketEIP1559Transaction as EIP1559Transaction,
5 FeeMarketEIP1559TxData as EIP1559TxData,
6} from '@ethereumjs/tx';
7import { toHex, toWei } from 'web3-utils';
8import retry from 'async-retry';
9import { NETWORK_TYPES } from './network';
10import { walletConnectSignTransaction } from './WalletConnect';
11import { metamaskSignTransaction } from './metamask';
12import { addHexPrefix } from './utils/address';
15 EIP1559_TRANSACTION_TYPE,
18import Web3 from 'web3';
19import { TransactionConfig, TransactionReceipt } from 'web3-core';
20import BridgeWallet from './types/BridgeWallet';
21import { GasPriceData } from 'components/L2/Dropdowns/FeeDropdown';
22import { ITxData } from './types/ITxData';
24const RETRY_OPTIONS = {
27 minTimeout: CHECK_BLOCK_EVERY_MS,
31export type FakeSignableTx = EIP1559Transaction;
33type TxSender = (txn: FakeSignableTx, web3: Web3) => Promise<string>;
35export type FakeSignedTx = {
38 serialize: () => string;
41const FakeSignResult = (txn: FakeSignableTx, send: TxSender): FakeSignedTx => {
45 return '???'; //NOTE update tank.js when changing this!
51interface signTransactionProps {
54 walletHdPath: string; // TODO: is this still needed?
56 txn: { data: string; to: string; value: number };
57 nonce: number | string;
58 chainId: number | string;
59 gasPriceData: GasPriceData;
61 txnSigner?: (args: ITxData) => Promise<string>;
62 txnSender?: (args: ITxData) => Promise<string>;
66 const ENDPOINT = `https://mainnet.infura.io/v3/${
67 import.meta.env.VITE_INFURA_ENDPOINT
69 return new Web3(new Web3.providers.HttpProvider(ENDPOINT));
72const estimateGasLimit = async (utx: TransactionConfig) => {
74 const estimate = await web3.eth.estimateGas(utx);
78 .divn(100); // 20% cushion
81const getMaxFeePerGas = async () => {
83 const fee = await web3.eth.getGasPrice();
84 return (Number(fee) * 1.2).toFixed(0); // 20% cushion
87const signTransaction = async ({
92 txn, // output of transactionBuilder in useEthereumTransaction
95 gasPriceData, // GasPriceData
96 gasLimit, // TODO: do we need the default values anymore? now that the estiamte is loaded dynamically
97 txnSigner, // optionally inject a transaction signing function,
98 txnSender, // and a sending function, for wallets that need these passed in.
99}: signTransactionProps) => {
100 const from = wallet.address;
101 const estimate = await estimateGasLimit({ ...txn, from });
102 const maxFeePerGas = await getMaxFeePerGas();
104 const txParams: EIP1559TxData = {
105 data: toHex(txn.data),
107 gasLimit: toHex(estimate),
108 maxFeePerGas: toHex(maxFeePerGas),
109 maxPriorityFeePerGas: toHex(
110 toWei(Math.round(gasPriceData.maxPriorityFeePerGas).toFixed(0), 'gwei')
113 chainId: toHex(chainId),
114 type: toHex(EIP1559_TRANSACTION_TYPE),
118 networkType === NETWORK_TYPES.GOERLI ? Chain.Goerli : Chain.Mainnet;
120 const txConfig: TxOptions = {
124 hardfork: Hardfork.Merge,
128 let stx = EIP1559Transaction.fromTxData(txParams, txConfig);
130 if (walletType === WALLET_TYPES.METAMASK) {
131 return metamaskSignTransaction(stx);
132 } else if (walletType === WALLET_TYPES.WALLET_CONNECT) {
133 if (!(txnSender && txnSigner)) {
134 throw Error('WalletConnect TX signer unavailable');
137 stx = await walletConnectSignTransaction({
145 stx = stx.sign(wallet.privateKey!);
151const sendSignedTransaction = (
153 stx: EIP1559Transaction | FakeSignedTx,
154 doubtNonceError: boolean
155): Promise<string> => {
156 // if we couldn't sign it, we depend on the given sender function
157 if (!(stx instanceof EIP1559Transaction)) {
159 if (doubtNonceError) {
160 console.log('why doubting nonce error? tank unavailable without rawtx.');
163 throw new Error('no sign+sending function available');
165 return stx.send(stx.txn, web3);
168 let rawTx: string = hexify(stx.serialize());
169 let eventEmitter = web3.eth.sendSignedTransaction(rawTx);
170 return new Promise(async (resolve, reject) => {
172 .on('transactionHash', (hash: string) => {
175 .on('error', err => {
176 // if there's a nonce error, but we used the gas tank, it's likely
177 // that it's because the tank already submitted our transaction.
178 // we just wait for first confirmation here.
179 const message = typeof err === 'string' ? err : err.message || '';
181 message.includes('known transaction') ||
182 message.includes('already known');
184 message.includes("the tx doesn't have the correct nonce.") ||
185 message.includes('nonce too low');
186 if (rawTx && (isKnownError || (doubtNonceError && isNonceError))) {
188 'tx send error likely from gas tank submission, ignoring:',
191 const txHash = web3.utils.keccak256(rawTx);
195 const wrappedErr = err instanceof Error ? err : new Error(message);
202// returns a Promise<void>, throwing on tx failure
203const waitForTransactionConfirm = (web3: Web3, txHash: string) => {
204 return retry(async (bail, n) => {
205 const receipt = await web3.eth.getTransactionReceipt(txHash);
206 const confirmed = receipt !== null;
208 throw new Error('Transaction not confirmed.');
211 const success = receipt.status === true;
213 return bail(new Error('Transaction failed.'));
219// returns a Promise that resolves when all stxs have been sent & confirmed
220const sendAndAwaitAll = (
222 stxs: EIP1559Transaction[] | FakeSignedTx[],
223 doubtNonceError: boolean
226 stxs.map(async tx => {
227 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
228 return await waitForTransactionConfirm(web3, txHash);
233const sendAndAwaitAllSerial = (
235 stxs: EIP1559Transaction[] | FakeSignedTx[],
236 doubtNonceError: boolean
238 //@ts-expect-error tsc complains that stxs.reduce() is not callable
241 promise: Promise<TransactionReceipt[]>,
242 stx: EIP1559Transaction | FakeSignedTx
244 promise.then(async (receipts = []) => {
245 const txHash = await sendSignedTransaction(web3, stx, doubtNonceError);
246 return [...receipts, await waitForTransactionConfirm(web3, txHash)];
252const sendTransactionsAndAwaitConfirm = async (
254 signedTxs: EIP1559Transaction[] | FakeSignedTx[],
257 Promise.all(signedTxs.map(tx => sendSignedTransaction(web3, tx, usedTank)));
259const hexify = (val: string | Buffer) => addHexPrefix(val.toString('hex'));
265 sendSignedTransaction,
266 waitForTransactionConfirm,
267 sendTransactionsAndAwaitConfirm,
269 sendAndAwaitAllSerial,
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