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