on cf8ece3 help sign in
bridge/src/views/Invite/InviteEmail.js
537 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 knowAll = true;
193 let alreadyReceived = [];
194 await Promise.all(
195 inputs.map(async input => {
196 const email = input.data;
197 const hasReceived = getHasReceived(email).matchWith({
198 Nothing: () => 'unknown', // loading
199 Just: p => p.value,
200 });
201 if (hasReceived === 'unknown') {
202 knowAll = false;
203 } else if (hasReceived) {
204 alreadyReceived.push(email);
205 }
206 })
207 );
208 if (!knowAll) {
209 throw new Error('No word yet from email service...');
210 }
211 if (alreadyReceived.length > 0) {
212 throw new Error(
213 'The following recipients already own a point: ' +
214 alreadyReceived.join(', ')
215 );
216 }
218 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
219 const chainId = await _web3.eth.net.getId();
220 const planets = await azimuth.delegatedSending.getPlanetsToSend(
221 _contracts,
222 point,
223 inputs.length
224 );
226 // account for the race condition where invites got used up while we were
227 // composing our target list
228 if (planets.length < inputs.length) {
229 // resync invites to the cache, since they're out of date
230 syncInvites(point);
232 throw new Error(
233 `Can currently only send ${planets.length} invites. ` +
234 `Please remove invites until you are within the limit.`
235 );
236 }
238 clearInvites();
239 // NB(shrugs) - must be processed in serial because main thread, etc
240 let errorCount = 0;
241 for (let i = 0; i < inputs.length; i++) {
242 const input = inputs[i];
243 try {
244 const { data: email, name } = inputs[i];
246 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
247 MIN_PLANET
248 // we're always giving planets, so generate a ticket of the correct size
249 );
251 const inviteTx = azimuth.delegatedSending.sendPoint(
252 _contracts,
253 point,
254 planets[i],
255 owner.keys.address
256 );
257 const signedTx = await signTransaction({
258 wallet: _wallet,
259 walletType,
260 walletHdPath,
261 networkType,
262 // TODO: ^ make a useTransactionSigner to encapsulate this logic
263 txn: inviteTx,
264 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
265 gasLimit: GAS_LIMIT.toString(),
266 nonce: nonce + i,
267 chainId,
268 });
269 const rawTx = hexify(signedTx.serialize());
271 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
272 } catch (error) {
273 console.error(error);
274 errorCount++;
275 addError({ [input.name]: `Wallet Error: ${input.email}` });
276 }
277 }
279 if (errorCount > 0) {
280 throw new Error(
281 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
282 errorCount,
283 'error'
284 )} while generating wallets.`
285 );
286 }
287 }, [
288 contracts,
289 web3,
290 wallet,
291 inputs,
292 point,
293 clearInvites,
294 getHasReceived,
295 addError,
296 syncInvites,
297 walletType,
298 walletHdPath,
299 networkType,
300 addInvite,
301 ]);
303 const sendInvites = useCallback(async () => {
304 const _web3 = web3.getOrElse(null);
305 const _wallet = wallet.getOrElse(null);
306 if (!_web3 || !_wallet) {
307 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
308 }
310 setStatus(STATUS.FUNDING);
311 const tankWasUsed = await tank.ensureFundsFor(
312 _web3,
313 point,
314 _wallet.address,
315 INVITE_COST * inputs.length,
316 inputs.map(input => invites[input.name].rawTx),
317 (address, minBalance, balance) =>
318 setNeedFunds({ address, minBalance, balance }),
319 () => setNeedFunds(undefined)
320 );
322 setStatus(STATUS.SENDING);
323 clearReceipts();
325 let errorCount = 0;
326 const txAndMailings = inputs.map(async input => {
327 const invite = invites[input.name];
328 try {
329 const txHash = await sendSignedTransaction(
330 _web3,
331 invite.signedTx,
332 tankWasUsed
333 );
335 // TODO: waitForTransactionConfirm never rejects
336 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
337 if (!didConfirm) throw new Error();
338 } catch (error) {
339 console.error(error);
340 errorCount++;
341 addError({
342 [input.name]: `Transaction Failure for ${invite.email}`,
343 });
344 return;
345 }
347 try {
348 const success = await sendMail(
349 invite.email,
350 invite.ticket,
351 ob.patp(point),
352 invite.rawTx
353 );
354 if (!success) throw new Error('Failed to send mail');
355 } catch (error) {
356 console.error(error);
357 errorCount++;
358 //TODO make sure this actually gets displayed
359 addError({
360 [input.name]: `Mailing Failure for ${invite.email}, please send them this code manually: ${invite.ticket}`,
361 });
362 }
364 addReceipt({ [input.name]: true });
365 });
367 await Promise.all(txAndMailings);
368 // if there are any receipt errors, throw a general error
369 if (errorCount > 0) {
370 throw new Error(
371 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
372 errorCount,
373 'error'
374 )} while sending transactions.`
375 );
376 }
377 }, [
378 web3,
379 inputs,
380 addReceipt,
381 clearReceipts,
382 invites,
383 point,
384 wallet,
385 addError,
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 }
417 }, [inputs]);
419 // when we transition to done, sync invites because we just sent some
420 // and therefore know that state has changed
421 useEffect(() => {
422 if (isDone) {
423 syncInvites(point);
424 }
425 }, [isDone, syncInvites, point]);
427 useEffect(() => {
428 for (const input of inputs) {
429 if (input.pass) {
430 syncHasReceivedForEmail(input.data);
431 }
432 }
433 }, [inputs, syncHasReceivedForEmail]);
435 return (
436 <Grid gap={3}>
437 <Grid.Item as={Grid} full>
438 <Grid.Item as={Flex} cols={[1, 11]} align="center">
439 <MiniBackButton onClick={() => pop()} />
440 </Grid.Item>
441 <Grid.Item cols={[11, 13]} justifySelf="end">
442 {/* use hidden class instead of removing component from dom */}
443 {/* in order to avoid janky reflow */}
444 <IconButton
445 onClick={() => appendInput()}
446 disabled={!canAddInvite}
447 className={cn({ hidden: isDone })}
448 solid>
449 +
450 </IconButton>
451 </Grid.Item>
452 </Grid.Item>
454 {isDone && (
455 <>
456 <Grid.Item as={Text} className="f5" full>
457 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
458 {pluralize(inputs.length, 'has', 'have')} been successfully sent
459 </Grid.Item>
460 {inputs.map(input => (
461 <Grid.Item as={HelpText} key={input.name} full>
462 {invites[input.name].email}
463 </Grid.Item>
464 ))}
465 </>
466 )}
468 {!isDone && (
469 <>
470 {/* email inputs */}
471 {inputs.map((input, i) => {
472 const isFirst = i === 0;
473 return (
474 <Grid.Item
475 key={input.name}
476 as={Grid}
477 gap={3}
478 onMouseOver={() => setHovered({ [input.name]: true })}
479 onMouseLeave={() => setHovered({ [input.name]: false })}
480 full>
481 <Grid.Item
482 as={Input}
483 cols={[1, 11]}
484 {...input}
485 accessory={accessoryFor(input.name)}
486 />
487 {!isFirst &&
488 (input.focused || hovered[input.name]) &&
489 canInput && (
490 <Grid.Item
491 cols={[11, 13]}
492 justifySelf="end"
493 alignSelf="center">
494 <IconButton
495 onClick={() => removeInputAt(i)}
496 solid
497 secondary>
498 -
499 </IconButton>
500 </Grid.Item>
501 )}
502 </Grid.Item>
503 );
504 })}
506 <Grid.Item
507 full
508 as={LoadableButton}
509 disabled={!canGenerate && !canSend}
510 accessory={`${visualProgress}/${inputs.length}`}
511 onClick={onClick}
512 success={canSend}
513 solid>
514 {buttonText(status, inputs.length)}
515 </Grid.Item>
517 {needFunds && (
518 <Grid.Item full>
519 <Highlighted>
520 Your ownership address {needFunds.address} needs at least{' '}
521 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
522 {fromWei(needFunds.balance)} ETH. Waiting until the account has
523 enough funds.
524 </Highlighted>
525 </Grid.Item>
526 )}
528 {generalError && (
529 <Grid.Item full>
530 <ErrorText>{generalError.message.toString()}</ErrorText>
531 </Grid.Item>
532 )}
533 </>
534 )}
535 </Grid>
536 );