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