8import cn from 'classnames';
9import ob from 'urbit-ob';
10import * as azimuth from 'azimuth-js';
21import { uniq } from 'lodash';
22import { toWei, toBN } from 'web3-utils';
23import { FieldArray } from 'react-final-form-arrays';
24import { Field } from 'react-final-form';
26import { usePointCursor } from 'store/pointCursor';
27import { useNetwork } from 'store/network';
28import { usePointCache } from 'store/pointCache';
29import { useWallet } from 'store/wallet';
31// for transaction generation and signing
34 sendSignedTransaction,
35 waitForTransactionConfirm,
38import * as tank from 'lib/tank';
39import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
40import * as need from 'lib/need';
41import * as wg from 'lib/walletgen';
42import useSetState from 'lib/useSetState';
43import pluralize from 'lib/pluralize';
44import useMailer from 'lib/useMailer';
46import ProgressButton from 'components/ProgressButton';
47import Highlighted from 'components/Highlighted';
48import { ForwardButton } from 'components/Buttons';
49import NeedFundsNotice from 'components/NeedFundsNotice';
51import BridgeForm from 'form/BridgeForm';
52import { EmailInput } from 'form/Inputs';
58} from 'form/validators';
59import { FORM_ERROR } from 'final-form';
60import SubmitButton from 'form/SubmitButton';
61import FormError from 'form/FormError';
62import { WARNING, onlyHasWarning } from 'form/helpers';
63import useGasPrice from 'lib/useGasPrice';
64import timeout from 'lib/timeout';
66const INITIAL_VALUES = { emails: [''] };
68const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
69const HAS_RECEIVED_TEXT = 'This email has already received an invite: ';
73 GENERATING: 'GENERATING',
81const nameForEmailField = i => `emails[${i}]`;
83const buttonText = (status, count) => {
86 return `Generate ${pluralize(count, 'Invite')}`;
87 case STATUS.GENERATING:
88 return `Generating ${pluralize(count, 'Invite')}...`;
90 return `Send ${pluralize(count, 'Invite')}`;
92 return `Waiting on Funds...`;
94 return `Sending ${pluralize(count, 'Invite')}...`;
101const buildAccessoryFor = (dones, errors) => name => {
102 if (dones[name]) return <AccessoryIcon.Success />;
103 if (errors[name]) return <AccessoryIcon.Failure />;
104 return <AccessoryIcon.Pending />;
107export default function InviteEmail() {
108 const { contracts, web3, networkType } = useNetwork();
109 const { wallet, walletType, walletHdPath } = useWallet();
110 const { syncInvites, getInvites } = usePointCache();
111 const { pointCursor } = usePointCursor();
112 const point = need.point(pointCursor);
113 const { getHasReceived, sendMail } = useMailer();
114 const { gasPrice } = useGasPrice();
116 const cachedEmails = useRef({});
118 const { availableInvites } = getInvites(point);
119 const maxInvitesToSend = availableInvites.matchWith({
124 // manage per-input state
125 const [hovered, setHovered] = useSetState();
126 const [invites, addInvite, clearInvites] = useSetState();
127 const [receipts, addReceipt, clearReceipts] = useSetState();
128 const [errors, addError] = useSetState();
130 // manage general state that affects the whole form
131 const [message, setMessage] = useState('');
132 const [status, setStatus] = useState(STATUS.INPUT);
133 const [needFunds, setNeedFunds] = useState(null);
134 const [generalError, setGeneralError] = useState(null);
136 // derive booleans from status
137 const canInput = status === STATUS.INPUT;
138 const isGenerating = status === STATUS.GENERATING;
139 const canSend = status === STATUS.CAN_SEND;
140 const isFunding = status === STATUS.FUNDING;
141 const isSending = status === STATUS.SENDING;
142 const isFailed = status === STATUS.FAILURE;
143 const isDone = status === STATUS.SUCCESS;
145 const validateHasReceived = useCallback(
147 const hasReceived = await getHasReceived(email);
149 return HAS_RECEIVED_TEXT + email;
155 const validateForm = useCallback((values, errors) => {
156 if (hasErrors(errors)) {
160 // check for email uniqenesss
161 const emails = values.emails.filter(d => !!d);
162 if (uniq(emails).length !== emails.length) {
163 return { [FORM_ERROR]: 'Duplicate email.' };
167 const validate = useMemo(
171 emails: buildArrayValidator(buildEmailValidator(validateHasReceived)),
175 [validateForm, validateHasReceived]
178 // progress is [0, .length] of invites or receipts, as we're generating them
179 const progress = isGenerating
180 ? Object.keys(invites).length
182 ? Object.keys(receipts).length
184 const percentProgress =
186 ? progress / Object.keys(cachedEmails.current).length
188 const visualProgress = progress === null ? '-' : `${progress + 1}`;
190 // build a builder for the accessory to the input, depending on status
191 const accessoryFor = (() => {
192 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
193 if (isSending) return buildAccessoryFor(receipts, errors);
194 if (isFailed) return buildAccessoryFor({}, errors);
198 const generateInvites = useCallback(
200 const _contracts = contracts.getOrElse(null);
201 const _web3 = web3.getOrElse(null);
202 const _wallet = wallet.getOrElse(null);
203 if (!_contracts || !_web3 || !_wallet) {
204 // not using need because we want a custom error
205 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
208 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
209 const chainId = await _web3.eth.net.getId();
210 const planets = await azimuth.delegatedSending.getPlanetsToSend(
216 // account for the race condition where invites got used up while we were
217 // composing our target list
218 if (planets.length < values.emails.length) {
219 // resync invites to the cache, since they're out of date
224 `Can currently only send ${planets.length} invites. ` +
225 `Please remove invites until you are within the limit.`,
230 // NB(shrugs) - must be processed in serial because main thread, etc
232 for (let i = 0; i < values.emails.length; i++) {
233 const name = nameForEmailField(i);
235 const email = values.emails[i];
236 const planet = planets[i];
238 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
240 // we're always giving planets, so generate a ticket of the correct size
243 const inviteTx = azimuth.delegatedSending.sendPoint(
250 const signedTx = await signTransaction({
257 // TODO: ^ make a useTransactionSigner to encapsulate this logic
259 gasPrice: gasPrice.toFixed(), // expects string gwei
260 gasLimit: GAS_LIMIT.toFixed(),
263 const rawTx = hexify(signedTx.serialize());
265 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
267 console.error(error);
269 addError({ [name]: 'Error generating invite.' });
273 if (errorCount > 0) {
275 [WARNING]: `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
278 )} while generating wallets. You can still send the invites that generated correctly.`,
298 const sendInvites = useCallback(async () => {
299 // compute all of the names of the fields
300 const allFieldNames = Object.keys(cachedEmails.current);
301 // only emails we're sending are the valid ones with invites
302 const names = allFieldNames.filter(name => !!invites[name]);
303 const emails = allFieldNames.map(name => cachedEmails.current[name]);
305 const _web3 = web3.getOrElse(null);
306 const _wallet = wallet.getOrElse(null);
307 if (!_web3 || !_wallet) {
308 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
311 setStatus(STATUS.FUNDING);
312 const totalCost = toBN(GAS_LIMIT)
314 .mul(toBN(emails.length));
315 const tankWasUsed = await tank.ensureFundsFor(
320 toWei(totalCost.toString(), 'gwei'),
321 names.map(name => invites[name].rawTx),
322 (address, minBalance, balance) =>
323 setNeedFunds({ address, minBalance, balance }),
324 () => setNeedFunds(undefined)
327 setStatus(STATUS.SENDING);
330 let unsentInvites = [];
331 let orphanedInvites = [];
332 const txAndMailings = names.map(async name => {
333 const invite = invites[name];
335 const txHash = await sendSignedTransaction(
341 await waitForTransactionConfirm(_web3, txHash);
343 console.error(error);
344 unsentInvites.push(invite);
357 console.error(error);
358 orphanedInvites.push(invite);
361 addReceipt({ [name]: true });
364 await Promise.all(txAndMailings);
365 // if there are any receipt errors, throw a general error
366 let errorString = '';
367 if (orphanedInvites.length > 0) {
369 'Not all invite emails were sent. ' +
370 'Please send the following invite codes manually: ' +
371 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
374 if (unsentInvites.length > 0) {
377 'Not all invites were created. ' +
378 'Did not send invites for: ' +
379 unsentInvites.map(i => i.email).join(', ') +
382 if (errorString !== '') {
383 throw new Error(errorString);
398 const onSubmit = useCallback(
400 setMessage(values.message);
401 cachedEmails.current = values.emails.reduce((memo, email, i) => {
402 memo[nameForEmailField(i)] = email;
405 setStatus(STATUS.GENERATING);
406 const errors = await generateInvites(values);
407 if (hasErrors(errors)) {
408 if (onlyHasWarning(errors)) {
409 setStatus(STATUS.CAN_SEND);
415 await timeout(500); // wait for progress animation to complete.
417 setStatus(STATUS.CAN_SEND);
422 const doSend = useCallback(async () => {
423 setGeneralError(null);
425 setStatus(STATUS.SENDING);
427 setStatus(STATUS.SUCCESS);
429 console.error(error);
430 setGeneralError(error.message);
431 setStatus(STATUS.FAILURE);
435 // when we transition to done, sync invites because we just sent some
436 // and therefore know that state has changed
441 }, [isDone, syncInvites, point]);
443 const renderButton = ({ handleSubmit, fields }) => {
449 handleSubmit={handleSubmit}
450 accessory={`${visualProgress}/${fields.length}`}>
451 {buttonText(status, fields.length)}
464 accessory={`${visualProgress}/${fields.length}`}
465 progress={percentProgress}
467 {buttonText(status, fields.length)}
481 {buttonText(status, fields.length)}
495 accessory={`${visualProgress}/${fields.length}`}>
496 {buttonText(status, fields.length)}
510 accessory={`${visualProgress}/${fields.length}`}
511 progress={percentProgress}
512 color={isGenerating ? 'black' : 'green4'}>
513 {buttonText(status, fields.length)}
526 initialValues={INITIAL_VALUES}>
527 {({ handleSubmit }) => (
528 <FieldArray name="emails">
530 const sentInviteNames = Object.keys(receipts);
533 <Grid.Item full as={Flex} justify="end">
534 {/* use hidden class instead of removing component from dom */}
535 {/* in order to avoid janky reflow */}
537 onClick={() => fields.push('')}
538 disabled={!canInput || fields.length >= maxInvitesToSend}
539 className={cn({ hidden: isDone })}
547 <Grid.Item as={Text} className="f5" full>
549 {pluralize(sentInviteNames.length, 'invite')}
551 {pluralize(sentInviteNames.length, 'has', 'have')} been
555 {sentInviteNames.map(name => (
556 <Grid.Item as={HelpText} key={name} full>
558 {({ input: { value } }) => value}
565 {fields.map((name, i) => {
566 const isFirst = i === 0;
573 onMouseOver={() => setHovered({ [name]: true })}
574 onMouseLeave={() => setHovered({ [name]: false })}>
579 label={isFirst ? 'Email Address' : undefined}
580 accessory={accessoryFor(name)}
583 {({ meta: { active } }) => {
587 (active || hovered[name]) &&
594 onClick={() => fields.remove(i)}
614 label="Message (optional)"
615 placeholder="Welcome aboard!"
619 {renderButton({ handleSubmit, fields })}
622 <Grid.Item full as={NeedFundsNotice} {...needFunds} />
625 <Grid.Item full as={FormError} />
628 <Grid.Item full as={ErrorText}>
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list