@@ -1,642 +0,0 @@
8−import cn from 'classnames';
9−import ob from 'urbit-ob';
10−import * as azimuth from 'azimuth-js';
20−} from 'indigo-react';
21−import { uniq } from 'lodash';
22−import { toWei, toBN } from 'web3-utils';
23−import { FieldArray } from 'react-final-form-arrays';
24−import { Field } from 'react-final-form';
26−import { usePointCursor } from 'store/pointCursor';
27−import { useNetwork } from 'store/network';
28−import { usePointCache } from 'store/pointCache';
29−import { useWallet } from 'store/wallet';
31−// for transaction generation and signing
34− sendSignedTransaction,
35− waitForTransactionConfirm,
38−import * as tank from 'lib/tank';
39−import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
40−import * as need from 'lib/need';
41−import * as wg from 'lib/walletgen';
42−import useSetState from 'lib/useSetState';
43−import pluralize from 'lib/pluralize';
44−import useMailer from 'lib/useMailer';
46−import ProgressButton from 'components/ProgressButton';
47−import Highlighted from 'components/Highlighted';
48−import { ForwardButton } from 'components/Buttons';
49−import NeedFundsNotice from 'components/NeedFundsNotice';
51−import BridgeForm from 'form/BridgeForm';
52−import { EmailInput } from 'form/Inputs';
58−} from 'form/validators';
59−import { FORM_ERROR } from 'final-form';
60−import SubmitButton from 'form/SubmitButton';
61−import FormError from 'form/FormError';
62−import { WARNING, onlyHasWarning } from 'form/helpers';
63−import useGasPrice from 'lib/useGasPrice';
64−import timeout from 'lib/timeout';
66−const INITIAL_VALUES = { emails: [''] };
68−const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
69−const HAS_RECEIVED_TEXT = 'This email has already received an invite: ';
73− GENERATING: 'GENERATING',
74− CAN_SEND: 'CAN_SEND',
81−const nameForEmailField = i => `emails[${i}]`;
83−const buttonText = (status, count) => {
86− return `Generate ${pluralize(count, 'Invite')}`;
87− case STATUS.GENERATING:
88− return `Generating ${pluralize(count, 'Invite')}...`;
89− case STATUS.CAN_SEND:
90− return `Send ${pluralize(count, 'Invite')}`;
92− return `Waiting on Funds...`;
94− return `Sending ${pluralize(count, 'Invite')}...`;
101−const buildAccessoryFor = (dones, errors) => name => {
102− if (dones[name]) return <AccessoryIcon.Success />;
103− if (errors[name]) return <AccessoryIcon.Failure />;
104− return <AccessoryIcon.Pending />;
107−export 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(
213− values.emails.length
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)
313− .mul(toBN(gasPrice))
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);
426− await sendInvites();
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}>