on 5c991af help sign in
bridge/src/views/Invite/InviteEmail.js
491 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 { Grid, Flex, Input, IconButton, HelpText, Text } from 'indigo-react';
6import { uniq } from 'lodash';
8import * as need from 'lib/need';
9import { hasReceived, sendMail } from 'lib/inviteMail';
10import * as wg from 'lib/walletgen';
12// for transaction generation and signing
13import {
14 signTransaction,
15 sendSignedTransaction,
16 waitForTransactionConfirm,
17 hexify,
18 fromWei,
19 toWei,
20} from 'lib/txn';
21import * as tank from 'lib/tank';
22import { useLocalRouter } from 'lib/LocalRouter';
24import MiniBackButton from 'components/MiniBackButton';
25import useInvites from 'lib/useInvites';
26import { usePointCursor } from 'store/pointCursor';
27import LoadableButton from 'components/LoadableButton';
28import useArray from 'lib/useArray';
29import useForm from 'indigo-react/lib/useForm';
30import { buildEmailInputConfig } from 'components/Inputs';
31import { MIN_PLANET } from 'lib/constants';
32import Highlighted from 'components/Highlighted';
33import { useNetwork } from 'store/network';
34import { usePointCache } from 'store/pointCache';
35import { useWallet } from 'store/wallet';
36import useSetState from 'lib/useSetState';
37import pluralize from 'lib/pluralize';
39const kStubMailer = process.env.REACT_APP_STUB_MAILER === 'true';
41const GAS_PRICE_GWEI = 20; // we pay the premium for faster ux
42const GAS_LIMIT = 350000;
43const INVITE_COST = toWei((GAS_PRICE_GWEI * GAS_LIMIT).toString(), 'gwei');
45const STATUS = {
46 INPUT: 'INPUT',
47 GENERATING: 'GENERATING',
48 CAN_SEND: 'CAN_SEND',
49 FUNDING: 'FUNDING',
50 SENDING: 'SENDING',
51 SUCCESS: 'SUCCESS',
52 FAILURE: 'FAILURE',
53};
55const buttonText = (status, count) => {
56 switch (status) {
57 case STATUS.INPUT:
58 return `Generate ${pluralize(count, 'Invite')}`;
59 case STATUS.GENERATING:
60 return `Generating ${pluralize(count, 'Invite')}...`;
61 case STATUS.CAN_SEND:
62 return `Send ${pluralize(count, 'Invite')}`;
63 case STATUS.FUNDING:
64 return `Waiting on Funds...`;
65 case STATUS.SENDING:
66 return `Sending ${pluralize(count, 'Invite')}...`;
67 case STATUS.FAILURE:
68 default:
69 return 'Error';
70 }
71};
73const kPendingAccessory = '⋯';
74const kSuccessAccessory = '✔';
75const kFailureAccessory = '×';
77// world's simplest uid
78let id = 0;
79const buildInputConfig = (extra = {}) =>
80 buildEmailInputConfig({ name: `email-${id++}`, ...extra });
82const buildAccessoryFor = (dones, errors) => name => (
83 <Flex justify="center" align="center" style={{ height: '100%' }}>
84 {(() => {
85 if (dones[name]) return kSuccessAccessory;
86 if (errors[name]) return kFailureAccessory;
87 return kPendingAccessory;
88 })()}
89 </Flex>
90);
92// TODO: refactor transactions + mailer into hooks
93// TODO: put accessory inside of input
94// TODO: implement hasReceived cache with useHasReceived
95export default function NewInviteEmail() {
96 // TODO: resumption after error?
97 const { pop } = useLocalRouter();
98 const { contracts, web3, networkType } = useNetwork();
99 const { wallet, walletType, walletHdPath } = useWallet();
100 const { syncInvites } = usePointCache();
101 const { pointCursor } = usePointCursor();
102 const point = need.pointCursor(pointCursor);
104 const { availableInvites } = useInvites(point);
105 const maxInvitesToSend = availableInvites.matchWith({
106 Nothing: () => 0,
107 Just: p => p.value,
108 });
110 const [
111 inputConfigs,
112 { append: appendInput, removeAt: removeInputAt },
113 ] = useArray(
114 [buildInputConfig({ placeholder: 'Email Addresss' })],
115 buildInputConfig
116 );
118 const [hovered, setHovered] = useSetState({});
119 const [invites, addInvite, clearInvites] = useSetState({});
120 const [receipts, addReceipt, clearReceipts] = useSetState({});
121 const [errors, addError, clearError] = useSetState({});
123 const [status, setStatus] = useState(STATUS.INPUT);
124 const [needFunds, setNeedFunds] = useState(null);
125 const [generalError, setGeneralError] = useState(null);
127 const canInput = status === STATUS.INPUT;
128 const canSend = status === STATUS.CAN_SEND;
129 const isGenerating = status === STATUS.GENERATING;
130 const isSending = status === STATUS.SENDING;
131 const isFunding = status === STATUS.FUNDING;
132 const isFailed = status === STATUS.FAILURE;
133 const isDone = status === STATUS.SUCCESS;
135 const dynamicConfigs = useMemo(
136 () =>
137 inputConfigs.map(config => {
138 config.disabled = !canInput;
139 console.log(config.name, errors[config.name]);
140 config.error = errors[config.name];
141 return config;
142 }),
143 [inputConfigs, errors, canInput]
144 );
145 const { inputs, pass } = useForm(dynamicConfigs);
147 const canAddInvite = canInput && inputs.length < maxInvitesToSend;
148 const allPass = pass && !generalError;
149 const canGenerate = allPass && status === STATUS.INPUT;
151 const progress = isGenerating
152 ? Object.keys(invites).length
153 : isSending
154 ? Object.keys(receipts).length
155 : null;
156 const visualProgress = progress === null ? '-' : `${progress + 1}`;
158 const accessoryFor = (() => {
159 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
160 if (isSending) return buildAccessoryFor(receipts, errors);
161 if (isFailed) return buildAccessoryFor({}, errors);
162 return () => null;
163 })();
165 const generateInvites = useCallback(async () => {
166 const _contracts = contracts.getOrElse(null);
167 const _web3 = web3.getOrElse(null);
168 const _wallet = wallet.getOrElse(null);
169 if (!_contracts || !_web3 || !_wallet) {
170 // not using need because we want a custom error
171 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
172 }
174 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
175 const chainId = await _web3.eth.net.getId();
176 const planets = await azimuth.delegatedSending.getPlanetsToSend(
177 _contracts,
178 point,
179 inputs.length
180 );
182 // account for the race condition where invites got used up while we were
183 // composing our target list
184 if (planets.length < inputs.length) {
185 // resync invites to the cache, since they're out of date
186 syncInvites();
188 throw new Error(
189 `Can currently only send ${planets.length} invites. ` +
190 `Please remove invites until you are within the limit.`
191 );
192 }
194 let errorCount = 0;
195 clearInvites();
196 // NB(shrugs) - must be processed in serial because main thread, etc
197 for (let i = 0; i < inputs.length; i++) {
198 const input = inputs[i];
199 try {
200 const { data: email, name } = inputs[i];
202 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
203 MIN_PLANET
204 // we're always giving planets, so generate a ticket of the correct size
205 );
207 const inviteTx = azimuth.delegatedSending.sendPoint(
208 _contracts,
209 point,
210 planets[i],
211 owner.keys.address
212 );
213 const signedTx = await signTransaction({
214 wallet,
215 walletType,
216 walletHdPath,
217 networkType,
218 // TODO: ^ make a useTransactionSigner to encapsulate this logic
219 txn: Maybe.Just(inviteTx),
220 gasPrice: GAS_PRICE_GWEI.toString(),
221 gasLimit: GAS_LIMIT.toString(),
222 nonce: nonce + i,
223 chainId,
224 setStx: () => {},
225 });
226 const rawTx = hexify(signedTx.serialize());
228 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
229 } catch (error) {
230 console.error(error);
231 errorCount++;
232 addError({ [input.name]: `Wallet Error: ${input.email}` });
233 }
234 }
236 if (errorCount > 0) {
237 throw new Error(
238 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
239 errorCount,
240 'error'
241 )} while generating wallets.`
242 );
243 }
244 }, [
245 point,
246 contracts,
247 web3,
248 addInvite,
249 clearInvites,
250 syncInvites,
251 inputs,
252 networkType,
253 wallet,
254 walletType,
255 walletHdPath,
256 addError,
257 ]);
259 const sendInvites = useCallback(async () => {
260 const _web3 = web3.getOrElse(null);
261 const _wallet = wallet.getOrElse(null);
262 if (!_web3 || !_wallet) {
263 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
264 }
266 setStatus(STATUS.FUNDING);
267 const tankWasUsed = await tank.ensureFundsFor(
268 _web3,
269 point,
270 _wallet.address,
271 INVITE_COST * inputs.length,
272 inputs.map(input => invites[input.name].rawTx),
273 (address, minBalance, balance) =>
274 setNeedFunds({ address, minBalance, balance }),
275 () => setNeedFunds(false)
276 );
278 setStatus(STATUS.SENDING);
279 clearReceipts();
281 let errorCount = 0;
282 const txAndMailings = inputs.map(async input => {
283 const invite = invites[input.name];
284 try {
285 const txHash = await sendSignedTransaction(
286 _web3,
287 Maybe.Just(invite.signedTx),
288 tankWasUsed,
289 () => {}
290 );
292 // TODO: waitForTransactionConfirm never rejects
293 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
294 if (!didConfirm) throw new Error();
295 } catch (error) {
296 console.error(error);
297 errorCount++;
298 addError({
299 [input.name]: `Transaction Failure for ${invite.email}`,
300 });
301 }
303 try {
304 if (kStubMailer) {
305 console.log(`${invite.email} - ${invite.ticket}`);
306 return;
307 }
309 const mailSuccess = await sendMail(
310 invite.email,
311 invite.ticket,
312 invite.rawTx
313 );
314 if (!mailSuccess) throw new Error();
315 } catch (error) {
316 console.error(error);
317 errorCount++;
318 addError({
319 [input.name]: `Mailing Failure for ${invite.email}`,
320 });
321 }
323 addReceipt({ [input.name]: true });
324 });
326 await Promise.all(txAndMailings);
327 // if there are any receipt errors, throw a general error
328 if (errorCount > 0) {
329 throw new Error(
330 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
331 errorCount,
332 'error'
333 )} while sending transactions.`
334 );
335 }
336 }, [
337 web3,
338 inputs,
339 addReceipt,
340 clearReceipts,
341 invites,
342 point,
343 wallet,
344 addError,
345 ]);
347 const onClickGenerate = useCallback(async () => {
348 setGeneralError(null);
349 setStatus(STATUS.GENERATING);
350 try {
351 await generateInvites();
352 setStatus(STATUS.CAN_SEND);
353 } catch (error) {
354 console.error(error);
355 setGeneralError(error);
356 setStatus(STATUS.FAILURE);
357 }
358 }, [setStatus, setGeneralError, generateInvites]);
360 const onClickSend = useCallback(async () => {
361 setGeneralError(null);
362 setStatus(STATUS.SENDING);
363 try {
364 await sendInvites();
365 setStatus(STATUS.SUCCESS);
366 } catch (error) {
367 console.error(error);
368 setGeneralError(error);
369 setStatus(STATUS.FAILURE);
370 }
371 }, [setStatus, sendInvites, setGeneralError]);
373 const onClick = useCallback(() => {
374 if (canGenerate) {
375 onClickGenerate();
376 } else if (canSend) {
377 onClickSend();
378 }
379 }, [canGenerate, canSend, onClickGenerate, onClickSend]);
381 useEffect(() => {
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 return (
391 <Grid gap={12}>
392 <Grid.Item as={Grid} full>
393 <Grid.Item as={Flex} cols={[1, 11]} align="center">
394 <MiniBackButton onClick={() => pop()} />
395 </Grid.Item>
396 <Grid.Item cols={[11, 13]} justifySelf="end">
397 {/* use hidden class instead of removing component from dom */}
398 {/* in order to avoid janky reflow */}
399 <IconButton
400 onClick={() => appendInput()}
401 disabled={!canAddInvite}
402 className={cn({ hidden: isDone })}
403 solid>
404 +
405 </IconButton>
406 </Grid.Item>
407 </Grid.Item>
409 {isDone && (
410 <>
411 <Grid.Item as={Text} full>
412 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
413 {pluralize(inputs.length, 'has', 'have')} been successfully sent
414 </Grid.Item>
415 {inputs.map(input => (
416 <Grid.Item as={HelpText} key={input.name} full>
417 {invites[input.name].email}
418 </Grid.Item>
419 ))}
420 </>
421 )}
423 {!isDone && (
424 <>
425 {/* email inputs */}
426 {inputs.map((input, i) => {
427 const isFirst = i === 0;
428 return (
429 <Grid.Item
430 key={input.name}
431 as={Grid}
432 gap={12}
433 onMouseOver={() => setHovered({ [input.name]: true })}
434 onMouseLeave={() => setHovered({ [input.name]: false })}
435 full>
436 <Grid.Item
437 as={Input}
438 cols={[1, 11]}
439 {...input}
440 accessory={accessoryFor(input.name)}
441 />
442 {!isFirst &&
443 (input.focused || hovered[input.name]) &&
444 canInput && (
445 <Grid.Item
446 cols={[11, 13]}
447 justifySelf="end"
448 alignSelf="center">
449 <IconButton
450 onClick={() => removeInputAt(i)}
451 solid
452 secondary>
453 -
454 </IconButton>
455 </Grid.Item>
456 )}
457 </Grid.Item>
458 );
459 })}
461 <Grid.Item
462 full
463 as={LoadableButton}
464 disabled={!canGenerate && !canSend}
465 accessory={`${visualProgress}/${inputs.length}`}
466 onClick={onClick}
467 success={canSend}
468 solid>
469 {buttonText(status, inputs.length)}
470 </Grid.Item>
472 {needFunds && (
473 <Grid.Item full>
474 <Highlighted>
475 Your ownership address {needFunds.address} needs at least{' '}
476 {fromWei(needFunds.minBalance)}ETH and currently has{' '}
477 {fromWei(needFunds.balance)}.
478 </Highlighted>
479 </Grid.Item>
480 )}
482 {generalError && (
483 <Grid.Item full>
484 <Highlighted>{generalError.message.toString()}</Highlighted>
485 </Grid.Item>
486 )}
487 </>
488 )}
489 </Grid>
490 );