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