8import cn from 'classnames';
9import * as ob from 'urbit-ob';
10import * as azimuth from 'azimuth-js';
20import { uniq } from 'lodash';
21import { fromWei, toWei } from 'web3-utils';
22import { FieldArray } from 'react-final-form-arrays';
24import { usePointCursor } from 'store/pointCursor';
25import { useNetwork } from 'store/network';
26import { usePointCache } from 'store/pointCache';
27import { useWallet } from 'store/wallet';
29// for transaction generation and signing
32 sendSignedTransaction,
33 waitForTransactionConfirm,
36import * as tank from 'lib/tank';
37import { MIN_PLANET, GAS_LIMITS } from 'lib/constants';
38import { useSuggestedGasPrice } from 'lib/useSuggestedGasPrice';
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 LoadableButton from 'components/LoadableButton';
46import Highlighted from 'components/Highlighted';
47import BridgeForm from 'form/BridgeForm';
48import { Field } from 'react-final-form';
49import { EmailInput } from 'form/Inputs';
55} from 'form/validators';
56import { FORM_ERROR } from 'final-form';
57import SubmitButton from 'form/SubmitButton';
58import FormError from 'form/FormError';
60const INITIAL_VALUES = { emails: [''] };
62const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
63const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
67 GENERATING: 'GENERATING',
75const buttonText = (status, count) => {
78 return `Generate ${pluralize(count, 'Invite')}`;
79 case STATUS.GENERATING:
80 return `Generating ${pluralize(count, 'Invite')}...`;
82 return `Send ${pluralize(count, 'Invite')}`;
84 return `Waiting on Funds...`;
86 return `Sending ${pluralize(count, 'Invite')}...`;
93const buildAccessoryFor = (dones, errors) => name => {
94 if (dones[name]) return <AccessoryIcon.Success />;
95 if (errors[name]) return <AccessoryIcon.Failure />;
96 return <AccessoryIcon.Pending />;
99export default function InviteEmail() {
100 const { contracts, web3, networkType } = useNetwork();
101 const { wallet, walletType, walletHdPath } = useWallet();
102 const { syncInvites, getInvites } = usePointCache();
103 const { pointCursor } = usePointCursor();
104 const point = need.point(pointCursor);
105 const { getHasReceived, sendMail } = useMailer();
106 const { gasPrice } = useSuggestedGasPrice(networkType);
108 const cachedEmails = useRef([]);
110 const { availableInvites } = getInvites(point);
111 const maxInvitesToSend = availableInvites.matchWith({
116 // manage per-input state
117 const [hovered, setHovered] = useSetState();
118 const [invites, addInvite, clearInvites] = useSetState();
119 const [receipts, addReceipt, clearReceipts] = useSetState();
120 const [errors, addError] = useSetState();
122 // manage general state that affects the whole form
123 const [status, setStatus] = useState(STATUS.INPUT);
124 const [needFunds, setNeedFunds] = useState(null);
125 const [generalError, setGeneralError] = useState(null);
127 // derive booleans from status
128 const canInput = status === STATUS.INPUT;
129 const canSend = status === STATUS.CAN_SEND;
130 const isGenerating = status === STATUS.GENERATING;
131 const isSending = status === STATUS.SENDING;
132 const isFailed = status === STATUS.FAILURE;
133 const isDone = status === STATUS.SUCCESS;
135 const validateHasReceived = useCallback(
137 const hasReceived = await getHasReceived(email);
139 return HAS_RECEIVED_TEXT;
145 const validateForm = useCallback(async (values, errors) => {
146 if (hasErrors(errors)) {
150 // check for email uniqenesss
151 const emails = values.emails.filter(d => !!d);
152 if (uniq(emails).length !== emails.length) {
153 return { [FORM_ERROR]: 'Duplicate email.' };
157 const validate = useMemo(
161 emails: buildArrayValidator(
162 buildEmailValidator([validateHasReceived])
167 [validateForm, validateHasReceived]
170 // progress is [0, .length] of invites or receipts, as we're generating them
171 const progress = isGenerating
172 ? Object.keys(invites).length
174 ? Object.keys(receipts).length
176 const visualProgress = progress === null ? '-' : `${progress + 1}`;
178 // build a builder for the accessory to the input, depending on status
179 const accessoryFor = (() => {
180 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
181 if (isSending) return buildAccessoryFor(receipts, errors);
182 if (isFailed) return buildAccessoryFor({}, errors);
186 const generateInvites = useCallback(
188 const _contracts = contracts.getOrElse(null);
189 const _web3 = web3.getOrElse(null);
190 const _wallet = wallet.getOrElse(null);
191 if (!_contracts || !_web3 || !_wallet) {
192 // not using need because we want a custom error
193 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
196 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
197 const chainId = await _web3.eth.net.getId();
198 const planets = await azimuth.delegatedSending.getPlanetsToSend(
204 // account for the race condition where invites got used up while we were
205 // composing our target list
206 if (planets.length < values.emails.length) {
207 // resync invites to the cache, since they're out of date
212 `Can currently only send ${planets.length} invites. ` +
213 `Please remove invites until you are within the limit.`,
218 // NB(shrugs) - must be processed in serial because main thread, etc
220 for (let i = 0; i < values.emails.length; i++) {
222 const email = values.emails[i];
223 const planet = planets[i];
225 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
227 // we're always giving planets, so generate a ticket of the correct size
230 const inviteTx = azimuth.delegatedSending.sendPoint(
237 const signedTx = await signTransaction({
244 // TODO: ^ make a useTransactionSigner to encapsulate this logic
246 gasPrice: gasPrice.toString(),
247 gasLimit: GAS_LIMIT.toString(),
250 const rawTx = hexify(signedTx.serialize());
252 addInvite({ [email]: { email, ticket, signedTx, rawTx } });
254 console.error(error);
259 if (errorCount > 0) {
261 [FORM_ERROR]: `There ${pluralize(
265 )} ${pluralize(errorCount, 'error')} while generating wallets.`,
284 const sendInvites = useCallback(async () => {
285 const emails = cachedEmails.current;
286 const _web3 = web3.getOrElse(null);
287 const _wallet = wallet.getOrElse(null);
288 if (!_web3 || !_wallet) {
289 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
292 setStatus(STATUS.FUNDING);
293 const tankWasUsed = await tank.ensureFundsFor(
297 toWei((gasPrice * GAS_LIMIT * emails.length).toString(), 'gwei'),
298 emails.map(email => invites[email].rawTx),
299 (address, minBalance, balance) =>
300 setNeedFunds({ address, minBalance, balance }),
301 () => setNeedFunds(undefined)
304 setStatus(STATUS.SENDING);
307 let unsentInvites = [];
308 let orphanedInvites = [];
309 const txAndMailings = emails.map(async email => {
310 const invite = invites[email];
312 const txHash = await sendSignedTransaction(
318 await waitForTransactionConfirm(_web3, txHash);
320 console.error(error);
321 unsentInvites.push(invite);
333 console.error(error);
334 orphanedInvites.push(invite);
337 addReceipt({ [email]: true });
340 await Promise.all(txAndMailings);
341 // if there are any receipt errors, throw a general error
342 let errorString = '';
343 if (orphanedInvites.length > 0) {
345 'Not all invite emails were sent. ' +
346 'Please send the following invite codes manually: ' +
347 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
350 if (unsentInvites.length > 0) {
353 'Not all invites were created. ' +
354 'Did not send invites for: ' +
355 unsentInvites.map(i => i.email).join(', ') +
358 if (errorString !== '') {
359 throw new Error(errorString);
372 const onSubmit = useCallback(
374 cachedEmails.current = values.emails;
375 setStatus(STATUS.GENERATING);
376 const errors = await generateInvites(values);
380 setStatus(STATUS.CAN_SEND);
385 const doSend = useCallback(async () => {
386 setGeneralError(null);
388 setStatus(STATUS.SENDING);
390 setStatus(STATUS.SUCCESS);
392 console.error(error);
393 setGeneralError(error.message);
394 setStatus(STATUS.FAILURE);
398 // when we transition to done, sync invites because we just sent some
399 // and therefore know that state has changed
404 }, [isDone, syncInvites, point]);
411 initialValues={INITIAL_VALUES}>
412 {({ handleSubmit, valid, values }) => (
413 <FieldArray name="emails">
416 <Grid.Item full as={Flex} justify="end">
417 {/* use hidden class instead of removing component from dom */}
418 {/* in order to avoid janky reflow */}
420 onClick={() => fields.push('')}
421 disabled={!canInput || fields.length >= maxInvitesToSend}
422 className={cn({ hidden: isDone })}
430 <Grid.Item as={Text} className="f5" full>
432 {pluralize(fields.length, 'invite')}
434 {pluralize(fields.length, 'has', 'have')} been
438 {fields.map(name => (
439 <Grid.Item as={HelpText} key={name} full>
441 {({ input: { value } }) => value}
448 {fields.map((name, i) => {
449 const isFirst = i === 0;
456 onMouseOver={() => setHovered({ [name]: true })}
457 onMouseLeave={() => setHovered({ [name]: false })}>
462 label={isFirst ? 'Email Address' : undefined}
463 accessory={accessoryFor(name)}
466 {({ meta: { active } }) => {
470 (active || hovered[name]) &&
477 onClick={() => fields.remove(i)}
496 handleSubmit={handleSubmit}
497 accessory={`${visualProgress}/${fields.length}`}>
498 {buttonText(status, fields.length)}
506 accessory={`${visualProgress}/${fields.length}`}
510 {buttonText(status, fields.length)}
516 <Highlighted warning>
517 Your ownership address {needFunds.address} needs at
518 least {fromWei(needFunds.minBalance)} ETH and
519 currently has {fromWei(needFunds.balance)} ETH.
520 Waiting until the account has enough funds.
525 <Grid.Item full as={FormError} />
528 <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