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, DEFAULT_GAS_PRICE_GWEI } from 'lib/constants';
38import * as need from 'lib/need';
39import * as wg from 'lib/walletgen';
40import useSetState from 'lib/useSetState';
41import pluralize from 'lib/pluralize';
42import useMailer from 'lib/useMailer';
44import LoadableButton from 'components/LoadableButton';
45import Highlighted from 'components/Highlighted';
46import BridgeForm from 'form/BridgeForm';
47import { Field } from 'react-final-form';
48import { EmailInput } from 'form/Inputs';
53} from 'form/validators';
54import { FORM_ERROR } from 'final-form';
55import SubmitButton from 'form/SubmitButton';
56import FormError from 'form/FormError';
58const INITIAL_VALUES = { emails: [''] };
60const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
61const INVITE_COST = toWei(
62 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
65const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
69 GENERATING: 'GENERATING',
77const buttonText = (status, count) => {
80 return `Generate ${pluralize(count, 'Invite')}`;
81 case STATUS.GENERATING:
82 return `Generating ${pluralize(count, 'Invite')}...`;
84 return `Send ${pluralize(count, 'Invite')}`;
86 return `Waiting on Funds...`;
88 return `Sending ${pluralize(count, 'Invite')}...`;
95const buildAccessoryFor = (dones, errors) => name => {
96 if (dones[name]) return <AccessoryIcon.Success />;
97 if (errors[name]) return <AccessoryIcon.Failure />;
98 return <AccessoryIcon.Pending />;
101const emailFormatValidator = buildEmailValidator();
103export default function InviteEmail() {
104 const { contracts, web3, networkType } = useNetwork();
105 const { wallet, walletType, walletHdPath } = useWallet();
106 const { syncInvites, getInvites } = usePointCache();
107 const { pointCursor } = usePointCursor();
108 const point = need.point(pointCursor);
109 const { getHasReceived, sendMail } = useMailer();
111 const cachedEmails = useRef([]);
113 const { availableInvites } = getInvites(point);
114 const maxInvitesToSend = availableInvites.matchWith({
119 // manage per-input state
120 const [hovered, setHovered] = useSetState();
121 const [invites, addInvite, clearInvites] = useSetState();
122 const [receipts, addReceipt, clearReceipts] = useSetState();
123 const [errors, addError] = useSetState();
125 // manage general state that affects the whole form
126 const [status, setStatus] = useState(STATUS.INPUT);
127 const [needFunds, setNeedFunds] = useState(null);
128 const [generalError, setGeneralError] = useState(null);
130 // derive booleans from status
131 const canInput = status === STATUS.INPUT;
132 const canSend = status === STATUS.CAN_SEND;
133 const isGenerating = status === STATUS.GENERATING;
134 const isSending = status === STATUS.SENDING;
135 const isFailed = status === STATUS.FAILURE;
136 const isDone = status === STATUS.SUCCESS;
138 const validateEmail = useCallback(
140 // check individual email validity
141 const error = await emailFormatValidator(email);
146 const hasReceived = await getHasReceived(email);
148 return HAS_RECEIVED_TEXT;
154 const validateEmails = useCallback(
155 async emails => await Promise.all(emails.map(validateEmail)),
159 const validateForm = useCallback(async (values, errors) => {
160 if (hasErrors(errors)) {
164 // check for email uniqenesss
165 const emails = values.emails.filter(d => !!d);
166 if (uniq(emails).length !== emails.length) {
167 return { [FORM_ERROR]: 'Duplicate email.' };
171 const validate = useMemo(
172 () => composeValidator({ emails: validateEmails }, validateForm),
173 [validateEmails, validateForm]
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 visualProgress = progress === null ? '-' : `${progress + 1}`;
184 // build a builder for the accessory to the input, depending on status
185 const accessoryFor = (() => {
186 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
187 if (isSending) return buildAccessoryFor(receipts, errors);
188 if (isFailed) return buildAccessoryFor({}, errors);
192 const generateInvites = useCallback(
194 const _contracts = contracts.getOrElse(null);
195 const _web3 = web3.getOrElse(null);
196 const _wallet = wallet.getOrElse(null);
197 if (!_contracts || !_web3 || !_wallet) {
198 // not using need because we want a custom error
199 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
202 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
203 const chainId = await _web3.eth.net.getId();
204 const planets = await azimuth.delegatedSending.getPlanetsToSend(
210 // account for the race condition where invites got used up while we were
211 // composing our target list
212 if (planets.length < values.emails.length) {
213 // resync invites to the cache, since they're out of date
218 `Can currently only send ${planets.length} invites. ` +
219 `Please remove invites until you are within the limit.`,
224 // NB(shrugs) - must be processed in serial because main thread, etc
226 for (let i = 0; i < values.emails.length; i++) {
228 const email = values.emails[i];
229 const planet = planets[i];
231 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
233 // we're always giving planets, so generate a ticket of the correct size
236 const inviteTx = azimuth.delegatedSending.sendPoint(
243 const signedTx = await signTransaction({
250 // TODO: ^ make a useTransactionSigner to encapsulate this logic
252 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
253 gasLimit: GAS_LIMIT.toString(),
256 const rawTx = hexify(signedTx.serialize());
258 addInvite({ [email]: { email, ticket, signedTx, rawTx } });
260 console.error(error);
265 if (errorCount > 0) {
267 [FORM_ERROR]: `There ${pluralize(
271 )} ${pluralize(errorCount, 'error')} while generating wallets.`,
289 const sendInvites = useCallback(async () => {
290 const emails = cachedEmails.current;
291 const _web3 = web3.getOrElse(null);
292 const _wallet = wallet.getOrElse(null);
293 if (!_web3 || !_wallet) {
294 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
297 setStatus(STATUS.FUNDING);
298 const tankWasUsed = await tank.ensureFundsFor(
302 INVITE_COST * emails.length,
303 emails.map(email => invites[email].rawTx),
304 (address, minBalance, balance) =>
305 setNeedFunds({ address, minBalance, balance }),
306 () => setNeedFunds(undefined)
309 setStatus(STATUS.SENDING);
312 let unsentInvites = [];
313 let orphanedInvites = [];
314 const txAndMailings = emails.map(async email => {
315 const invite = invites[email];
317 const txHash = await sendSignedTransaction(
323 // TODO: waitForTransactionConfirm never rejects
324 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
325 if (!didConfirm) throw new Error();
327 console.error(error);
328 unsentInvites.push(invite);
340 console.error(error);
341 orphanedInvites.push(invite);
344 addReceipt({ [email]: true });
347 await Promise.all(txAndMailings);
348 // if there are any receipt errors, throw a general error
349 let errorString = '';
350 if (orphanedInvites.length > 0) {
352 'Not all invite emails were sent. ' +
353 'Please send the following invite codes manually: ' +
354 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
357 if (unsentInvites.length > 0) {
360 'Not all invites were created. ' +
361 'Did not send invites for: ' +
362 unsentInvites.map(i => i.email).join(', ') +
365 if (errorString !== '') {
366 throw new Error(errorString);
368 }, [web3, addReceipt, clearReceipts, invites, point, wallet, sendMail]);
370 const onSubmit = useCallback(
372 cachedEmails.current = values.emails;
373 setStatus(STATUS.GENERATING);
374 const errors = await generateInvites(values);
378 setStatus(STATUS.CAN_SEND);
383 const doSend = useCallback(async () => {
384 setGeneralError(null);
386 setStatus(STATUS.SENDING);
388 setStatus(STATUS.SUCCESS);
390 console.error(error);
391 setGeneralError(error.message);
392 setStatus(STATUS.FAILURE);
396 // when we transition to done, sync invites because we just sent some
397 // and therefore know that state has changed
402 }, [isDone, syncInvites, point]);
409 initialValues={INITIAL_VALUES}>
410 {({ handleSubmit, valid, values }) => (
411 <FieldArray name="emails">
414 <Grid.Item full as={Flex} justify="end">
415 {/* use hidden class instead of removing component from dom */}
416 {/* in order to avoid janky reflow */}
418 onClick={() => fields.push('')}
419 disabled={!canInput || fields.length >= maxInvitesToSend}
420 className={cn({ hidden: isDone })}
428 <Grid.Item as={Text} className="f5" full>
430 {pluralize(fields.length, 'invite')}
432 {pluralize(fields.length, 'has', 'have')} been
436 {fields.map(name => (
437 <Grid.Item as={HelpText} key={name} full>
439 {({ input: { value } }) => value}
446 {fields.map((name, i) => {
447 const isFirst = i === 0;
454 onMouseOver={() => setHovered({ [name]: true })}
455 onMouseLeave={() => setHovered({ [name]: false })}>
460 label={isFirst ? 'Email Address' : undefined}
461 accessory={accessoryFor(name)}
464 {({ meta: { active } }) => {
468 (active || hovered[name]) &&
475 onClick={() => fields.remove(i)}
494 handleSubmit={handleSubmit}
495 accessory={`${visualProgress}/${fields.length}`}>
496 {buttonText(status, fields.length)}
504 accessory={`${visualProgress}/${fields.length}`}
508 {buttonText(status, fields.length)}
514 <Highlighted warning>
515 Your ownership address {needFunds.address} needs at
516 least {fromWei(needFunds.minBalance)} ETH and
517 currently has {fromWei(needFunds.balance)} ETH.
518 Waiting until the account has enough funds.
523 <Grid.Item full as={FormError} />
526 <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