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(stx, wallet.address);
97 stx.sign(wallet.privateKey);
103const sendSignedTransaction = (web3, stx, doubtNonceError) => {
104 // Handle fake metamask transaction
105 if (stx instanceof FakeMetamaskTransaction) {
106 const { ethereum } = window;
108 method: 'eth_sendTransaction',
109 params: [stx.txnData],
110 from: stx.txnData.from,
112 return new Promise((resolve, reject) =>
113 ethereum.sendAsync(sendTxs, (err, data) =>
114 err ? reject(err) : resolve(data.result)
118 const rawTx = hexify(stx.serialize());
120 return new Promise(async (resolve, reject) => {
122 .sendSignedTransaction(rawTx)
123 .on('transactionHash', hash => {
126 .on('error', err => {
127 // if there's a nonce error, but we used the gas tank, it's likely
128 // that it's because the tank already submitted our transaction.
129 // we just wait for first confirmation here.
130 const message = typeof err === 'string' ? err : err.message || '';
131 const isKnownError = message.includes('known transaction: ');
133 message.includes("the tx doesn't have the correct nonce.") ||
134 message.includes('nonce too low');
135 if (isKnownError || (doubtNonceError && isNonceError)) {
137 'tx send error likely from gas tank submission, ignoring:',
140 const txHash = web3.utils.keccak256(rawTx);
144 reject(err.message || 'Transaction sending failed!');
150// returns a Promise<void>, throwing on tx failure
151const waitForTransactionConfirm = (web3, txHash) => {
152 return retry(async (bail, n) => {
153 const receipt = await web3.eth.getTransactionReceipt(txHash);
154 const confirmed = receipt !== null;
156 throw new Error('Transaction not confirmed.');
159 const success = receipt.status === true;
161 return bail(new Error('Transaction failed.'));
166// returns a Promise that resolves when all stxs have been sent & confirmed
167const sendAndAwaitAll = (web3, stxs, doubtNonceError) => {
169 stxs.map(async tx => {
170 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
171 await waitForTransactionConfirm(web3, txHash);
176const sendAndAwaitAllSerial = (web3, stxs, doubtNonceError) => {
179 promise.then(async () => {
180 const txHash = await sendSignedTransaction(web3, stx, doubtNonceError);
181 await waitForTransactionConfirm(web3, txHash);
187const sendTransactionsAndAwaitConfirm = async (web3, signedTxs, usedTank) =>
188 Promise.all(signedTxs.map(tx => sendSignedTransaction(web3, tx, usedTank)));
190const hexify = val => addHexPrefix(val.toString('hex'));
192const renderSignedTx = stx => ({
193 messageHash: hexify(stx.hash()),
197 rawTransaction: hexify(stx.serialize()),
200const getTxnInfo = async (web3, addr) => {
201 let nonce = await web3.eth.getTransactionCount(addr);
202 let chainId = await web3.eth.net.getId();
203 let gasPrice = await web3.eth.getGasPrice();
208 gasPrice: safeFromWei(gasPrice, 'gwei'),
212// TODO(shrugs): deprecate, unifiy with other callsites
213const canDecodePatp = p => {
225 sendSignedTransaction,
226 waitForTransactionConfirm,
227 sendTransactionsAndAwaitConfirm,
229 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