1import Common, { Chain, Hardfork } from '@ethereumjs/common';
2import { JsonTx, Transaction } from '@ethereumjs/tx';
3import { ITxData } from '@walletconnect/types';
4import { toHex } from 'web3-utils';
5import { safeFromWei, safeToWei } from './lib';
6import retry from 'async-retry';
8import { NETWORK_TYPES } from './network';
9import { ledgerSignTransaction } from './ledger';
10import { trezorSignTransaction } from './trezor';
11import { walletConnectSignTransaction } from './WalletConnect';
12import { metamaskSignTransaction } from './metamask';
13import { addHexPrefix } from './utils/address';
14import { CHECK_BLOCK_EVERY_MS, WALLET_TYPES } from './constants';
15import { patp2dec } from './patp2dec';
16import Web3 from 'web3';
18const RETRY_OPTIONS = {
21 minTimeout: CHECK_BLOCK_EVERY_MS,
25// catch-all type: Metamask passes an obj shaped like ITxData, WC passes JsonTx + from
26export type FakeSignableTx =
28 | (JsonTx & { from: string; to: string; gas: string });
30type TxSender = (txn: FakeSignableTx, web3: Web3) => Promise<string>; // Metamask requires Web3 (txhash)
33 serialize: () => string;
36type FakeSignedTx = SignedTx & {
41const FakeSignResult = (txn: FakeSignableTx, send: TxSender): FakeSignedTx => {
45 return '???'; //NOTE update tank.js when changing this!
51const signTransaction = async ({
59 gasPrice, // string, in gwei
60 gasLimit, // string | number
61 txnSigner, // optionally inject a transaction signing function,
62 txnSender, // and a sending function, for wallets that need these passed in.
64 // TODO: require these in txn object
66 chainId = toHex(chainId);
67 gasPrice = toHex(safeToWei(gasPrice, 'gwei'));
68 gasLimit = toHex(gasLimit);
69 const from = wallet.address;
71 const txParams = { nonce, chainId, gasPrice, gasLimit, from };
75 // Ledger does not seem to handle EIP-155 automatically. When using a Ledger,
76 // if the block number is at least FORK_BLKNUM = 2675000, one needs to
77 // pre-set the ECDSA signature parameters with r = 0, s = 0, and v = chainId
80 // The easiest way to handle this is to just branch on the network, since
81 // mainnet and Ropsten have obviously passed FORK_BLKNUM. This is somewhat
82 // awkward when dealing with offline transactions, since we might want to
83 // test them on a local network as well.
85 // The best thing to do is probably to add an 'advanced' tab to offline
86 // transaction generation where one can disable the defaulted-on EIP-155
87 // settings in this case. This is pretty low-priority, but is a
88 // comprehensive solution.
92 // See https://github.com/LedgerHQ/ledgerjs/issues/43#issuecomment-366984725
94 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
96 const eip155Params = {
102 const defaultEip155Networks = [
103 NETWORK_TYPES.MAINNET,
104 NETWORK_TYPES.ROPSTEN,
105 NETWORK_TYPES.OFFLINE,
108 const needEip155Params =
109 walletType === WALLET_TYPES.LEDGER &&
110 defaultEip155Networks.includes(networkType);
112 const signingParams = needEip155Params
113 ? Object.assign(txParams, eip155Params)
116 const utx = Object.assign(txn, signingParams);
118 const txConfig: any = { freeze: false };
119 // we must specify the chain *either* in the Common object,
120 // *or* eip155 style, but never both!
122 if (!needEip155Params) {
124 networkType === NETWORK_TYPES.ROPSTEN ? Chain.Ropsten : Chain.Mainnet;
125 txConfig.common = new Common({
127 hardfork: Hardfork.MuirGlacier,
131 let stx = Transaction.fromTxData(utx, txConfig);
133 //TODO should try-catch and display error message to user,
134 // ie ledger's "pls enable contract data"
135 // needs to maybe happen at call-site though
136 if (walletType === WALLET_TYPES.LEDGER) {
137 await ledgerSignTransaction(stx, walletHdPath);
138 } else if (walletType === WALLET_TYPES.TREZOR) {
139 await trezorSignTransaction(stx, walletHdPath);
140 } else if (walletType === WALLET_TYPES.METAMASK) {
141 return metamaskSignTransaction(utx, wallet.address);
142 } else if (walletType === WALLET_TYPES.WALLET_CONNECT) {
143 stx = await walletConnectSignTransaction({
150 stx = stx.sign(wallet.privateKey);
156const sendSignedTransaction = (
158 stx: Transaction | FakeSignedTx,
159 doubtNonceError: boolean
160): Promise<string> => {
161 // if we couldn't sign it, we depend on the given sender function
162 if (!(stx instanceof Transaction)) {
163 if (doubtNonceError) {
164 console.log('why doubting nonce error? tank unavailable without rawtx.');
167 throw new Error('no sign+sending function available');
169 return stx.send(stx.txn, web3);
172 let rawTx: string = hexify(stx.serialize());
173 let eventEmitter = web3.eth.sendSignedTransaction(rawTx);
174 return new Promise(async (resolve, reject) => {
176 .on('transactionHash', (hash: string) => {
179 .on('error', err => {
180 // if there's a nonce error, but we used the gas tank, it's likely
181 // that it's because the tank already submitted our transaction.
182 // we just wait for first confirmation here.
183 const message = typeof err === 'string' ? err : err.message || '';
185 message.includes('known transaction') ||
186 message.includes('already known');
188 message.includes("the tx doesn't have the correct nonce.") ||
189 message.includes('nonce too low');
190 if (rawTx && (isKnownError || (doubtNonceError && isNonceError))) {
192 'tx send error likely from gas tank submission, ignoring:',
195 const txHash = web3.utils.keccak256(rawTx);
199 const wrappedErr = err instanceof Error ? err : new Error(message);
206// returns a Promise<void>, throwing on tx failure
207const waitForTransactionConfirm = (web3, txHash) => {
208 return retry(async (bail, n) => {
209 const receipt = await web3.eth.getTransactionReceipt(txHash);
210 const confirmed = receipt !== null;
212 throw new Error('Transaction not confirmed.');
215 const success = receipt.status === true;
217 return bail(new Error('Transaction failed.'));
223// returns a Promise that resolves when all stxs have been sent & confirmed
224const sendAndAwaitAll = (web3, stxs, doubtNonceError) => {
226 stxs.map(async tx => {
227 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
228 return await waitForTransactionConfirm(web3, txHash);
233const sendAndAwaitAllSerial = (web3, stxs, doubtNonceError) => {
236 promise.then(async (receipts = []) => {
237 const txHash = await sendSignedTransaction(web3, stx, doubtNonceError);
238 return [...receipts, await waitForTransactionConfirm(web3, txHash)];
244const sendTransactionsAndAwaitConfirm = async (web3, signedTxs, usedTank) =>
245 Promise.all(signedTxs.map(tx => sendSignedTransaction(web3, tx, usedTank)));
247const hexify = val => addHexPrefix(val.toString('hex'));
249const renderSignedTx = stx => ({
250 messageHash: hexify(stx.hash()),
254 rawTransaction: hexify(stx.serialize()),
257const getTxnInfo = async (web3, addr) => {
258 let nonce = await web3.eth.getTransactionCount(addr);
259 let chainId = await web3.eth.net.getId();
260 let gasPrice = await web3.eth.getGasPrice();
265 gasPrice: safeFromWei(gasPrice, 'gwei'),
269// TODO(shrugs): deprecate, unifiy with other callsites
270const canDecodePatp = p => {
283 sendSignedTransaction,
284 waitForTransactionConfirm,
285 sendTransactionsAndAwaitConfirm,
287 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