on 5eceb4e help sign in
bridge/src/lib/txn.js
230 lines 6.9 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 =
124 message.includes('known transaction') ||
125 message.includes('already known');
126 const isNonceError =
127 message.includes("the tx doesn't have the correct nonce.") ||
128 message.includes('nonce too low');
129 if (rawTx && (isKnownError || (doubtNonceError && isNonceError))) {
130 console.log(
131 'tx send error likely from gas tank submission, ignoring:',
132 message
133 );
134 const txHash = web3.utils.keccak256(rawTx);
135 resolve(txHash);
136 } else {
137 console.error(err);
138 const wrappedErr = err instanceof Error ? err : new Error(message);
139 reject(wrappedErr);
140 }
141 });
142 });
143};
145// returns a Promise<void>, throwing on tx failure
146const waitForTransactionConfirm = (web3, txHash) => {
147 return retry(async (bail, n) => {
148 const receipt = await web3.eth.getTransactionReceipt(txHash);
149 const confirmed = receipt !== null;
150 if (!confirmed) {
151 throw new Error('Transaction not confirmed.');
152 }
154 const success = receipt.status === true;
155 if (!success) {
156 return bail(new Error('Transaction failed.'));
157 }
158 return receipt;
159 }, RETRY_OPTIONS);
160};
162// returns a Promise that resolves when all stxs have been sent & confirmed
163const sendAndAwaitAll = (web3, stxs, doubtNonceError) => {
164 return Promise.all(
165 stxs.map(async tx => {
166 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
167 return await waitForTransactionConfirm(web3, txHash);
168 })
169 );
170};
172const sendAndAwaitAllSerial = (web3, stxs, doubtNonceError) => {
173 return stxs.reduce(
174 (promise, stx) =>
175 promise.then(async (receipts = []) => {
176 const txHash = await sendSignedTransaction(web3, stx, doubtNonceError);
177 return [...receipts, await waitForTransactionConfirm(web3, txHash)];
178 }),
179 Promise.resolve()
180 );
181};
183const sendTransactionsAndAwaitConfirm = async (web3, signedTxs, usedTank) =>
184 Promise.all(signedTxs.map(tx => sendSignedTransaction(web3, tx, usedTank)));
186const hexify = val => addHexPrefix(val.toString('hex'));
188const renderSignedTx = stx => ({
189 messageHash: hexify(stx.hash()),
190 v: hexify(stx.v),
191 s: hexify(stx.s),
192 r: hexify(stx.r),
193 rawTransaction: hexify(stx.serialize()),
194});
196const getTxnInfo = async (web3, addr) => {
197 let nonce = await web3.eth.getTransactionCount(addr);
198 let chainId = await web3.eth.net.getId();
199 let gasPrice = await web3.eth.getGasPrice();
201 return {
202 nonce: nonce,
203 chainId: chainId,
204 gasPrice: safeFromWei(gasPrice, 'gwei'),
205 };
206};
208// TODO(shrugs): deprecate, unifiy with other callsites
209const canDecodePatp = p => {
210 try {
211 patp2dec(p);
212 return true;
213 } catch (_) {
214 return false;
215 }
216};
218export {
219 RETRY_OPTIONS,
220 signTransaction,
221 sendSignedTransaction,
222 waitForTransactionConfirm,
223 sendTransactionsAndAwaitConfirm,
224 sendAndAwaitAll,
225 sendAndAwaitAllSerial,
226 getTxnInfo,
227 hexify,
228 renderSignedTx,
229 canDecodePatp,
230};