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 = {
19 minTimeout: CHECK_BLOCK_EVERY_MS,
23const signTransaction = async ({
31 gasPrice, // string, in gwei
32 gasLimit, // string | number
33 txnSigner, // optionally inject a transaction signing function
35 // TODO: require these in txn object
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 };
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
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.
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.
63 // See https://github.com/LedgerHQ/ledgerjs/issues/43#issuecomment-366984725
65 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
67 const eip155Params = {
73 const defaultEip155Networks = [
74 NETWORK_TYPES.MAINNET,
75 NETWORK_TYPES.ROPSTEN,
76 NETWORK_TYPES.OFFLINE,
79 const needEip155Params =
80 walletType === WALLET_TYPES.LEDGER &&
81 defaultEip155Networks.includes(networkType);
83 const signingParams = needEip155Params
84 ? Object.assign(txParams, eip155Params)
87 const utx = Object.assign(txn, signingParams);
90 networkType === NETWORK_TYPES.ROPSTEN ? Chain.Ropsten : Chain.Mainnet;
91 const common = new Common({
93 hardfork: Hardfork.MuirGlacier,
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({
113 stx = stx.sign(wallet.privateKey);
119const sendSignedTransaction = (web3, stx, doubtNonceError) => {
120 // Handle fake metamask transaction
123 if (stx instanceof FakeMetamaskTransaction) {
124 eventEmitter = web3.eth.sendTransaction(stx.txnData);
126 rawTx = hexify(stx.serialize());
127 eventEmitter = web3.eth.sendSignedTransaction(rawTx);
129 return new Promise(async (resolve, reject) => {
131 .on('transactionHash', hash => {
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 || '';
140 message.includes('known transaction') ||
141 message.includes('already known');
143 message.includes("the tx doesn't have the correct nonce.") ||
144 message.includes('nonce too low');
145 if (rawTx && (isKnownError || (doubtNonceError && isNonceError))) {
147 'tx send error likely from gas tank submission, ignoring:',
150 const txHash = web3.utils.keccak256(rawTx);
154 const wrappedErr = err instanceof Error ? err : new Error(message);
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;
167 throw new Error('Transaction not confirmed.');
170 const success = receipt.status === true;
172 return bail(new Error('Transaction failed.'));
178// returns a Promise that resolves when all stxs have been sent & confirmed
179const sendAndAwaitAll = (web3, stxs, doubtNonceError) => {
181 stxs.map(async tx => {
182 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
183 return await waitForTransactionConfirm(web3, txHash);
188const sendAndAwaitAllSerial = (web3, stxs, doubtNonceError) => {
191 promise.then(async (receipts = []) => {
192 const txHash = await sendSignedTransaction(web3, stx, doubtNonceError);
193 return [...receipts, await waitForTransactionConfirm(web3, txHash)];
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()),
209 rawTransaction: hexify(stx.serialize()),
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();
220 gasPrice: safeFromWei(gasPrice, 'gwei'),
224// TODO(shrugs): deprecate, unifiy with other callsites
225const canDecodePatp = p => {
237 sendSignedTransaction,
238 waitForTransactionConfirm,
239 sendTransactionsAndAwaitConfirm,
241 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