on bc552c8 help sign in
bridge/src/lib/txn.js
250 lines 6.9 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';
6import { BRIDGE_ERROR } from './error';
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 TXN_PURPOSE = {
16 SET_MANAGEMENT_PROXY: Symbol('SET_MANAGEMENT_PROXY'),
17 SET_TRANSFER_PROXY: Symbol('SET_TRANSFER_PROXY'),
18 SET_SPAWN_PROXY: Symbol('SET_SPAWN_PROXY'),
19 CREATE_GALAXY: Symbol('CREATE_GALAXY'),
20 ISSUE_CHILD: Symbol('ISSUE_CHILD'),
21 SET_KEYS: Symbol('SET_KEYS'),
22 TRANSFER: Symbol('TRANSFER'),
23 CANCEL_TRANSFER: Symbol('CANCEL_TRANSFER'),
24};
26const renderTxnPurpose = purpose =>
27 purpose === TXN_PURPOSE.SET_MANAGEMENT_PROXY
28 ? 'set this management proxy'
29 : purpose === TXN_PURPOSE.SET_SPAWN_PROXY
30 ? 'set this spawn proxy'
31 : purpose === TXN_PURPOSE.SET_TRANSFER_PROXY
32 ? 'set this transfer proxy'
33 : purpose === TXN_PURPOSE.CREATE_GALAXY
34 ? 'create this galaxy'
35 : purpose === TXN_PURPOSE.ISSUE_CHILD
36 ? 'issue this point'
37 : purpose === TXN_PURPOSE.SET_KEYS
38 ? 'set these network keys'
39 : purpose === TXN_PURPOSE.TRANSFER
40 ? 'transfer this point'
41 : purpose === TXN_PURPOSE.CANCEL_TRANSFER
42 ? 'cancel this transfer'
43 : 'perform this transaction';
45const signTransaction = async config => {
46 let {
47 wallet,
48 walletType,
49 walletHdPath,
50 networkType,
51 txn,
52 setStx,
53 nonce,
54 chainId,
55 gasPrice,
56 gasLimit,
57 } = config;
59 nonce = toHex(nonce);
60 chainId = toHex(chainId);
61 gasPrice = toHex(toWei(gasPrice, 'gwei'));
62 gasLimit = toHex(gasLimit);
64 const txParams = { nonce, chainId, gasPrice, gasLimit };
66 // NB (jtobin)
67 //
68 // Ledger does not seem to handle EIP-155 automatically. When using a Ledger,
69 // if the block number is at least FORK_BLKNUM = 2675000, one needs to
70 // pre-set the ECDSA signature parameters with r = 0, s = 0, and v = chainId
71 // prior to signing.
72 //
73 // The easiest way to handle this is to just branch on the network, since
74 // mainnet and Ropsten have obviously passed FORK_BLKNUM. This is somewhat
75 // awkward when dealing with offline transactions, since we might want to
76 // test them on a local network as well.
77 //
78 // The best thing to do is probably to add an 'advanced' tab to offline
79 // transaction generation where one can disable the defaulted-on EIP-155
80 // settings in this case. This is pretty low-priority, but is a
81 // comprehensive solution.
82 //
83 // See:
84 //
85 // See https://github.com/LedgerHQ/ledgerjs/issues/43#issuecomment-366984725
86 //
87 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
89 const eip155Params = {
90 r: '0x00',
91 s: '0x00',
92 v: chainId,
93 };
95 const defaultEip155Networks = [
96 NETWORK_TYPES.MAINNET,
97 NETWORK_TYPES.ROPSTEN,
98 NETWORK_TYPES.OFFLINE,
99 ];
101 const needEip155Params =
102 walletType === WALLET_TYPES.LEDGER &&
103 defaultEip155Networks.includes(networkType);
105 const signingParams = needEip155Params
106 ? Object.assign(txParams, eip155Params)
107 : txParams;
109 const wal = wallet.matchWith({
110 Just: w => w.value,
111 Nothing: () => {
112 throw BRIDGE_ERROR.MISSING_WALLET;
113 },
114 });
116 const sec = wal.privateKey;
118 const utx = txn.matchWith({
119 Just: tx => Object.assign(tx.value, signingParams),
120 Nothing: () => {
121 throw BRIDGE_ERROR.MISSING_TXN;
122 },
123 });
125 const stx = new Tx(utx);
127 if (walletType === WALLET_TYPES.LEDGER) {
128 await ledgerSignTransaction(stx, walletHdPath);
129 } else if (walletType === WALLET_TYPES.TREZOR) {
130 await trezorSignTransaction(stx, walletHdPath);
131 } else {
132 stx.sign(sec);
133 }
135 setStx(Just(stx));
136 return stx;
137};
139const sendSignedTransaction = (web3, stx, doubtNonceError) => {
140 const txn = stx.matchWith({
141 Just: tx => tx.value,
142 Nothing: () => {
143 throw BRIDGE_ERROR.MISSING_TXN;
144 },
145 });
147 const rawTx = hexify(txn.serialize());
149 return new Promise(async (resolve, reject) => {
150 web3.eth
151 .sendSignedTransaction(rawTx)
152 .on('transactionHash', hash => {
153 resolve(hash);
154 })
155 .on('error', err => {
156 // if there's a nonce error, but we used the gas tank, it's likely
157 // that it's because the tank already submitted our transaction.
158 // we just wait for first confirmation here.
159 console.error(err);
160 const isKnownError = (err.message || '').includes(
161 'known transaction: '
162 );
163 const isNonceError = (err.message || '').includes(
164 "the tx doesn't have the correct nonce."
165 );
166 if (isKnownError || (doubtNonceError && isNonceError)) {
167 console.log(
168 'tx send error likely from gas tank submission, ignoring'
169 );
170 const txHash = web3.utils.keccak256(rawTx);
171 resolve(txHash);
172 } else {
173 reject(err.message || 'Transaction sending failed!');
174 }
175 });
176 });
177};
179// returns a Promise<bool>, where the bool indicates tx success/failure
180const waitForTransactionConfirm = (web3, txHash) => {
181 return new Promise((resolve, reject) => {
182 const checkForConfirm = async () => {
183 console.log('checking for confirm', txHash);
184 const receipt = await web3.eth.getTransactionReceipt(txHash);
185 console.log('tried, got', receipt);
186 let confirmed = receipt !== null;
187 if (confirmed) resolve(receipt.status === true);
188 else setTimeout(checkForConfirm, CHECK_BLOCK_EVERY_MS);
189 };
190 checkForConfirm();
191 });
192};
194const sendAndAwaitAll = async (web3, stxs, doubtNonceError) => {
195 await Promise.all(
196 stxs.map(tx => {
197 return new Promise(async (resolve, reject) => {
198 const txHash = await sendSignedTransaction(web3, tx, doubtNonceError);
199 await waitForTransactionConfirm(web3, txHash);
200 resolve();
201 });
202 })
203 );
204};
206const hexify = val => addHexPrefix(val.toString('hex'));
208const renderSignedTx = stx => ({
209 messageHash: hexify(stx.hash()),
210 v: hexify(stx.v),
211 s: hexify(stx.s),
212 r: hexify(stx.r),
213 rawTransaction: hexify(stx.serialize()),
214});
216const getTxnInfo = async (web3, addr) => {
217 let nonce = await web3.eth.getTransactionCount(addr);
218 let chainId = await web3.eth.net.getId();
219 let gasPrice = await web3.eth.getGasPrice();
220 return {
221 nonce: nonce,
222 chainId: chainId,
223 gasPrice: fromWei(gasPrice, 'gwei'),
224 };
225};
227const canDecodePatp = p => {
228 try {
229 ob.patp2dec(p);
230 return true;
231 } catch (_) {
232 return false;
233 }
234};
236export {
237 signTransaction,
238 sendSignedTransaction,
239 waitForTransactionConfirm,
240 sendAndAwaitAll,
241 TXN_PURPOSE,
242 getTxnInfo,
243 renderTxnPurpose,
244 hexify,
245 renderSignedTx,
246 toHex,
247 toWei,
248 fromWei,
249 canDecodePatp,
250};