on 69a57bc help sign in
bridge/src/views/Invite/InviteEmail.js
642 lines 19 kB history raw
1import React, {
2 useCallback,
3 useEffect,
4 useRef,
5 useMemo,
6 useState,
7} from 'react';
8import cn from 'classnames';
9import ob from 'urbit-ob';
10import * as azimuth from 'azimuth-js';
11import {
12 Grid,
13 Flex,
14 Input,
15 IconButton,
16 HelpText,
17 Text,
18 ErrorText,
19 AccessoryIcon,
20} from 'indigo-react';
21import { uniq } from 'lodash';
22import { toWei, toBN } from 'web3-utils';
23import { FieldArray } from 'react-final-form-arrays';
24import { Field } from 'react-final-form';
26import { usePointCursor } from 'store/pointCursor';
27import { useNetwork } from 'store/network';
28import { usePointCache } from 'store/pointCache';
29import { useWallet } from 'store/wallet';
31// for transaction generation and signing
32import {
33 signTransaction,
34 sendSignedTransaction,
35 waitForTransactionConfirm,
36 hexify,
37} from 'lib/txn';
38import * as tank from 'lib/tank';
39import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
40import * as need from 'lib/need';
41import * as wg from 'lib/walletgen';
42import useSetState from 'lib/useSetState';
43import pluralize from 'lib/pluralize';
44import useMailer from 'lib/useMailer';
46import ProgressButton from 'components/ProgressButton';
47import Highlighted from 'components/Highlighted';
48import { ForwardButton } from 'components/Buttons';
49import NeedFundsNotice from 'components/NeedFundsNotice';
51import BridgeForm from 'form/BridgeForm';
52import { EmailInput } from 'form/Inputs';
53import {
54 buildEmailValidator,
55 composeValidator,
56 hasErrors,
57 buildArrayValidator,
58} from 'form/validators';
59import { FORM_ERROR } from 'final-form';
60import SubmitButton from 'form/SubmitButton';
61import FormError from 'form/FormError';
62import { WARNING, onlyHasWarning } from 'form/helpers';
63import useGasPrice from 'lib/useGasPrice';
64import timeout from 'lib/timeout';
66const INITIAL_VALUES = { emails: [''] };
68const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
69const HAS_RECEIVED_TEXT = 'This email has already received an invite: ';
71const STATUS = {
72 INPUT: 'INPUT',
73 GENERATING: 'GENERATING',
74 CAN_SEND: 'CAN_SEND',
75 FUNDING: 'FUNDING',
76 SENDING: 'SENDING',
77 SUCCESS: 'SUCCESS',
78 FAILURE: 'FAILURE',
79};
81const nameForEmailField = i => `emails[${i}]`;
83const buttonText = (status, count) => {
84 switch (status) {
85 case STATUS.INPUT:
86 return `Generate ${pluralize(count, 'Invite')}`;
87 case STATUS.GENERATING:
88 return `Generating ${pluralize(count, 'Invite')}...`;
89 case STATUS.CAN_SEND:
90 return `Send ${pluralize(count, 'Invite')}`;
91 case STATUS.FUNDING:
92 return `Waiting on Funds...`;
93 case STATUS.SENDING:
94 return `Sending ${pluralize(count, 'Invite')}...`;
95 case STATUS.FAILURE:
96 default:
97 return 'Error';
98 }
99};
101const buildAccessoryFor = (dones, errors) => name => {
102 if (dones[name]) return <AccessoryIcon.Success />;
103 if (errors[name]) return <AccessoryIcon.Failure />;
104 return <AccessoryIcon.Pending />;
105};
107export default function InviteEmail() {
108 const { contracts, web3, networkType } = useNetwork();
109 const { wallet, walletType, walletHdPath } = useWallet();
110 const { syncInvites, getInvites } = usePointCache();
111 const { pointCursor } = usePointCursor();
112 const point = need.point(pointCursor);
113 const { getHasReceived, sendMail } = useMailer();
114 const { gasPrice } = useGasPrice();
116 const cachedEmails = useRef({});
118 const { availableInvites } = getInvites(point);
119 const maxInvitesToSend = availableInvites.matchWith({
120 Nothing: () => 0,
121 Just: p => p.value,
122 });
124 // manage per-input state
125 const [hovered, setHovered] = useSetState();
126 const [invites, addInvite, clearInvites] = useSetState();
127 const [receipts, addReceipt, clearReceipts] = useSetState();
128 const [errors, addError] = useSetState();
130 // manage general state that affects the whole form
131 const [message, setMessage] = useState('');
132 const [status, setStatus] = useState(STATUS.INPUT);
133 const [needFunds, setNeedFunds] = useState(null);
134 const [generalError, setGeneralError] = useState(null);
136 // derive booleans from status
137 const canInput = status === STATUS.INPUT;
138 const isGenerating = status === STATUS.GENERATING;
139 const canSend = status === STATUS.CAN_SEND;
140 const isFunding = status === STATUS.FUNDING;
141 const isSending = status === STATUS.SENDING;
142 const isFailed = status === STATUS.FAILURE;
143 const isDone = status === STATUS.SUCCESS;
145 const validateHasReceived = useCallback(
146 async email => {
147 const hasReceived = await getHasReceived(email);
148 if (hasReceived) {
149 return HAS_RECEIVED_TEXT + email;
150 }
151 },
152 [getHasReceived]
153 );
155 const validateForm = useCallback((values, errors) => {
156 if (hasErrors(errors)) {
157 return errors;
158 }
160 // check for email uniqenesss
161 const emails = values.emails.filter(d => !!d);
162 if (uniq(emails).length !== emails.length) {
163 return { [FORM_ERROR]: 'Duplicate email.' };
164 }
165 }, []);
167 const validate = useMemo(
168 () =>
169 composeValidator(
170 {
171 emails: buildArrayValidator(buildEmailValidator(validateHasReceived)),
172 },
173 validateForm
174 ),
175 [validateForm, validateHasReceived]
176 );
178 // progress is [0, .length] of invites or receipts, as we're generating them
179 const progress = isGenerating
180 ? Object.keys(invites).length
181 : isSending
182 ? Object.keys(receipts).length
183 : null;
184 const percentProgress =
185 progress !== null
186 ? progress / Object.keys(cachedEmails.current).length
187 : null;
188 const visualProgress = progress === null ? '-' : `${progress + 1}`;
190 // build a builder for the accessory to the input, depending on status
191 const accessoryFor = (() => {
192 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
193 if (isSending) return buildAccessoryFor(receipts, errors);
194 if (isFailed) return buildAccessoryFor({}, errors);
195 return () => null;
196 })();
198 const generateInvites = useCallback(
199 async values => {
200 const _contracts = contracts.getOrElse(null);
201 const _web3 = web3.getOrElse(null);
202 const _wallet = wallet.getOrElse(null);
203 if (!_contracts || !_web3 || !_wallet) {
204 // not using need because we want a custom error
205 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
206 }
208 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
209 const chainId = await _web3.eth.net.getId();
210 const planets = await azimuth.delegatedSending.getPlanetsToSend(
211 _contracts,
212 point,
213 values.emails.length
214 );
216 // account for the race condition where invites got used up while we were
217 // composing our target list
218 if (planets.length < values.emails.length) {
219 // resync invites to the cache, since they're out of date
220 syncInvites(point);
222 return {
223 [FORM_ERROR]:
224 `Can currently only send ${planets.length} invites. ` +
225 `Please remove invites until you are within the limit.`,
226 };
227 }
229 clearInvites();
230 // NB(shrugs) - must be processed in serial because main thread, etc
231 let errorCount = 0;
232 for (let i = 0; i < values.emails.length; i++) {
233 const name = nameForEmailField(i);
234 try {
235 const email = values.emails[i];
236 const planet = planets[i];
238 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
239 MIN_PLANET
240 // we're always giving planets, so generate a ticket of the correct size
241 );
243 const inviteTx = azimuth.delegatedSending.sendPoint(
244 _contracts,
245 point,
246 planet,
247 owner.keys.address
248 );
250 const signedTx = await signTransaction({
251 wallet: _wallet,
252 walletType,
253 walletHdPath,
254 networkType,
255 chainId,
256 nonce: nonce + i,
257 // TODO: ^ make a useTransactionSigner to encapsulate this logic
258 txn: inviteTx,
259 gasPrice: gasPrice.toFixed(), // expects string gwei
260 gasLimit: GAS_LIMIT.toFixed(),
261 });
263 const rawTx = hexify(signedTx.serialize());
265 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
266 } catch (error) {
267 console.error(error);
268 errorCount++;
269 addError({ [name]: 'Error generating invite.' });
270 }
271 }
273 if (errorCount > 0) {
274 return {
275 [WARNING]: `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
276 errorCount,
277 'error'
278 )} while generating wallets. You can still send the invites that generated correctly.`,
279 };
280 }
281 },
282 [
283 contracts,
284 web3,
285 wallet,
286 point,
287 clearInvites,
288 syncInvites,
289 walletType,
290 walletHdPath,
291 networkType,
292 gasPrice,
293 addInvite,
294 addError,
295 ]
296 );
298 const sendInvites = useCallback(async () => {
299 // compute all of the names of the fields
300 const allFieldNames = Object.keys(cachedEmails.current);
301 // only emails we're sending are the valid ones with invites
302 const names = allFieldNames.filter(name => !!invites[name]);
303 const emails = allFieldNames.map(name => cachedEmails.current[name]);
305 const _web3 = web3.getOrElse(null);
306 const _wallet = wallet.getOrElse(null);
307 if (!_web3 || !_wallet) {
308 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
309 }
311 setStatus(STATUS.FUNDING);
312 const totalCost = toBN(GAS_LIMIT)
313 .mul(toBN(gasPrice))
314 .mul(toBN(emails.length));
315 const tankWasUsed = await tank.ensureFundsFor(
316 _web3,
317 point,
318 _wallet.address,
319 walletType,
320 toWei(totalCost.toString(), 'gwei'),
321 names.map(name => invites[name].rawTx),
322 (address, minBalance, balance) =>
323 setNeedFunds({ address, minBalance, balance }),
324 () => setNeedFunds(undefined)
325 );
327 setStatus(STATUS.SENDING);
328 clearReceipts();
330 let unsentInvites = [];
331 let orphanedInvites = [];
332 const txAndMailings = names.map(async name => {
333 const invite = invites[name];
334 try {
335 const txHash = await sendSignedTransaction(
336 _web3,
337 invite.signedTx,
338 tankWasUsed
339 );
341 await waitForTransactionConfirm(_web3, txHash);
342 } catch (error) {
343 console.error(error);
344 unsentInvites.push(invite);
345 return;
346 }
348 try {
349 await sendMail(
350 invite.email,
351 invite.ticket,
352 ob.patp(point),
353 message,
354 invite.rawTx
355 );
356 } catch (error) {
357 console.error(error);
358 orphanedInvites.push(invite);
359 }
361 addReceipt({ [name]: true });
362 });
364 await Promise.all(txAndMailings);
365 // if there are any receipt errors, throw a general error
366 let errorString = '';
367 if (orphanedInvites.length > 0) {
368 errorString =
369 'Not all invite emails were sent. ' +
370 'Please send the following invite codes manually: ' +
371 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
372 '. ';
373 }
374 if (unsentInvites.length > 0) {
375 errorString =
376 errorString +
377 'Not all invites were created. ' +
378 'Did not send invites for: ' +
379 unsentInvites.map(i => i.email).join(', ') +
380 '.';
381 }
382 if (errorString !== '') {
383 throw new Error(errorString);
384 }
385 }, [
386 web3,
387 wallet,
388 walletType,
389 gasPrice,
390 point,
391 clearReceipts,
392 invites,
393 addReceipt,
394 sendMail,
395 message,
396 ]);
398 const onSubmit = useCallback(
399 async values => {
400 setMessage(values.message);
401 cachedEmails.current = values.emails.reduce((memo, email, i) => {
402 memo[nameForEmailField(i)] = email;
403 return memo;
404 }, {});
405 setStatus(STATUS.GENERATING);
406 const errors = await generateInvites(values);
407 if (hasErrors(errors)) {
408 if (onlyHasWarning(errors)) {
409 setStatus(STATUS.CAN_SEND);
410 }
412 return errors;
413 }
415 await timeout(500); // wait for progress animation to complete.
417 setStatus(STATUS.CAN_SEND);
418 },
419 [generateInvites]
420 );
422 const doSend = useCallback(async () => {
423 setGeneralError(null);
424 try {
425 setStatus(STATUS.SENDING);
426 await sendInvites();
427 setStatus(STATUS.SUCCESS);
428 } catch (error) {
429 console.error(error);
430 setGeneralError(error.message);
431 setStatus(STATUS.FAILURE);
432 }
433 }, [sendInvites]);
435 // when we transition to done, sync invites because we just sent some
436 // and therefore know that state has changed
437 useEffect(() => {
438 if (isDone) {
439 syncInvites(point);
440 }
441 }, [isDone, syncInvites, point]);
443 const renderButton = ({ handleSubmit, fields }) => {
444 if (canInput) {
445 return (
446 <Grid.Item
447 full
448 as={SubmitButton}
449 handleSubmit={handleSubmit}
450 accessory={`${visualProgress}/${fields.length}`}>
451 {buttonText(status, fields.length)}
452 </Grid.Item>
453 );
454 }
456 if (isGenerating) {
457 return (
458 <Grid.Item
459 full
460 as={ProgressButton}
461 solid
462 disabled
463 className="mt4"
464 accessory={`${visualProgress}/${fields.length}`}
465 progress={percentProgress}
466 color="black">
467 {buttonText(status, fields.length)}
468 </Grid.Item>
469 );
470 }
472 if (canSend) {
473 return (
474 <Grid.Item
475 full
476 as={ForwardButton}
477 className="mt4"
478 solid
479 success
480 onClick={doSend}>
481 {buttonText(status, fields.length)}
482 </Grid.Item>
483 );
484 }
486 if (isFunding) {
487 return (
488 <Grid.Item
489 full
490 as={ForwardButton}
491 className="mt4"
492 solid
493 success
494 disabled
495 accessory={`${visualProgress}/${fields.length}`}>
496 {buttonText(status, fields.length)}
497 </Grid.Item>
498 );
499 }
501 if (isSending) {
502 return (
503 <Grid.Item
504 full
505 as={ProgressButton}
506 className="mt4"
507 solid
508 success
509 disabled
510 accessory={`${visualProgress}/${fields.length}`}
511 progress={percentProgress}
512 color={isGenerating ? 'black' : 'green4'}>
513 {buttonText(status, fields.length)}
514 </Grid.Item>
515 );
516 }
518 return null;
519 };
521 return (
522 <Grid gap={3}>
523 <BridgeForm
524 validate={validate}
525 onSubmit={onSubmit}
526 initialValues={INITIAL_VALUES}>
527 {({ handleSubmit }) => (
528 <FieldArray name="emails">
529 {({ fields }) => {
530 const sentInviteNames = Object.keys(receipts);
531 return (
532 <>
533 <Grid.Item full as={Flex} justify="end">
534 {/* use hidden class instead of removing component from dom */}
535 {/* in order to avoid janky reflow */}
536 <IconButton
537 onClick={() => fields.push('')}
538 disabled={!canInput || fields.length >= maxInvitesToSend}
539 className={cn({ hidden: isDone })}
540 solid>
541 +
542 </IconButton>
543 </Grid.Item>
545 {isDone ? (
546 <>
547 <Grid.Item as={Text} className="f5" full>
548 <Highlighted>
549 {pluralize(sentInviteNames.length, 'invite')}
550 </Highlighted>{' '}
551 {pluralize(sentInviteNames.length, 'has', 'have')} been
552 successfully sent
553 </Grid.Item>
555 {sentInviteNames.map(name => (
556 <Grid.Item as={HelpText} key={name} full>
557 <Field name={name}>
558 {({ input: { value } }) => value}
559 </Field>
560 </Grid.Item>
561 ))}
562 </>
563 ) : (
564 <>
565 {fields.map((name, i) => {
566 const isFirst = i === 0;
567 return (
568 <Grid.Item
569 key={name}
570 full
571 as={Grid}
572 gap={3}
573 onMouseOver={() => setHovered({ [name]: true })}
574 onMouseLeave={() => setHovered({ [name]: false })}>
575 <Grid.Item
576 cols={[1, 11]}
577 as={EmailInput}
578 name={name}
579 label={isFirst ? 'Email Address' : undefined}
580 accessory={accessoryFor(name)}
581 />
582 <Field name={name}>
583 {({ meta: { active } }) => {
584 return (
585 <>
586 {!isFirst &&
587 (active || hovered[name]) &&
588 canInput && (
589 <Grid.Item
590 cols={[11, 13]}
591 justifySelf="end"
592 alignSelf="center">
593 <IconButton
594 onClick={() => fields.remove(i)}
595 solid
596 secondary>
597 -
598 </IconButton>
599 </Grid.Item>
600 )}
601 </>
602 );
603 }}
604 </Field>
605 </Grid.Item>
606 );
607 })}
609 <Grid.Item
610 full
611 as={Input}
612 type="text"
613 name="message"
614 label="Message (optional)"
615 placeholder="Welcome aboard!"
616 value={message}
617 />
619 {renderButton({ handleSubmit, fields })}
621 {needFunds && (
622 <Grid.Item full as={NeedFundsNotice} {...needFunds} />
623 )}
625 <Grid.Item full as={FormError} />
627 {generalError && (
628 <Grid.Item full as={ErrorText}>
629 {generalError}
630 </Grid.Item>
631 )}
632 </>
633 )}
634 </>
635 );
636 }}
637 </FieldArray>
638 )}
639 </BridgeForm>
640 </Grid>
641 );