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