on 350b308 help sign in
bridge/src/views/Invite/InviteEmail.js
640 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 gasPrice,
388 point,
389 clearReceipts,
390 invites,
391 addReceipt,
392 sendMail,
393 message,
394 ]);
396 const onSubmit = useCallback(
397 async values => {
398 setMessage(values.message);
399 cachedEmails.current = values.emails.reduce((memo, email, i) => {
400 memo[nameForEmailField(i)] = email;
401 return memo;
402 }, {});
403 setStatus(STATUS.GENERATING);
404 const errors = await generateInvites(values);
405 if (hasErrors(errors)) {
406 if (onlyHasWarning(errors)) {
407 setStatus(STATUS.CAN_SEND);
408 }
410 return errors;
411 }
413 await timeout(500); // wait for progress animation to complete.
415 setStatus(STATUS.CAN_SEND);
416 },
417 [generateInvites]
418 );
420 const doSend = useCallback(async () => {
421 setGeneralError(null);
422 try {
423 setStatus(STATUS.SENDING);
424 await sendInvites();
425 setStatus(STATUS.SUCCESS);
426 } catch (error) {
427 console.error(error);
428 setGeneralError(error.message);
429 setStatus(STATUS.FAILURE);
430 }
431 }, [sendInvites]);
433 // when we transition to done, sync invites because we just sent some
434 // and therefore know that state has changed
435 useEffect(() => {
436 if (isDone) {
437 syncInvites(point);
438 }
439 }, [isDone, syncInvites, point]);
441 const renderButton = ({ handleSubmit, fields }) => {
442 if (canInput) {
443 return (
444 <Grid.Item
445 full
446 as={SubmitButton}
447 handleSubmit={handleSubmit}
448 accessory={`${visualProgress}/${fields.length}`}>
449 {buttonText(status, fields.length)}
450 </Grid.Item>
451 );
452 }
454 if (isGenerating) {
455 return (
456 <Grid.Item
457 full
458 as={ProgressButton}
459 solid
460 disabled
461 className="mt4"
462 accessory={`${visualProgress}/${fields.length}`}
463 progress={percentProgress}
464 color="black">
465 {buttonText(status, fields.length)}
466 </Grid.Item>
467 );
468 }
470 if (canSend) {
471 return (
472 <Grid.Item
473 full
474 as={ForwardButton}
475 className="mt4"
476 solid
477 success
478 onClick={doSend}>
479 {buttonText(status, fields.length)}
480 </Grid.Item>
481 );
482 }
484 if (isFunding) {
485 return (
486 <Grid.Item
487 full
488 as={ForwardButton}
489 className="mt4"
490 solid
491 success
492 disabled
493 accessory={`${visualProgress}/${fields.length}`}>
494 {buttonText(status, fields.length)}
495 </Grid.Item>
496 );
497 }
499 if (isSending) {
500 return (
501 <Grid.Item
502 full
503 as={ProgressButton}
504 className="mt4"
505 solid
506 success
507 disabled
508 accessory={`${visualProgress}/${fields.length}`}
509 progress={percentProgress}
510 color={isGenerating ? 'black' : 'green4'}>
511 {buttonText(status, fields.length)}
512 </Grid.Item>
513 );
514 }
516 return null;
517 };
519 return (
520 <Grid gap={3}>
521 <BridgeForm
522 validate={validate}
523 onSubmit={onSubmit}
524 initialValues={INITIAL_VALUES}>
525 {({ handleSubmit }) => (
526 <FieldArray name="emails">
527 {({ fields }) => {
528 const sentInviteNames = Object.keys(receipts);
529 return (
530 <>
531 <Grid.Item full as={Flex} justify="end">
532 {/* use hidden class instead of removing component from dom */}
533 {/* in order to avoid janky reflow */}
534 <IconButton
535 onClick={() => fields.push('')}
536 disabled={!canInput || fields.length >= maxInvitesToSend}
537 className={cn({ hidden: isDone })}
538 solid>
539 +
540 </IconButton>
541 </Grid.Item>
543 {isDone ? (
544 <>
545 <Grid.Item as={Text} className="f5" full>
546 <Highlighted>
547 {pluralize(sentInviteNames.length, 'invite')}
548 </Highlighted>{' '}
549 {pluralize(sentInviteNames.length, 'has', 'have')} been
550 successfully sent
551 </Grid.Item>
553 {sentInviteNames.map(name => (
554 <Grid.Item as={HelpText} key={name} full>
555 <Field name={name}>
556 {({ input: { value } }) => value}
557 </Field>
558 </Grid.Item>
559 ))}
560 </>
561 ) : (
562 <>
563 {fields.map((name, i) => {
564 const isFirst = i === 0;
565 return (
566 <Grid.Item
567 key={name}
568 full
569 as={Grid}
570 gap={3}
571 onMouseOver={() => setHovered({ [name]: true })}
572 onMouseLeave={() => setHovered({ [name]: false })}>
573 <Grid.Item
574 cols={[1, 11]}
575 as={EmailInput}
576 name={name}
577 label={isFirst ? 'Email Address' : undefined}
578 accessory={accessoryFor(name)}
579 />
580 <Field name={name}>
581 {({ meta: { active } }) => {
582 return (
583 <>
584 {!isFirst &&
585 (active || hovered[name]) &&
586 canInput && (
587 <Grid.Item
588 cols={[11, 13]}
589 justifySelf="end"
590 alignSelf="center">
591 <IconButton
592 onClick={() => fields.remove(i)}
593 solid
594 secondary>
595 -
596 </IconButton>
597 </Grid.Item>
598 )}
599 </>
600 );
601 }}
602 </Field>
603 </Grid.Item>
604 );
605 })}
607 <Grid.Item
608 full
609 as={Input}
610 type="text"
611 name="message"
612 label="Message (optional)"
613 placeholder="Welcome aboard!"
614 value={message}
615 />
617 {renderButton({ handleSubmit, fields })}
619 {needFunds && (
620 <Grid.Item full as={NeedFundsNotice} {...needFunds} />
621 )}
623 <Grid.Item full as={FormError} />
625 {generalError && (
626 <Grid.Item full as={ErrorText}>
627 {generalError}
628 </Grid.Item>
629 )}
630 </>
631 )}
632 </>
633 );
634 }}
635 </FieldArray>
636 )}
637 </BridgeForm>
638 </Grid>
639 );