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