on 84f0413 help sign in
bridge/src/views/Invite/InviteEmail.js
529 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, 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 errorCount = 0;
193 await Promise.all(
194 inputs.map(async input => {
195 const email = input.data;
196 const hasReceived = getHasReceived(email).matchWith({
197 Nothing: () => false, // loading
198 Just: p => p.value,
199 });
200 if (hasReceived) {
201 errorCount++;
202 addError({
203 [input.name]: `${email} has already received an invite.`,
204 });
205 }
206 })
207 );
208 if (errorCount > 0) {
209 throw new Error(`Some of these already have a point!`);
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 for (let i = 0; i < inputs.length; i++) {
235 const input = inputs[i];
236 try {
237 const { data: email, name } = inputs[i];
239 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
240 MIN_PLANET
241 // we're always giving planets, so generate a ticket of the correct size
242 );
244 const inviteTx = azimuth.delegatedSending.sendPoint(
245 _contracts,
246 point,
247 planets[i],
248 owner.keys.address
249 );
250 const signedTx = await signTransaction({
251 wallet: _wallet,
252 walletType,
253 walletHdPath,
254 networkType,
255 // TODO: ^ make a useTransactionSigner to encapsulate this logic
256 txn: inviteTx,
257 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
258 gasLimit: GAS_LIMIT.toString(),
259 nonce: nonce + i,
260 chainId,
261 });
262 const rawTx = hexify(signedTx.serialize());
264 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
265 } catch (error) {
266 console.error(error);
267 errorCount++;
268 addError({ [input.name]: `Wallet Error: ${input.email}` });
269 }
270 }
272 if (errorCount > 0) {
273 throw new Error(
274 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
275 errorCount,
276 'error'
277 )} while generating wallets.`
278 );
279 }
280 }, [
281 contracts,
282 web3,
283 wallet,
284 inputs,
285 point,
286 clearInvites,
287 getHasReceived,
288 addError,
289 syncInvites,
290 walletType,
291 walletHdPath,
292 networkType,
293 addInvite,
294 ]);
296 const sendInvites = useCallback(async () => {
297 const _web3 = web3.getOrElse(null);
298 const _wallet = wallet.getOrElse(null);
299 if (!_web3 || !_wallet) {
300 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
301 }
303 setStatus(STATUS.FUNDING);
304 const tankWasUsed = await tank.ensureFundsFor(
305 _web3,
306 point,
307 _wallet.address,
308 INVITE_COST * inputs.length,
309 inputs.map(input => invites[input.name].rawTx),
310 (address, minBalance, balance) =>
311 setNeedFunds({ address, minBalance, balance }),
312 () => setNeedFunds(false)
313 );
315 setStatus(STATUS.SENDING);
316 clearReceipts();
318 let errorCount = 0;
319 const txAndMailings = inputs.map(async input => {
320 const invite = invites[input.name];
321 try {
322 const txHash = await sendSignedTransaction(
323 _web3,
324 invite.signedTx,
325 tankWasUsed
326 );
328 // TODO: waitForTransactionConfirm never rejects
329 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
330 if (!didConfirm) throw new Error();
331 } catch (error) {
332 console.error(error);
333 errorCount++;
334 addError({
335 [input.name]: `Transaction Failure for ${invite.email}`,
336 });
337 return;
338 }
340 try {
341 const success = await sendMail(
342 invite.email,
343 invite.ticket,
344 invite.rawTx
345 );
346 if (!success) throw new Error('Failed to send mail');
347 } catch (error) {
348 console.error(error);
349 errorCount++;
350 //TODO make sure this actually gets displayed
351 addError({
352 [input.name]: `Mailing Failure for ${invite.email}, please send them this code manually: ${invite.ticket}`,
353 });
354 }
356 addReceipt({ [input.name]: true });
357 });
359 await Promise.all(txAndMailings);
360 // if there are any receipt errors, throw a general error
361 if (errorCount > 0) {
362 throw new Error(
363 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
364 errorCount,
365 'error'
366 )} while sending transactions.`
367 );
368 }
369 }, [
370 web3,
371 inputs,
372 addReceipt,
373 clearReceipts,
374 invites,
375 point,
376 wallet,
377 addError,
378 sendMail,
379 ]);
381 const onClick = useCallback(async () => {
382 setGeneralError(null);
383 try {
384 if (canGenerate) {
385 setStatus(STATUS.GENERATING);
386 await generateInvites();
387 setStatus(STATUS.CAN_SEND);
388 } else if (canSend) {
389 setStatus(STATUS.SENDING);
390 await sendInvites();
391 setStatus(STATUS.SUCCESS);
392 }
393 } catch (error) {
394 console.error(error);
395 setGeneralError(error);
396 setStatus(STATUS.FAILURE);
397 }
398 }, [canGenerate, canSend, generateInvites, sendInvites]);
400 // when inputs update, check to see if any of them are duplicates
401 useEffect(() => {
402 // compute the list of valid emails
403 const emails = inputs.map(i => i.data).filter(d => !!d);
404 if (uniq(emails).length !== emails.length) {
405 setGeneralError(new Error(`Duplicate email.`));
406 } else {
407 setGeneralError(null);
408 }
409 }, [inputs]);
411 // when we transition to done, sync invites because we just sent some
412 // and therefore know that state has changed
413 useEffect(() => {
414 if (isDone) {
415 syncInvites(point);
416 }
417 }, [isDone, syncInvites, point]);
419 useEffect(() => {
420 for (const input of inputs) {
421 if (input.pass) {
422 syncHasReceivedForEmail(input.data);
423 }
424 }
425 }, [inputs, syncHasReceivedForEmail]);
427 return (
428 <Grid gap={3}>
429 <Grid.Item as={Grid} full>
430 <Grid.Item as={Flex} cols={[1, 11]} align="center">
431 <MiniBackButton onClick={() => pop()} />
432 </Grid.Item>
433 <Grid.Item cols={[11, 13]} justifySelf="end">
434 {/* use hidden class instead of removing component from dom */}
435 {/* in order to avoid janky reflow */}
436 <IconButton
437 onClick={() => appendInput()}
438 disabled={!canAddInvite}
439 className={cn({ hidden: isDone })}
440 solid>
441 +
442 </IconButton>
443 </Grid.Item>
444 </Grid.Item>
446 {isDone && (
447 <>
448 <Grid.Item as={Text} className="f5" full>
449 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
450 {pluralize(inputs.length, 'has', 'have')} been successfully sent
451 </Grid.Item>
452 {inputs.map(input => (
453 <Grid.Item as={HelpText} key={input.name} full>
454 {invites[input.name].email}
455 </Grid.Item>
456 ))}
457 </>
458 )}
460 {!isDone && (
461 <>
462 {/* email inputs */}
463 {inputs.map((input, i) => {
464 const isFirst = i === 0;
465 return (
466 <Grid.Item
467 key={input.name}
468 as={Grid}
469 gap={3}
470 onMouseOver={() => setHovered({ [input.name]: true })}
471 onMouseLeave={() => setHovered({ [input.name]: false })}
472 full>
473 <Grid.Item
474 as={Input}
475 cols={[1, 11]}
476 {...input}
477 accessory={accessoryFor(input.name)}
478 />
479 {!isFirst &&
480 (input.focused || hovered[input.name]) &&
481 canInput && (
482 <Grid.Item
483 cols={[11, 13]}
484 justifySelf="end"
485 alignSelf="center">
486 <IconButton
487 onClick={() => removeInputAt(i)}
488 solid
489 secondary>
490 -
491 </IconButton>
492 </Grid.Item>
493 )}
494 </Grid.Item>
495 );
496 })}
498 <Grid.Item
499 full
500 as={LoadableButton}
501 disabled={!canGenerate && !canSend}
502 accessory={`${visualProgress}/${inputs.length}`}
503 onClick={onClick}
504 success={canSend}
505 solid>
506 {buttonText(status, inputs.length)}
507 </Grid.Item>
509 {needFunds && (
510 <Grid.Item full>
511 <Highlighted>
512 Your ownership address {needFunds.address} needs at least{' '}
513 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
514 {fromWei(needFunds.balance)} ETH. Waiting until the account has
515 enough funds.
516 </Highlighted>
517 </Grid.Item>
518 )}
520 {generalError && (
521 <Grid.Item full>
522 <ErrorText>{generalError.message.toString()}</ErrorText>
523 </Grid.Item>
524 )}
525 </>
526 )}
527 </Grid>
528 );