on 2fe1d2f help sign in
bridge/src/lib/txn.js
230 lines 6.5 kB history raw
1import * as ob from 'urbit-ob';
2import { Just } from 'folktale/maybe';
3import Tx from 'ethereumjs-tx';
4import { toWei, fromWei, toHex } from 'web3-utils';
5import * as retry from 'async-retry';
7import { NETWORK_TYPES } from './network';
8import { ledgerSignTransaction } from './ledger';
9import { trezorSignTransaction } from './trezor';
10import { WALLET_TYPES, addHexPrefix } from './wallet';
12const CHECK_BLOCK_EVERY_MS =
13 process.env.NODE_ENV === 'development' ? 1000 : 5000;
15const RETRY_OPTIONS = {
16 retries: 99999,
17 factor: 1,
18 minTimeout: CHECK_BLOCK_EVERY_MS,
19 randomize: false,
20};
22const TXN_PURPOSE = {
23 SET_MANAGEMENT_PROXY: Symbol('SET_MANAGEMENT_PROXY'),
24 SET_TRANSFER_PROXY: Symbol('SET_TRANSFER_PROXY'),
25 SET_SPAWN_PROXY: Symbol('SET_SPAWN_PROXY'),
26 CREATE_GALAXY: Symbol('CREATE_GALAXY'),
27 ISSUE_CHILD: Symbol('ISSUE_CHILD'),
28 SET_KEYS: Symbol('SET_KEYS'),
29 TRANSFER: Symbol('TRANSFER'),
30 CANCEL_TRANSFER: Symbol('CANCEL_TRANSFER'),
31};
33const renderTxnPurpose = purpose =>
34 purpose === TXN_PURPOSE.SET_MANAGEMENT_PROXY
35 ? 'set this management proxy'
36 : purpose === TXN_PURPOSE.SET_SPAWN_PROXY
37 ? 'set this spawn proxy'
38 : purpose === TXN_PURPOSE.SET_TRANSFER_PROXY
39 ? 'set this transfer proxy'
40 : purpose === TXN_PURPOSE.CREATE_GALAXY
41 ? 'create this galaxy'
42 : purpose === TXN_PURPOSE.ISSUE_CHILD
43 ? 'issue this point'
44 : purpose === TXN_PURPOSE.SET_KEYS
45 ? 'set these network keys'
46 : purpose === TXN_PURPOSE.TRANSFER
47 ? 'transfer this point'
48 : purpose === TXN_PURPOSE.CANCEL_TRANSFER
49 ? 'cancel this transfer'
50 : 'perform this transaction';
52const signTransaction = async config => {
53 let {
54 wallet,
55 walletType,
56 walletHdPath,
57 networkType,
58 txn,
59 setStx,
60 nonce,
61 chainId,
62 gasPrice,
63 gasLimit,
64 } = config;
66 nonce = toHex(nonce);
67 chainId = toHex(chainId);
68 gasPrice = toHex(toWei(gasPrice, 'gwei'));
69 gasLimit = toHex(gasLimit);
71 const txParams = { nonce, chainId, gasPrice, gasLimit };
73 // NB (jtobin)
74 //
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
78 // prior to signing.
79 //
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.
84 //
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.
89 //
90 // See:
91 //
92 // See https://github.com/LedgerHQ/ledgerjs/issues/43#issuecomment-366984725
93 //
94 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
96 const eip155Params = {
97 r: '0x00',
98 s: '0x00',
99 v: chainId,
100 };
102 const defaultEip155Networks = [
103 NETWORK_TYPES.MAINNET,
104 NETWORK_TYPES.ROPSTEN,
105 NETWORK_TYPES.OFFLINE,
106 ];
108 const needEip155Params =
109 walletType === WALLET_TYPES.LEDGER &&
110 defaultEip155Networks.includes(networkType);
112 const signingParams = needEip155Params
113 ? Object.assign(txParams, eip155Params)
114 : txParams;
116 const utx = Object.assign(txn, signingParams);
118 const stx = new Tx(utx);
120 if (walletType === WALLET_TYPES.LEDGER) {
121 await ledgerSignTransaction(stx, walletHdPath);
122 } else if (walletType === WALLET_TYPES.TREZOR) {
123 await trezorSignTransaction(stx, walletHdPath);
124 } else {
125 stx.sign(wallet.privateKey);
126 }
128 setStx(Just(stx));
129 return stx;
130};
132const sendSignedTransaction = (web3, stx, doubtNonceError) => {
133 const rawTx = hexify(stx.serialize());
135 return new Promise(async (resolve, reject) => {
136 web3.eth
137 .sendSignedTransaction(rawTx)
138 .on('transactionHash', hash => {
139 resolve(hash);
140 })
141 .on('error', err => {
142 // if there's a nonce error, but we used the gas tank, it's likely
143 // that it's because the tank already submitted our transaction.
144 // we just wait for first confirmation here.
145 console.error(err);
146 const isKnownError = (err.message || '').includes(
147 'known transaction: '
148 );
149 const isNonceError = (err.message || '').includes(
150 "the tx doesn't have the correct nonce."
151 );
152 if (isKnownError || (doubtNonceError && isNonceError)) {
153 console.log(
154 'tx send error likely from gas tank submission, ignoring'
155 );
156 const txHash = web3.utils.keccak256(rawTx);
157 resolve(txHash);
158 } else {
159 reject(err.message || 'Transaction sending failed!');
160 }
161 });
162 });
163};
165// returns a Promise<bool>, where the bool indicates tx success/failure
166const waitForTransactionConfirm = (web3, txHash) => {
167 return retry(async (bail, n) => {
168 const receipt = await web3.eth.getTransactionReceipt(txHash);
169 let confirmed = receipt !== null;
170 if (confirmed) return receipt.status === true;
171 else throw new Error('retrying');
172 }, RETRY_OPTIONS);
173};
175// returns a Promise that resolves when all stxs have been sent & confirmed
176const sendAndAwaitAll = (web3, stxs, doubtNonceError) => {
177 return Promise.all(
178 stxs.map(async tx => {
179 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
180 await waitForTransactionConfirm(web3, txHash);
181 })
182 );
183};
185const hexify = val => addHexPrefix(val.toString('hex'));
187const renderSignedTx = stx => ({
188 messageHash: hexify(stx.hash()),
189 v: hexify(stx.v),
190 s: hexify(stx.s),
191 r: hexify(stx.r),
192 rawTransaction: hexify(stx.serialize()),
193});
195const getTxnInfo = async (web3, addr) => {
196 let nonce = await web3.eth.getTransactionCount(addr);
197 let chainId = await web3.eth.net.getId();
198 let gasPrice = await web3.eth.getGasPrice();
199 return {
200 nonce: nonce,
201 chainId: chainId,
202 gasPrice: fromWei(gasPrice, 'gwei'),
203 };
204};
206const canDecodePatp = p => {
207 try {
208 ob.patp2dec(p);
209 return true;
210 } catch (_) {
211 return false;
212 }
213};
215export {
216 RETRY_OPTIONS,
217 signTransaction,
218 sendSignedTransaction,
219 waitForTransactionConfirm,
220 sendAndAwaitAll,
221 TXN_PURPOSE,
222 getTxnInfo,
223 renderTxnPurpose,
224 hexify,
225 renderSignedTx,
226 toHex,
227 toWei,
228 fromWei,
229 canDecodePatp,
230};