on 1ff1d11 help sign in
bridge/src/views/Invite/InviteEmail.js
502 lines 15 kB history raw
1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import { Just } from 'folktale/maybe';
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';
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 fromWei,
30 toWei,
31} from 'lib/txn';
32import * as tank from 'lib/tank';
33import { useLocalRouter } from 'lib/LocalRouter';
34import useArray from 'lib/useArray';
35import { buildEmailInputConfig } from 'lib/useInputs';
36import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
37import * as need from 'lib/need';
38import * as wg from 'lib/walletgen';
39import useSetState from 'lib/useSetState';
40import pluralize from 'lib/pluralize';
41import useMailer from 'lib/useMailer';
43import MiniBackButton from 'components/MiniBackButton';
44import LoadableButton from 'components/LoadableButton';
45import Highlighted from 'components/Highlighted';
47const GAS_PRICE_GWEI = 20; // we pay the premium for faster ux
48const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
49const INVITE_COST = toWei((GAS_PRICE_GWEI * GAS_LIMIT).toString(), 'gwei');
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, clearErrors] = 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 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
191 const chainId = await _web3.eth.net.getId();
192 const planets = await azimuth.delegatedSending.getPlanetsToSend(
193 _contracts,
194 point,
195 inputs.length
196 );
198 // account for the race condition where invites got used up while we were
199 // composing our target list
200 if (planets.length < inputs.length) {
201 // resync invites to the cache, since they're out of date
202 syncInvites(point);
204 throw new Error(
205 `Can currently only send ${planets.length} invites. ` +
206 `Please remove invites until you are within the limit.`
207 );
208 }
210 let errorCount = 0;
211 clearInvites();
212 // NB(shrugs) - must be processed in serial because main thread, etc
213 for (let i = 0; i < inputs.length; i++) {
214 const input = inputs[i];
215 try {
216 const { data: email, name } = inputs[i];
218 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
219 MIN_PLANET
220 // we're always giving planets, so generate a ticket of the correct size
221 );
223 const inviteTx = azimuth.delegatedSending.sendPoint(
224 _contracts,
225 point,
226 planets[i],
227 owner.keys.address
228 );
229 const signedTx = await signTransaction({
230 wallet,
231 walletType,
232 walletHdPath,
233 networkType,
234 // TODO: ^ make a useTransactionSigner to encapsulate this logic
235 txn: Just(inviteTx),
236 gasPrice: GAS_PRICE_GWEI.toString(),
237 gasLimit: GAS_LIMIT.toString(),
238 nonce: nonce + i,
239 chainId,
240 setStx: () => {},
241 });
242 const rawTx = hexify(signedTx.serialize());
244 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
245 } catch (error) {
246 console.error(error);
247 errorCount++;
248 addError({ [input.name]: `Wallet Error: ${input.email}` });
249 }
250 }
252 if (errorCount > 0) {
253 throw new Error(
254 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
255 errorCount,
256 'error'
257 )} while generating wallets.`
258 );
259 }
260 }, [
261 point,
262 contracts,
263 web3,
264 addInvite,
265 clearInvites,
266 syncInvites,
267 inputs,
268 networkType,
269 wallet,
270 walletType,
271 walletHdPath,
272 addError,
273 ]);
275 const sendInvites = useCallback(async () => {
276 const _web3 = web3.getOrElse(null);
277 const _wallet = wallet.getOrElse(null);
278 if (!_web3 || !_wallet) {
279 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
280 }
282 setStatus(STATUS.FUNDING);
283 const tankWasUsed = await tank.ensureFundsFor(
284 _web3,
285 point,
286 _wallet.address,
287 INVITE_COST * inputs.length,
288 inputs.map(input => invites[input.name].rawTx),
289 (address, minBalance, balance) =>
290 setNeedFunds({ address, minBalance, balance }),
291 () => setNeedFunds(false)
292 );
294 setStatus(STATUS.SENDING);
295 clearReceipts();
297 let errorCount = 0;
298 const txAndMailings = inputs.map(async input => {
299 const invite = invites[input.name];
300 try {
301 const txHash = await sendSignedTransaction(
302 _web3,
303 Just(invite.signedTx),
304 tankWasUsed,
305 () => {}
306 );
308 // TODO: waitForTransactionConfirm never rejects
309 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
310 if (!didConfirm) throw new Error();
311 } catch (error) {
312 console.error(error);
313 errorCount++;
314 addError({
315 [input.name]: `Transaction Failure for ${invite.email}`,
316 });
317 return;
318 }
320 try {
321 const success = await sendMail(
322 invite.email,
323 invite.ticket,
324 invite.rawTx
325 );
326 if (!success) throw new Error('Failed to send mail');
327 } catch (error) {
328 console.error(error);
329 errorCount++;
330 addError({
331 [input.name]: `Mailing Failure for ${invite.email}`,
332 });
333 }
335 addReceipt({ [input.name]: true });
336 });
338 await Promise.all(txAndMailings);
339 // if there are any receipt errors, throw a general error
340 if (errorCount > 0) {
341 throw new Error(
342 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
343 errorCount,
344 'error'
345 )} while sending transactions.`
346 );
347 }
348 }, [
349 web3,
350 inputs,
351 addReceipt,
352 clearReceipts,
353 invites,
354 point,
355 wallet,
356 addError,
357 sendMail,
358 ]);
360 const onClick = useCallback(async () => {
361 setGeneralError(null);
362 try {
363 if (canGenerate) {
364 setStatus(STATUS.GENERATING);
365 await generateInvites();
366 setStatus(STATUS.CAN_SEND);
367 } else if (canSend) {
368 setStatus(STATUS.SENDING);
369 await sendInvites();
370 setStatus(STATUS.SUCCESS);
371 }
372 } catch (error) {
373 console.error(error);
374 setGeneralError(error);
375 setStatus(STATUS.FAILURE);
376 }
377 }, [canGenerate, canSend, generateInvites, sendInvites]);
379 // when inputs update, check to see if any of them are duplicates
380 useEffect(() => {
381 // compute the list of valid emails
382 const emails = inputs.map(i => i.data).filter(d => !!d);
383 if (uniq(emails).length !== emails.length) {
384 setGeneralError(new Error(`Duplicate email.`));
385 } else {
386 setGeneralError(null);
387 }
388 }, [inputs]);
390 // when we transition to done, sync invites because we just sent some
391 // and therefore know that state has changed
392 useEffect(() => {
393 if (isDone) {
394 syncInvites(point);
395 }
396 }, [isDone, syncInvites, point]);
398 return (
399 <Grid gap={3}>
400 <Grid.Item as={Grid} full>
401 <Grid.Item as={Flex} cols={[1, 11]} align="center">
402 <MiniBackButton onClick={() => pop()} />
403 </Grid.Item>
404 <Grid.Item cols={[11, 13]} justifySelf="end">
405 {/* use hidden class instead of removing component from dom */}
406 {/* in order to avoid janky reflow */}
407 <IconButton
408 onClick={() => appendInput()}
409 disabled={!canAddInvite}
410 className={cn({ hidden: isDone })}
411 solid>
412 +
413 </IconButton>
414 </Grid.Item>
415 </Grid.Item>
417 {isDone && (
418 <>
419 <Grid.Item as={Text} className="f5" full>
420 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
421 {pluralize(inputs.length, 'has', 'have')} been successfully sent
422 </Grid.Item>
423 {inputs.map(input => (
424 <Grid.Item as={HelpText} key={input.name} full>
425 {invites[input.name].email}
426 </Grid.Item>
427 ))}
428 </>
429 )}
431 {!isDone && (
432 <>
433 {/* email inputs */}
434 {inputs.map((input, i) => {
435 const isFirst = i === 0;
436 return (
437 <Grid.Item
438 key={input.name}
439 as={Grid}
440 gap={3}
441 onMouseOver={() => setHovered({ [input.name]: true })}
442 onMouseLeave={() => setHovered({ [input.name]: false })}
443 full>
444 <Grid.Item
445 as={Input}
446 cols={[1, 11]}
447 {...input}
448 onValue={email => syncHasReceivedForEmail(email)}
449 // NB(shrugs): ^ this feels like a hack?
450 accessory={accessoryFor(input.name)}
451 />
452 {!isFirst &&
453 (input.focused || hovered[input.name]) &&
454 canInput && (
455 <Grid.Item
456 cols={[11, 13]}
457 justifySelf="end"
458 alignSelf="center">
459 <IconButton
460 onClick={() => removeInputAt(i)}
461 solid
462 secondary>
463 -
464 </IconButton>
465 </Grid.Item>
466 )}
467 </Grid.Item>
468 );
469 })}
471 <Grid.Item
472 full
473 as={LoadableButton}
474 disabled={!canGenerate && !canSend}
475 accessory={`${visualProgress}/${inputs.length}`}
476 onClick={onClick}
477 success={canSend}
478 solid>
479 {buttonText(status, inputs.length)}
480 </Grid.Item>
482 {needFunds && (
483 <Grid.Item full>
484 <Highlighted>
485 Your ownership address {needFunds.address} needs at least{' '}
486 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
487 {fromWei(needFunds.balance)} ETH. Waiting until the account has
488 enough funds.
489 </Highlighted>
490 </Grid.Item>
491 )}
493 {generalError && (
494 <Grid.Item full>
495 <ErrorText>{generalError.message.toString()}</ErrorText>
496 </Grid.Item>
497 )}
498 </>
499 )}
500 </Grid>
501 );