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';
54} from 'form/validators';
55import { FORM_ERROR } from 'final-form';
56import SubmitButton from 'form/SubmitButton';
57import FormError from 'form/FormError';
59const INITIAL_VALUES = { emails: [''] };
61const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
62const INVITE_COST = toWei(
63 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
66const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
70 GENERATING: 'GENERATING',
78const buttonText = (status, count) => {
81 return `Generate ${pluralize(count, 'Invite')}`;
82 case STATUS.GENERATING:
83 return `Generating ${pluralize(count, 'Invite')}...`;
85 return `Send ${pluralize(count, 'Invite')}`;
87 return `Waiting on Funds...`;
89 return `Sending ${pluralize(count, 'Invite')}...`;
96const buildAccessoryFor = (dones, errors) => name => {
97 if (dones[name]) return <AccessoryIcon.Success />;
98 if (errors[name]) return <AccessoryIcon.Failure />;
99 return <AccessoryIcon.Pending />;
102export default function InviteEmail() {
103 const { contracts, web3, networkType } = useNetwork();
104 const { wallet, walletType, walletHdPath } = useWallet();
105 const { syncInvites, getInvites } = usePointCache();
106 const { pointCursor } = usePointCursor();
107 const point = need.point(pointCursor);
108 const { getHasReceived, sendMail } = useMailer();
110 const cachedEmails = useRef([]);
112 const { availableInvites } = getInvites(point);
113 const maxInvitesToSend = availableInvites.matchWith({
118 // manage per-input state
119 const [hovered, setHovered] = useSetState();
120 const [invites, addInvite, clearInvites] = useSetState();
121 const [receipts, addReceipt, clearReceipts] = useSetState();
122 const [errors, addError] = useSetState();
124 // manage general state that affects the whole form
125 const [status, setStatus] = useState(STATUS.INPUT);
126 const [needFunds, setNeedFunds] = useState(null);
127 const [generalError, setGeneralError] = useState(null);
129 // derive booleans from status
130 const canInput = status === STATUS.INPUT;
131 const canSend = status === STATUS.CAN_SEND;
132 const isGenerating = status === STATUS.GENERATING;
133 const isSending = status === STATUS.SENDING;
134 const isFailed = status === STATUS.FAILURE;
135 const isDone = status === STATUS.SUCCESS;
137 const validateHasReceived = useCallback(
139 const hasReceived = await getHasReceived(email);
141 return HAS_RECEIVED_TEXT;
147 const validateForm = useCallback(async (values, errors) => {
148 if (hasErrors(errors)) {
152 // check for email uniqenesss
153 const emails = values.emails.filter(d => !!d);
154 if (uniq(emails).length !== emails.length) {
155 return { [FORM_ERROR]: 'Duplicate email.' };
159 const validate = useMemo(
163 emails: buildArrayValidator(
164 buildEmailValidator([validateHasReceived])
169 [validateForm, validateHasReceived]
172 // progress is [0, .length] of invites or receipts, as we're generating them
173 const progress = isGenerating
174 ? Object.keys(invites).length
176 ? Object.keys(receipts).length
178 const visualProgress = progress === null ? '-' : `${progress + 1}`;
180 // build a builder for the accessory to the input, depending on status
181 const accessoryFor = (() => {
182 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
183 if (isSending) return buildAccessoryFor(receipts, errors);
184 if (isFailed) return buildAccessoryFor({}, errors);
188 const generateInvites = useCallback(
190 const _contracts = contracts.getOrElse(null);
191 const _web3 = web3.getOrElse(null);
192 const _wallet = wallet.getOrElse(null);
193 if (!_contracts || !_web3 || !_wallet) {
194 // not using need because we want a custom error
195 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
198 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
199 const chainId = await _web3.eth.net.getId();
200 const planets = await azimuth.delegatedSending.getPlanetsToSend(
206 // account for the race condition where invites got used up while we were
207 // composing our target list
208 if (planets.length < values.emails.length) {
209 // resync invites to the cache, since they're out of date
214 `Can currently only send ${planets.length} invites. ` +
215 `Please remove invites until you are within the limit.`,
220 // NB(shrugs) - must be processed in serial because main thread, etc
222 for (let i = 0; i < values.emails.length; i++) {
224 const email = values.emails[i];
225 const planet = planets[i];
227 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
229 // we're always giving planets, so generate a ticket of the correct size
232 const inviteTx = azimuth.delegatedSending.sendPoint(
239 const signedTx = await signTransaction({
246 // TODO: ^ make a useTransactionSigner to encapsulate this logic
248 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
249 gasLimit: GAS_LIMIT.toString(),
252 const rawTx = hexify(signedTx.serialize());
254 addInvite({ [email]: { email, ticket, signedTx, rawTx } });
256 console.error(error);
261 if (errorCount > 0) {
263 [FORM_ERROR]: `There ${pluralize(
267 )} ${pluralize(errorCount, 'error')} while generating wallets.`,
285 const sendInvites = useCallback(async () => {
286 const emails = cachedEmails.current;
287 const _web3 = web3.getOrElse(null);
288 const _wallet = wallet.getOrElse(null);
289 if (!_web3 || !_wallet) {
290 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
293 setStatus(STATUS.FUNDING);
294 const tankWasUsed = await tank.ensureFundsFor(
298 INVITE_COST * emails.length,
299 emails.map(email => invites[email].rawTx),
300 (address, minBalance, balance) =>
301 setNeedFunds({ address, minBalance, balance }),
302 () => setNeedFunds(undefined)
305 setStatus(STATUS.SENDING);
308 let unsentInvites = [];
309 let orphanedInvites = [];
310 const txAndMailings = emails.map(async email => {
311 const invite = invites[email];
313 const txHash = await sendSignedTransaction(
319 // TODO: waitForTransactionConfirm never rejects
320 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
321 if (!didConfirm) throw new Error();
323 console.error(error);
324 unsentInvites.push(invite);
336 console.error(error);
337 orphanedInvites.push(invite);
340 addReceipt({ [email]: true });
343 await Promise.all(txAndMailings);
344 // if there are any receipt errors, throw a general error
345 let errorString = '';
346 if (orphanedInvites.length > 0) {
348 'Not all invite emails were sent. ' +
349 'Please send the following invite codes manually: ' +
350 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
353 if (unsentInvites.length > 0) {
356 'Not all invites were created. ' +
357 'Did not send invites for: ' +
358 unsentInvites.map(i => i.email).join(', ') +
361 if (errorString !== '') {
362 throw new Error(errorString);
364 }, [web3, addReceipt, clearReceipts, invites, point, wallet, sendMail]);
366 const onSubmit = useCallback(
368 cachedEmails.current = values.emails;
369 setStatus(STATUS.GENERATING);
370 const errors = await generateInvites(values);
374 setStatus(STATUS.CAN_SEND);
379 const doSend = useCallback(async () => {
380 setGeneralError(null);
382 setStatus(STATUS.SENDING);
384 setStatus(STATUS.SUCCESS);
386 console.error(error);
387 setGeneralError(error.message);
388 setStatus(STATUS.FAILURE);
392 // when we transition to done, sync invites because we just sent some
393 // and therefore know that state has changed
398 }, [isDone, syncInvites, point]);
405 initialValues={INITIAL_VALUES}>
406 {({ handleSubmit, valid, values }) => (
407 <FieldArray name="emails">
410 <Grid.Item full as={Flex} justify="end">
411 {/* use hidden class instead of removing component from dom */}
412 {/* in order to avoid janky reflow */}
414 onClick={() => fields.push('')}
415 disabled={!canInput || fields.length >= maxInvitesToSend}
416 className={cn({ hidden: isDone })}
424 <Grid.Item as={Text} className="f5" full>
426 {pluralize(fields.length, 'invite')}
428 {pluralize(fields.length, 'has', 'have')} been
432 {fields.map(name => (
433 <Grid.Item as={HelpText} key={name} full>
435 {({ input: { value } }) => value}
442 {fields.map((name, i) => {
443 const isFirst = i === 0;
450 onMouseOver={() => setHovered({ [name]: true })}
451 onMouseLeave={() => setHovered({ [name]: false })}>
456 label={isFirst ? 'Email Address' : undefined}
457 accessory={accessoryFor(name)}
460 {({ meta: { active } }) => {
464 (active || hovered[name]) &&
471 onClick={() => fields.remove(i)}
490 handleSubmit={handleSubmit}
491 accessory={`${visualProgress}/${fields.length}`}>
492 {buttonText(status, fields.length)}
500 accessory={`${visualProgress}/${fields.length}`}
504 {buttonText(status, fields.length)}
510 <Highlighted warning>
511 Your ownership address {needFunds.address} needs at
512 least {fromWei(needFunds.minBalance)} ETH and
513 currently has {fromWei(needFunds.balance)} ETH.
514 Waiting until the account has enough funds.
519 <Grid.Item full as={FormError} />
522 <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