on e82c628 help sign in
bridge/src/views/Invite/InviteEmail.js
539 lines 17 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, DEFAULT_GAS_PRICE_GWEI } 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 LoadableButton from 'components/LoadableButton';
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} from 'form/validators';
54import { FORM_ERROR } from 'final-form';
55import SubmitButton from 'form/SubmitButton';
56import FormError from 'form/FormError';
58const INITIAL_VALUES = { emails: [''] };
60const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
61const INVITE_COST = toWei(
62 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
63 'gwei'
64);
65const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
67const STATUS = {
68 INPUT: 'INPUT',
69 GENERATING: 'GENERATING',
70 CAN_SEND: 'CAN_SEND',
71 FUNDING: 'FUNDING',
72 SENDING: 'SENDING',
73 SUCCESS: 'SUCCESS',
74 FAILURE: 'FAILURE',
75};
77const buttonText = (status, count) => {
78 switch (status) {
79 case STATUS.INPUT:
80 return `Generate ${pluralize(count, 'Invite')}`;
81 case STATUS.GENERATING:
82 return `Generating ${pluralize(count, 'Invite')}...`;
83 case STATUS.CAN_SEND:
84 return `Send ${pluralize(count, 'Invite')}`;
85 case STATUS.FUNDING:
86 return `Waiting on Funds...`;
87 case STATUS.SENDING:
88 return `Sending ${pluralize(count, 'Invite')}...`;
89 case STATUS.FAILURE:
90 default:
91 return 'Error';
92 }
93};
95const buildAccessoryFor = (dones, errors) => name => {
96 if (dones[name]) return <AccessoryIcon.Success />;
97 if (errors[name]) return <AccessoryIcon.Failure />;
98 return <AccessoryIcon.Pending />;
99};
101const emailFormatValidator = buildEmailValidator();
103export default function InviteEmail() {
104 const { contracts, web3, networkType } = useNetwork();
105 const { wallet, walletType, walletHdPath } = useWallet();
106 const { syncInvites, getInvites } = usePointCache();
107 const { pointCursor } = usePointCursor();
108 const point = need.point(pointCursor);
109 const { getHasReceived, sendMail } = useMailer();
111 const cachedEmails = useRef([]);
113 const { availableInvites } = getInvites(point);
114 const maxInvitesToSend = availableInvites.matchWith({
115 Nothing: () => 0,
116 Just: p => p.value,
117 });
119 // manage per-input state
120 const [hovered, setHovered] = useSetState();
121 const [invites, addInvite, clearInvites] = useSetState();
122 const [receipts, addReceipt, clearReceipts] = useSetState();
123 const [errors, addError] = useSetState();
125 // manage general state that affects the whole form
126 const [status, setStatus] = useState(STATUS.INPUT);
127 const [needFunds, setNeedFunds] = useState(null);
128 const [generalError, setGeneralError] = useState(null);
130 // derive booleans from status
131 const canInput = status === STATUS.INPUT;
132 const canSend = status === STATUS.CAN_SEND;
133 const isGenerating = status === STATUS.GENERATING;
134 const isSending = status === STATUS.SENDING;
135 const isFailed = status === STATUS.FAILURE;
136 const isDone = status === STATUS.SUCCESS;
138 const validateEmail = useCallback(
139 async email => {
140 // check individual email validity
141 const error = await emailFormatValidator(email);
142 if (error) {
143 return error;
144 }
146 const hasReceived = await getHasReceived(email);
147 if (hasReceived) {
148 return HAS_RECEIVED_TEXT;
149 }
150 },
151 [getHasReceived]
152 );
154 const validateEmails = useCallback(
155 async emails => await Promise.all(emails.map(validateEmail)),
156 [validateEmail]
157 );
159 const validateForm = useCallback(async (values, errors) => {
160 if (hasErrors(errors)) {
161 return errors;
162 }
164 // check for email uniqenesss
165 const emails = values.emails.filter(d => !!d);
166 if (uniq(emails).length !== emails.length) {
167 return { [FORM_ERROR]: 'Duplicate email.' };
168 }
169 }, []);
171 const validate = useMemo(
172 () => composeValidator({ emails: validateEmails }, validateForm),
173 [validateEmails, validateForm]
174 );
176 // progress is [0, .length] of invites or receipts, as we're generating them
177 const progress = isGenerating
178 ? Object.keys(invites).length
179 : isSending
180 ? Object.keys(receipts).length
181 : null;
182 const visualProgress = progress === null ? '-' : `${progress + 1}`;
184 // build a builder for the accessory to the input, depending on status
185 const accessoryFor = (() => {
186 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
187 if (isSending) return buildAccessoryFor(receipts, errors);
188 if (isFailed) return buildAccessoryFor({}, errors);
189 return () => null;
190 })();
192 const generateInvites = useCallback(
193 async values => {
194 const _contracts = contracts.getOrElse(null);
195 const _web3 = web3.getOrElse(null);
196 const _wallet = wallet.getOrElse(null);
197 if (!_contracts || !_web3 || !_wallet) {
198 // not using need because we want a custom error
199 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
200 }
202 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
203 const chainId = await _web3.eth.net.getId();
204 const planets = await azimuth.delegatedSending.getPlanetsToSend(
205 _contracts,
206 point,
207 values.emails.length
208 );
210 // account for the race condition where invites got used up while we were
211 // composing our target list
212 if (planets.length < values.emails.length) {
213 // resync invites to the cache, since they're out of date
214 syncInvites(point);
216 return {
217 [FORM_ERROR]:
218 `Can currently only send ${planets.length} invites. ` +
219 `Please remove invites until you are within the limit.`,
220 };
221 }
223 clearInvites();
224 // NB(shrugs) - must be processed in serial because main thread, etc
225 let errorCount = 0;
226 for (let i = 0; i < values.emails.length; i++) {
227 try {
228 const email = values.emails[i];
229 const planet = planets[i];
231 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
232 MIN_PLANET
233 // we're always giving planets, so generate a ticket of the correct size
234 );
236 const inviteTx = azimuth.delegatedSending.sendPoint(
237 _contracts,
238 point,
239 planet,
240 owner.keys.address
241 );
243 const signedTx = await signTransaction({
244 wallet: _wallet,
245 walletType,
246 walletHdPath,
247 networkType,
248 chainId,
249 nonce: nonce + i,
250 // TODO: ^ make a useTransactionSigner to encapsulate this logic
251 txn: inviteTx,
252 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
253 gasLimit: GAS_LIMIT.toString(),
254 });
256 const rawTx = hexify(signedTx.serialize());
258 addInvite({ [email]: { email, ticket, signedTx, rawTx } });
259 } catch (error) {
260 console.error(error);
261 errorCount++;
262 }
263 }
265 if (errorCount > 0) {
266 return {
267 [FORM_ERROR]: `There ${pluralize(
268 errorCount,
269 'was',
270 'were'
271 )} ${pluralize(errorCount, 'error')} while generating wallets.`,
272 };
273 }
274 },
275 [
276 contracts,
277 web3,
278 wallet,
279 point,
280 clearInvites,
281 syncInvites,
282 walletType,
283 walletHdPath,
284 networkType,
285 addInvite,
286 ]
287 );
289 const sendInvites = useCallback(async () => {
290 const emails = cachedEmails.current;
291 const _web3 = web3.getOrElse(null);
292 const _wallet = wallet.getOrElse(null);
293 if (!_web3 || !_wallet) {
294 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
295 }
297 setStatus(STATUS.FUNDING);
298 const tankWasUsed = await tank.ensureFundsFor(
299 _web3,
300 point,
301 _wallet.address,
302 INVITE_COST * emails.length,
303 emails.map(email => invites[email].rawTx),
304 (address, minBalance, balance) =>
305 setNeedFunds({ address, minBalance, balance }),
306 () => setNeedFunds(undefined)
307 );
309 setStatus(STATUS.SENDING);
310 clearReceipts();
312 let unsentInvites = [];
313 let orphanedInvites = [];
314 const txAndMailings = emails.map(async email => {
315 const invite = invites[email];
316 try {
317 const txHash = await sendSignedTransaction(
318 _web3,
319 invite.signedTx,
320 tankWasUsed
321 );
323 // TODO: waitForTransactionConfirm never rejects
324 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
325 if (!didConfirm) throw new Error();
326 } catch (error) {
327 console.error(error);
328 unsentInvites.push(invite);
329 return;
330 }
332 try {
333 await sendMail(
334 invite.email,
335 invite.ticket,
336 ob.patp(point),
337 invite.rawTx
338 );
339 } catch (error) {
340 console.error(error);
341 orphanedInvites.push(invite);
342 }
344 addReceipt({ [email]: true });
345 });
347 await Promise.all(txAndMailings);
348 // if there are any receipt errors, throw a general error
349 let errorString = '';
350 if (orphanedInvites.length > 0) {
351 errorString =
352 'Not all invite emails were sent. ' +
353 'Please send the following invite codes manually: ' +
354 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
355 '. ';
356 }
357 if (unsentInvites.length > 0) {
358 errorString =
359 errorString +
360 'Not all invites were created. ' +
361 'Did not send invites for: ' +
362 unsentInvites.map(i => i.email).join(', ') +
363 '.';
364 }
365 if (errorString !== '') {
366 throw new Error(errorString);
367 }
368 }, [web3, addReceipt, clearReceipts, invites, point, wallet, sendMail]);
370 const onSubmit = useCallback(
371 async values => {
372 cachedEmails.current = values.emails;
373 setStatus(STATUS.GENERATING);
374 const errors = await generateInvites(values);
375 if (errors) {
376 return errors;
377 }
378 setStatus(STATUS.CAN_SEND);
379 },
380 [generateInvites]
381 );
383 const doSend = useCallback(async () => {
384 setGeneralError(null);
385 try {
386 setStatus(STATUS.SENDING);
387 await sendInvites();
388 setStatus(STATUS.SUCCESS);
389 } catch (error) {
390 console.error(error);
391 setGeneralError(error.message);
392 setStatus(STATUS.FAILURE);
393 }
394 }, [sendInvites]);
396 // when we transition to done, sync invites because we just sent some
397 // and therefore know that state has changed
398 useEffect(() => {
399 if (isDone) {
400 syncInvites(point);
401 }
402 }, [isDone, syncInvites, point]);
404 return (
405 <Grid gap={3}>
406 <BridgeForm
407 validate={validate}
408 onSubmit={onSubmit}
409 initialValues={INITIAL_VALUES}>
410 {({ handleSubmit, valid, values }) => (
411 <FieldArray name="emails">
412 {({ fields }) => (
413 <>
414 <Grid.Item full as={Flex} justify="end">
415 {/* use hidden class instead of removing component from dom */}
416 {/* in order to avoid janky reflow */}
417 <IconButton
418 onClick={() => fields.push('')}
419 disabled={!canInput || fields.length >= maxInvitesToSend}
420 className={cn({ hidden: isDone })}
421 solid>
422 +
423 </IconButton>
424 </Grid.Item>
426 {isDone ? (
427 <>
428 <Grid.Item as={Text} className="f5" full>
429 <Highlighted>
430 {pluralize(fields.length, 'invite')}
431 </Highlighted>{' '}
432 {pluralize(fields.length, 'has', 'have')} been
433 successfully sent
434 </Grid.Item>
436 {fields.map(name => (
437 <Grid.Item as={HelpText} key={name} full>
438 <Field name={name}>
439 {({ input: { value } }) => value}
440 </Field>
441 </Grid.Item>
442 ))}
443 </>
444 ) : (
445 <>
446 {fields.map((name, i) => {
447 const isFirst = i === 0;
448 return (
449 <Grid.Item
450 key={name}
451 full
452 as={Grid}
453 gap={3}
454 onMouseOver={() => setHovered({ [name]: true })}
455 onMouseLeave={() => setHovered({ [name]: false })}>
456 <Grid.Item
457 cols={[1, 11]}
458 as={EmailInput}
459 name={name}
460 label={isFirst ? 'Email Address' : undefined}
461 accessory={accessoryFor(name)}
462 />
463 <Field name={name}>
464 {({ meta: { active } }) => {
465 return (
466 <>
467 {!isFirst &&
468 (active || hovered[name]) &&
469 canInput && (
470 <Grid.Item
471 cols={[11, 13]}
472 justifySelf="end"
473 alignSelf="center">
474 <IconButton
475 onClick={() => fields.remove(i)}
476 solid
477 secondary>
478 -
479 </IconButton>
480 </Grid.Item>
481 )}
482 </>
483 );
484 }}
485 </Field>
486 </Grid.Item>
487 );
488 })}
490 {canInput ? (
491 <Grid.Item
492 full
493 as={SubmitButton}
494 handleSubmit={handleSubmit}
495 accessory={`${visualProgress}/${fields.length}`}>
496 {buttonText(status, fields.length)}
497 </Grid.Item>
498 ) : (
499 <Grid.Item
500 full
501 as={LoadableButton}
502 className="mt4"
503 disabled={!canSend}
504 accessory={`${visualProgress}/${fields.length}`}
505 onClick={doSend}
506 success={canSend}
507 solid>
508 {buttonText(status, fields.length)}
509 </Grid.Item>
510 )}
512 {needFunds && (
513 <Grid.Item full>
514 <Highlighted warning>
515 Your ownership address {needFunds.address} needs at
516 least {fromWei(needFunds.minBalance)} ETH and
517 currently has {fromWei(needFunds.balance)} ETH.
518 Waiting until the account has enough funds.
519 </Highlighted>
520 </Grid.Item>
521 )}
523 <Grid.Item full as={FormError} />
525 {generalError && (
526 <Grid.Item full as={ErrorText}>
527 {generalError}
528 </Grid.Item>
529 )}
530 </>
531 )}
532 </>
533 )}
534 </FieldArray>
535 )}
536 </BridgeForm>
537 </Grid>
538 );