on 228dce8 help sign in
bridge/src/views/Invite/InviteEmail.js
535 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 buildArrayValidator,
54} from 'form/validators';
55import { FORM_ERROR } from 'final-form';
56import SubmitButton from 'form/SubmitButton';
57import FormError from 'form/FormError';
59const INITIAL_VALUES = { emails: [''] };
61const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
62const INVITE_COST = toWei(
63 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
64 'gwei'
65);
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 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();
110 const cachedEmails = useRef([]);
112 const { availableInvites } = getInvites(point);
113 const maxInvitesToSend = availableInvites.matchWith({
114 Nothing: () => 0,
115 Just: p => p.value,
116 });
118 // manage per-input state
119 const [hovered, setHovered] = useSetState();
120 const [invites, addInvite, clearInvites] = useSetState();
121 const [receipts, addReceipt, clearReceipts] = useSetState();
122 const [errors, addError] = useSetState();
124 // manage general state that affects the whole form
125 const [status, setStatus] = useState(STATUS.INPUT);
126 const [needFunds, setNeedFunds] = useState(null);
127 const [generalError, setGeneralError] = useState(null);
129 // derive booleans from status
130 const canInput = status === STATUS.INPUT;
131 const canSend = status === STATUS.CAN_SEND;
132 const isGenerating = status === STATUS.GENERATING;
133 const isSending = status === STATUS.SENDING;
134 const isFailed = status === STATUS.FAILURE;
135 const isDone = status === STATUS.SUCCESS;
137 const validateHasReceived = useCallback(
138 async email => {
139 const hasReceived = await getHasReceived(email);
140 if (hasReceived) {
141 return HAS_RECEIVED_TEXT;
142 }
143 },
144 [getHasReceived]
145 );
147 const validateForm = useCallback(async (values, errors) => {
148 if (hasErrors(errors)) {
149 return errors;
150 }
152 // check for email uniqenesss
153 const emails = values.emails.filter(d => !!d);
154 if (uniq(emails).length !== emails.length) {
155 return { [FORM_ERROR]: 'Duplicate email.' };
156 }
157 }, []);
159 const validate = useMemo(
160 () =>
161 composeValidator(
162 {
163 emails: buildArrayValidator(
164 buildEmailValidator([validateHasReceived])
165 ),
166 },
167 validateForm
168 ),
169 [validateForm, validateHasReceived]
170 );
172 // progress is [0, .length] of invites or receipts, as we're generating them
173 const progress = isGenerating
174 ? Object.keys(invites).length
175 : isSending
176 ? Object.keys(receipts).length
177 : null;
178 const visualProgress = progress === null ? '-' : `${progress + 1}`;
180 // build a builder for the accessory to the input, depending on status
181 const accessoryFor = (() => {
182 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
183 if (isSending) return buildAccessoryFor(receipts, errors);
184 if (isFailed) return buildAccessoryFor({}, errors);
185 return () => null;
186 })();
188 const generateInvites = useCallback(
189 async values => {
190 const _contracts = contracts.getOrElse(null);
191 const _web3 = web3.getOrElse(null);
192 const _wallet = wallet.getOrElse(null);
193 if (!_contracts || !_web3 || !_wallet) {
194 // not using need because we want a custom error
195 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
196 }
198 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
199 const chainId = await _web3.eth.net.getId();
200 const planets = await azimuth.delegatedSending.getPlanetsToSend(
201 _contracts,
202 point,
203 values.emails.length
204 );
206 // account for the race condition where invites got used up while we were
207 // composing our target list
208 if (planets.length < values.emails.length) {
209 // resync invites to the cache, since they're out of date
210 syncInvites(point);
212 return {
213 [FORM_ERROR]:
214 `Can currently only send ${planets.length} invites. ` +
215 `Please remove invites until you are within the limit.`,
216 };
217 }
219 clearInvites();
220 // NB(shrugs) - must be processed in serial because main thread, etc
221 let errorCount = 0;
222 for (let i = 0; i < values.emails.length; 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: DEFAULT_GAS_PRICE_GWEI.toString(),
249 gasLimit: GAS_LIMIT.toString(),
250 });
252 const rawTx = hexify(signedTx.serialize());
254 addInvite({ [email]: { email, ticket, signedTx, rawTx } });
255 } catch (error) {
256 console.error(error);
257 errorCount++;
258 }
259 }
261 if (errorCount > 0) {
262 return {
263 [FORM_ERROR]: `There ${pluralize(
264 errorCount,
265 'was',
266 'were'
267 )} ${pluralize(errorCount, 'error')} while generating wallets.`,
268 };
269 }
270 },
271 [
272 contracts,
273 web3,
274 wallet,
275 point,
276 clearInvites,
277 syncInvites,
278 walletType,
279 walletHdPath,
280 networkType,
281 addInvite,
282 ]
283 );
285 const sendInvites = useCallback(async () => {
286 const emails = cachedEmails.current;
287 const _web3 = web3.getOrElse(null);
288 const _wallet = wallet.getOrElse(null);
289 if (!_web3 || !_wallet) {
290 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
291 }
293 setStatus(STATUS.FUNDING);
294 const tankWasUsed = await tank.ensureFundsFor(
295 _web3,
296 point,
297 _wallet.address,
298 INVITE_COST * emails.length,
299 emails.map(email => invites[email].rawTx),
300 (address, minBalance, balance) =>
301 setNeedFunds({ address, minBalance, balance }),
302 () => setNeedFunds(undefined)
303 );
305 setStatus(STATUS.SENDING);
306 clearReceipts();
308 let unsentInvites = [];
309 let orphanedInvites = [];
310 const txAndMailings = emails.map(async email => {
311 const invite = invites[email];
312 try {
313 const txHash = await sendSignedTransaction(
314 _web3,
315 invite.signedTx,
316 tankWasUsed
317 );
319 // TODO: waitForTransactionConfirm never rejects
320 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
321 if (!didConfirm) throw new Error();
322 } catch (error) {
323 console.error(error);
324 unsentInvites.push(invite);
325 return;
326 }
328 try {
329 await sendMail(
330 invite.email,
331 invite.ticket,
332 ob.patp(point),
333 invite.rawTx
334 );
335 } catch (error) {
336 console.error(error);
337 orphanedInvites.push(invite);
338 }
340 addReceipt({ [email]: true });
341 });
343 await Promise.all(txAndMailings);
344 // if there are any receipt errors, throw a general error
345 let errorString = '';
346 if (orphanedInvites.length > 0) {
347 errorString =
348 'Not all invite emails were sent. ' +
349 'Please send the following invite codes manually: ' +
350 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
351 '. ';
352 }
353 if (unsentInvites.length > 0) {
354 errorString =
355 errorString +
356 'Not all invites were created. ' +
357 'Did not send invites for: ' +
358 unsentInvites.map(i => i.email).join(', ') +
359 '.';
360 }
361 if (errorString !== '') {
362 throw new Error(errorString);
363 }
364 }, [web3, addReceipt, clearReceipts, invites, point, wallet, sendMail]);
366 const onSubmit = useCallback(
367 async values => {
368 cachedEmails.current = values.emails;
369 setStatus(STATUS.GENERATING);
370 const errors = await generateInvites(values);
371 if (errors) {
372 return errors;
373 }
374 setStatus(STATUS.CAN_SEND);
375 },
376 [generateInvites]
377 );
379 const doSend = useCallback(async () => {
380 setGeneralError(null);
381 try {
382 setStatus(STATUS.SENDING);
383 await sendInvites();
384 setStatus(STATUS.SUCCESS);
385 } catch (error) {
386 console.error(error);
387 setGeneralError(error.message);
388 setStatus(STATUS.FAILURE);
389 }
390 }, [sendInvites]);
392 // when we transition to done, sync invites because we just sent some
393 // and therefore know that state has changed
394 useEffect(() => {
395 if (isDone) {
396 syncInvites(point);
397 }
398 }, [isDone, syncInvites, point]);
400 return (
401 <Grid gap={3}>
402 <BridgeForm
403 validate={validate}
404 onSubmit={onSubmit}
405 initialValues={INITIAL_VALUES}>
406 {({ handleSubmit, valid, values }) => (
407 <FieldArray name="emails">
408 {({ fields }) => (
409 <>
410 <Grid.Item full as={Flex} justify="end">
411 {/* use hidden class instead of removing component from dom */}
412 {/* in order to avoid janky reflow */}
413 <IconButton
414 onClick={() => fields.push('')}
415 disabled={!canInput || fields.length >= maxInvitesToSend}
416 className={cn({ hidden: isDone })}
417 solid>
418 +
419 </IconButton>
420 </Grid.Item>
422 {isDone ? (
423 <>
424 <Grid.Item as={Text} className="f5" full>
425 <Highlighted>
426 {pluralize(fields.length, 'invite')}
427 </Highlighted>{' '}
428 {pluralize(fields.length, 'has', 'have')} been
429 successfully sent
430 </Grid.Item>
432 {fields.map(name => (
433 <Grid.Item as={HelpText} key={name} full>
434 <Field name={name}>
435 {({ input: { value } }) => value}
436 </Field>
437 </Grid.Item>
438 ))}
439 </>
440 ) : (
441 <>
442 {fields.map((name, i) => {
443 const isFirst = i === 0;
444 return (
445 <Grid.Item
446 key={name}
447 full
448 as={Grid}
449 gap={3}
450 onMouseOver={() => setHovered({ [name]: true })}
451 onMouseLeave={() => setHovered({ [name]: false })}>
452 <Grid.Item
453 cols={[1, 11]}
454 as={EmailInput}
455 name={name}
456 label={isFirst ? 'Email Address' : undefined}
457 accessory={accessoryFor(name)}
458 />
459 <Field name={name}>
460 {({ meta: { active } }) => {
461 return (
462 <>
463 {!isFirst &&
464 (active || hovered[name]) &&
465 canInput && (
466 <Grid.Item
467 cols={[11, 13]}
468 justifySelf="end"
469 alignSelf="center">
470 <IconButton
471 onClick={() => fields.remove(i)}
472 solid
473 secondary>
474 -
475 </IconButton>
476 </Grid.Item>
477 )}
478 </>
479 );
480 }}
481 </Field>
482 </Grid.Item>
483 );
484 })}
486 {canInput ? (
487 <Grid.Item
488 full
489 as={SubmitButton}
490 handleSubmit={handleSubmit}
491 accessory={`${visualProgress}/${fields.length}`}>
492 {buttonText(status, fields.length)}
493 </Grid.Item>
494 ) : (
495 <Grid.Item
496 full
497 as={LoadableButton}
498 className="mt4"
499 disabled={!canSend}
500 accessory={`${visualProgress}/${fields.length}`}
501 onClick={doSend}
502 success={canSend}
503 solid>
504 {buttonText(status, fields.length)}
505 </Grid.Item>
506 )}
508 {needFunds && (
509 <Grid.Item full>
510 <Highlighted warning>
511 Your ownership address {needFunds.address} needs at
512 least {fromWei(needFunds.minBalance)} ETH and
513 currently has {fromWei(needFunds.balance)} ETH.
514 Waiting until the account has enough funds.
515 </Highlighted>
516 </Grid.Item>
517 )}
519 <Grid.Item full as={FormError} />
521 {generalError && (
522 <Grid.Item full as={ErrorText}>
523 {generalError}
524 </Grid.Item>
525 )}
526 </>
527 )}
528 </>
529 )}
530 </FieldArray>
531 )}
532 </BridgeForm>
533 </Grid>
534 );