on 79bacf2 help sign in
bridge/src/views/Invite/InviteEmail.js
615 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, toBN } 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';
61import { ForwardButton } from 'components/Buttons';
63const INITIAL_VALUES = { emails: [''] };
65const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
66const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
68const STATUS = {
69 INPUT: 'INPUT',
70 GENERATING: 'GENERATING',
71 CAN_SEND: 'CAN_SEND',
72 FUNDING: 'FUNDING',
73 SENDING: 'SENDING',
74 SUCCESS: 'SUCCESS',
75 FAILURE: 'FAILURE',
76};
78const nameForEmailField = i => `emails[${i}]`;
80const buttonText = (status, count) => {
81 switch (status) {
82 case STATUS.INPUT:
83 return `Generate ${pluralize(count, 'Invite')}`;
84 case STATUS.GENERATING:
85 return `Generating ${pluralize(count, 'Invite')}...`;
86 case STATUS.CAN_SEND:
87 return `Send ${pluralize(count, 'Invite')}`;
88 case STATUS.FUNDING:
89 return `Waiting on Funds...`;
90 case STATUS.SENDING:
91 return `Sending ${pluralize(count, 'Invite')}...`;
92 case STATUS.FAILURE:
93 default:
94 return 'Error';
95 }
96};
98const buildAccessoryFor = (dones, errors) => name => {
99 if (dones[name]) return <AccessoryIcon.Success />;
100 if (errors[name]) return <AccessoryIcon.Failure />;
101 return <AccessoryIcon.Pending />;
102};
104export default function InviteEmail() {
105 const { contracts, web3, networkType } = useNetwork();
106 const { wallet, walletType, walletHdPath } = useWallet();
107 const { syncInvites, getInvites } = usePointCache();
108 const { pointCursor } = usePointCursor();
109 const point = need.point(pointCursor);
110 const { getHasReceived, sendMail } = useMailer();
111 const { gasPrice } = useGasPrice();
113 const cachedEmails = useRef({});
115 const { availableInvites } = getInvites(point);
116 const maxInvitesToSend = availableInvites.matchWith({
117 Nothing: () => 0,
118 Just: p => p.value,
119 });
121 // manage per-input state
122 const [hovered, setHovered] = useSetState();
123 const [invites, addInvite, clearInvites] = useSetState();
124 const [receipts, addReceipt, clearReceipts] = useSetState();
125 const [errors, addError] = useSetState();
127 // manage general state that affects the whole form
128 const [status, setStatus] = useState(STATUS.INPUT);
129 const [needFunds, setNeedFunds] = useState(null);
130 const [generalError, setGeneralError] = useState(null);
132 // derive booleans from status
133 const canInput = status === STATUS.INPUT;
134 const isGenerating = status === STATUS.GENERATING;
135 const canSend = status === STATUS.CAN_SEND;
136 const isSending = status === STATUS.SENDING;
137 const isFailed = status === STATUS.FAILURE;
138 const isDone = status === STATUS.SUCCESS;
140 const validateHasReceived = useCallback(
141 async email => {
142 const hasReceived = await getHasReceived(email);
143 if (hasReceived) {
144 return HAS_RECEIVED_TEXT;
145 }
146 },
147 [getHasReceived]
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 }, [
379 web3,
380 wallet,
381 point,
382 gasPrice,
383 invites,
384 clearReceipts,
385 addReceipt,
386 sendMail,
387 ]);
389 const onSubmit = useCallback(
390 async values => {
391 cachedEmails.current = values.emails.reduce((memo, email, i) => {
392 memo[nameForEmailField(i)] = email;
393 return memo;
394 }, {});
395 setStatus(STATUS.GENERATING);
396 const errors = await generateInvites(values);
397 if (hasErrors(errors)) {
398 if (onlyHasWarning(errors)) {
399 setStatus(STATUS.CAN_SEND);
400 }
402 return errors;
403 }
405 await timeout(500); // wait for progress animation to complete.
407 setStatus(STATUS.CAN_SEND);
408 },
409 [generateInvites]
410 );
412 const doSend = useCallback(async () => {
413 setGeneralError(null);
414 try {
415 setStatus(STATUS.SENDING);
416 await sendInvites();
417 setStatus(STATUS.SUCCESS);
418 } catch (error) {
419 console.error(error);
420 setGeneralError(error.message);
421 setStatus(STATUS.FAILURE);
422 }
423 }, [sendInvites]);
425 // when we transition to done, sync invites because we just sent some
426 // and therefore know that state has changed
427 useEffect(() => {
428 if (isDone) {
429 syncInvites(point);
430 }
431 }, [isDone, syncInvites, point]);
433 const renderButton = ({ handleSubmit, fields }) => {
434 if (canInput) {
435 return (
436 <Grid.Item
437 full
438 as={SubmitButton}
439 handleSubmit={handleSubmit}
440 accessory={`${visualProgress}/${fields.length}`}>
441 {buttonText(status, fields.length)}
442 </Grid.Item>
443 );
444 }
446 if (isGenerating) {
447 return (
448 <Grid.Item
449 full
450 as={ProgressButton}
451 solid
452 disabled
453 className="mt4"
454 accessory={`${visualProgress}/${fields.length}`}
455 progress={percentProgress}
456 color="black">
457 {buttonText(status, fields.length)}
458 </Grid.Item>
459 );
460 }
462 if (canSend) {
463 return (
464 <Grid.Item
465 full
466 as={ForwardButton}
467 className="mt4"
468 solid
469 success
470 accessory={`${visualProgress}/${fields.length}`}
471 onClick={doSend}>
472 {buttonText(status, fields.length)}
473 </Grid.Item>
474 );
475 }
477 if (isSending) {
478 return (
479 <Grid.Item
480 full
481 as={ProgressButton}
482 className="mt4"
483 solid
484 success
485 disabled
486 accessory={`${visualProgress}/${fields.length}`}
487 progress={percentProgress}
488 color={isGenerating ? 'black' : 'green4'}>
489 {buttonText(status, fields.length)}
490 </Grid.Item>
491 );
492 }
494 return null;
495 };
497 return (
498 <Grid gap={3}>
499 <BridgeForm
500 validate={validate}
501 onSubmit={onSubmit}
502 initialValues={INITIAL_VALUES}>
503 {({ handleSubmit }) => (
504 <FieldArray name="emails">
505 {({ fields }) => {
506 const sentInviteNames = Object.keys(receipts);
507 return (
508 <>
509 <Grid.Item full as={Flex} justify="end">
510 {/* use hidden class instead of removing component from dom */}
511 {/* in order to avoid janky reflow */}
512 <IconButton
513 onClick={() => fields.push('')}
514 disabled={!canInput || fields.length >= maxInvitesToSend}
515 className={cn({ hidden: isDone })}
516 solid>
517 +
518 </IconButton>
519 </Grid.Item>
521 {isDone ? (
522 <>
523 <Grid.Item as={Text} className="f5" full>
524 <Highlighted>
525 {pluralize(sentInviteNames.length, 'invite')}
526 </Highlighted>{' '}
527 {pluralize(sentInviteNames.length, 'has', 'have')} been
528 successfully sent
529 </Grid.Item>
531 {sentInviteNames.map(name => (
532 <Grid.Item as={HelpText} key={name} full>
533 <Field name={name}>
534 {({ input: { value } }) => value}
535 </Field>
536 </Grid.Item>
537 ))}
538 </>
539 ) : (
540 <>
541 {fields.map((name, i) => {
542 const isFirst = i === 0;
543 return (
544 <Grid.Item
545 key={name}
546 full
547 as={Grid}
548 gap={3}
549 onMouseOver={() => setHovered({ [name]: true })}
550 onMouseLeave={() => setHovered({ [name]: false })}>
551 <Grid.Item
552 cols={[1, 11]}
553 as={EmailInput}
554 name={name}
555 label={isFirst ? 'Email Address' : undefined}
556 accessory={accessoryFor(name)}
557 />
558 <Field name={name}>
559 {({ meta: { active } }) => {
560 return (
561 <>
562 {!isFirst &&
563 (active || hovered[name]) &&
564 canInput && (
565 <Grid.Item
566 cols={[11, 13]}
567 justifySelf="end"
568 alignSelf="center">
569 <IconButton
570 onClick={() => fields.remove(i)}
571 solid
572 secondary>
573 -
574 </IconButton>
575 </Grid.Item>
576 )}
577 </>
578 );
579 }}
580 </Field>
581 </Grid.Item>
582 );
583 })}
585 {renderButton({ handleSubmit, fields })}
587 {needFunds && (
588 <Grid.Item full>
589 <Highlighted warning>
590 Your ownership address {needFunds.address} needs at
591 least {fromWei(needFunds.minBalance)} ETH and
592 currently has {fromWei(needFunds.balance)} ETH.
593 Waiting until the account has enough funds.
594 </Highlighted>
595 </Grid.Item>
596 )}
598 <Grid.Item full as={FormError} />
600 {generalError && (
601 <Grid.Item full as={ErrorText}>
602 {generalError}
603 </Grid.Item>
604 )}
605 </>
606 )}
607 </>
608 );
609 }}
610 </FieldArray>
611 )}
612 </BridgeForm>
613 </Grid>
614 );