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