on 44dc2fe help sign in
bridge/src/views/Invite/InviteEmail.js
637 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(async email => {
146 // const hasReceived = await getHasReceived(email);
147 // if (hasReceived) {
148 // return HAS_RECEIVED_TEXT;
149 // }
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 totalCost = toBN(GAS_LIMIT)
310 .mul(toBN(gasPrice))
311 .mul(toBN(emails.length));
312 const tankWasUsed = await tank.ensureFundsFor(
313 _web3,
314 point,
315 _wallet.address,
316 toWei(totalCost.toString(), 'gwei'),
317 names.map(name => invites[name].rawTx),
318 (address, minBalance, balance) =>
319 setNeedFunds({ address, minBalance, balance }),
320 () => setNeedFunds(undefined)
321 );
323 setStatus(STATUS.SENDING);
324 clearReceipts();
326 let unsentInvites = [];
327 let orphanedInvites = [];
328 const txAndMailings = names.map(async name => {
329 const invite = invites[name];
330 try {
331 const txHash = await sendSignedTransaction(
332 _web3,
333 invite.signedTx,
334 tankWasUsed
335 );
337 await waitForTransactionConfirm(_web3, txHash);
338 } catch (error) {
339 console.error(error);
340 unsentInvites.push(invite);
341 return;
342 }
344 try {
345 await sendMail(
346 invite.email,
347 invite.ticket,
348 ob.patp(point),
349 message,
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 }, [
382 web3,
383 wallet,
384 gasPrice,
385 point,
386 clearReceipts,
387 invites,
388 addReceipt,
389 sendMail,
390 message,
391 ]);
393 const onSubmit = useCallback(
394 async values => {
395 setMessage(values.message);
396 cachedEmails.current = values.emails.reduce((memo, email, i) => {
397 memo[nameForEmailField(i)] = email;
398 return memo;
399 }, {});
400 setStatus(STATUS.GENERATING);
401 const errors = await generateInvites(values);
402 if (hasErrors(errors)) {
403 if (onlyHasWarning(errors)) {
404 setStatus(STATUS.CAN_SEND);
405 }
407 return errors;
408 }
410 await timeout(500); // wait for progress animation to complete.
412 setStatus(STATUS.CAN_SEND);
413 },
414 [generateInvites]
415 );
417 const doSend = useCallback(async () => {
418 setGeneralError(null);
419 try {
420 setStatus(STATUS.SENDING);
421 await sendInvites();
422 setStatus(STATUS.SUCCESS);
423 } catch (error) {
424 console.error(error);
425 setGeneralError(error.message);
426 setStatus(STATUS.FAILURE);
427 }
428 }, [sendInvites]);
430 // when we transition to done, sync invites because we just sent some
431 // and therefore know that state has changed
432 useEffect(() => {
433 if (isDone) {
434 syncInvites(point);
435 }
436 }, [isDone, syncInvites, point]);
438 const renderButton = ({ handleSubmit, fields }) => {
439 if (canInput) {
440 return (
441 <Grid.Item
442 full
443 as={SubmitButton}
444 handleSubmit={handleSubmit}
445 accessory={`${visualProgress}/${fields.length}`}>
446 {buttonText(status, fields.length)}
447 </Grid.Item>
448 );
449 }
451 if (isGenerating) {
452 return (
453 <Grid.Item
454 full
455 as={ProgressButton}
456 solid
457 disabled
458 className="mt4"
459 accessory={`${visualProgress}/${fields.length}`}
460 progress={percentProgress}
461 color="black">
462 {buttonText(status, fields.length)}
463 </Grid.Item>
464 );
465 }
467 if (canSend) {
468 return (
469 <Grid.Item
470 full
471 as={ForwardButton}
472 className="mt4"
473 solid
474 success
475 onClick={doSend}>
476 {buttonText(status, fields.length)}
477 </Grid.Item>
478 );
479 }
481 if (isFunding) {
482 return (
483 <Grid.Item
484 full
485 as={ForwardButton}
486 className="mt4"
487 solid
488 success
489 disabled
490 accessory={`${visualProgress}/${fields.length}`}>
491 {buttonText(status, fields.length)}
492 </Grid.Item>
493 );
494 }
496 if (isSending) {
497 return (
498 <Grid.Item
499 full
500 as={ProgressButton}
501 className="mt4"
502 solid
503 success
504 disabled
505 accessory={`${visualProgress}/${fields.length}`}
506 progress={percentProgress}
507 color={isGenerating ? 'black' : 'green4'}>
508 {buttonText(status, fields.length)}
509 </Grid.Item>
510 );
511 }
513 return null;
514 };
516 return (
517 <Grid gap={3}>
518 <BridgeForm
519 validate={validate}
520 onSubmit={onSubmit}
521 initialValues={INITIAL_VALUES}>
522 {({ handleSubmit }) => (
523 <FieldArray name="emails">
524 {({ fields }) => {
525 const sentInviteNames = Object.keys(receipts);
526 return (
527 <>
528 <Grid.Item full as={Flex} justify="end">
529 {/* use hidden class instead of removing component from dom */}
530 {/* in order to avoid janky reflow */}
531 <IconButton
532 onClick={() => fields.push('')}
533 disabled={!canInput || fields.length >= maxInvitesToSend}
534 className={cn({ hidden: isDone })}
535 solid>
536 +
537 </IconButton>
538 </Grid.Item>
540 {isDone ? (
541 <>
542 <Grid.Item as={Text} className="f5" full>
543 <Highlighted>
544 {pluralize(sentInviteNames.length, 'invite')}
545 </Highlighted>{' '}
546 {pluralize(sentInviteNames.length, 'has', 'have')} been
547 successfully sent
548 </Grid.Item>
550 {sentInviteNames.map(name => (
551 <Grid.Item as={HelpText} key={name} full>
552 <Field name={name}>
553 {({ input: { value } }) => value}
554 </Field>
555 </Grid.Item>
556 ))}
557 </>
558 ) : (
559 <>
560 {fields.map((name, i) => {
561 const isFirst = i === 0;
562 return (
563 <Grid.Item
564 key={name}
565 full
566 as={Grid}
567 gap={3}
568 onMouseOver={() => setHovered({ [name]: true })}
569 onMouseLeave={() => setHovered({ [name]: false })}>
570 <Grid.Item
571 cols={[1, 11]}
572 as={EmailInput}
573 name={name}
574 label={isFirst ? 'Email Address' : undefined}
575 accessory={accessoryFor(name)}
576 />
577 <Field name={name}>
578 {({ meta: { active } }) => {
579 return (
580 <>
581 {!isFirst &&
582 (active || hovered[name]) &&
583 canInput && (
584 <Grid.Item
585 cols={[11, 13]}
586 justifySelf="end"
587 alignSelf="center">
588 <IconButton
589 onClick={() => fields.remove(i)}
590 solid
591 secondary>
592 -
593 </IconButton>
594 </Grid.Item>
595 )}
596 </>
597 );
598 }}
599 </Field>
600 </Grid.Item>
601 );
602 })}
604 <Grid.Item
605 full
606 as={Input}
607 type="text"
608 name="message"
609 label="Message (optional)"
610 placeholder="Welcome aboard!"
611 value={message}
612 />
614 {renderButton({ handleSubmit, fields })}
616 {needFunds && (
617 <Grid.Item full as={NeedFundsNotice} {...needFunds} />
618 )}
620 <Grid.Item full as={FormError} />
622 {generalError && (
623 <Grid.Item full as={ErrorText}>
624 {generalError}
625 </Grid.Item>
626 )}
627 </>
628 )}
629 </>
630 );
631 }}
632 </FieldArray>
633 )}
634 </BridgeForm>
635 </Grid>
636 );