on d49f060 help sign in
bridge/src/views/Invite/InviteEmail.js
480 lines 14 kB history raw
1import React, { useCallback, useEffect, useState } from 'react';
2import cn from 'classnames';
3import Maybe, { Just, Nothing } 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: include input-specific error info in form elements
94// TODO: put accessory inside of input
95// TODO: implement hasReceived cache with useHasReceived
96export default function NewInviteEmail() {
97 // TODO: resumption after error?
98 const { pop } = useLocalRouter();
99 const { contracts, web3, networkType } = useNetwork();
100 const { wallet, walletType, walletHdPath } = useWallet();
101 const { syncInvites } = usePointCache();
102 const { pointCursor } = usePointCursor();
103 const point = need.pointCursor(pointCursor);
105 const { availableInvites } = useInvites(point);
106 const maxInvitesToSend = availableInvites.matchWith({
107 Nothing: () => 0,
108 Just: p => p.value,
109 });
111 const [
112 inputConfigs,
113 { append: appendInput, removeAt: removeInputAt },
114 ] = useArray(
115 [buildInputConfig({ placeholder: 'Email Addresss' })],
116 buildInputConfig
117 );
119 const [hovered, _setHovered] = useState({});
120 const setHovered = (name, value) => () =>
121 _setHovered((value = { ...value, [name]: value }));
123 // TODO: pass disabled, error info into the useForm hook?
124 const { inputs, pass } = useForm(inputConfigs);
126 const [invites, addInvite, clearInvites] = useSetState({});
127 const [receipts, addReceipt, clearReceipts] = useSetState({});
128 const [errors, addError, clearError] = useSetState({});
130 const [status, setStatus] = useState(STATUS.INPUT);
131 const [needFunds, setNeedFunds] = useState(null);
132 const [generalError, setGeneralError] = useState(null);
134 const allPass = pass && !generalError;
136 const canInput = status === STATUS.INPUT;
137 const canGenerate = allPass && status === STATUS.INPUT;
138 const canSend = status === STATUS.CAN_SEND;
139 const isGenerating = status === STATUS.GENERATING;
140 const isSending = status === STATUS.SENDING;
141 const isFunding = status === STATUS.FUNDING;
142 const isFailed = status === STATUS.FAILURE;
143 const isDone = status === STATUS.SUCCESS;
144 const canAddInvite = canInput && inputs.length < maxInvitesToSend;
146 const progress = isGenerating
147 ? Object.keys(invites).length
148 : isSending
149 ? Object.keys(receipts).length
150 : null;
151 const visualProgress = progress === null ? '-' : `${progress + 1}`;
153 const accessoryFor = (() => {
154 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
155 if (isSending) return buildAccessoryFor(receipts, errors);
156 if (isFailed) return buildAccessoryFor({}, errors);
157 return () => null;
158 })();
160 const generateInvites = useCallback(async () => {
161 const _contracts = contracts.getOrElse(null);
162 const _web3 = web3.getOrElse(null);
163 const _wallet = wallet.getOrElse(null);
164 if (!_contracts || !_web3 || !_wallet) {
165 // not using need because we want a custom error
166 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
167 }
169 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
170 const chainId = await _web3.eth.net.getId();
171 const planets = await azimuth.delegatedSending.getPlanetsToSend(
172 _contracts,
173 point,
174 inputs.length
175 );
177 // account for the race condition where invites got used up while we were
178 // composing our target list
179 if (planets.length < inputs.length) {
180 // resync invites to the cache, since they're out of date
181 syncInvites();
183 throw new Error(
184 `Can currently only send ${planets.length} invites. ` +
185 `Please remove invites until you are within the limit.`
186 );
187 }
189 let errorCount = 0;
190 clearInvites();
191 // NB(shrugs) - must be processed in serial because main thread, etc
192 for (let i = 0; i < inputs.length; i++) {
193 const input = inputs[i];
194 try {
195 const { data: email, name } = inputs[i];
197 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
198 MIN_PLANET
199 // we're always giving planets, so generate a ticket of the correct size
200 );
202 const inviteTx = azimuth.delegatedSending.sendPoint(
203 _contracts,
204 point,
205 planets[i],
206 owner.keys.address
207 );
208 const signedTx = await signTransaction({
209 wallet,
210 walletType,
211 walletHdPath,
212 networkType,
213 // TODO: ^ make a useTransactionSigner to encapsulate this logic
214 txn: Just(inviteTx),
215 gasPrice: GAS_PRICE_GWEI.toString(),
216 gasLimit: GAS_LIMIT.toString(),
217 nonce: nonce + i,
218 chainId,
219 setStx: () => {},
220 });
221 const rawTx = hexify(signedTx.serialize());
223 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
224 } catch (error) {
225 console.error(error);
226 errorCount++;
227 addError({ [input.name]: `Wallet Error: ${input.email}` });
228 }
229 }
231 if (errorCount > 0) {
232 throw new Error(
233 `There were ${errorCount} errors while generating wallets.`
234 );
235 }
236 }, [
237 point,
238 contracts,
239 web3,
240 addInvite,
241 clearInvites,
242 syncInvites,
243 inputs,
244 networkType,
245 wallet,
246 walletType,
247 walletHdPath,
248 addError,
249 ]);
251 const sendInvites = useCallback(async () => {
252 const _web3 = web3.getOrElse(null);
253 const _wallet = wallet.getOrElse(null);
254 if (!_web3 || !_wallet) {
255 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
256 }
258 setStatus(STATUS.FUNDING);
259 const tankWasUsed = await tank.ensureFundsFor(
260 _web3,
261 point,
262 _wallet.address,
263 INVITE_COST * inputs.length,
264 inputs.map(input => invites[input.name].rawTx),
265 (address, minBalance, balance) =>
266 setNeedFunds({ address, minBalance, balance }),
267 () => setNeedFunds(false)
268 );
270 setStatus(STATUS.SENDING);
271 clearReceipts();
273 let errorCount = 0;
274 const txAndMailings = inputs.map(async input => {
275 const invite = invites[input.name];
276 try {
277 const txHash = await sendSignedTransaction(
278 _web3,
279 Just(invite.signedTx),
280 tankWasUsed,
281 () => {}
282 );
284 // TODO: waitForTransactionConfirm never rejects
285 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
286 if (!didConfirm) throw new Error();
287 } catch (error) {
288 console.error(error);
289 errorCount++;
290 addError({
291 [input.name]: `Transaction Failure for ${invite.email}}`,
292 });
293 }
295 try {
296 if (kStubMailer) {
297 console.log(`${invite.email} - ${invite.ticket}`);
298 return;
299 }
301 const mailSuccess = await sendMail(
302 invite.email,
303 invite.ticket,
304 invite.rawTx
305 );
306 if (!mailSuccess) throw new Error();
307 } catch (error) {
308 console.error(error);
309 errorCount++;
310 addError({
311 [input.name]: `Mailing Failure for ${invite.email}}`,
312 });
313 }
315 addReceipt({ [input.name]: true });
316 });
318 await Promise.all(txAndMailings);
319 // if there are any receipt errors, throw a general error
320 if (errorCount > 0) {
321 throw new Error(
322 `There were ${errorCount} errors while sending transactions.`
323 );
324 }
325 }, [
326 web3,
327 inputs,
328 addReceipt,
329 clearReceipts,
330 invites,
331 point,
332 wallet,
333 addError,
334 ]);
336 const onClickGenerate = useCallback(async () => {
337 setGeneralError(null);
338 setStatus(STATUS.GENERATING);
339 try {
340 await generateInvites();
341 setStatus(STATUS.CAN_SEND);
342 } catch (error) {
343 console.error(error);
344 setGeneralError(error);
345 setStatus(STATUS.FAILURE);
346 }
347 }, [setStatus, setGeneralError, generateInvites]);
349 const onClickSend = useCallback(async () => {
350 setGeneralError(null);
351 setStatus(STATUS.SENDING);
352 try {
353 await sendInvites();
354 setStatus(STATUS.SUCCESS);
355 } catch (error) {
356 console.error(error);
357 setGeneralError(error);
358 setStatus(STATUS.FAILURE);
359 }
360 }, [setStatus, sendInvites, setGeneralError]);
362 const onClick = useCallback(() => {
363 if (canGenerate) {
364 onClickGenerate();
365 } else if (canSend) {
366 onClickSend();
367 }
368 }, [canGenerate, canSend, onClickGenerate, onClickSend]);
370 useEffect(() => {
371 if (uniq(inputs.map(i => i.data)).length !== inputs.length) {
372 setGeneralError(new Error(`Duplicate email.`));
373 } else {
374 setGeneralError(null);
375 }
376 }, [inputs]);
378 return (
379 <Grid gap={12}>
380 <Grid.Item as={Grid} full>
381 <Grid.Item as={Flex} cols={[1, 11]} align="center">
382 <MiniBackButton onClick={() => pop()} />
383 </Grid.Item>
384 <Grid.Item cols={[11, 13]} justifySelf="end">
385 {/* use hidden class instead of removing component from dom */}
386 {/* in order to avoid janky reflow */}
387 <IconButton
388 onClick={() => appendInput()}
389 disabled={!canAddInvite}
390 className={cn({ hidden: isDone })}
391 solid>
392 +
393 </IconButton>
394 </Grid.Item>
395 </Grid.Item>
397 {isDone && (
398 <>
399 <Grid.Item as={Text} full>
400 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
401 {pluralize(inputs.length, 'has', 'have')} been successfully sent
402 </Grid.Item>
403 {inputs.map(input => (
404 <Grid.Item as={HelpText} key={input.name} full>
405 {invites[input.name].email}
406 </Grid.Item>
407 ))}
408 </>
409 )}
411 {!isDone && (
412 <>
413 {/* email inputs */}
414 {inputs.map((input, i) => {
415 const isFirst = i === 0;
416 return (
417 <Grid.Item
418 key={input.name}
419 as={Grid}
420 gap={12}
421 onMouseEnter={setHovered(input.name, true)}
422 onMouseLeave={setHovered(input.name, false)}
423 full>
424 <Grid.Item
425 as={Input}
426 cols={[1, 11]}
427 {...input}
428 accessory={accessoryFor(input.name)}
429 disabled={!canInput}
430 />
431 {!isFirst &&
432 (input.focused || hovered[input.name]) &&
433 canInput && (
434 <Grid.Item
435 cols={[11, 13]}
436 justifySelf="end"
437 alignSelf="center">
438 <IconButton
439 onClick={() => removeInputAt(i)}
440 solid
441 secondary>
442 -
443 </IconButton>
444 </Grid.Item>
445 )}
446 </Grid.Item>
447 );
448 })}
450 <Grid.Item
451 full
452 as={LoadableButton}
453 disabled={!canGenerate && !canSend}
454 accessory={`${visualProgress}/${inputs.length}`}
455 onClick={onClick}
456 success={canSend}
457 solid>
458 {buttonText(status, inputs.length)}
459 </Grid.Item>
461 {needFunds && (
462 <Grid.Item full>
463 <Highlighted>
464 Your ownership address {needFunds.address} needs at least{' '}
465 {fromWei(needFunds.minBalance)}ETH and currently has{' '}
466 {fromWei(needFunds.balance)}.
467 </Highlighted>
468 </Grid.Item>
469 )}
471 {generalError && (
472 <Grid.Item full>
473 <Highlighted>{generalError.message.toString()}</Highlighted>
474 </Grid.Item>
475 )}
476 </>
477 )}
478 </Grid>
479 );