on 1cfc674 help sign in
bridge/src/components/old/StatelessTransaction.js
596 lines 14 kB history raw
1import { Nothing, Just } from 'folktale/maybe';
2import { Ok } from 'folktale/result';
3import React from 'react';
4import * as need from '../../lib/need';
6import { Code, H3 } from './Base';
7import { Button } from './Base';
8import { CheckboxButton, Input, InnerLabel, InnerLabelDropdown } from './Base';
9import { Warning } from './Base';
11import { BRIDGE_ERROR } from '../../lib/error';
12import { ROUTE_NAMES } from '../../lib/routeNames';
13import { compose } from '../../lib/lib';
14import * as tank from '../../lib/tank';
15import {
16 sendSignedTransaction,
17 fromWei,
18 toWei,
19 hexify,
20 renderSignedTx,
21 signTransaction,
22} from '../../lib/txn';
24import { withTxnConfirmations } from '../../store/txnConfirmations';
25import { withNetwork } from '../../store/network';
26import { withHistory } from '../../store/history';
27import { withWallet } from '../../store/wallet';
28import { withTxnCursor } from '../../store/txnCursor';
30const SUBMISSION_STATES = {
31 PROMPT: 'Send transaction',
32 PREPARING: 'Preparing...',
33 FUNDING: 'Finding transaction funding...',
34 SENDING: 'Sending transaction...',
35};
37class StatelessTransaction extends React.Component {
38 constructor(props) {
39 super(props);
41 this.state = {
42 gasPrice: '5',
43 gasLimit: '600000',
44 showGasDetails: false,
45 userApproval: false,
46 chainId: '1',
47 customChain: false,
48 nonce: '0',
49 stx: Nothing(),
50 txn: Nothing(),
51 txStatus: SUBMISSION_STATES.PROMPT,
52 txError: Nothing(),
53 };
55 this.createUnsignedTxn = this.createUnsignedTxn.bind(this);
56 this.setUserApproval = this.setUserApproval.bind(this);
57 this.setTxn = this.setTxn.bind(this);
58 this.setStx = this.setStx.bind(this);
59 this.sendTxn = this.sendTxn.bind(this);
60 this.setNonce = this.setNonce.bind(this);
61 this.setChainId = this.setChainId.bind(this);
62 this.setGasPrice = this.setGasPrice.bind(this);
63 this.setGasLimit = this.setGasLimit.bind(this);
64 this.rangeChange = this.rangeChange.bind(this);
65 this.toggleGasDetails = this.toggleGasDetails.bind(this);
66 this.handleChainUpdate = this.handleChainUpdate.bind(this);
67 }
69 componentDidMount() {
70 const { props } = this;
72 const addr = need.addressFromWallet(props.wallet);
74 props.web3.matchWith({
75 Nothing: () => {},
76 Just: w3 => {
77 const validWeb3 = w3.value;
79 const getTxMetadata = [
80 validWeb3.eth.getTransactionCount(addr),
81 validWeb3.eth.net.getId(),
82 validWeb3.eth.getGasPrice(),
83 ];
85 Promise.all(getTxMetadata).then(r => {
86 const txMetadata = {
87 nonce: r[0],
88 chainId: r[1],
89 gasPrice: fromWei(r[2], 'gwei'),
90 };
92 this.setState({ ...txMetadata });
93 });
94 },
95 });
96 }
98 handleChainUpdate(chainId) {
99 if (chainId === 'custom') {
100 this.setState({
101 customChain: true,
102 });
103 } else {
104 this.setState({
105 customChain: false,
106 chainId,
107 });
108 }
110 this.clearStx();
111 }
113 setUserApproval() {
114 const { state } = this;
115 this.setState({ userApproval: !state.userApproval });
116 }
118 toggleGasDetails() {
119 this.setState({
120 showGasDetails: !this.state.showGasDetails,
121 });
122 }
124 setStx(stx) {
125 this.setState({
126 stx,
127 userApproval: false,
128 });
129 }
131 setTxn(txn) {
132 this.setState({ txn });
133 }
135 createUnsignedTxn() {
136 const txn = this.props.createUnsignedTxn();
138 this.setState({ txn });
139 }
141 clearTxn() {
142 this.setState({
143 userApproval: false,
144 txn: Nothing(),
145 stx: Nothing(),
146 });
147 }
149 setNonce(nonce) {
150 this.setState({ nonce });
151 this.clearStx();
152 }
154 setChainId(chainId) {
155 this.setState({ chainId });
156 this.clearStx();
157 }
159 setGasPrice(gasPrice) {
160 this.setState({ gasPrice });
161 this.clearStx();
162 }
164 rangeChange(e) {
165 this.setGasPrice(e.target.value);
166 }
168 setGasLimit(gasLimit) {
169 this.setState({ gasLimit });
170 this.clearStx();
171 }
173 clearStx() {
174 this.setState({
175 userApproval: false,
176 stx: Nothing(),
177 });
178 }
180 async sendTxn() {
181 const { props, state } = this;
182 const web3 = props.web3.value;
184 const stx = state.stx.matchWith({
185 Just: tx => tx.value,
186 Nothing: () => {
187 throw BRIDGE_ERROR.MISSING_TXN;
188 },
189 });
191 if (props.beforeSend) {
192 try {
193 this.setState({ txStatus: SUBMISSION_STATES.PREPARING });
194 const res = await props.beforeSend(stx);
195 if (res === false) throw new Error('beforeSend disallowed sending');
196 } catch (e) {
197 console.log('beforeSend error', e);
198 this.setState({
199 txStatus: SUBMISSION_STATES.PROMPT,
200 txError: Just('Something went wrong!'),
201 });
202 return;
203 }
204 }
206 this.setState({ txStatus: SUBMISSION_STATES.FUNDING });
208 const rawTx = hexify(stx.serialize());
209 const cost = state.gasLimit * toWei(state.gasPrice, 'gwei');
211 const address = need.addressFromWallet(props.wallet);
212 let balance = await web3.eth.getBalance(address);
213 let hasBalance = balance >= cost;
215 let usedTank = false;
216 // if we need to, try and fund the transaction
217 if (!hasBalance) {
218 usedTank = await this.ensureFundsFor(web3, address, cost, [rawTx]);
219 hasBalance = usedTank;
220 }
222 // if we still don't have sufficient balance, fail and tell the user
223 if (!hasBalance) {
224 this.setState({
225 txStatus: SUBMISSION_STATES.PROMPT,
226 txError: Just(`Insufficient funds.
227 Address ${address} needs at least ${fromWei(cost.toString())} ETH,
228 currently has ${fromWei(balance.toString())} ETH.`),
229 });
231 // if we have the balance, proceed with submission
232 } else {
233 this.setState({ txStatus: SUBMISSION_STATES.SENDING });
235 sendSignedTransaction(
236 web3,
237 state.stx,
238 usedTank,
239 props.setTxnConfirmations
240 )
241 .then(txHash => {
242 props.setTxnCursor(Just(Ok(txHash)));
244 let routeData = {};
245 if (props.newNetworkSeed) {
246 props.setNetworkSeed(Just(props.newNetworkSeed));
247 routeData.promptKeyfile = true;
248 }
250 if (props.newRevision) {
251 props.setNetworkRevision(Just(props.newRevision));
252 }
254 props.history.popAndPush(ROUTE_NAMES.SENT_TRANSACTION, routeData);
255 })
256 .catch(err => {
257 this.setState({
258 txStatus: SUBMISSION_STATES.PROMPT,
259 txError: Just(err),
260 });
261 });
262 }
263 }
265 // uses the gas tank to ensure funds, but if we have to ask the user
266 // for funding, just resolve instead of waiting
267 // returns true if the gas tank was used, false otherwise
268 ensureFundsFor(web3, address, cost, signedTxs) {
269 return new Promise((resolve, reject) => {
270 tank
271 .ensureFundsFor(web3, null, address, cost, signedTxs, () => {
272 resolve(false);
273 })
274 .then(res => {
275 resolve(res);
276 });
277 });
278 }
280 getChainTitle(chainId) {
281 let map = {
282 '1': 'Mainnet - 1',
283 '2': 'Morden - 2',
284 '3': 'Ropsten - 3',
285 '4': 'Goerli - 4',
286 '42': 'Kovan - 42',
287 '1337': 'Geth private chains - 1337',
288 custom: 'Custom',
289 };
291 return map[chainId];
292 }
294 getChainOptions() {
295 return [
296 {
297 title: this.getChainTitle('1'),
298 value: '1',
299 },
300 {
301 title: this.getChainTitle('2'),
302 value: '2',
303 },
304 {
305 title: this.getChainTitle('3'),
306 value: '3',
307 },
308 {
309 title: this.getChainTitle('4'),
310 value: '4',
311 },
312 {
313 title: this.getChainTitle('42'),
314 value: '42',
315 },
316 {
317 title: this.getChainTitle('1337'),
318 value: '1337',
319 },
320 {
321 title: this.getChainTitle('custom'),
322 value: 'custom',
323 },
324 ];
325 }
327 render() {
328 const { web3, canGenerate } = this.props;
329 const {
330 gasPrice,
331 gasLimit,
332 nonce,
333 chainId,
334 txn,
335 stx,
336 userApproval,
337 showGasDetails,
338 customChain,
339 txStatus,
340 } = this.state;
342 const {
343 setNonce,
344 setChainId,
345 setGasLimit,
346 setGasPrice,
347 toggleGasDetails,
348 setUserApproval,
349 sendTxn,
350 createUnsignedTxn,
351 handleChainUpdate,
352 } = this;
354 const { state } = this;
356 const canSign = Just.hasInstance(txn);
357 const canApprove = Just.hasInstance(stx);
358 const canSend = Just.hasInstance(stx) && userApproval === true;
360 const chainOptions = this.getChainOptions();
362 const generateButtonColor = Nothing.hasInstance(txn) ? 'blue' : 'green';
364 const signerButtonColor = Nothing.hasInstance(stx) ? 'blue' : 'green';
366 const generateTxnButton = (
367 <Button
368 className={'mt-8'}
369 disabled={!canGenerate}
370 prop-color={generateButtonColor}
371 prop-size={'lg wide'}
372 onClick={createUnsignedTxn}>
373 {'Generate Transaction'}
374 </Button>
375 );
377 const unsignedTxnDisplay = txn.matchWith({
378 Nothing: _ => '',
379 Just: tx => (
380 <React.Fragment>
381 <H3 className={'mt-8'}>{'Unsigned Transaction'}</H3>
382 <Code>{JSON.stringify(tx.value, null, 2)}</Code>
383 </React.Fragment>
384 ),
385 });
387 const gasPriceRangeDialogue = (
388 <React.Fragment>
389 <div className="mt-12 flex space-between align-baseline">
390 <div>
391 <span>Gas Price:</span>
392 <span className="ml-4 text-700 text-sm">{gasPrice} gwei</span>
393 </div>
394 <div className="text-sm">
395 <span>Max transaction fee: </span>
396 <span className="text-700">
397 {(gasPrice * gasLimit) / 1000000000} eth
398 </span>
399 </div>
400 </div>
402 <input
403 className="mt-4"
404 type="range"
405 min="2"
406 max="20"
407 list="gweiVals"
408 value={gasPrice}
409 onChange={this.rangeChange}
410 />
412 <div className="flex space-between text-sm mb-8">
413 <div>Cheap</div>
414 <div>Fast</div>
415 </div>
416 </React.Fragment>
417 );
419 const toggleGasDetailsDialogue = (
420 <span className="text-link" onClick={toggleGasDetails}>
421 Gas Details
422 </span>
423 );
425 const gasPriceDialogue = (
426 <Input
427 className={'mono mt-4'}
428 prop-size={'md'}
429 prop-format={'innerLabel'}
430 value={gasPrice}
431 onChange={setGasPrice}>
432 <InnerLabel>{'Gas Price (gwei)'}</InnerLabel>
433 </Input>
434 );
436 const gasLimitDialogue = (
437 <Input
438 className={'mono mt-4'}
439 prop-size={'md'}
440 prop-format={'innerLabel'}
441 value={gasLimit}
442 onChange={setGasLimit}>
443 <InnerLabel>{'Gas Limit'}</InnerLabel>
444 </Input>
445 );
447 const nonceDialogue = (
448 <Input
449 className={'mono mt-4 mb-4'}
450 prop-size={'md'}
451 prop-format={'innerLabel'}
452 value={nonce}
453 onChange={setNonce}>
454 <InnerLabel>{'Nonce'}</InnerLabel>
455 </Input>
456 );
458 const chainDialogueTitle = customChain
459 ? 'Custom'
460 : this.getChainTitle(chainId);
461 const chainDialogue = (
462 <InnerLabelDropdown
463 className={'mt-6'}
464 fullWidth={true}
465 title={'Chain ID'}
466 options={chainOptions}
467 handleUpdate={handleChainUpdate}
468 currentSelectionTitle={chainDialogueTitle}
469 />
470 );
472 const customChainDialogue = !customChain ? null : (
473 <Input
474 className={'mono mt-4 mb-8'}
475 prop-size={'md'}
476 prop-format={'innerLabel'}
477 value={chainId}
478 onChange={setChainId}>
479 <InnerLabel>{'Chain ID'}</InnerLabel>
480 </Input>
481 );
483 const onlineParamsDialogue = web3.matchWith({
484 Just: _ => <div />,
485 Nothing: _ => (
486 <React.Fragment>
487 {nonceDialogue}
488 {chainDialogue}
489 {customChainDialogue}
490 </React.Fragment>
491 ),
492 });
494 const signTxnButton = (
495 <Button
496 disabled={!canSign}
497 className={'mt-8'}
498 prop-size={'lg wide'}
499 prop-color={signerButtonColor}
500 onClick={() =>
501 signTransaction({ ...this.props, ...this.state, setStx: this.setStx })
502 }>
503 {'Sign Transaction'}
504 </Button>
505 );
507 const signedTxnDisplay = stx.matchWith({
508 Nothing: _ => '',
509 Just: tx => (
510 <React.Fragment>
511 <H3 className={'mt-8'}>{'Signed Transaction'}</H3>
512 <Code>{JSON.stringify(renderSignedTx(tx.value), null, 2)}</Code>
513 </React.Fragment>
514 ),
515 });
517 const confirmButton = (
518 <CheckboxButton
519 className={'mt-8'}
520 disabled={!canApprove}
521 onToggle={setUserApproval}
522 state={userApproval}
523 label="I approve this transaction and wish to send."
524 />
525 );
527 const sending = txStatus !== SUBMISSION_STATES.PROMPT;
528 const sendTxnSpinner = sending ? '' : 'hide';
529 const sendTxnButton = (
530 <Button
531 prop-size={'xl wide'}
532 className={'mt-8'}
533 disabled={!canSend || sending}
534 onClick={sendTxn}>
535 <span className="relative">
536 <span className={`btn-spinner ${sendTxnSpinner}`} />
537 {txStatus}
538 </span>
539 </Button>
540 );
542 const sendDialogue = web3.matchWith({
543 Nothing: _ => '',
544 Just: _ => (
545 <React.Fragment>
546 {confirmButton}
547 {sendTxnButton}
548 </React.Fragment>
549 ),
550 });
552 const txnErrorDialogue = Nothing.hasInstance(state.txError) ? (
553 ''
554 ) : (
555 <Warning className={'mt-8'}>
556 <H3 style={{ marginTop: 0, paddingTop: 0 }}>
557 {'There was an error sending your transaction.'}
558 </H3>
559 {state.txError.value}
560 </Warning>
561 );
563 return (
564 <React.Fragment>
565 {generateTxnButton}
566 {unsignedTxnDisplay}
568 {gasPriceRangeDialogue}
569 {toggleGasDetailsDialogue}
571 {showGasDetails && (
572 <div>
573 {gasPriceDialogue}
574 {gasLimitDialogue}
575 </div>
576 )}
577 {onlineParamsDialogue}
579 {signTxnButton}
581 {signedTxnDisplay}
582 {sendDialogue}
584 {txnErrorDialogue}
585 </React.Fragment>
586 );
587 }
590export default compose(
591 withNetwork,
592 withTxnConfirmations,
593 withHistory,
594 withWallet,
595 withTxnCursor
596)(StatelessTransaction);