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