@@ -1,20 +1,17 @@
1−import Common, { Chain, Hardfork } from '@ethereumjs/common';
2−import { JsonTx, Transaction } from '@ethereumjs/tx';
1+import { Common, Chain, Hardfork } from '@ethereumjs/common';
2+import { JsonTx, Transaction, FeeMarketEIP1559Transaction as EIP1559Transaction, TxOptions, TxData, FeeMarketEIP1559TxData as EIP1559TxData } from '@ethereumjs/tx';
33import { ITxData } from '@walletconnect/types';
4−import { toHex } from 'web3-utils';
5−import { safeFromWei, safeToWei } from './lib';
4+import { toHex, toWei } from 'web3-utils';
65import retry from 'async-retry';
7−
86import { NETWORK_TYPES } from './network';
9−import { ledgerSignTransaction } from './ledger';
10−import { trezorSignTransaction } from './trezor';
117import { walletConnectSignTransaction } from './WalletConnect';
128import { metamaskSignTransaction } from './metamask';
139import { addHexPrefix } from './utils/address';
14−import { CHECK_BLOCK_EVERY_MS, WALLET_TYPES } from './constants';
10+import { CHECK_BLOCK_EVERY_MS, EIP1559_TRANSACTION_TYPE, WALLET_TYPES } from './constants';
1511import Web3 from 'web3';
16−import { TransactionReceipt } from 'web3-core';
12+import { TransactionConfig, TransactionReceipt } from 'web3-core';
1713import BridgeWallet from './types/BridgeWallet';
14+import { GasPriceData } from 'components/L2/Dropdowns/FeeDropdown';
1815
1916const RETRY_OPTIONS = {
2017 retries: 99999,
@@ -23,12 +20,12 @@ const RETRY_OPTIONS = {
2320 randomize: false,
2421};
2522
26−type SignableTx = Transaction & {
23+type SignableTx = (Transaction | EIP1559Transaction) & {
2724 nonce: string;
2825 chainId: string;
29− gasPrice: string;
30− gasLimit: string;
31− from: string;
26+ gasPrice?: string; // TODO: is this still needed?
27+ gasLimit: string; // TODO: is this still needed?
28+ from?: string;
3229};
3330
3431// catch-all type: Metamask passes an obj shaped like ITxData, WC passes JsonTx + from
@@ -39,13 +36,10 @@ export type FakeSignableTx =
3936
4037type TxSender = (txn: FakeSignableTx, web3: Web3) => Promise<string>; // Metamask requires Web3 (txhash)
4138
42−type SignedTx = {
43− serialize: () => string;
44−};
45−
46−export type FakeSignedTx = SignedTx & {
39+export type FakeSignedTx = {
4740 txn: FakeSignableTx;
4841 send: TxSender;
42+ serialize: () => string;
4943};
5044
5145const FakeSignResult = (txn: FakeSignableTx, send: TxSender): FakeSignedTx => {
@@ -61,107 +55,81 @@ const FakeSignResult = (txn: FakeSignableTx, send: TxSender): FakeSignedTx => {
6155interface signTransactionProps {
6256 wallet: BridgeWallet;
6357 walletType: symbol;
64− walletHdPath: string;
58+ walletHdPath: string; // TODO: is this still needed?
6559 networkType: symbol;
66− txn: Transaction;
60+ txn: Transaction | EIP1559Transaction;
6761 nonce: number | string;
6862 chainId: number | string;
69− gasPrice: string;
70− gasLimit: string;
63+ gasPriceData: GasPriceData;
64+ gasLimit: number;
7165 txnSigner?: (args: ITxData) => Promise<string>;
7266 txnSender?: (args: ITxData) => Promise<string>;
7367}
7468
69+const _web3 = () => {
70+ const ENDPOINT = `https://mainnet.infura.io/v3/${import.meta.env.VITE_INFURA_ENDPOINT}`;
71+ return new Web3(new Web3.providers.HttpProvider(ENDPOINT));
72+}
73+
74+const estimateGasLimit = async (utx: TransactionConfig) => {
75+ const web3 = _web3();
76+ const estimate = await web3.eth.estimateGas(utx);
77+ console.log(estimate);
78+ return web3.utils.toBN(estimate).muln(120).divn(100); // 20% cushion
79+}
80+
81+const getMaxFeePerGas = async () => {
82+ const web3 = _web3();
83+ const fee = await web3.eth.getGasPrice();
84+ return (Number(fee) * 1.20).toFixed(0); // 20% cushion
85+}
86+
7587const signTransaction = async ({
7688 wallet,
7789 walletType,
78− walletHdPath,
90+ walletHdPath, // TODO
7991 networkType,
8092 txn,
8193 nonce, // number
8294 chainId, // number
83− gasPrice, // string, in gwei
84− gasLimit, // string | number
95+ gasPriceData, // GasPriceData
96+ gasLimit, // TODO: do we need the default values anymore? now that the estiamte is loaded dynamically
8597 txnSigner, // optionally inject a transaction signing function,
8698 txnSender, // and a sending function, for wallets that need these passed in.
8799}: signTransactionProps) => {
88− // TODO: require these in txn object
89− nonce = toHex(nonce);
90− chainId = toHex(chainId);
91− gasPrice = toHex(safeToWei(gasPrice, 'gwei'));
92− gasLimit = toHex(gasLimit);
100+ console.log('txn', txn);
93101 const from = wallet.address;
102+ const estimate = await estimateGasLimit({...txn, from });
103+ const maxFeePerGas = await getMaxFeePerGas();
94104
95− const txParams = { nonce, chainId, gasPrice, gasLimit, from };
105+ const txParams: EIP1559TxData = {
106+ data: toHex(txn.data),
107+ to: toHex(txn.to),
108+ gasLimit: toHex(estimate),
109+ maxFeePerGas: toHex(maxFeePerGas),
110+ maxPriorityFeePerGas: toHex(toWei(Math.round(gasPriceData.maxPriorityFeePerGas).toFixed(0), 'gwei')),
111+ nonce: toHex(nonce),
112+ chainId: toHex(chainId),
113+ type: toHex(EIP1559_TRANSACTION_TYPE),
114+ }
96115
97− // NB (jtobin)
98− //
99− // Ledger does not seem to handle EIP-155 automatically. When using a Ledger,
100− // if the block number is at least FORK_BLKNUM = 2675000, one needs to
101− // pre-set the ECDSA signature parameters with r = 0, s = 0, and v = chainId
102− // prior to signing.
103− //
104− // The easiest way to handle this is to just branch on the network, since
105− // mainnet and Ropsten have obviously passed FORK_BLKNUM. This is somewhat
106− // awkward when dealing with offline transactions, since we might want to
107− // test them on a local network as well.
108− //
109− // The best thing to do is probably to add an 'advanced' tab to offline
110− // transaction generation where one can disable the defaulted-on EIP-155
111− // settings in this case. This is pretty low-priority, but is a
112− // comprehensive solution.
113− //
114− // See:
115− //
116− // See https://github.com/LedgerHQ/ledgerjs/issues/43#issuecomment-366984725
117− //
118− // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
116+ const utx: SignableTx = Object.assign(txn, txParams);
117+
118+ // TODO: Ropsten will sunset Q4 2022, need to replace w/ support for Goerli
119+ const chain =
120+ networkType === NETWORK_TYPES.ROPSTEN ? Chain.Ropsten : Chain.Mainnet;
119121
120− const eip155Params = {
121− r: '0x00',
122− s: '0x00',
123− v: chainId,
122+ const txConfig: TxOptions = {
123+ freeze: false,
124+ common: new Common({
125+ chain,
126+ hardfork: Hardfork.Merge,
127+ })
124128 };
125129
126− const defaultEip155Networks = [
127− NETWORK_TYPES.MAINNET,
128− NETWORK_TYPES.ROPSTEN,
129− NETWORK_TYPES.OFFLINE,
130− ];
131−
132− const needEip155Params =
133− walletType === WALLET_TYPES.LEDGER &&
134− defaultEip155Networks.includes(networkType);
135−
136− const signingParams = needEip155Params
137− ? Object.assign(txParams, eip155Params)
138− : txParams;
139−
140− const utx: SignableTx = Object.assign(txn, signingParams);
141−
142− const txConfig: any = { freeze: false };
143− // we must specify the chain *either* in the Common object,
144− // *or* eip155 style, but never both!
145− //
146− if (!needEip155Params) {
147− const chain =
148− networkType === NETWORK_TYPES.ROPSTEN ? Chain.Ropsten : Chain.Mainnet;
149− txConfig.common = new Common({
150− chain: chain,
151− hardfork: Hardfork.MuirGlacier,
152− });
153− }
154−
155− let stx: Transaction | FakeSignedTx = Transaction.fromTxData(utx, txConfig);
130+ let stx = EIP1559Transaction.fromTxData(txParams, txConfig)
156131
157− //TODO should try-catch and display error message to user,
158− // ie ledger's "pls enable contract data"
159− // needs to maybe happen at call-site though
160− if (walletType === WALLET_TYPES.LEDGER) {
161− await ledgerSignTransaction(stx, walletHdPath);
162− } else if (walletType === WALLET_TYPES.TREZOR) {
163− await trezorSignTransaction(stx, walletHdPath);
164− } else if (walletType === WALLET_TYPES.METAMASK) {
132+ if (walletType === WALLET_TYPES.METAMASK) {
165133 return metamaskSignTransaction(utx);
166134 } else if (walletType === WALLET_TYPES.WALLET_CONNECT) {
167135 if (!(txnSender && txnSigner)) {
@@ -184,11 +152,12 @@ const signTransaction = async ({
184152
185153const sendSignedTransaction = (
186154 web3: Web3,
187− stx: Transaction | FakeSignedTx,
155+ // TODO: do we still need legacy TX type? elsewhere too
156+ stx: Transaction | EIP1559Transaction | FakeSignedTx,
188157 doubtNonceError: boolean
189158): Promise<string> => {
190159 // if we couldn't sign it, we depend on the given sender function
191− if (!(stx instanceof Transaction)) {
160+ if (!(stx instanceof Transaction || stx instanceof EIP1559Transaction)) { // TODO
192161 if (doubtNonceError) {
193162 console.log('why doubting nonce error? tank unavailable without rawtx.');
194163 }
@@ -252,7 +221,7 @@ const waitForTransactionConfirm = (web3: Web3, txHash: string) => {
252221// returns a Promise that resolves when all stxs have been sent & confirmed
253222const sendAndAwaitAll = (
254223 web3: Web3,
255− stxs: Transaction[] | FakeSignedTx[],
224+ stxs: Transaction[] | EIP1559Transaction[] | FakeSignedTx[],
256225 doubtNonceError: boolean
257226) => {
258227 return Promise.all(
@@ -265,7 +234,7 @@ const sendAndAwaitAll = (
265234
266235const sendAndAwaitAllSerial = (
267236 web3: Web3,
268− stxs: Array<Transaction> | Array<FakeSignedTx>,
237+ stxs: Array<Transaction> | Array<EIP1559Transaction> | Array<FakeSignedTx>,
269238 doubtNonceError: boolean
270239) => {
271240 // tsc complains that stxs.reduce() is not callable
@@ -282,7 +251,7 @@ const sendAndAwaitAllSerial = (
282251
283252const sendTransactionsAndAwaitConfirm = async (
284253 web3: Web3,
285− signedTxs: Array<Transaction> | Array<FakeSignedTx>,
254+ signedTxs: Array<Transaction> | Array<EIP1559Transaction> | Array<FakeSignedTx>,
286255 usedTank: boolean
287256) =>
288257 Promise.all(signedTxs.map(tx => sendSignedTransaction(web3, tx, usedTank)));