@@ -1,20 +1,25 @@
1−import React, { useCallback, useEffect, useMemo, useState } from 'react';
1+import React, {
2import cn from 'classnames';
8import cn from 'classnames';
3import * as ob from 'urbit-ob';
9import * as ob from 'urbit-ob';
4import * as azimuth from 'azimuth-js';
10import * as azimuth from 'azimuth-js';
9 IconButton,
14 IconButton,
12 ErrorText,
17 ErrorText,
13 AccessoryIcon,
18 AccessoryIcon,
15} from 'indigo-react';
19} from 'indigo-react';
16import { uniq } from 'lodash';
20import { uniq } from 'lodash';
17import { fromWei, toWei } from 'web3-utils';
21import { fromWei, toWei } from 'web3-utils';
22+import { FieldArray } from 'react-final-form-arrays';
19import { usePointCursor } from 'store/pointCursor';
24import { usePointCursor } from 'store/pointCursor';
20import { useNetwork } from 'store/network';
25import { useNetwork } from 'store/network';
@@ -29,10 +34,8 @@ import {
30} from 'lib/txn';
35} from 'lib/txn';
31import * as tank from 'lib/tank';
36import * as tank from 'lib/tank';
32−import { useSuggestedGasPrice } from 'lib/useSuggestedGasPrice';
33−import useArray from 'lib/useArray';
34−import { buildEmailInputConfig } from 'lib/useInputs';
35import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
37import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
38+import { useSuggestedGasPrice } from 'lib/useSuggestedGasPrice';
36import * as need from 'lib/need';
39import * as need from 'lib/need';
37import * as wg from 'lib/walletgen';
40import * as wg from 'lib/walletgen';
38import useSetState from 'lib/useSetState';
41import useSetState from 'lib/useSetState';
@@ -41,6 +44,21 @@ import useMailer from 'lib/useMailer';
42import LoadableButton from 'components/LoadableButton';
45import LoadableButton from 'components/LoadableButton';
43import Highlighted from 'components/Highlighted';
46import Highlighted from 'components/Highlighted';
47+import BridgeForm from 'form/BridgeForm';
48+import { Field } from 'react-final-form';
49+import { EmailInput } from 'form/Inputs';
55+} from 'form/validators';
56+import { FORM_ERROR } from 'final-form';
57+import SubmitButton from 'form/SubmitButton';
58+import FormError from 'form/FormError';
59+import { WARNING, onlyHasWarning } from 'form/helpers';
61+const INITIAL_VALUES = { emails: [''] };
45const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
63const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
46const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
64const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
@@ -55,6 +73,8 @@ const STATUS = {
55 FAILURE: 'FAILURE',
73 FAILURE: 'FAILURE',
76+const nameForEmailField = i => `emails[${i}]`;
58const buttonText = (status, count) => {
78const buttonText = (status, count) => {
59 switch (status) {
79 switch (status) {
60 case STATUS.INPUT:
80 case STATUS.INPUT:
@@ -73,47 +93,29 @@ const buttonText = (status, count) => {
76−// world's simplest uid
78−const buildInputConfig = (extra = {}) =>
79− buildEmailInputConfig({
80− name: `email-${id++}`,
81− placeholder: 'Email Address',
85const buildAccessoryFor = (dones, errors) => name => {
96const buildAccessoryFor = (dones, errors) => name => {
86 if (dones[name]) return <AccessoryIcon.Success />;
97 if (dones[name]) return <AccessoryIcon.Success />;
87 if (errors[name]) return <AccessoryIcon.Failure />;
98 if (errors[name]) return <AccessoryIcon.Failure />;
88 return <AccessoryIcon.Pending />;
99 return <AccessoryIcon.Pending />;
91−// TODO: test with tank, successful txs
92export default function InviteEmail() {
102export default function InviteEmail() {
93− // TODO: resumption after error?
94 const { contracts, web3, networkType } = useNetwork();
103 const { contracts, web3, networkType } = useNetwork();
95 const { wallet, walletType, walletHdPath } = useWallet();
104 const { wallet, walletType, walletHdPath } = useWallet();
96 const { syncInvites, getInvites } = usePointCache();
105 const { syncInvites, getInvites } = usePointCache();
97 const { pointCursor } = usePointCursor();
106 const { pointCursor } = usePointCursor();
98 const point = need.point(pointCursor);
107 const point = need.point(pointCursor);
99− const { getHasReceived, syncHasReceivedForEmail, sendMail } = useMailer();
108+ const { getHasReceived, sendMail } = useMailer();
100 const { gasPrice } = useSuggestedGasPrice(networkType);
109 const { gasPrice } = useSuggestedGasPrice(networkType);
111+ const cachedEmails = useRef({});
102 const { availableInvites } = getInvites(point);
113 const { availableInvites } = getInvites(point);
103 const maxInvitesToSend = availableInvites.matchWith({
114 const maxInvitesToSend = availableInvites.matchWith({
104 Nothing: () => 0,
115 Nothing: () => 0,
105 Just: p => p.value,
116 Just: p => p.value,
108− // manage the array of input configs
111− { append: appendInput, removeAt: removeInputAt },
113− [buildInputConfig({ label: 'Email Address', autoFocus: true })],
117 // manage per-input state
119 // manage per-input state
118 const [hovered, setHovered] = useSetState();
120 const [hovered, setHovered] = useSetState();
119 const [invites, addInvite, clearInvites] = useSetState();
121 const [invites, addInvite, clearInvites] = useSetState();
@@ -133,30 +135,38 @@ export default function InviteEmail() {
133 const isFailed = status === STATUS.FAILURE;
135 const isFailed = status === STATUS.FAILURE;
134 const isDone = status === STATUS.SUCCESS;
136 const isDone = status === STATUS.SUCCESS;
136− // add disabled, error info to input configs
138+ const validateHasReceived = useCallback(
137− const dynamicConfigs = useMemo(
139+ async email => {
139− inputConfigs.map(config => {
140− config.disabled = !canInput;
141− const hasReceivedError = getHasReceived(config.name).matchWith({
140+ const hasReceived = await getHasReceived(email);
142− Nothing: () => null, // loading
141+ if (hasReceived) {
143− Just: p => p.value && HAS_RECEIVED_TEXT,
142+ return HAS_RECEIVED_TEXT;
145− config.error = hasReceivedError || errors[config.name];
148− [inputConfigs, errors, canInput, getHasReceived]
145+ [getHasReceived]
151− // construct the state of the set of inputs we're rendering below
148+ const validateForm = useCallback((values, errors) => {
152− const { inputs, pass } = useForm(dynamicConfigs);
149+ if (hasErrors(errors)) {
153− // did all of the inputs pass inspection (and there are no general errors)?
150+ return errors;
154− const allPass = pass && !generalError;
151+ }
155− // the form is submittable iff passing and input is allowed
152+
156− const canGenerate = allPass && canInput;
153+ // check for email uniqenesss
157− // additional inputs can be added iff input is allowed and we have enough
154+ const emails = values.emails.filter(d => !!d);
158− // invites to send
155+ if (uniq(emails).length !== emails.length) {
159− const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
156+ return { [FORM_ERROR]: 'Duplicate email.' };
160+ const validate = useMemo(
164+ emails: buildArrayValidator(buildEmailValidator(validateHasReceived)),
168+ [validateForm, validateHasReceived]
161 // progress is [0, .length] of invites or receipts, as we're generating them
171 // progress is [0, .length] of invites or receipts, as we're generating them
162 const progress = isGenerating
172 const progress = isGenerating
@@ -174,128 +184,113 @@ export default function InviteEmail() {
174 return () => null;
184 return () => null;
177− const generateInvites = useCallback(async () => {
187+ const generateInvites = useCallback(
178− const _contracts = contracts.getOrElse(null);
189+ const _contracts = contracts.getOrElse(null);
179− const _web3 = web3.getOrElse(null);
190+ const _web3 = web3.getOrElse(null);
180− const _wallet = wallet.getOrElse(null);
191+ const _wallet = wallet.getOrElse(null);
181− if (!_contracts || !_web3 || !_wallet) {
192+ if (!_contracts || !_web3 || !_wallet) {
182− // not using need because we want a custom error
193+ // not using need because we want a custom error
183− throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
194+ throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
186− //TODO want to do this on-input, but that gets weird. see #188
188− let alreadyReceived = [];
190− inputs.map(async input => {
191− const email = input.data;
192− getHasReceived(email).matchWith({
197− if (p.value) alreadyReceived.push(email);
203− throw new Error('No word yet from email service...');
205− if (alreadyReceived.length > 0) {
207− 'The following recipients already own a point: ' +
208− alreadyReceived.join(', ')
212− const nonce = await _web3.eth.getTransactionCount(_wallet.address);
213− const chainId = await _web3.eth.net.getId();
214− const planets = await azimuth.delegatedSending.getPlanetsToSend(
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
226− throw new Error(
197+ const nonce = await _web3.eth.getTransactionCount(_wallet.address);
227− `Can currently only send ${planets.length} invites. ` +
198+ const chainId = await _web3.eth.net.getId();
228− `Please remove invites until you are within the limit.`
199+ const planets = await azimuth.delegatedSending.getPlanetsToSend(
202+ values.emails.length
232− clearInvites();
205+ // account for the race condition where invites got used up while we were
233− // NB(shrugs) - must be processed in serial because main thread, etc
206+ // composing our target list
234− let errorCount = 0;
207+ if (planets.length < values.emails.length) {
235− for (let i = 0; i < inputs.length; i++) {
208+ // resync invites to the cache, since they're out of date
236− const input = inputs[i];
209+ syncInvites(point);
238− const { data: email, name } = inputs[i];
211+ return {
240− const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
213+ `Can currently only send ${planets.length} invites. ` +
241− MIN_PLANET
214+ `Please remove invites until you are within the limit.`,
242− // we're always giving planets, so generate a ticket of the correct size
219+ // NB(shrugs) - must be processed in serial because main thread, etc
221+ for (let i = 0; i < values.emails.length; i++) {
222+ const name = nameForEmailField(i);
224+ const email = values.emails[i];
225+ const planet = planets[i];
227+ const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
229+ // we're always giving planets, so generate a ticket of the correct size
245− const inviteTx = azimuth.delegatedSending.sendPoint(
232+ const inviteTx = azimuth.delegatedSending.sendPoint(
246− _contracts,
233+ _contracts,
248− planets[i],
235+ planet,
249− owner.keys.address
236+ owner.keys.address
251− const signedTx = await signTransaction({
239+ const signedTx = await signTransaction({
252− wallet: _wallet,
240+ wallet: _wallet,
253− walletType,
241+ walletType,
254− walletHdPath,
242+ walletHdPath,
255− networkType,
243+ networkType,
256− // TODO: ^ make a useTransactionSigner to encapsulate this logic
246+ // TODO: ^ make a useTransactionSigner to encapsulate this logic
257− txn: inviteTx,
247+ txn: inviteTx,
258− gasPrice: gasPrice.toString(),
248+ gasPrice: gasPrice.toString(),
259− gasLimit: GAS_LIMIT.toString(),
249+ gasLimit: GAS_LIMIT.toString(),
263− const rawTx = hexify(signedTx.serialize());
252+ const rawTx = hexify(signedTx.serialize());
265− addInvite({ [name]: { email, ticket, signedTx, rawTx } });
254+ addInvite({ [name]: { email, ticket, signedTx, rawTx } });
266− } catch (error) {
255+ } catch (error) {
267− console.error(error);
256+ console.error(error);
268− errorCount++;
257+ errorCount++;
269− addError({ [input.name]: `Wallet Error: ${input.email}` });
258+ addError({ [name]: 'Error generating invite.' });
273− if (errorCount > 0) {
262+ if (errorCount > 0) {
274− throw new Error(
263+ return {
275− `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
264+ [WARNING]: `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
276− errorCount,
265+ errorCount,
278− )} while generating wallets.`
267+ )} while generating wallets. You can still send the invites that generated correctly.`,
282− contracts,
272+ contracts,
288− clearInvites,
276+ clearInvites,
291− syncInvites,
277+ syncInvites,
292− walletType,
278+ walletType,
293− walletHdPath,
279+ walletHdPath,
294− networkType,
280+ networkType,
295− addInvite,
282+ addInvite,
298 const sendInvites = useCallback(async () => {
287 const sendInvites = useCallback(async () => {
288+ // compute all of the names of the fields
289+ const allFieldNames = Object.keys(cachedEmails.current);
290+ // only emails we're sending are the valid ones with invites
291+ const names = allFieldNames.filter(name => !!invites[name]);
292+ const emails = allFieldNames.map(name => cachedEmails.current[name]);
299 const _web3 = web3.getOrElse(null);
294 const _web3 = web3.getOrElse(null);
300 const _wallet = wallet.getOrElse(null);
295 const _wallet = wallet.getOrElse(null);
301 if (!_web3 || !_wallet) {
296 if (!_web3 || !_wallet) {
@@ -307,8 +302,8 @@ export default function InviteEmail() {
309 _wallet.address,
304 _wallet.address,
310− toWei((gasPrice * GAS_LIMIT * inputs.length).toString(), 'gwei'),
305+ toWei((gasPrice * GAS_LIMIT * emails.length).toString(), 'gwei'),
311− inputs.map(input => invites[input.name].rawTx),
306+ names.map(name => invites[name].rawTx),
312 (address, minBalance, balance) =>
307 (address, minBalance, balance) =>
313 setNeedFunds({ address, minBalance, balance }),
308 setNeedFunds({ address, minBalance, balance }),
314 () => setNeedFunds(undefined)
309 () => setNeedFunds(undefined)
@@ -319,8 +314,8 @@ export default function InviteEmail() {
320 let unsentInvites = [];
315 let unsentInvites = [];
321 let orphanedInvites = [];
316 let orphanedInvites = [];
322− const txAndMailings = inputs.map(async input => {
317+ const txAndMailings = names.map(async name => {
323− const invite = invites[input.name];
318+ const invite = invites[name];
325 const txHash = await sendSignedTransaction(
320 const txHash = await sendSignedTransaction(
@@ -328,9 +323,7 @@ export default function InviteEmail() {
328 tankWasUsed
323 tankWasUsed
331− // TODO: waitForTransactionConfirm never rejects
332− const didConfirm = await waitForTransactionConfirm(_web3, txHash);
326+ await waitForTransactionConfirm(_web3, txHash);
333− if (!didConfirm) throw new Error();
334 } catch (error) {
327 } catch (error) {
335 console.error(error);
328 console.error(error);
336 unsentInvites.push(invite);
329 unsentInvites.push(invite);
@@ -338,19 +331,18 @@ export default function InviteEmail() {
341− const success = await sendMail(
334+ await sendMail(
342 invite.email,
335 invite.email,
343 invite.ticket,
336 invite.ticket,
344 ob.patp(point),
337 ob.patp(point),
345 invite.rawTx
338 invite.rawTx
347− if (!success) throw new Error('Failed to send mail');
348 } catch (error) {
340 } catch (error) {
349 console.error(error);
341 console.error(error);
350 orphanedInvites.push(invite);
342 orphanedInvites.push(invite);
353− addReceipt({ [input.name]: true });
345+ addReceipt({ [name]: true });
356 await Promise.all(txAndMailings);
348 await Promise.all(txAndMailings);
@@ -376,46 +368,48 @@ export default function InviteEmail() {
379 gasPrice,
373 gasPrice,
384− point,
375+ clearReceipts,
385− wallet,
376+ addReceipt,
386 sendMail,
377 sendMail,
380+ const onSubmit = useCallback(
382+ cachedEmails.current = values.emails.reduce((memo, email, i) => {
383+ memo[nameForEmailField(i)] = email;
386+ setStatus(STATUS.GENERATING);
387+ const errors = await generateInvites(values);
388+ if (hasErrors(errors)) {
389+ if (onlyHasWarning(errors)) {
390+ setStatus(STATUS.CAN_SEND);
396+ setStatus(STATUS.CAN_SEND);
389− const onClick = useCallback(async () => {
401+ const doSend = useCallback(async () => {
390 setGeneralError(null);
402 setGeneralError(null);
393− setStatus(STATUS.GENERATING);
394− await generateInvites();
395− setStatus(STATUS.CAN_SEND);
396− } else if (canSend) {
397− setStatus(STATUS.SENDING);
404+ setStatus(STATUS.SENDING);
398− await sendInvites();
405+ await sendInvites();
399− setStatus(STATUS.SUCCESS);
406+ setStatus(STATUS.SUCCESS);
401 } catch (error) {
407 } catch (error) {
402 console.error(error);
408 console.error(error);
403− setGeneralError(error);
409+ setGeneralError(error.message);
404 setStatus(STATUS.FAILURE);
410 setStatus(STATUS.FAILURE);
406− }, [canGenerate, canSend, generateInvites, sendInvites]);
412+ }, [sendInvites]);
408− // when inputs update, check to see if any of them are duplicates
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.`));
415− setGeneralError(null);
416− setStatus(STATUS.INPUT);
420 // when we transition to done, sync invites because we just sent some
414 // when we transition to done, sync invites because we just sent some
421 // and therefore know that state has changed
415 // and therefore know that state has changed
@@ -425,109 +419,142 @@ export default function InviteEmail() {
426 }, [isDone, syncInvites, point]);
420 }, [isDone, syncInvites, point]);
429− for (const input of inputs) {
431− syncHasReceivedForEmail(input.data);
434− }, [inputs, syncHasReceivedForEmail]);
437 <Grid gap={3}>
423 <Grid gap={3}>
427+ initialValues={INITIAL_VALUES}>
428+ {({ handleSubmit }) => (
429+ <FieldArray name="emails">
431+ const sentInviteNames = Object.keys(receipts);
438− <Grid.Item full as={Flex} justify="end">
434+ <Grid.Item full as={Flex} justify="end">
439− {/* use hidden class instead of removing component from dom */}
435+ {/* use hidden class instead of removing component from dom */}
440− {/* in order to avoid janky reflow */}
436+ {/* in order to avoid janky reflow */}
441− <IconButton
437+ <IconButton
442− onClick={() => appendInput()}
438+ onClick={() => fields.push('')}
443− disabled={!canAddInvite}
439+ disabled={!canInput || fields.length >= maxInvitesToSend}
444− className={cn({ hidden: isDone })}
440+ className={cn({ hidden: isDone })}
447− </IconButton>
443+ </IconButton>
448− </Grid.Item>
444+ </Grid.Item>
450− {isDone && (
446+ {isDone ? (
452− <Grid.Item as={Text} className="f5" full>
448+ <Grid.Item as={Text} className="f5" full>
453− <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
450+ {pluralize(sentInviteNames.length, 'invite')}
454− {pluralize(inputs.length, 'has', 'have')} been successfully sent
452+ {pluralize(sentInviteNames.length, 'has', 'have')} been
455− </Grid.Item>
454+ </Grid.Item>
456− {inputs.map(input => (
455+
456+ {sentInviteNames.map(name => (
457− <Grid.Item as={HelpText} key={input.name} full>
457+ <Grid.Item as={HelpText} key={name} full>
458− {invites[input.name].email}
458+ <Field name={name}>
459+ {({ input: { value } }) => value}
459− </Grid.Item>
461+ </Grid.Item>
466− {/* email inputs */}
466+ {fields.map((name, i) => {
467− {inputs.map((input, i) => {
468− const isFirst = i === 0;
467+ const isFirst = i === 0;
469− return (
468+ return (
470− <Grid.Item
469+ <Grid.Item
471− key={input.name}
470+ key={name}
472− as={Grid}
472+ as={Grid}
474− onMouseOver={() => setHovered({ [input.name]: true })}
474+ onMouseOver={() => setHovered({ [name]: true })}
475− onMouseLeave={() => setHovered({ [input.name]: false })}
475+ onMouseLeave={() => setHovered({ [name]: false })}>
477− <Grid.Item
476+ <Grid.Item
479− cols={[1, 11]}
477+ cols={[1, 11]}
480− {...input}
478+ as={EmailInput}
480+ label={isFirst ? 'Email Address' : undefined}
481− accessory={accessoryFor(input.name)}
481+ accessory={accessoryFor(name)}
484+ {({ meta: { active } }) => {
483− {!isFirst &&
487+ {!isFirst &&
484− (input.focused || hovered[input.name]) &&
488+ (active || hovered[name]) &&
485− canInput && (
489+ canInput && (
486− <Grid.Item
490+ <Grid.Item
487− cols={[11, 13]}
491+ cols={[11, 13]}
488− justifySelf="end"
492+ justifySelf="end"
489− alignSelf="center">
493+ alignSelf="center">
490− <IconButton
494+ <IconButton
491− onClick={() => removeInputAt(i)}
495+ onClick={() => fields.remove(i)}
493− secondary>
497+ secondary>
495− </IconButton>
499+ </IconButton>
514+ handleSubmit={handleSubmit}
515+ accessory={`${visualProgress}/${fields.length}`}>
516+ {buttonText(status, fields.length)}
524+ accessory={`${visualProgress}/${fields.length}`}
528+ {buttonText(status, fields.length)}
534+ <Highlighted warning>
535+ Your ownership address {needFunds.address} needs at
536+ least {fromWei(needFunds.minBalance)} ETH and
537+ currently has {fromWei(needFunds.balance)} ETH.
538+ Waiting until the account has enough funds.
543+ <Grid.Item full as={FormError} />
546+ <Grid.Item full as={ErrorText}>
496− </Grid.Item>
548+ </Grid.Item>
498− </Grid.Item>
552+ </>
503− full
557+ </BridgeForm>
505− disabled={!canGenerate && !canSend}
506− accessory={`${visualProgress}/${inputs.length}`}
510− {buttonText(status, inputs.length)}
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
526− <ErrorText>{generalError.message.toString()}</ErrorText>