on 4b0ca21 help sign in
bridge/src/lib/txn.ts
246 lines 7.5 kB history raw
1import Common, { Chain, Hardfork } from '@ethereumjs/common';
2import { Transaction } from '@ethereumjs/tx';
3import { toHex } from 'web3-utils';
4import { safeFromWei, safeToWei } from './lib';
5import retry from 'async-retry';
7import { NETWORK_TYPES } from './network';
8import { ledgerSignTransaction } from './ledger';
9import { trezorSignTransaction } from './trezor';
10import { walletConnectSignTransaction } from './WalletConnect';
11import { metamaskSignTransaction, FakeMetamaskTransaction } from './metamask';
12import { addHexPrefix } from './utils/address';
13import { CHECK_BLOCK_EVERY_MS, WALLET_TYPES } from './constants';
14import { patp2dec } from './patp2dec';
16const RETRY_OPTIONS = {
17 retries: 99999,
18 factor: 1,
19 minTimeout: CHECK_BLOCK_EVERY_MS,
20 randomize: false,
21};
23const signTransaction = async ({
24 wallet,
25 walletType,
26 walletHdPath,
27 networkType,
28 txn,
29 nonce, // number
30 chainId, // number
31 gasPrice, // string, in gwei
32 gasLimit, // string | number
33 txnSigner, // optionally inject a transaction signing function
34}) => {
35 // TODO: require these in txn object
36 nonce = toHex(nonce);
37 chainId = toHex(chainId);
38 gasPrice = toHex(safeToWei(gasPrice, 'gwei'));
39 gasLimit = toHex(gasLimit);
40 const from = wallet.address;
42 const txParams = { nonce, chainId, gasPrice, gasLimit, from };
44 // NB (jtobin)
45 //
46 // Ledger does not seem to handle EIP-155 automatically. When using a Ledger,
47 // if the block number is at least FORK_BLKNUM = 2675000, one needs to
48 // pre-set the ECDSA signature parameters with r = 0, s = 0, and v = chainId
49 // prior to signing.
50 //
51 // The easiest way to handle this is to just branch on the network, since
52 // mainnet and Ropsten have obviously passed FORK_BLKNUM. This is somewhat
53 // awkward when dealing with offline transactions, since we might want to
54 // test them on a local network as well.
55 //
56 // The best thing to do is probably to add an 'advanced' tab to offline
57 // transaction generation where one can disable the defaulted-on EIP-155
58 // settings in this case. This is pretty low-priority, but is a
59 // comprehensive solution.
60 //
61 // See:
62 //
63 // See https://github.com/LedgerHQ/ledgerjs/issues/43#issuecomment-366984725
64 //
65 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
67 const eip155Params = {
68 r: '0x00',
69 s: '0x00',
70 v: chainId,
71 };
73 const defaultEip155Networks = [
74 NETWORK_TYPES.MAINNET,
75 NETWORK_TYPES.ROPSTEN,
76 NETWORK_TYPES.OFFLINE,
77 ];
79 const needEip155Params =
80 walletType === WALLET_TYPES.LEDGER &&
81 defaultEip155Networks.includes(networkType);
83 const signingParams = needEip155Params
84 ? Object.assign(txParams, eip155Params)
85 : txParams;
87 const utx = Object.assign(txn, signingParams);
89 const chain =
90 networkType === NETWORK_TYPES.ROPSTEN ? Chain.Ropsten : Chain.Mainnet;
91 const common = new Common({
92 chain: chain,
93 hardfork: Hardfork.MuirGlacier,
94 });
95 let stx = Transaction.fromTxData(utx, { common, freeze: false });
97 //TODO should try-catch and display error message to user,
98 // ie ledger's "pls enable contract data"
99 // needs to maybe happen at call-site though
100 if (walletType === WALLET_TYPES.LEDGER) {
101 await ledgerSignTransaction(stx, walletHdPath);
102 } else if (walletType === WALLET_TYPES.TREZOR) {
103 await trezorSignTransaction(stx, walletHdPath);
104 } else if (walletType === WALLET_TYPES.METAMASK) {
105 return metamaskSignTransaction(utx, wallet.address);
106 } else if (walletType === WALLET_TYPES.WALLET_CONNECT) {
107 stx = await walletConnectSignTransaction({
108 from,
109 txn: stx,
110 txnSigner,
111 });
112 } else {
113 stx = stx.sign(wallet.privateKey);
114 }
116 return stx;
117};
119const sendSignedTransaction = (web3, stx, doubtNonceError) => {
120 // Handle fake metamask transaction
121 let eventEmitter;
122 let rawTx;
123 if (stx instanceof FakeMetamaskTransaction) {
124 eventEmitter = web3.eth.sendTransaction(stx.txnData);
125 } else {
126 rawTx = hexify(stx.serialize());
127 eventEmitter = web3.eth.sendSignedTransaction(rawTx);
128 }
129 return new Promise(async (resolve, reject) => {
130 eventEmitter
131 .on('transactionHash', hash => {
132 resolve(hash);
133 })
134 .on('error', err => {
135 // if there's a nonce error, but we used the gas tank, it's likely
136 // that it's because the tank already submitted our transaction.
137 // we just wait for first confirmation here.
138 const message = typeof err === 'string' ? err : err.message || '';
139 const isKnownError =
140 message.includes('known transaction') ||
141 message.includes('already known');
142 const isNonceError =
143 message.includes("the tx doesn't have the correct nonce.") ||
144 message.includes('nonce too low');
145 if (rawTx && (isKnownError || (doubtNonceError && isNonceError))) {
146 console.log(
147 'tx send error likely from gas tank submission, ignoring:',
148 message
149 );
150 const txHash = web3.utils.keccak256(rawTx);
151 resolve(txHash);
152 } else {
153 console.error(err);
154 const wrappedErr = err instanceof Error ? err : new Error(message);
155 reject(wrappedErr);
156 }
157 });
158 });
159};
161// returns a Promise<void>, throwing on tx failure
162const waitForTransactionConfirm = (web3, txHash) => {
163 return retry(async (bail, n) => {
164 const receipt = await web3.eth.getTransactionReceipt(txHash);
165 const confirmed = receipt !== null;
166 if (!confirmed) {
167 throw new Error('Transaction not confirmed.');
168 }
170 const success = receipt.status === true;
171 if (!success) {
172 return bail(new Error('Transaction failed.'));
173 }
174 return receipt;
175 }, RETRY_OPTIONS);
176};
178// returns a Promise that resolves when all stxs have been sent & confirmed
179const sendAndAwaitAll = (web3, stxs, doubtNonceError) => {
180 return Promise.all(
181 stxs.map(async tx => {
182 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
183 return await waitForTransactionConfirm(web3, txHash);
184 })
185 );
186};
188const sendAndAwaitAllSerial = (web3, stxs, doubtNonceError) => {
189 return stxs.reduce(
190 (promise, stx) =>
191 promise.then(async (receipts = []) => {
192 const txHash = await sendSignedTransaction(web3, stx, doubtNonceError);
193 return [...receipts, await waitForTransactionConfirm(web3, txHash)];
194 }),
195 Promise.resolve()
196 );
197};
199const sendTransactionsAndAwaitConfirm = async (web3, signedTxs, usedTank) =>
200 Promise.all(signedTxs.map(tx => sendSignedTransaction(web3, tx, usedTank)));
202const hexify = val => addHexPrefix(val.toString('hex'));
204const renderSignedTx = stx => ({
205 messageHash: hexify(stx.hash()),
206 v: hexify(stx.v),
207 s: hexify(stx.s),
208 r: hexify(stx.r),
209 rawTransaction: hexify(stx.serialize()),
210});
212const getTxnInfo = async (web3, addr) => {
213 let nonce = await web3.eth.getTransactionCount(addr);
214 let chainId = await web3.eth.net.getId();
215 let gasPrice = await web3.eth.getGasPrice();
217 return {
218 nonce: nonce,
219 chainId: chainId,
220 gasPrice: safeFromWei(gasPrice, 'gwei'),
221 };
222};
224// TODO(shrugs): deprecate, unifiy with other callsites
225const canDecodePatp = p => {
226 try {
227 patp2dec(p);
228 return true;
229 } catch (_) {
230 return false;
231 }
232};
234export {
235 RETRY_OPTIONS,
236 signTransaction,
237 sendSignedTransaction,
238 waitForTransactionConfirm,
239 sendTransactionsAndAwaitConfirm,
240 sendAndAwaitAll,
241 sendAndAwaitAllSerial,
242 getTxnInfo,
243 hexify,
244 renderSignedTx,
245 canDecodePatp,
246};