on b465a33 help sign in
bridge/src/views/Invite/InviteEmail.js
493 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 * as wg from 'lib/walletgen';
11// for transaction generation and signing
12import {
13 signTransaction,
14 sendSignedTransaction,
15 waitForTransactionConfirm,
16 hexify,
17 fromWei,
18 toWei,
19} from 'lib/txn';
20import * as tank from 'lib/tank';
21import { useLocalRouter } from 'lib/LocalRouter';
23import MiniBackButton from 'components/MiniBackButton';
24import useInvites from 'lib/useInvites';
25import { usePointCursor } from 'store/pointCursor';
26import LoadableButton from 'components/LoadableButton';
27import useArray from 'lib/useArray';
28import useForm from 'indigo-react/lib/useForm';
29import { buildEmailInputConfig } from 'components/Inputs';
30import { MIN_PLANET } from 'lib/constants';
31import Highlighted from 'components/Highlighted';
32import { useNetwork } from 'store/network';
33import { usePointCache } from 'store/pointCache';
34import { useWallet } from 'store/wallet';
35import useSetState from 'lib/useSetState';
36import pluralize from 'lib/pluralize';
37import useMailer from 'lib/useMailer';
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: how to handle dependency loop between inputConfigs and hasReceived?
93// TODO: test with tank, successful txs
94// TODO: put accessory inside of input
95export default function InviteEmail() {
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 config.error = errors[config.name];
140 return config;
141 }),
142 [inputConfigs, errors, canInput]
143 );
144 const { inputs, pass } = useForm(dynamicConfigs);
145 const emails = useMemo(() => inputs.map(i => i.data).filter(d => !!d), [
146 inputs,
147 ]);
148 const { getHasRecieved, sendMail } = useMailer(emails);
150 const canAddInvite = canInput && inputs.length < maxInvitesToSend;
151 const allPass = pass && !generalError;
152 const canGenerate = allPass && status === STATUS.INPUT;
154 const progress = isGenerating
155 ? Object.keys(invites).length
156 : isSending
157 ? Object.keys(receipts).length
158 : null;
159 const visualProgress = progress === null ? '-' : `${progress + 1}`;
161 const accessoryFor = (() => {
162 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
163 if (isSending) return buildAccessoryFor(receipts, errors);
164 if (isFailed) return buildAccessoryFor({}, errors);
165 return () => null;
166 })();
168 const generateInvites = useCallback(async () => {
169 const _contracts = contracts.getOrElse(null);
170 const _web3 = web3.getOrElse(null);
171 const _wallet = wallet.getOrElse(null);
172 if (!_contracts || !_web3 || !_wallet) {
173 // not using need because we want a custom error
174 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
175 }
177 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
178 const chainId = await _web3.eth.net.getId();
179 const planets = await azimuth.delegatedSending.getPlanetsToSend(
180 _contracts,
181 point,
182 inputs.length
183 );
185 // account for the race condition where invites got used up while we were
186 // composing our target list
187 if (planets.length < inputs.length) {
188 // resync invites to the cache, since they're out of date
189 syncInvites();
191 throw new Error(
192 `Can currently only send ${planets.length} invites. ` +
193 `Please remove invites until you are within the limit.`
194 );
195 }
197 let errorCount = 0;
198 clearInvites();
199 // NB(shrugs) - must be processed in serial because main thread, etc
200 for (let i = 0; i < inputs.length; i++) {
201 const input = inputs[i];
202 try {
203 const { data: email, name } = inputs[i];
205 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
206 MIN_PLANET
207 // we're always giving planets, so generate a ticket of the correct size
208 );
210 const inviteTx = azimuth.delegatedSending.sendPoint(
211 _contracts,
212 point,
213 planets[i],
214 owner.keys.address
215 );
216 const signedTx = await signTransaction({
217 wallet,
218 walletType,
219 walletHdPath,
220 networkType,
221 // TODO: ^ make a useTransactionSigner to encapsulate this logic
222 txn: Maybe.Just(inviteTx),
223 gasPrice: GAS_PRICE_GWEI.toString(),
224 gasLimit: GAS_LIMIT.toString(),
225 nonce: nonce + i,
226 chainId,
227 setStx: () => {},
228 });
229 const rawTx = hexify(signedTx.serialize());
231 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
232 } catch (error) {
233 console.error(error);
234 errorCount++;
235 addError({ [input.name]: `Wallet Error: ${input.email}` });
236 }
237 }
239 if (errorCount > 0) {
240 throw new Error(
241 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
242 errorCount,
243 'error'
244 )} while generating wallets.`
245 );
246 }
247 }, [
248 point,
249 contracts,
250 web3,
251 addInvite,
252 clearInvites,
253 syncInvites,
254 inputs,
255 networkType,
256 wallet,
257 walletType,
258 walletHdPath,
259 addError,
260 ]);
262 const sendInvites = useCallback(async () => {
263 const _web3 = web3.getOrElse(null);
264 const _wallet = wallet.getOrElse(null);
265 if (!_web3 || !_wallet) {
266 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
267 }
269 setStatus(STATUS.FUNDING);
270 const tankWasUsed = await tank.ensureFundsFor(
271 _web3,
272 point,
273 _wallet.address,
274 INVITE_COST * inputs.length,
275 inputs.map(input => invites[input.name].rawTx),
276 (address, minBalance, balance) =>
277 setNeedFunds({ address, minBalance, balance }),
278 () => setNeedFunds(false)
279 );
281 setStatus(STATUS.SENDING);
282 clearReceipts();
284 let errorCount = 0;
285 const txAndMailings = inputs.map(async input => {
286 const invite = invites[input.name];
287 try {
288 const txHash = await sendSignedTransaction(
289 _web3,
290 Maybe.Just(invite.signedTx),
291 tankWasUsed,
292 () => {}
293 );
295 // TODO: waitForTransactionConfirm never rejects
296 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
297 if (!didConfirm) throw new Error();
298 } catch (error) {
299 console.error(error);
300 errorCount++;
301 addError({
302 [input.name]: `Transaction Failure for ${invite.email}`,
303 });
304 }
306 try {
307 if (kStubMailer) {
308 console.log(`${invite.email} - ${invite.ticket}`);
309 return;
310 }
312 const mailSuccess = await sendMail(
313 invite.email,
314 invite.ticket,
315 invite.rawTx
316 );
317 if (!mailSuccess) throw new Error();
318 } catch (error) {
319 console.error(error);
320 errorCount++;
321 addError({
322 [input.name]: `Mailing Failure for ${invite.email}`,
323 });
324 }
326 addReceipt({ [input.name]: true });
327 });
329 await Promise.all(txAndMailings);
330 // if there are any receipt errors, throw a general error
331 if (errorCount > 0) {
332 throw new Error(
333 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
334 errorCount,
335 'error'
336 )} while sending transactions.`
337 );
338 }
339 }, [
340 web3,
341 inputs,
342 addReceipt,
343 clearReceipts,
344 invites,
345 point,
346 wallet,
347 addError,
348 ]);
350 const onClickGenerate = useCallback(async () => {
351 setGeneralError(null);
352 setStatus(STATUS.GENERATING);
353 try {
354 await generateInvites();
355 setStatus(STATUS.CAN_SEND);
356 } catch (error) {
357 console.error(error);
358 setGeneralError(error);
359 setStatus(STATUS.FAILURE);
360 }
361 }, [setStatus, setGeneralError, generateInvites]);
363 const onClickSend = useCallback(async () => {
364 setGeneralError(null);
365 setStatus(STATUS.SENDING);
366 try {
367 await sendInvites();
368 setStatus(STATUS.SUCCESS);
369 } catch (error) {
370 console.error(error);
371 setGeneralError(error);
372 setStatus(STATUS.FAILURE);
373 }
374 }, [setStatus, sendInvites, setGeneralError]);
376 const onClick = useCallback(() => {
377 if (canGenerate) {
378 onClickGenerate();
379 } else if (canSend) {
380 onClickSend();
381 }
382 }, [canGenerate, canSend, onClickGenerate, onClickSend]);
384 useEffect(() => {
385 if (uniq(emails).length !== emails.length) {
386 setGeneralError(new Error(`Duplicate email.`));
387 } else {
388 setGeneralError(null);
389 }
390 }, [emails]);
392 return (
393 <Grid gap={12}>
394 <Grid.Item as={Grid} full>
395 <Grid.Item as={Flex} cols={[1, 11]} align="center">
396 <MiniBackButton onClick={() => pop()} />
397 </Grid.Item>
398 <Grid.Item cols={[11, 13]} justifySelf="end">
399 {/* use hidden class instead of removing component from dom */}
400 {/* in order to avoid janky reflow */}
401 <IconButton
402 onClick={() => appendInput()}
403 disabled={!canAddInvite}
404 className={cn({ hidden: isDone })}
405 solid>
406 +
407 </IconButton>
408 </Grid.Item>
409 </Grid.Item>
411 {isDone && (
412 <>
413 <Grid.Item as={Text} full>
414 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
415 {pluralize(inputs.length, 'has', 'have')} been successfully sent
416 </Grid.Item>
417 {inputs.map(input => (
418 <Grid.Item as={HelpText} key={input.name} full>
419 {invites[input.name].email}
420 </Grid.Item>
421 ))}
422 </>
423 )}
425 {!isDone && (
426 <>
427 {/* email inputs */}
428 {inputs.map((input, i) => {
429 const isFirst = i === 0;
430 return (
431 <Grid.Item
432 key={input.name}
433 as={Grid}
434 gap={12}
435 onMouseOver={() => setHovered({ [input.name]: true })}
436 onMouseLeave={() => setHovered({ [input.name]: false })}
437 full>
438 <Grid.Item
439 as={Input}
440 cols={[1, 11]}
441 {...input}
442 accessory={accessoryFor(input.name)}
443 />
444 {!isFirst &&
445 (input.focused || hovered[input.name]) &&
446 canInput && (
447 <Grid.Item
448 cols={[11, 13]}
449 justifySelf="end"
450 alignSelf="center">
451 <IconButton
452 onClick={() => removeInputAt(i)}
453 solid
454 secondary>
455 -
456 </IconButton>
457 </Grid.Item>
458 )}
459 </Grid.Item>
460 );
461 })}
463 <Grid.Item
464 full
465 as={LoadableButton}
466 disabled={!canGenerate && !canSend}
467 accessory={`${visualProgress}/${inputs.length}`}
468 onClick={onClick}
469 success={canSend}
470 solid>
471 {buttonText(status, inputs.length)}
472 </Grid.Item>
474 {needFunds && (
475 <Grid.Item full>
476 <Highlighted>
477 Your ownership address {needFunds.address} needs at least{' '}
478 {fromWei(needFunds.minBalance)}ETH and currently has{' '}
479 {fromWei(needFunds.balance)}.
480 </Highlighted>
481 </Grid.Item>
482 )}
484 {generalError && (
485 <Grid.Item full>
486 <Highlighted>{generalError.message.toString()}</Highlighted>
487 </Grid.Item>
488 )}
489 </>
490 )}
491 </Grid>
492 );