on 74ef976 help sign in
bridge/src/views/Invite/InviteEmail.js
541 lines 16 kB history raw
1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import * as ob from 'urbit-ob';
4import * as azimuth from 'azimuth-js';
5import {
6 Grid,
7 Flex,
8 Input,
9 IconButton,
10 HelpText,
11 Text,
12 ErrorText,
13 AccessoryIcon,
14 useForm,
15} from 'indigo-react';
16import { uniq } from 'lodash';
17import { fromWei, toWei } from 'web3-utils';
19import { usePointCursor } from 'store/pointCursor';
20import { useNetwork } from 'store/network';
21import { usePointCache } from 'store/pointCache';
22import { useWallet } from 'store/wallet';
24// for transaction generation and signing
25import {
26 signTransaction,
27 sendSignedTransaction,
28 waitForTransactionConfirm,
29 hexify,
30} from 'lib/txn';
31import * as tank from 'lib/tank';
32import { useLocalRouter } from 'lib/LocalRouter';
33import useArray from 'lib/useArray';
34import { buildEmailInputConfig } from 'lib/useInputs';
35import { MIN_PLANET, GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } from 'lib/constants';
36import * as need from 'lib/need';
37import * as wg from 'lib/walletgen';
38import useSetState from 'lib/useSetState';
39import pluralize from 'lib/pluralize';
40import useMailer from 'lib/useMailer';
42import MiniBackButton from 'components/MiniBackButton';
43import LoadableButton from 'components/LoadableButton';
44import Highlighted from 'components/Highlighted';
46const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
47const INVITE_COST = toWei(
48 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
49 'gwei'
50);
51const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
53const STATUS = {
54 INPUT: 'INPUT',
55 GENERATING: 'GENERATING',
56 CAN_SEND: 'CAN_SEND',
57 FUNDING: 'FUNDING',
58 SENDING: 'SENDING',
59 SUCCESS: 'SUCCESS',
60 FAILURE: 'FAILURE',
61};
63const buttonText = (status, count) => {
64 switch (status) {
65 case STATUS.INPUT:
66 return `Generate ${pluralize(count, 'Invite')}`;
67 case STATUS.GENERATING:
68 return `Generating ${pluralize(count, 'Invite')}...`;
69 case STATUS.CAN_SEND:
70 return `Send ${pluralize(count, 'Invite')}`;
71 case STATUS.FUNDING:
72 return `Waiting on Funds...`;
73 case STATUS.SENDING:
74 return `Sending ${pluralize(count, 'Invite')}...`;
75 case STATUS.FAILURE:
76 default:
77 return 'Error';
78 }
79};
81// world's simplest uid
82let id = 0;
83const buildInputConfig = (extra = {}) =>
84 buildEmailInputConfig({
85 name: `email-${id++}`,
86 placeholder: 'Email Address',
87 ...extra,
88 });
90const buildAccessoryFor = (dones, errors) => name => {
91 if (dones[name]) return <AccessoryIcon.Success />;
92 if (errors[name]) return <AccessoryIcon.Failure />;
93 return <AccessoryIcon.Pending />;
94};
96// TODO: test with tank, successful txs
97export default function InviteEmail() {
98 // TODO: resumption after error?
99 const { pop } = useLocalRouter();
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, syncHasReceivedForEmail, sendMail } = useMailer();
107 const { availableInvites } = getInvites(point);
108 const maxInvitesToSend = availableInvites.matchWith({
109 Nothing: () => 0,
110 Just: p => p.value,
111 });
113 // manage the array of input configs
114 const [
115 inputConfigs,
116 { append: appendInput, removeAt: removeInputAt },
117 ] = useArray(
118 [buildInputConfig({ label: 'Email Address', autoFocus: true })],
119 buildInputConfig
120 );
122 // manage per-input state
123 const [hovered, setHovered] = useSetState();
124 const [invites, addInvite, clearInvites] = useSetState();
125 const [receipts, addReceipt, clearReceipts] = useSetState();
126 const [errors, addError] = useSetState();
128 // manage general state that affects the whole form
129 const [status, setStatus] = useState(STATUS.INPUT);
130 const [needFunds, setNeedFunds] = useState(null);
131 const [generalError, setGeneralError] = useState(null);
133 // derive booleans from status
134 const canInput = status === STATUS.INPUT;
135 const canSend = status === STATUS.CAN_SEND;
136 const isGenerating = status === STATUS.GENERATING;
137 const isSending = status === STATUS.SENDING;
138 const isFailed = status === STATUS.FAILURE;
139 const isDone = status === STATUS.SUCCESS;
141 // add disabled, error info to input configs
142 const dynamicConfigs = useMemo(
143 () =>
144 inputConfigs.map(config => {
145 config.disabled = !canInput;
146 const hasReceivedError = getHasReceived(config.name).matchWith({
147 Nothing: () => null, // loading
148 Just: p => p.value && HAS_RECEIVED_TEXT,
149 });
150 config.error = hasReceivedError || errors[config.name];
151 return config;
152 }),
153 [inputConfigs, errors, canInput, getHasReceived]
154 );
156 // construct the state of the set of inputs we're rendering below
157 const { inputs, pass } = useForm(dynamicConfigs);
158 // did all of the inputs pass inspection (and there are no general errors)?
159 const allPass = pass && !generalError;
160 // the form is submittable iff passing and input is allowed
161 const canGenerate = allPass && canInput;
162 // additional inputs can be added iff input is allowed and we have enough
163 // invites to send
164 const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
166 // progress is [0, .length] of invites or receipts, as we're generating them
167 const progress = isGenerating
168 ? Object.keys(invites).length
169 : isSending
170 ? Object.keys(receipts).length
171 : null;
172 const visualProgress = progress === null ? '-' : `${progress + 1}`;
174 // build a builder for the accessory to the input, depending on status
175 const accessoryFor = (() => {
176 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
177 if (isSending) return buildAccessoryFor(receipts, errors);
178 if (isFailed) return buildAccessoryFor({}, errors);
179 return () => null;
180 })();
182 const generateInvites = useCallback(async () => {
183 const _contracts = contracts.getOrElse(null);
184 const _web3 = web3.getOrElse(null);
185 const _wallet = wallet.getOrElse(null);
186 if (!_contracts || !_web3 || !_wallet) {
187 // not using need because we want a custom error
188 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
189 }
191 //TODO want to do this on-input, but that gets weird. see #188
192 let knowAll = true;
193 let alreadyReceived = [];
194 await Promise.all(
195 inputs.map(async input => {
196 const email = input.data;
197 getHasReceived(email).matchWith({
198 Nothing: () => {
199 knowAll = false;
200 },
201 Just: p => {
202 if (p.value) alreadyReceived.push(email);
203 },
204 });
205 })
206 );
207 if (!knowAll) {
208 throw new Error('No word yet from email service...');
209 }
210 if (alreadyReceived.length > 0) {
211 throw new Error(
212 'The following recipients already own a point: ' +
213 alreadyReceived.join(', ')
214 );
215 }
217 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
218 const chainId = await _web3.eth.net.getId();
219 const planets = await azimuth.delegatedSending.getPlanetsToSend(
220 _contracts,
221 point,
222 inputs.length
223 );
225 // account for the race condition where invites got used up while we were
226 // composing our target list
227 if (planets.length < inputs.length) {
228 // resync invites to the cache, since they're out of date
229 syncInvites(point);
231 throw new Error(
232 `Can currently only send ${planets.length} invites. ` +
233 `Please remove invites until you are within the limit.`
234 );
235 }
237 clearInvites();
238 // NB(shrugs) - must be processed in serial because main thread, etc
239 let errorCount = 0;
240 for (let i = 0; i < inputs.length; i++) {
241 const input = inputs[i];
242 try {
243 const { data: email, name } = inputs[i];
245 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
246 MIN_PLANET
247 // we're always giving planets, so generate a ticket of the correct size
248 );
250 const inviteTx = azimuth.delegatedSending.sendPoint(
251 _contracts,
252 point,
253 planets[i],
254 owner.keys.address
255 );
256 const signedTx = await signTransaction({
257 wallet: _wallet,
258 walletType,
259 walletHdPath,
260 networkType,
261 // TODO: ^ make a useTransactionSigner to encapsulate this logic
262 txn: inviteTx,
263 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
264 gasLimit: GAS_LIMIT.toString(),
265 nonce: nonce + i,
266 chainId,
267 });
268 const rawTx = hexify(signedTx.serialize());
270 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
271 } catch (error) {
272 console.error(error);
273 errorCount++;
274 addError({ [input.name]: `Wallet Error: ${input.email}` });
275 }
276 }
278 if (errorCount > 0) {
279 throw new Error(
280 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
281 errorCount,
282 'error'
283 )} while generating wallets.`
284 );
285 }
286 }, [
287 contracts,
288 web3,
289 wallet,
290 inputs,
291 point,
292 clearInvites,
293 getHasReceived,
294 addError,
295 syncInvites,
296 walletType,
297 walletHdPath,
298 networkType,
299 addInvite,
300 ]);
302 const sendInvites = useCallback(async () => {
303 const _web3 = web3.getOrElse(null);
304 const _wallet = wallet.getOrElse(null);
305 if (!_web3 || !_wallet) {
306 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
307 }
309 setStatus(STATUS.FUNDING);
310 const tankWasUsed = await tank.ensureFundsFor(
311 _web3,
312 point,
313 _wallet.address,
314 INVITE_COST * inputs.length,
315 inputs.map(input => invites[input.name].rawTx),
316 (address, minBalance, balance) =>
317 setNeedFunds({ address, minBalance, balance }),
318 () => setNeedFunds(undefined)
319 );
321 setStatus(STATUS.SENDING);
322 clearReceipts();
324 let unsentInvites = [];
325 let orphanedInvites = [];
326 const txAndMailings = inputs.map(async input => {
327 const invite = invites[input.name];
328 try {
329 const txHash = await sendSignedTransaction(
330 _web3,
331 invite.signedTx,
332 tankWasUsed
333 );
335 // TODO: waitForTransactionConfirm never rejects
336 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
337 if (!didConfirm) throw new Error();
338 } catch (error) {
339 console.error(error);
340 unsentInvites.push(invite);
341 return;
342 }
344 try {
345 const success = await sendMail(
346 invite.email,
347 invite.ticket,
348 ob.patp(point),
349 invite.rawTx
350 );
351 if (!success) throw new Error('Failed to send mail');
352 } catch (error) {
353 console.error(error);
354 orphanedInvites.push(invite);
355 }
357 addReceipt({ [input.name]: true });
358 });
360 await Promise.all(txAndMailings);
361 // if there are any receipt errors, throw a general error
362 let errorString = '';
363 if (orphanedInvites.length > 0) {
364 errorString =
365 'Not all invite emails were sent. ' +
366 'Please send the following invite codes manually: ' +
367 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
368 '. ';
369 }
370 if (unsentInvites.length > 0) {
371 errorString =
372 errorString +
373 'Not all invites were created. ' +
374 'Did not send invites for: ' +
375 unsentInvites.map(i => i.email).join(', ') +
376 '.';
377 }
378 if (errorString !== '') {
379 throw new Error(errorString);
380 }
381 }, [
382 web3,
383 inputs,
384 addReceipt,
385 clearReceipts,
386 invites,
387 point,
388 wallet,
389 sendMail,
390 ]);
392 const onClick = useCallback(async () => {
393 setGeneralError(null);
394 try {
395 if (canGenerate) {
396 setStatus(STATUS.GENERATING);
397 await generateInvites();
398 setStatus(STATUS.CAN_SEND);
399 } else if (canSend) {
400 setStatus(STATUS.SENDING);
401 await sendInvites();
402 setStatus(STATUS.SUCCESS);
403 }
404 } catch (error) {
405 console.error(error);
406 setGeneralError(error);
407 setStatus(STATUS.FAILURE);
408 }
409 }, [canGenerate, canSend, generateInvites, sendInvites]);
411 // when inputs update, check to see if any of them are duplicates
412 useEffect(() => {
413 // compute the list of valid emails
414 const emails = inputs.map(i => i.data).filter(d => !!d);
415 if (uniq(emails).length !== emails.length) {
416 setGeneralError(new Error(`Duplicate email.`));
417 } else {
418 setGeneralError(null);
419 setStatus(STATUS.INPUT);
420 }
421 }, [inputs]);
423 // when we transition to done, sync invites because we just sent some
424 // and therefore know that state has changed
425 useEffect(() => {
426 if (isDone) {
427 syncInvites(point);
428 }
429 }, [isDone, syncInvites, point]);
431 useEffect(() => {
432 for (const input of inputs) {
433 if (input.pass) {
434 syncHasReceivedForEmail(input.data);
435 }
436 }
437 }, [inputs, syncHasReceivedForEmail]);
439 return (
440 <Grid gap={3}>
441 <Grid.Item as={Grid} full>
442 <Grid.Item as={Flex} cols={[1, 11]} align="center">
443 <MiniBackButton onClick={() => pop()} />
444 </Grid.Item>
445 <Grid.Item cols={[11, 13]} justifySelf="end">
446 {/* use hidden class instead of removing component from dom */}
447 {/* in order to avoid janky reflow */}
448 <IconButton
449 onClick={() => appendInput()}
450 disabled={!canAddInvite}
451 className={cn({ hidden: isDone })}
452 solid>
453 +
454 </IconButton>
455 </Grid.Item>
456 </Grid.Item>
458 {isDone && (
459 <>
460 <Grid.Item as={Text} className="f5" full>
461 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
462 {pluralize(inputs.length, 'has', 'have')} been successfully sent
463 </Grid.Item>
464 {inputs.map(input => (
465 <Grid.Item as={HelpText} key={input.name} full>
466 {invites[input.name].email}
467 </Grid.Item>
468 ))}
469 </>
470 )}
472 {!isDone && (
473 <>
474 {/* email inputs */}
475 {inputs.map((input, i) => {
476 const isFirst = i === 0;
477 return (
478 <Grid.Item
479 key={input.name}
480 as={Grid}
481 gap={3}
482 onMouseOver={() => setHovered({ [input.name]: true })}
483 onMouseLeave={() => setHovered({ [input.name]: false })}
484 full>
485 <Grid.Item
486 as={Input}
487 cols={[1, 11]}
488 {...input}
489 accessory={accessoryFor(input.name)}
490 />
491 {!isFirst &&
492 (input.focused || hovered[input.name]) &&
493 canInput && (
494 <Grid.Item
495 cols={[11, 13]}
496 justifySelf="end"
497 alignSelf="center">
498 <IconButton
499 onClick={() => removeInputAt(i)}
500 solid
501 secondary>
502 -
503 </IconButton>
504 </Grid.Item>
505 )}
506 </Grid.Item>
507 );
508 })}
510 <Grid.Item
511 full
512 as={LoadableButton}
513 disabled={!canGenerate && !canSend}
514 accessory={`${visualProgress}/${inputs.length}`}
515 onClick={onClick}
516 success={canSend}
517 solid>
518 {buttonText(status, inputs.length)}
519 </Grid.Item>
521 {needFunds && (
522 <Grid.Item full>
523 <Highlighted>
524 Your ownership address {needFunds.address} needs at least{' '}
525 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
526 {fromWei(needFunds.balance)} ETH. Waiting until the account has
527 enough funds.
528 </Highlighted>
529 </Grid.Item>
530 )}
532 {generalError && (
533 <Grid.Item full>
534 <ErrorText>{generalError.message.toString()}</ErrorText>
535 </Grid.Item>
536 )}
537 </>
538 )}
539 </Grid>
540 );