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