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