on 98fd7cb help sign in
bridge/src/views/Invite/InviteEmail.js
639 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;
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 toWei(totalCost.toString(), 'gwei'),
320 names.map(name => invites[name].rawTx),
321 (address, minBalance, balance) =>
322 setNeedFunds({ address, minBalance, balance }),
323 () => setNeedFunds(undefined)
324 );
326 setStatus(STATUS.SENDING);
327 clearReceipts();
329 let unsentInvites = [];
330 let orphanedInvites = [];
331 const txAndMailings = names.map(async name => {
332 const invite = invites[name];
333 try {
334 const txHash = await sendSignedTransaction(
335 _web3,
336 invite.signedTx,
337 tankWasUsed
338 );
340 await waitForTransactionConfirm(_web3, txHash);
341 } catch (error) {
342 console.error(error);
343 unsentInvites.push(invite);
344 return;
345 }
347 try {
348 await sendMail(
349 invite.email,
350 invite.ticket,
351 ob.patp(point),
352 message,
353 invite.rawTx
354 );
355 } catch (error) {
356 console.error(error);
357 orphanedInvites.push(invite);
358 }
360 addReceipt({ [name]: true });
361 });
363 await Promise.all(txAndMailings);
364 // if there are any receipt errors, throw a general error
365 let errorString = '';
366 if (orphanedInvites.length > 0) {
367 errorString =
368 'Not all invite emails were sent. ' +
369 'Please send the following invite codes manually: ' +
370 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
371 '. ';
372 }
373 if (unsentInvites.length > 0) {
374 errorString =
375 errorString +
376 'Not all invites were created. ' +
377 'Did not send invites for: ' +
378 unsentInvites.map(i => i.email).join(', ') +
379 '.';
380 }
381 if (errorString !== '') {
382 throw new Error(errorString);
383 }
384 }, [
385 web3,
386 wallet,
387 point,
388 gasPrice,
389 invites,
390 clearReceipts,
391 addReceipt,
392 sendMail,
393 ]);
395 const onSubmit = useCallback(
396 async values => {
397 setMessage(values.message);
398 cachedEmails.current = values.emails.reduce((memo, email, i) => {
399 memo[nameForEmailField(i)] = email;
400 return memo;
401 }, {});
402 setStatus(STATUS.GENERATING);
403 const errors = await generateInvites(values);
404 if (hasErrors(errors)) {
405 if (onlyHasWarning(errors)) {
406 setStatus(STATUS.CAN_SEND);
407 }
409 return errors;
410 }
412 await timeout(500); // wait for progress animation to complete.
414 setStatus(STATUS.CAN_SEND);
415 },
416 [generateInvites]
417 );
419 const doSend = useCallback(async () => {
420 setGeneralError(null);
421 try {
422 setStatus(STATUS.SENDING);
423 await sendInvites();
424 setStatus(STATUS.SUCCESS);
425 } catch (error) {
426 console.error(error);
427 setGeneralError(error.message);
428 setStatus(STATUS.FAILURE);
429 }
430 }, [sendInvites]);
432 // when we transition to done, sync invites because we just sent some
433 // and therefore know that state has changed
434 useEffect(() => {
435 if (isDone) {
436 syncInvites(point);
437 }
438 }, [isDone, syncInvites, point]);
440 const renderButton = ({ handleSubmit, fields }) => {
441 if (canInput) {
442 return (
443 <Grid.Item
444 full
445 as={SubmitButton}
446 handleSubmit={handleSubmit}
447 accessory={`${visualProgress}/${fields.length}`}>
448 {buttonText(status, fields.length)}
449 </Grid.Item>
450 );
451 }
453 if (isGenerating) {
454 return (
455 <Grid.Item
456 full
457 as={ProgressButton}
458 solid
459 disabled
460 className="mt4"
461 accessory={`${visualProgress}/${fields.length}`}
462 progress={percentProgress}
463 color="black">
464 {buttonText(status, fields.length)}
465 </Grid.Item>
466 );
467 }
469 if (canSend) {
470 return (
471 <Grid.Item
472 full
473 as={ForwardButton}
474 className="mt4"
475 solid
476 success
477 onClick={doSend}>
478 {buttonText(status, fields.length)}
479 </Grid.Item>
480 );
481 }
483 if (isFunding) {
484 return (
485 <Grid.Item
486 full
487 as={ForwardButton}
488 className="mt4"
489 solid
490 success
491 disabled
492 accessory={`${visualProgress}/${fields.length}`}>
493 {buttonText(status, fields.length)}
494 </Grid.Item>
495 );
496 }
498 if (isSending) {
499 return (
500 <Grid.Item
501 full
502 as={ProgressButton}
503 className="mt4"
504 solid
505 success
506 disabled
507 accessory={`${visualProgress}/${fields.length}`}
508 progress={percentProgress}
509 color={isGenerating ? 'black' : 'green4'}>
510 {buttonText(status, fields.length)}
511 </Grid.Item>
512 );
513 }
515 return null;
516 };
518 return (
519 <Grid gap={3}>
520 <BridgeForm
521 validate={validate}
522 onSubmit={onSubmit}
523 initialValues={INITIAL_VALUES}>
524 {({ handleSubmit }) => (
525 <FieldArray name="emails">
526 {({ fields }) => {
527 const sentInviteNames = Object.keys(receipts);
528 return (
529 <>
530 <Grid.Item full as={Flex} justify="end">
531 {/* use hidden class instead of removing component from dom */}
532 {/* in order to avoid janky reflow */}
533 <IconButton
534 onClick={() => fields.push('')}
535 disabled={!canInput || fields.length >= maxInvitesToSend}
536 className={cn({ hidden: isDone })}
537 solid>
538 +
539 </IconButton>
540 </Grid.Item>
542 {isDone ? (
543 <>
544 <Grid.Item as={Text} className="f5" full>
545 <Highlighted>
546 {pluralize(sentInviteNames.length, 'invite')}
547 </Highlighted>{' '}
548 {pluralize(sentInviteNames.length, 'has', 'have')} been
549 successfully sent
550 </Grid.Item>
552 {sentInviteNames.map(name => (
553 <Grid.Item as={HelpText} key={name} full>
554 <Field name={name}>
555 {({ input: { value } }) => value}
556 </Field>
557 </Grid.Item>
558 ))}
559 </>
560 ) : (
561 <>
562 {fields.map((name, i) => {
563 const isFirst = i === 0;
564 return (
565 <Grid.Item
566 key={name}
567 full
568 as={Grid}
569 gap={3}
570 onMouseOver={() => setHovered({ [name]: true })}
571 onMouseLeave={() => setHovered({ [name]: false })}>
572 <Grid.Item
573 cols={[1, 11]}
574 as={EmailInput}
575 name={name}
576 label={isFirst ? 'Email Address' : undefined}
577 accessory={accessoryFor(name)}
578 />
579 <Field name={name}>
580 {({ meta: { active } }) => {
581 return (
582 <>
583 {!isFirst &&
584 (active || hovered[name]) &&
585 canInput && (
586 <Grid.Item
587 cols={[11, 13]}
588 justifySelf="end"
589 alignSelf="center">
590 <IconButton
591 onClick={() => fields.remove(i)}
592 solid
593 secondary>
594 -
595 </IconButton>
596 </Grid.Item>
597 )}
598 </>
599 );
600 }}
601 </Field>
602 </Grid.Item>
603 );
604 })}
606 <Grid.Item
607 full
608 as={Input}
609 type="text"
610 name="message"
611 label="Message (optional)"
612 placeholder="Welcome aboard!"
613 value={message}
614 />
616 {renderButton({ handleSubmit, fields })}
618 {needFunds && (
619 <Grid.Item full as={NeedFundsNotice} {...needFunds} />
620 )}
622 <Grid.Item full as={FormError} />
624 {generalError && (
625 <Grid.Item full as={ErrorText}>
626 {generalError}
627 </Grid.Item>
628 )}
629 </>
630 )}
631 </>
632 );
633 }}
634 </FieldArray>
635 )}
636 </BridgeForm>
637 </Grid>
638 );