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 = {
17 minTimeout: CHECK_BLOCK_EVERY_MS,
21const signTransaction = async ({
29 gasPrice, // string, in gwei
30 gasLimit, // string | number
32 // TODO: require these in txn object
34 chainId = toHex(chainId);
35 gasPrice = toHex(safeToWei(gasPrice, 'gwei'));
36 gasLimit = toHex(gasLimit);
38 const txParams = { nonce, chainId, gasPrice, gasLimit };
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
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.
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.
59 // See https://github.com/LedgerHQ/ledgerjs/issues/43#issuecomment-366984725
61 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
63 const eip155Params = {
69 const defaultEip155Networks = [
70 NETWORK_TYPES.MAINNET,
71 NETWORK_TYPES.ROPSTEN,
72 NETWORK_TYPES.OFFLINE,
75 const needEip155Params =
76 walletType === WALLET_TYPES.LEDGER &&
77 defaultEip155Networks.includes(networkType);
79 const signingParams = needEip155Params
80 ? Object.assign(txParams, eip155Params)
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);
97 stx.sign(wallet.privateKey);
103const sendSignedTransaction = (web3, stx, doubtNonceError) => {
104 // Handle fake metamask transaction
107 if (stx instanceof FakeMetamaskTransaction) {
108 eventEmitter = web3.eth.sendTransaction(stx.txnData);
110 rawTx = hexify(stx.serialize());
111 eventEmitter = web3.eth.sendSignedTransaction(rawTx);
113 return new Promise(async (resolve, reject) => {
115 .on('transactionHash', hash => {
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 || '';
124 message.includes('known transaction') ||
125 message.includes('already known');
127 message.includes("the tx doesn't have the correct nonce.") ||
128 message.includes('nonce too low');
129 if (rawTx && (isKnownError || (doubtNonceError && isNonceError))) {
131 'tx send error likely from gas tank submission, ignoring:',
134 const txHash = web3.utils.keccak256(rawTx);
138 const wrappedErr = err instanceof Error ? err : new Error(message);
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;
151 throw new Error('Transaction not confirmed.');
154 const success = receipt.status === true;
156 return bail(new Error('Transaction failed.'));
162// returns a Promise that resolves when all stxs have been sent & confirmed
163const sendAndAwaitAll = (web3, stxs, doubtNonceError) => {
165 stxs.map(async tx => {
166 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
167 return await waitForTransactionConfirm(web3, txHash);
172const sendAndAwaitAllSerial = (web3, stxs, doubtNonceError) => {
175 promise.then(async (receipts = []) => {
176 const txHash = await sendSignedTransaction(web3, stx, doubtNonceError);
177 return [...receipts, await waitForTransactionConfirm(web3, txHash)];
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()),
193 rawTransaction: hexify(stx.serialize()),
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();
204 gasPrice: safeFromWei(gasPrice, 'gwei'),
208// TODO(shrugs): deprecate, unifiy with other callsites
209const canDecodePatp = p => {
221 sendSignedTransaction,
222 waitForTransactionConfirm,
223 sendTransactionsAndAwaitConfirm,
225 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