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