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