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