on fa92b34 help sign in
bridge/src/views/Invite/InviteEmail.js
533 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 useArray from 'lib/useArray';
33import { buildEmailInputConfig } from 'lib/useInputs';
34import { MIN_PLANET, GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } from 'lib/constants';
35import * as need from 'lib/need';
36import * as wg from 'lib/walletgen';
37import useSetState from 'lib/useSetState';
38import pluralize from 'lib/pluralize';
39import useMailer from 'lib/useMailer';
41import LoadableButton from 'components/LoadableButton';
42import Highlighted from 'components/Highlighted';
44const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
45const INVITE_COST = toWei(
46 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
47 'gwei'
48);
49const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
51const STATUS = {
52 INPUT: 'INPUT',
53 GENERATING: 'GENERATING',
54 CAN_SEND: 'CAN_SEND',
55 FUNDING: 'FUNDING',
56 SENDING: 'SENDING',
57 SUCCESS: 'SUCCESS',
58 FAILURE: 'FAILURE',
59};
61const buttonText = (status, count) => {
62 switch (status) {
63 case STATUS.INPUT:
64 return `Generate ${pluralize(count, 'Invite')}`;
65 case STATUS.GENERATING:
66 return `Generating ${pluralize(count, 'Invite')}...`;
67 case STATUS.CAN_SEND:
68 return `Send ${pluralize(count, 'Invite')}`;
69 case STATUS.FUNDING:
70 return `Waiting on Funds...`;
71 case STATUS.SENDING:
72 return `Sending ${pluralize(count, 'Invite')}...`;
73 case STATUS.FAILURE:
74 default:
75 return 'Error';
76 }
77};
79// world's simplest uid
80let id = 0;
81const buildInputConfig = (extra = {}) =>
82 buildEmailInputConfig({
83 name: `email-${id++}`,
84 placeholder: 'Email Address',
85 ...extra,
86 });
88const buildAccessoryFor = (dones, errors) => name => {
89 if (dones[name]) return <AccessoryIcon.Success />;
90 if (errors[name]) return <AccessoryIcon.Failure />;
91 return <AccessoryIcon.Pending />;
92};
94// TODO: test with tank, successful txs
95export default function InviteEmail() {
96 // TODO: resumption after error?
97 const { contracts, web3, networkType } = useNetwork();
98 const { wallet, walletType, walletHdPath } = useWallet();
99 const { syncInvites, getInvites } = usePointCache();
100 const { pointCursor } = usePointCursor();
101 const point = need.point(pointCursor);
102 const { getHasReceived, syncHasReceivedForEmail, sendMail } = useMailer();
104 const { availableInvites } = getInvites(point);
105 const maxInvitesToSend = availableInvites.matchWith({
106 Nothing: () => 0,
107 Just: p => p.value,
108 });
110 // manage the array of input configs
111 const [
112 inputConfigs,
113 { append: appendInput, removeAt: removeInputAt },
114 ] = useArray(
115 [buildInputConfig({ label: 'Email Address', autoFocus: true })],
116 buildInputConfig
117 );
119 // manage per-input state
120 const [hovered, setHovered] = useSetState();
121 const [invites, addInvite, clearInvites] = useSetState();
122 const [receipts, addReceipt, clearReceipts] = useSetState();
123 const [errors, addError] = useSetState();
125 // manage general state that affects the whole form
126 const [status, setStatus] = useState(STATUS.INPUT);
127 const [needFunds, setNeedFunds] = useState(null);
128 const [generalError, setGeneralError] = useState(null);
130 // derive booleans from status
131 const canInput = status === STATUS.INPUT;
132 const canSend = status === STATUS.CAN_SEND;
133 const isGenerating = status === STATUS.GENERATING;
134 const isSending = status === STATUS.SENDING;
135 const isFailed = status === STATUS.FAILURE;
136 const isDone = status === STATUS.SUCCESS;
138 // add disabled, error info to input configs
139 const dynamicConfigs = useMemo(
140 () =>
141 inputConfigs.map(config => {
142 config.disabled = !canInput;
143 const hasReceivedError = getHasReceived(config.name).matchWith({
144 Nothing: () => null, // loading
145 Just: p => p.value && HAS_RECEIVED_TEXT,
146 });
147 config.error = hasReceivedError || errors[config.name];
148 return config;
149 }),
150 [inputConfigs, errors, canInput, getHasReceived]
151 );
153 // construct the state of the set of inputs we're rendering below
154 const { inputs, pass } = useForm(dynamicConfigs);
155 // did all of the inputs pass inspection (and there are no general errors)?
156 const allPass = pass && !generalError;
157 // the form is submittable iff passing and input is allowed
158 const canGenerate = allPass && canInput;
159 // additional inputs can be added iff input is allowed and we have enough
160 // invites to send
161 const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
163 // progress is [0, .length] of invites or receipts, as we're generating them
164 const progress = isGenerating
165 ? Object.keys(invites).length
166 : isSending
167 ? Object.keys(receipts).length
168 : null;
169 const visualProgress = progress === null ? '-' : `${progress + 1}`;
171 // build a builder for the accessory to the input, depending on status
172 const accessoryFor = (() => {
173 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
174 if (isSending) return buildAccessoryFor(receipts, errors);
175 if (isFailed) return buildAccessoryFor({}, errors);
176 return () => null;
177 })();
179 const generateInvites = useCallback(async () => {
180 const _contracts = contracts.getOrElse(null);
181 const _web3 = web3.getOrElse(null);
182 const _wallet = wallet.getOrElse(null);
183 if (!_contracts || !_web3 || !_wallet) {
184 // not using need because we want a custom error
185 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
186 }
188 //TODO want to do this on-input, but that gets weird. see #188
189 let knowAll = true;
190 let alreadyReceived = [];
191 await Promise.all(
192 inputs.map(async input => {
193 const email = input.data;
194 getHasReceived(email).matchWith({
195 Nothing: () => {
196 knowAll = false;
197 },
198 Just: p => {
199 if (p.value) alreadyReceived.push(email);
200 },
201 });
202 })
203 );
204 if (!knowAll) {
205 throw new Error('No word yet from email service...');
206 }
207 if (alreadyReceived.length > 0) {
208 throw new Error(
209 'The following recipients already own a point: ' +
210 alreadyReceived.join(', ')
211 );
212 }
214 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
215 const chainId = await _web3.eth.net.getId();
216 const planets = await azimuth.delegatedSending.getPlanetsToSend(
217 _contracts,
218 point,
219 inputs.length
220 );
222 // account for the race condition where invites got used up while we were
223 // composing our target list
224 if (planets.length < inputs.length) {
225 // resync invites to the cache, since they're out of date
226 syncInvites(point);
228 throw new Error(
229 `Can currently only send ${planets.length} invites. ` +
230 `Please remove invites until you are within the limit.`
231 );
232 }
234 clearInvites();
235 // NB(shrugs) - must be processed in serial because main thread, etc
236 let errorCount = 0;
237 for (let i = 0; i < inputs.length; i++) {
238 const input = inputs[i];
239 try {
240 const { data: email, name } = inputs[i];
242 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
243 MIN_PLANET
244 // we're always giving planets, so generate a ticket of the correct size
245 );
247 const inviteTx = azimuth.delegatedSending.sendPoint(
248 _contracts,
249 point,
250 planets[i],
251 owner.keys.address
252 );
253 const signedTx = await signTransaction({
254 wallet: _wallet,
255 walletType,
256 walletHdPath,
257 networkType,
258 // TODO: ^ make a useTransactionSigner to encapsulate this logic
259 txn: inviteTx,
260 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
261 gasLimit: GAS_LIMIT.toString(),
262 nonce: nonce + i,
263 chainId,
264 });
265 const rawTx = hexify(signedTx.serialize());
267 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
268 } catch (error) {
269 console.error(error);
270 errorCount++;
271 addError({ [input.name]: `Wallet Error: ${input.email}` });
272 }
273 }
275 if (errorCount > 0) {
276 throw new Error(
277 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
278 errorCount,
279 'error'
280 )} while generating wallets.`
281 );
282 }
283 }, [
284 contracts,
285 web3,
286 wallet,
287 inputs,
288 point,
289 clearInvites,
290 getHasReceived,
291 addError,
292 syncInvites,
293 walletType,
294 walletHdPath,
295 networkType,
296 addInvite,
297 ]);
299 const sendInvites = useCallback(async () => {
300 const _web3 = web3.getOrElse(null);
301 const _wallet = wallet.getOrElse(null);
302 if (!_web3 || !_wallet) {
303 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
304 }
306 setStatus(STATUS.FUNDING);
307 const tankWasUsed = await tank.ensureFundsFor(
308 _web3,
309 point,
310 _wallet.address,
311 INVITE_COST * inputs.length,
312 inputs.map(input => invites[input.name].rawTx),
313 (address, minBalance, balance) =>
314 setNeedFunds({ address, minBalance, balance }),
315 () => setNeedFunds(undefined)
316 );
318 setStatus(STATUS.SENDING);
319 clearReceipts();
321 let unsentInvites = [];
322 let orphanedInvites = [];
323 const txAndMailings = inputs.map(async input => {
324 const invite = invites[input.name];
325 try {
326 const txHash = await sendSignedTransaction(
327 _web3,
328 invite.signedTx,
329 tankWasUsed
330 );
332 // TODO: waitForTransactionConfirm never rejects
333 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
334 if (!didConfirm) throw new Error();
335 } catch (error) {
336 console.error(error);
337 unsentInvites.push(invite);
338 return;
339 }
341 try {
342 const success = await sendMail(
343 invite.email,
344 invite.ticket,
345 ob.patp(point),
346 invite.rawTx
347 );
348 if (!success) throw new Error('Failed to send mail');
349 } catch (error) {
350 console.error(error);
351 orphanedInvites.push(invite);
352 }
354 addReceipt({ [input.name]: true });
355 });
357 await Promise.all(txAndMailings);
358 // if there are any receipt errors, throw a general error
359 let errorString = '';
360 if (orphanedInvites.length > 0) {
361 errorString =
362 'Not all invite emails were sent. ' +
363 'Please send the following invite codes manually: ' +
364 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
365 '. ';
366 }
367 if (unsentInvites.length > 0) {
368 errorString =
369 errorString +
370 'Not all invites were created. ' +
371 'Did not send invites for: ' +
372 unsentInvites.map(i => i.email).join(', ') +
373 '.';
374 }
375 if (errorString !== '') {
376 throw new Error(errorString);
377 }
378 }, [
379 web3,
380 inputs,
381 addReceipt,
382 clearReceipts,
383 invites,
384 point,
385 wallet,
386 sendMail,
387 ]);
389 const onClick = useCallback(async () => {
390 setGeneralError(null);
391 try {
392 if (canGenerate) {
393 setStatus(STATUS.GENERATING);
394 await generateInvites();
395 setStatus(STATUS.CAN_SEND);
396 } else if (canSend) {
397 setStatus(STATUS.SENDING);
398 await sendInvites();
399 setStatus(STATUS.SUCCESS);
400 }
401 } catch (error) {
402 console.error(error);
403 setGeneralError(error);
404 setStatus(STATUS.FAILURE);
405 }
406 }, [canGenerate, canSend, generateInvites, sendInvites]);
408 // when inputs update, check to see if any of them are duplicates
409 useEffect(() => {
410 // compute the list of valid emails
411 const emails = inputs.map(i => i.data).filter(d => !!d);
412 if (uniq(emails).length !== emails.length) {
413 setGeneralError(new Error(`Duplicate email.`));
414 } else {
415 setGeneralError(null);
416 setStatus(STATUS.INPUT);
417 }
418 }, [inputs]);
420 // when we transition to done, sync invites because we just sent some
421 // and therefore know that state has changed
422 useEffect(() => {
423 if (isDone) {
424 syncInvites(point);
425 }
426 }, [isDone, syncInvites, point]);
428 useEffect(() => {
429 for (const input of inputs) {
430 if (input.pass) {
431 syncHasReceivedForEmail(input.data);
432 }
433 }
434 }, [inputs, syncHasReceivedForEmail]);
436 return (
437 <Grid gap={3}>
438 <Grid.Item full as={Flex} justify="end">
439 {/* use hidden class instead of removing component from dom */}
440 {/* in order to avoid janky reflow */}
441 <IconButton
442 onClick={() => appendInput()}
443 disabled={!canAddInvite}
444 className={cn({ hidden: isDone })}
445 solid>
446 +
447 </IconButton>
448 </Grid.Item>
450 {isDone && (
451 <>
452 <Grid.Item as={Text} className="f5" full>
453 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
454 {pluralize(inputs.length, 'has', 'have')} been successfully sent
455 </Grid.Item>
456 {inputs.map(input => (
457 <Grid.Item as={HelpText} key={input.name} full>
458 {invites[input.name].email}
459 </Grid.Item>
460 ))}
461 </>
462 )}
464 {!isDone && (
465 <>
466 {/* email inputs */}
467 {inputs.map((input, i) => {
468 const isFirst = i === 0;
469 return (
470 <Grid.Item
471 key={input.name}
472 as={Grid}
473 gap={3}
474 onMouseOver={() => setHovered({ [input.name]: true })}
475 onMouseLeave={() => setHovered({ [input.name]: false })}
476 full>
477 <Grid.Item
478 as={Input}
479 cols={[1, 11]}
480 {...input}
481 accessory={accessoryFor(input.name)}
482 />
483 {!isFirst &&
484 (input.focused || hovered[input.name]) &&
485 canInput && (
486 <Grid.Item
487 cols={[11, 13]}
488 justifySelf="end"
489 alignSelf="center">
490 <IconButton
491 onClick={() => removeInputAt(i)}
492 solid
493 secondary>
494 -
495 </IconButton>
496 </Grid.Item>
497 )}
498 </Grid.Item>
499 );
500 })}
502 <Grid.Item
503 full
504 as={LoadableButton}
505 disabled={!canGenerate && !canSend}
506 accessory={`${visualProgress}/${inputs.length}`}
507 onClick={onClick}
508 success={canSend}
509 solid>
510 {buttonText(status, inputs.length)}
511 </Grid.Item>
513 {needFunds && (
514 <Grid.Item full>
515 <Highlighted warning>
516 Your ownership address {needFunds.address} needs at least{' '}
517 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
518 {fromWei(needFunds.balance)} ETH. Waiting until the account has
519 enough funds.
520 </Highlighted>
521 </Grid.Item>
522 )}
524 {generalError && (
525 <Grid.Item full>
526 <ErrorText>{generalError.message.toString()}</ErrorText>
527 </Grid.Item>
528 )}
529 </>
530 )}
531 </Grid>
532 );