on 42b3758 help sign in
bridge/src/views/Invite/InviteEmail.js
617 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 isSending = status === STATUS.SENDING;
139 const isFailed = status === STATUS.FAILURE;
140 const isDone = status === STATUS.SUCCESS;
142 const validateHasReceived = useCallback(
143 async email => {
144 const hasReceived = await getHasReceived(email);
145 if (hasReceived) {
146 return HAS_RECEIVED_TEXT;
147 }
148 },
149 [getHasReceived]
150 );
152 const validateForm = useCallback((values, errors) => {
153 if (hasErrors(errors)) {
154 return errors;
155 }
157 // check for email uniqenesss
158 const emails = values.emails.filter(d => !!d);
159 if (uniq(emails).length !== emails.length) {
160 return { [FORM_ERROR]: 'Duplicate email.' };
161 }
162 }, []);
164 const validate = useMemo(
165 () =>
166 composeValidator(
167 {
168 emails: buildArrayValidator(buildEmailValidator(validateHasReceived)),
169 },
170 validateForm
171 ),
172 [validateForm, validateHasReceived]
173 );
175 // progress is [0, .length] of invites or receipts, as we're generating them
176 const progress = isGenerating
177 ? Object.keys(invites).length
178 : isSending
179 ? Object.keys(receipts).length
180 : null;
181 const percentProgress =
182 progress !== null
183 ? progress / Object.keys(cachedEmails.current).length
184 : null;
185 const visualProgress = progress === null ? '-' : `${progress + 1}`;
187 // build a builder for the accessory to the input, depending on status
188 const accessoryFor = (() => {
189 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
190 if (isSending) return buildAccessoryFor(receipts, errors);
191 if (isFailed) return buildAccessoryFor({}, errors);
192 return () => null;
193 })();
195 const generateInvites = useCallback(
196 async values => {
197 const _contracts = contracts.getOrElse(null);
198 const _web3 = web3.getOrElse(null);
199 const _wallet = wallet.getOrElse(null);
200 if (!_contracts || !_web3 || !_wallet) {
201 // not using need because we want a custom error
202 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
203 }
205 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
206 const chainId = await _web3.eth.net.getId();
207 const planets = await azimuth.delegatedSending.getPlanetsToSend(
208 _contracts,
209 point,
210 values.emails.length
211 );
213 // account for the race condition where invites got used up while we were
214 // composing our target list
215 if (planets.length < values.emails.length) {
216 // resync invites to the cache, since they're out of date
217 syncInvites(point);
219 return {
220 [FORM_ERROR]:
221 `Can currently only send ${planets.length} invites. ` +
222 `Please remove invites until you are within the limit.`,
223 };
224 }
226 clearInvites();
227 // NB(shrugs) - must be processed in serial because main thread, etc
228 let errorCount = 0;
229 for (let i = 0; i < values.emails.length; i++) {
230 const name = nameForEmailField(i);
231 try {
232 const email = values.emails[i];
233 const planet = planets[i];
235 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
236 MIN_PLANET
237 // we're always giving planets, so generate a ticket of the correct size
238 );
240 const inviteTx = azimuth.delegatedSending.sendPoint(
241 _contracts,
242 point,
243 planet,
244 owner.keys.address
245 );
247 const signedTx = await signTransaction({
248 wallet: _wallet,
249 walletType,
250 walletHdPath,
251 networkType,
252 chainId,
253 nonce: nonce + i,
254 // TODO: ^ make a useTransactionSigner to encapsulate this logic
255 txn: inviteTx,
256 gasPrice: gasPrice.toFixed(), // expects string gwei
257 gasLimit: GAS_LIMIT.toFixed(),
258 });
260 const rawTx = hexify(signedTx.serialize());
262 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
263 } catch (error) {
264 console.error(error);
265 errorCount++;
266 addError({ [name]: 'Error generating invite.' });
267 }
268 }
270 if (errorCount > 0) {
271 return {
272 [WARNING]: `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
273 errorCount,
274 'error'
275 )} while generating wallets. You can still send the invites that generated correctly.`,
276 };
277 }
278 },
279 [
280 contracts,
281 web3,
282 wallet,
283 point,
284 clearInvites,
285 syncInvites,
286 walletType,
287 walletHdPath,
288 networkType,
289 gasPrice,
290 addInvite,
291 addError,
292 ]
293 );
295 const sendInvites = useCallback(async () => {
296 // compute all of the names of the fields
297 const allFieldNames = Object.keys(cachedEmails.current);
298 // only emails we're sending are the valid ones with invites
299 const names = allFieldNames.filter(name => !!invites[name]);
300 const emails = allFieldNames.map(name => cachedEmails.current[name]);
302 const _web3 = web3.getOrElse(null);
303 const _wallet = wallet.getOrElse(null);
304 if (!_web3 || !_wallet) {
305 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
306 }
308 setStatus(STATUS.FUNDING);
309 const tankWasUsed = await tank.ensureFundsFor(
310 _web3,
311 point,
312 _wallet.address,
313 toWei((gasPrice * GAS_LIMIT * emails.length).toFixed(), 'gwei'),
314 names.map(name => invites[name].rawTx),
315 (address, minBalance, balance) =>
316 setNeedFunds({ address, minBalance, balance }),
317 () => setNeedFunds(undefined)
318 );
320 setStatus(STATUS.SENDING);
321 clearReceipts();
323 let unsentInvites = [];
324 let orphanedInvites = [];
325 const txAndMailings = names.map(async name => {
326 const invite = invites[name];
327 try {
328 const txHash = await sendSignedTransaction(
329 _web3,
330 invite.signedTx,
331 tankWasUsed
332 );
334 await waitForTransactionConfirm(_web3, txHash);
335 } catch (error) {
336 console.error(error);
337 unsentInvites.push(invite);
338 return;
339 }
341 try {
342 await sendMail(
343 invite.email,
344 invite.ticket,
345 ob.patp(point),
346 invite.rawTx
347 );
348 } catch (error) {
349 console.error(error);
350 orphanedInvites.push(invite);
351 }
353 addReceipt({ [name]: true });
354 });
356 await Promise.all(txAndMailings);
357 // if there are any receipt errors, throw a general error
358 let errorString = '';
359 if (orphanedInvites.length > 0) {
360 errorString =
361 'Not all invite emails were sent. ' +
362 'Please send the following invite codes manually: ' +
363 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
364 '. ';
365 }
366 if (unsentInvites.length > 0) {
367 errorString =
368 errorString +
369 'Not all invites were created. ' +
370 'Did not send invites for: ' +
371 unsentInvites.map(i => i.email).join(', ') +
372 '.';
373 }
374 if (errorString !== '') {
375 throw new Error(errorString);
376 }
377 }, [
378 web3,
379 wallet,
380 point,
381 gasPrice,
382 invites,
383 clearReceipts,
384 addReceipt,
385 sendMail,
386 ]);
388 const onSubmit = useCallback(
389 async values => {
390 cachedEmails.current = values.emails.reduce((memo, email, i) => {
391 memo[nameForEmailField(i)] = email;
392 return memo;
393 }, {});
394 setStatus(STATUS.GENERATING);
395 const errors = await generateInvites(values);
396 if (hasErrors(errors)) {
397 if (onlyHasWarning(errors)) {
398 setStatus(STATUS.CAN_SEND);
399 }
401 return errors;
402 }
404 await timeout(500); // wait for progress animation to complete.
406 setStatus(STATUS.CAN_SEND);
407 },
408 [generateInvites]
409 );
411 const doSend = useCallback(async () => {
412 setGeneralError(null);
413 try {
414 setStatus(STATUS.SENDING);
415 await sendInvites();
416 setStatus(STATUS.SUCCESS);
417 } catch (error) {
418 console.error(error);
419 setGeneralError(error.message);
420 setStatus(STATUS.FAILURE);
421 }
422 }, [sendInvites]);
424 // when we transition to done, sync invites because we just sent some
425 // and therefore know that state has changed
426 useEffect(() => {
427 if (isDone) {
428 syncInvites(point);
429 }
430 }, [isDone, syncInvites, point]);
432 const renderButton = ({ handleSubmit, fields }) => {
433 if (canInput) {
434 return (
435 <Grid.Item
436 full
437 as={SubmitButton}
438 handleSubmit={handleSubmit}
439 accessory={`${visualProgress}/${fields.length}`}>
440 {buttonText(status, fields.length)}
441 </Grid.Item>
442 );
443 }
445 if (isGenerating) {
446 return (
447 <Grid.Item
448 full
449 as={ProgressButton}
450 solid
451 disabled
452 className="mt4"
453 accessory={`${visualProgress}/${fields.length}`}
454 progress={percentProgress}
455 color="black">
456 {buttonText(status, fields.length)}
457 </Grid.Item>
458 );
459 }
461 if (canSend) {
462 return (
463 <Grid.Item
464 full
465 as={ForwardButton}
466 className="mt4"
467 solid
468 success
469 accessory={`${visualProgress}/${fields.length}`}
470 onClick={doSend}>
471 {buttonText(status, fields.length)}
472 </Grid.Item>
473 );
474 }
476 if (isSending) {
477 return (
478 <Grid.Item
479 full
480 as={ProgressButton}
481 className="mt4"
482 solid
483 success
484 disabled
485 accessory={`${visualProgress}/${fields.length}`}
486 progress={percentProgress}
487 color={isGenerating ? 'black' : 'green4'}>
488 {buttonText(status, fields.length)}
489 </Grid.Item>
490 );
491 }
493 return null;
494 };
496 return (
497 <Grid gap={3}>
498 <BridgeForm
499 validate={validate}
500 onSubmit={onSubmit}
501 initialValues={INITIAL_VALUES}>
502 {({ handleSubmit }) => (
503 <FieldArray name="emails">
504 {({ fields }) => {
505 const sentInviteNames = Object.keys(receipts);
506 return (
507 <>
508 <Grid.Item full as={Flex} justify="end">
509 {/* use hidden class instead of removing component from dom */}
510 {/* in order to avoid janky reflow */}
511 <IconButton
512 onClick={() => fields.push('')}
513 disabled={!canInput || fields.length >= maxInvitesToSend}
514 className={cn({ hidden: isDone })}
515 solid>
516 +
517 </IconButton>
518 </Grid.Item>
520 {isDone ? (
521 <>
522 <Grid.Item as={Text} className="f5" full>
523 <Highlighted>
524 {pluralize(sentInviteNames.length, 'invite')}
525 </Highlighted>{' '}
526 {pluralize(sentInviteNames.length, 'has', 'have')} been
527 successfully sent
528 </Grid.Item>
530 {sentInviteNames.map(name => (
531 <Grid.Item as={HelpText} key={name} full>
532 <Field name={name}>
533 {({ input: { value } }) => value}
534 </Field>
535 </Grid.Item>
536 ))}
537 </>
538 ) : (
539 <>
540 {fields.map((name, i) => {
541 const isFirst = i === 0;
542 return (
543 <Grid.Item
544 key={name}
545 full
546 as={Grid}
547 gap={3}
548 onMouseOver={() => setHovered({ [name]: true })}
549 onMouseLeave={() => setHovered({ [name]: false })}>
550 <Grid.Item
551 cols={[1, 11]}
552 as={EmailInput}
553 name={name}
554 label={isFirst ? 'Email Address' : undefined}
555 accessory={accessoryFor(name)}
556 />
557 <Field name={name}>
558 {({ meta: { active } }) => {
559 return (
560 <>
561 {!isFirst &&
562 (active || hovered[name]) &&
563 canInput && (
564 <Grid.Item
565 cols={[11, 13]}
566 justifySelf="end"
567 alignSelf="center">
568 <IconButton
569 onClick={() => fields.remove(i)}
570 solid
571 secondary>
572 -
573 </IconButton>
574 </Grid.Item>
575 )}
576 </>
577 );
578 }}
579 </Field>
580 </Grid.Item>
581 );
582 })}
584 {renderButton({ handleSubmit, fields })}
586 {needFunds && (
587 <Grid.Item full>
588 <Highlighted warning>
589 Your ownership address{' '}
590 <CopiableAddress>
591 {needFunds.address}
592 </CopiableAddress>{' '}
593 needs at least {fromWei(needFunds.minBalance)} ETH
594 and currently has {fromWei(needFunds.balance)} ETH.
595 Waiting until the account has enough funds.
596 </Highlighted>
597 </Grid.Item>
598 )}
600 <Grid.Item full as={FormError} />
602 {generalError && (
603 <Grid.Item full as={ErrorText}>
604 {generalError}
605 </Grid.Item>
606 )}
607 </>
608 )}
609 </>
610 );
611 }}
612 </FieldArray>
613 )}
614 </BridgeForm>
615 </Grid>
616 );