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