8import cn from 'classnames';
9import ob from 'urbit-ob';
10import * as azimuth from 'azimuth-js';
20import { uniq } from 'lodash';
21import { toWei, toBN } from 'web3-utils';
22import { FieldArray } from 'react-final-form-arrays';
23import { Field } from 'react-final-form';
25import { usePointCursor } from 'store/pointCursor';
26import { useNetwork } from 'store/network';
27import { usePointCache } from 'store/pointCache';
28import { useWallet } from 'store/wallet';
30// for transaction generation and signing
33 sendSignedTransaction,
34 waitForTransactionConfirm,
37import * as tank from 'lib/tank';
38import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
39import * as need from 'lib/need';
40import * as wg from 'lib/walletgen';
41import useSetState from 'lib/useSetState';
42import pluralize from 'lib/pluralize';
43import useMailer from 'lib/useMailer';
45import ProgressButton from 'components/ProgressButton';
46import Highlighted from 'components/Highlighted';
47import { ForwardButton } from 'components/Buttons';
48import NeedFundsNotice from 'components/NeedFundsNotice';
50import BridgeForm from 'form/BridgeForm';
51import { EmailInput } from 'form/Inputs';
57} from 'form/validators';
58import { FORM_ERROR } from 'final-form';
59import SubmitButton from 'form/SubmitButton';
60import FormError from 'form/FormError';
61import { WARNING, onlyHasWarning } from 'form/helpers';
62import useGasPrice from 'lib/useGasPrice';
63import timeout from 'lib/timeout';
65const INITIAL_VALUES = { emails: [''] };
67const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
68const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
72 GENERATING: 'GENERATING',
80const nameForEmailField = i => `emails[${i}]`;
82const buttonText = (status, count) => {
85 return `Generate ${pluralize(count, 'Invite')}`;
86 case STATUS.GENERATING:
87 return `Generating ${pluralize(count, 'Invite')}...`;
89 return `Send ${pluralize(count, 'Invite')}`;
91 return `Waiting on Funds...`;
93 return `Sending ${pluralize(count, 'Invite')}...`;
100const buildAccessoryFor = (dones, errors) => name => {
101 if (dones[name]) return <AccessoryIcon.Success />;
102 if (errors[name]) return <AccessoryIcon.Failure />;
103 return <AccessoryIcon.Pending />;
106export default function InviteEmail() {
107 const { contracts, web3, networkType } = useNetwork();
108 const { wallet, walletType, walletHdPath } = useWallet();
109 const { syncInvites, getInvites } = usePointCache();
110 const { pointCursor } = usePointCursor();
111 const point = need.point(pointCursor);
112 const { getHasReceived, sendMail } = useMailer();
113 const { gasPrice } = useGasPrice();
115 const cachedEmails = useRef({});
117 const { availableInvites } = getInvites(point);
118 const maxInvitesToSend = availableInvites.matchWith({
123 // manage per-input state
124 const [hovered, setHovered] = useSetState();
125 const [invites, addInvite, clearInvites] = useSetState();
126 const [receipts, addReceipt, clearReceipts] = useSetState();
127 const [errors, addError] = useSetState();
129 // manage general state that affects the whole form
130 const [status, setStatus] = useState(STATUS.INPUT);
131 const [needFunds, setNeedFunds] = useState(null);
132 const [generalError, setGeneralError] = useState(null);
134 // derive booleans from status
135 const canInput = status === STATUS.INPUT;
136 const isGenerating = status === STATUS.GENERATING;
137 const canSend = status === STATUS.CAN_SEND;
138 const isFunding = status === STATUS.FUNDING;
139 const isSending = status === STATUS.SENDING;
140 const isFailed = status === STATUS.FAILURE;
141 const isDone = status === STATUS.SUCCESS;
143 const validateHasReceived = useCallback(
145 const hasReceived = await getHasReceived(email);
147 return HAS_RECEIVED_TEXT;
153 const validateForm = useCallback((values, errors) => {
154 if (hasErrors(errors)) {
158 // check for email uniqenesss
159 const emails = values.emails.filter(d => !!d);
160 if (uniq(emails).length !== emails.length) {
161 return { [FORM_ERROR]: 'Duplicate email.' };
165 const validate = useMemo(
169 emails: buildArrayValidator(buildEmailValidator(validateHasReceived)),
173 [validateForm, validateHasReceived]
176 // progress is [0, .length] of invites or receipts, as we're generating them
177 const progress = isGenerating
178 ? Object.keys(invites).length
180 ? Object.keys(receipts).length
182 const percentProgress =
184 ? progress / Object.keys(cachedEmails.current).length
186 const visualProgress = progress === null ? '-' : `${progress + 1}`;
188 // build a builder for the accessory to the input, depending on status
189 const accessoryFor = (() => {
190 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
191 if (isSending) return buildAccessoryFor(receipts, errors);
192 if (isFailed) return buildAccessoryFor({}, errors);
196 const generateInvites = useCallback(
198 const _contracts = contracts.getOrElse(null);
199 const _web3 = web3.getOrElse(null);
200 const _wallet = wallet.getOrElse(null);
201 if (!_contracts || !_web3 || !_wallet) {
202 // not using need because we want a custom error
203 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
206 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
207 const chainId = await _web3.eth.net.getId();
208 const planets = await azimuth.delegatedSending.getPlanetsToSend(
214 // account for the race condition where invites got used up while we were
215 // composing our target list
216 if (planets.length < values.emails.length) {
217 // resync invites to the cache, since they're out of date
222 `Can currently only send ${planets.length} invites. ` +
223 `Please remove invites until you are within the limit.`,
228 // NB(shrugs) - must be processed in serial because main thread, etc
230 for (let i = 0; i < values.emails.length; i++) {
231 const name = nameForEmailField(i);
233 const email = values.emails[i];
234 const planet = planets[i];
236 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
238 // we're always giving planets, so generate a ticket of the correct size
241 const inviteTx = azimuth.delegatedSending.sendPoint(
248 const signedTx = await signTransaction({
255 // TODO: ^ make a useTransactionSigner to encapsulate this logic
257 gasPrice: gasPrice.toFixed(), // expects string gwei
258 gasLimit: GAS_LIMIT.toFixed(),
261 const rawTx = hexify(signedTx.serialize());
263 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
265 console.error(error);
267 addError({ [name]: 'Error generating invite.' });
271 if (errorCount > 0) {
273 [WARNING]: `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
276 )} while generating wallets. You can still send the invites that generated correctly.`,
296 const sendInvites = useCallback(async () => {
297 // compute all of the names of the fields
298 const allFieldNames = Object.keys(cachedEmails.current);
299 // only emails we're sending are the valid ones with invites
300 const names = allFieldNames.filter(name => !!invites[name]);
301 const emails = allFieldNames.map(name => cachedEmails.current[name]);
303 const _web3 = web3.getOrElse(null);
304 const _wallet = wallet.getOrElse(null);
305 if (!_web3 || !_wallet) {
306 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
309 setStatus(STATUS.FUNDING);
310 const totalCost = toBN(GAS_LIMIT)
312 .mul(toBN(emails.length));
313 const tankWasUsed = await tank.ensureFundsFor(
317 toWei(totalCost.toString(), 'gwei'),
318 names.map(name => invites[name].rawTx),
319 (address, minBalance, balance) =>
320 setNeedFunds({ address, minBalance, balance }),
321 () => setNeedFunds(undefined)
324 setStatus(STATUS.SENDING);
327 let unsentInvites = [];
328 let orphanedInvites = [];
329 const txAndMailings = names.map(async name => {
330 const invite = invites[name];
332 const txHash = await sendSignedTransaction(
338 await waitForTransactionConfirm(_web3, txHash);
340 console.error(error);
341 unsentInvites.push(invite);
353 console.error(error);
354 orphanedInvites.push(invite);
357 addReceipt({ [name]: true });
360 await Promise.all(txAndMailings);
361 // if there are any receipt errors, throw a general error
362 let errorString = '';
363 if (orphanedInvites.length > 0) {
365 'Not all invite emails were sent. ' +
366 'Please send the following invite codes manually: ' +
367 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
370 if (unsentInvites.length > 0) {
373 'Not all invites were created. ' +
374 'Did not send invites for: ' +
375 unsentInvites.map(i => i.email).join(', ') +
378 if (errorString !== '') {
379 throw new Error(errorString);
392 const onSubmit = useCallback(
394 cachedEmails.current = values.emails.reduce((memo, email, i) => {
395 memo[nameForEmailField(i)] = email;
398 setStatus(STATUS.GENERATING);
399 const errors = await generateInvites(values);
400 if (hasErrors(errors)) {
401 if (onlyHasWarning(errors)) {
402 setStatus(STATUS.CAN_SEND);
408 await timeout(500); // wait for progress animation to complete.
410 setStatus(STATUS.CAN_SEND);
415 const doSend = useCallback(async () => {
416 setGeneralError(null);
418 setStatus(STATUS.SENDING);
420 setStatus(STATUS.SUCCESS);
422 console.error(error);
423 setGeneralError(error.message);
424 setStatus(STATUS.FAILURE);
428 // when we transition to done, sync invites because we just sent some
429 // and therefore know that state has changed
434 }, [isDone, syncInvites, point]);
436 const renderButton = ({ handleSubmit, fields }) => {
442 handleSubmit={handleSubmit}
443 accessory={`${visualProgress}/${fields.length}`}>
444 {buttonText(status, fields.length)}
457 accessory={`${visualProgress}/${fields.length}`}
458 progress={percentProgress}
460 {buttonText(status, fields.length)}
474 {buttonText(status, fields.length)}
488 accessory={`${visualProgress}/${fields.length}`}>
489 {buttonText(status, fields.length)}
503 accessory={`${visualProgress}/${fields.length}`}
504 progress={percentProgress}
505 color={isGenerating ? 'black' : 'green4'}>
506 {buttonText(status, fields.length)}
519 initialValues={INITIAL_VALUES}>
520 {({ handleSubmit }) => (
521 <FieldArray name="emails">
523 const sentInviteNames = Object.keys(receipts);
526 <Grid.Item full as={Flex} justify="end">
527 {/* use hidden class instead of removing component from dom */}
528 {/* in order to avoid janky reflow */}
530 onClick={() => fields.push('')}
531 disabled={!canInput || fields.length >= maxInvitesToSend}
532 className={cn({ hidden: isDone })}
540 <Grid.Item as={Text} className="f5" full>
542 {pluralize(sentInviteNames.length, 'invite')}
544 {pluralize(sentInviteNames.length, 'has', 'have')} been
548 {sentInviteNames.map(name => (
549 <Grid.Item as={HelpText} key={name} full>
551 {({ input: { value } }) => value}
558 {fields.map((name, i) => {
559 const isFirst = i === 0;
566 onMouseOver={() => setHovered({ [name]: true })}
567 onMouseLeave={() => setHovered({ [name]: false })}>
572 label={isFirst ? 'Email Address' : undefined}
573 accessory={accessoryFor(name)}
576 {({ meta: { active } }) => {
580 (active || hovered[name]) &&
587 onClick={() => fields.remove(i)}
602 {renderButton({ handleSubmit, fields })}
605 <Grid.Item full as={NeedFundsNotice} {...needFunds} />
608 <Grid.Item full as={FormError} />
611 <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