on 46dbb79 help sign in
bridge/src/lib/txn.js
256 lines 7.4 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, confirmationCb) => {
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 //TODO do we also reach this if network is slow? web3 only tries a set
156 // amount of times... should we instead do waitForTransactionConfirm
157 // in on-transactionHash? we don't care (much) about additional
158 // confirms anyway.
159 .on('confirmation', (confirmationNum, txn) => {
160 confirmationCb(txn.transactionHash, confirmationNum + 1);
161 resolve(txn.transactionHash);
162 })
163 .on('error', err => {
164 // if there's a nonce error, but we used the gas tank, it's likely
165 // that it's because the tank already submitted our transaction.
166 // we just wait for first confirmation here.
167 console.error(err);
168 if (
169 doubtNonceError &&
170 (err.message || '').includes("the tx doesn't have the correct nonce.")
171 ) {
172 console.log('nonce error, likely from gas tank submission, ignoring');
173 const txHash = web3.utils.keccak256(rawTx);
174 //TODO can we do does-exists check first?
175 //TODO max wait time before assume fail?
176 waitForTransactionConfirm(web3, txHash).then(res => {
177 if (res) {
178 resolve(txHash);
179 confirmationCb(txHash, 1);
180 } else {
181 reject('Unexpected tx failure');
182 }
183 });
184 } else {
185 reject(err.message);
186 }
187 });
188 });
189};
191// returns a Promise<bool>, where the bool indicates tx success/failure
192const waitForTransactionConfirm = (web3, txHash) => {
193 return new Promise((resolve, reject) => {
194 const checkForConfirm = async () => {
195 console.log('checking for confirm', txHash);
196 const receipt = await web3.eth.getTransactionReceipt(txHash);
197 console.log('tried, got', receipt);
198 let confirmed = receipt !== null;
199 if (confirmed) resolve(receipt.status === true);
200 else setTimeout(checkForConfirm, CHECK_BLOCK_EVERY_MS);
201 };
202 checkForConfirm();
203 });
204};
206const isTransactionConfirmed = async (web3, txHash) => {
207 const receipt = await web3.eth.getTransactionReceipt(txHash);
208 console.log('got confirm state', receipt !== null, receipt.confirmations);
209 return receipt !== null;
210};
212const hexify = val => addHexPrefix(val.toString('hex'));
214const renderSignedTx = stx => ({
215 messageHash: hexify(stx.hash()),
216 v: hexify(stx.v),
217 s: hexify(stx.s),
218 r: hexify(stx.r),
219 rawTransaction: hexify(stx.serialize()),
220});
222const getTxnInfo = async (web3, addr) => {
223 let nonce = await web3.eth.getTransactionCount(addr);
224 let chainId = await web3.eth.net.getId();
225 let gasPrice = await web3.eth.getGasPrice();
226 return {
227 nonce: nonce,
228 chainId: chainId,
229 gasPrice: fromWei(gasPrice, 'gwei'),
230 };
231};
233const canDecodePatp = p => {
234 try {
235 ob.patp2dec(p);
236 return true;
237 } catch (_) {
238 return false;
239 }
240};
242export {
243 signTransaction,
244 sendSignedTransaction,
245 waitForTransactionConfirm,
246 isTransactionConfirmed,
247 TXN_PURPOSE,
248 getTxnInfo,
249 renderTxnPurpose,
250 hexify,
251 renderSignedTx,
252 toHex,
253 toWei,
254 fromWei,
255 canDecodePatp,
256};