on 41b4692 help sign in
bridge/src/views/Invite/InviteEmail.js
616 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 IconButton,
15 HelpText,
16 Text,
17 ErrorText,
18 AccessoryIcon,
19} from 'indigo-react';
20import { uniq } from 'lodash';
21import { toWei, toBN } from 'web3-utils';
22import { FieldArray } from 'react-final-form-arrays';
23import { Field } from 'react-final-form';
25import { usePointCursor } from 'store/pointCursor';
26import { useNetwork } from 'store/network';
27import { usePointCache } from 'store/pointCache';
28import { useWallet } from 'store/wallet';
30// for transaction generation and signing
31import {
32 signTransaction,
33 sendSignedTransaction,
34 waitForTransactionConfirm,
35 hexify,
36} from 'lib/txn';
37import * as tank from 'lib/tank';
38import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
39import * as need from 'lib/need';
40import * as wg from 'lib/walletgen';
41import useSetState from 'lib/useSetState';
42import pluralize from 'lib/pluralize';
43import useMailer from 'lib/useMailer';
45import ProgressButton from 'components/ProgressButton';
46import Highlighted from 'components/Highlighted';
47import { ForwardButton } from 'components/Buttons';
48import NeedFundsNotice from 'components/NeedFundsNotice';
50import BridgeForm from 'form/BridgeForm';
51import { EmailInput } from 'form/Inputs';
52import {
53 buildEmailValidator,
54 composeValidator,
55 hasErrors,
56 buildArrayValidator,
57} from 'form/validators';
58import { FORM_ERROR } from 'final-form';
59import SubmitButton from 'form/SubmitButton';
60import FormError from 'form/FormError';
61import { WARNING, onlyHasWarning } from 'form/helpers';
62import useGasPrice from 'lib/useGasPrice';
63import timeout from 'lib/timeout';
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 totalCost = toBN(GAS_LIMIT)
311 .mul(toBN(gasPrice))
312 .mul(toBN(emails.length));
313 const tankWasUsed = await tank.ensureFundsFor(
314 _web3,
315 point,
316 _wallet.address,
317 toWei(totalCost.toString(), 'gwei'),
318 names.map(name => invites[name].rawTx),
319 (address, minBalance, balance) =>
320 setNeedFunds({ address, minBalance, balance }),
321 () => setNeedFunds(undefined)
322 );
324 setStatus(STATUS.SENDING);
325 clearReceipts();
327 let unsentInvites = [];
328 let orphanedInvites = [];
329 const txAndMailings = names.map(async name => {
330 const invite = invites[name];
331 try {
332 const txHash = await sendSignedTransaction(
333 _web3,
334 invite.signedTx,
335 tankWasUsed
336 );
338 await waitForTransactionConfirm(_web3, txHash);
339 } catch (error) {
340 console.error(error);
341 unsentInvites.push(invite);
342 return;
343 }
345 try {
346 await sendMail(
347 invite.email,
348 invite.ticket,
349 ob.patp(point),
350 invite.rawTx
351 );
352 } catch (error) {
353 console.error(error);
354 orphanedInvites.push(invite);
355 }
357 addReceipt({ [name]: true });
358 });
360 await Promise.all(txAndMailings);
361 // if there are any receipt errors, throw a general error
362 let errorString = '';
363 if (orphanedInvites.length > 0) {
364 errorString =
365 'Not all invite emails were sent. ' +
366 'Please send the following invite codes manually: ' +
367 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
368 '. ';
369 }
370 if (unsentInvites.length > 0) {
371 errorString =
372 errorString +
373 'Not all invites were created. ' +
374 'Did not send invites for: ' +
375 unsentInvites.map(i => i.email).join(', ') +
376 '.';
377 }
378 if (errorString !== '') {
379 throw new Error(errorString);
380 }
381 }, [web3, wallet, point, gasPrice, invites, clearReceipts, addReceipt]);
383 const onSubmit = useCallback(
384 async values => {
385 cachedEmails.current = values.emails.reduce((memo, email, i) => {
386 memo[nameForEmailField(i)] = email;
387 return memo;
388 }, {});
389 setStatus(STATUS.GENERATING);
390 const errors = await generateInvites(values);
391 if (hasErrors(errors)) {
392 if (onlyHasWarning(errors)) {
393 setStatus(STATUS.CAN_SEND);
394 }
396 return errors;
397 }
399 await timeout(500); // wait for progress animation to complete.
401 setStatus(STATUS.CAN_SEND);
402 },
403 [generateInvites]
404 );
406 const doSend = useCallback(async () => {
407 setGeneralError(null);
408 try {
409 setStatus(STATUS.SENDING);
410 await sendInvites();
411 setStatus(STATUS.SUCCESS);
412 } catch (error) {
413 console.error(error);
414 setGeneralError(error.message);
415 setStatus(STATUS.FAILURE);
416 }
417 }, [sendInvites]);
419 // when we transition to done, sync invites because we just sent some
420 // and therefore know that state has changed
421 useEffect(() => {
422 if (isDone) {
423 syncInvites(point);
424 }
425 }, [isDone, syncInvites, point]);
427 const renderButton = ({ handleSubmit, fields }) => {
428 if (canInput) {
429 return (
430 <Grid.Item
431 full
432 as={SubmitButton}
433 handleSubmit={handleSubmit}
434 accessory={`${visualProgress}/${fields.length}`}>
435 {buttonText(status, fields.length)}
436 </Grid.Item>
437 );
438 }
440 if (isGenerating) {
441 return (
442 <Grid.Item
443 full
444 as={ProgressButton}
445 solid
446 disabled
447 className="mt4"
448 accessory={`${visualProgress}/${fields.length}`}
449 progress={percentProgress}
450 color="black">
451 {buttonText(status, fields.length)}
452 </Grid.Item>
453 );
454 }
456 if (canSend) {
457 return (
458 <Grid.Item
459 full
460 as={ForwardButton}
461 className="mt4"
462 solid
463 success
464 onClick={doSend}>
465 {buttonText(status, fields.length)}
466 </Grid.Item>
467 );
468 }
470 if (isFunding) {
471 return (
472 <Grid.Item
473 full
474 as={ForwardButton}
475 className="mt4"
476 solid
477 success
478 disabled
479 accessory={`${visualProgress}/${fields.length}`}>
480 {buttonText(status, fields.length)}
481 </Grid.Item>
482 );
483 }
485 if (isSending) {
486 return (
487 <Grid.Item
488 full
489 as={ProgressButton}
490 className="mt4"
491 solid
492 success
493 disabled
494 accessory={`${visualProgress}/${fields.length}`}
495 progress={percentProgress}
496 color={isGenerating ? 'black' : 'green4'}>
497 {buttonText(status, fields.length)}
498 </Grid.Item>
499 );
500 }
502 return null;
503 };
505 return (
506 <Grid gap={3}>
507 <BridgeForm
508 validate={validate}
509 onSubmit={onSubmit}
510 initialValues={INITIAL_VALUES}>
511 {({ handleSubmit }) => (
512 <FieldArray name="emails">
513 {({ fields }) => {
514 const sentInviteNames = Object.keys(receipts);
515 return (
516 <>
517 <Grid.Item full as={Flex} justify="end">
518 {/* use hidden class instead of removing component from dom */}
519 {/* in order to avoid janky reflow */}
520 <IconButton
521 onClick={() => fields.push('')}
522 disabled={!canInput || fields.length >= maxInvitesToSend}
523 className={cn({ hidden: isDone })}
524 solid>
525 +
526 </IconButton>
527 </Grid.Item>
529 {isDone ? (
530 <>
531 <Grid.Item as={Text} className="f5" full>
532 <Highlighted>
533 {pluralize(sentInviteNames.length, 'invite')}
534 </Highlighted>{' '}
535 {pluralize(sentInviteNames.length, 'has', 'have')} been
536 successfully sent
537 </Grid.Item>
539 {sentInviteNames.map(name => (
540 <Grid.Item as={HelpText} key={name} full>
541 <Field name={name}>
542 {({ input: { value } }) => value}
543 </Field>
544 </Grid.Item>
545 ))}
546 </>
547 ) : (
548 <>
549 {fields.map((name, i) => {
550 const isFirst = i === 0;
551 return (
552 <Grid.Item
553 key={name}
554 full
555 as={Grid}
556 gap={3}
557 onMouseOver={() => setHovered({ [name]: true })}
558 onMouseLeave={() => setHovered({ [name]: false })}>
559 <Grid.Item
560 cols={[1, 11]}
561 as={EmailInput}
562 name={name}
563 label={isFirst ? 'Email Address' : undefined}
564 accessory={accessoryFor(name)}
565 />
566 <Field name={name}>
567 {({ meta: { active } }) => {
568 return (
569 <>
570 {!isFirst &&
571 (active || hovered[name]) &&
572 canInput && (
573 <Grid.Item
574 cols={[11, 13]}
575 justifySelf="end"
576 alignSelf="center">
577 <IconButton
578 onClick={() => fields.remove(i)}
579 solid
580 secondary>
581 -
582 </IconButton>
583 </Grid.Item>
584 )}
585 </>
586 );
587 }}
588 </Field>
589 </Grid.Item>
590 );
591 })}
593 {renderButton({ handleSubmit, fields })}
595 {needFunds && (
596 <Grid.Item full as={NeedFundsNotice} {...needFunds} />
597 )}
599 <Grid.Item full as={FormError} />
601 {generalError && (
602 <Grid.Item full as={ErrorText}>
603 {generalError}
604 </Grid.Item>
605 )}
606 </>
607 )}
608 </>
609 );
610 }}
611 </FieldArray>
612 )}
613 </BridgeForm>
614 </Grid>
615 );