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 * 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 ProgressButton from 'components/ProgressButton';
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';
58import { WARNING, onlyHasWarning } from 'form/helpers';
59import useGasPrice from 'lib/useGasPrice';
61const INITIAL_VALUES = { emails: [''] };
63const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
64const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
68 GENERATING: 'GENERATING',
76const nameForEmailField = i => `emails[${i}]`;
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();
109 const { gasPrice } = useGasPrice();
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 validateHasReceived = useCallback(
140 const hasReceived = await getHasReceived(email);
142 return HAS_RECEIVED_TEXT;
148 const validateForm = useCallback((values, errors) => {
149 if (hasErrors(errors)) {
153 // check for email uniqenesss
154 const emails = values.emails.filter(d => !!d);
155 if (uniq(emails).length !== emails.length) {
156 return { [FORM_ERROR]: 'Duplicate email.' };
160 const validate = useMemo(
164 emails: buildArrayValidator(buildEmailValidator(validateHasReceived)),
168 [validateForm, validateHasReceived]
171 // progress is [0, .length] of invites or receipts, as we're generating them
172 const progress = isGenerating
173 ? Object.keys(invites).length
175 ? Object.keys(receipts).length
177 const visualProgress = progress === null ? '-' : `${progress + 1}`;
179 // build a builder for the accessory to the input, depending on status
180 const accessoryFor = (() => {
181 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
182 if (isSending) return buildAccessoryFor(receipts, errors);
183 if (isFailed) return buildAccessoryFor({}, errors);
187 const generateInvites = useCallback(
189 const _contracts = contracts.getOrElse(null);
190 const _web3 = web3.getOrElse(null);
191 const _wallet = wallet.getOrElse(null);
192 if (!_contracts || !_web3 || !_wallet) {
193 // not using need because we want a custom error
194 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
197 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
198 const chainId = await _web3.eth.net.getId();
199 const planets = await azimuth.delegatedSending.getPlanetsToSend(
205 // account for the race condition where invites got used up while we were
206 // composing our target list
207 if (planets.length < values.emails.length) {
208 // resync invites to the cache, since they're out of date
213 `Can currently only send ${planets.length} invites. ` +
214 `Please remove invites until you are within the limit.`,
219 // NB(shrugs) - must be processed in serial because main thread, etc
221 for (let i = 0; i < values.emails.length; i++) {
222 const name = nameForEmailField(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: gasPrice.toString(), // expects string gwei
249 gasLimit: GAS_LIMIT.toString(),
252 const rawTx = hexify(signedTx.serialize());
254 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
256 console.error(error);
258 addError({ [name]: 'Error generating invite.' });
262 if (errorCount > 0) {
264 [WARNING]: `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
267 )} while generating wallets. You can still send the invites that generated correctly.`,
287 const sendInvites = useCallback(async () => {
288 // compute all of the names of the fields
289 const allFieldNames = Object.keys(cachedEmails.current);
290 // only emails we're sending are the valid ones with invites
291 const names = allFieldNames.filter(name => !!invites[name]);
292 const emails = allFieldNames.map(name => cachedEmails.current[name]);
294 const _web3 = web3.getOrElse(null);
295 const _wallet = wallet.getOrElse(null);
296 if (!_web3 || !_wallet) {
297 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
300 setStatus(STATUS.FUNDING);
301 const tankWasUsed = await tank.ensureFundsFor(
305 toWei((gasPrice * GAS_LIMIT * emails.length).toString(), 'gwei'),
306 names.map(name => invites[name].rawTx),
307 (address, minBalance, balance) =>
308 setNeedFunds({ address, minBalance, balance }),
309 () => setNeedFunds(undefined)
312 setStatus(STATUS.SENDING);
315 let unsentInvites = [];
316 let orphanedInvites = [];
317 const txAndMailings = names.map(async name => {
318 const invite = invites[name];
320 const txHash = await sendSignedTransaction(
326 await waitForTransactionConfirm(_web3, txHash);
328 console.error(error);
329 unsentInvites.push(invite);
341 console.error(error);
342 orphanedInvites.push(invite);
345 addReceipt({ [name]: true });
348 await Promise.all(txAndMailings);
349 // if there are any receipt errors, throw a general error
350 let errorString = '';
351 if (orphanedInvites.length > 0) {
353 'Not all invite emails were sent. ' +
354 'Please send the following invite codes manually: ' +
355 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
358 if (unsentInvites.length > 0) {
361 'Not all invites were created. ' +
362 'Did not send invites for: ' +
363 unsentInvites.map(i => i.email).join(', ') +
366 if (errorString !== '') {
367 throw new Error(errorString);
380 const onSubmit = useCallback(
382 cachedEmails.current = values.emails.reduce((memo, email, i) => {
383 memo[nameForEmailField(i)] = email;
386 setStatus(STATUS.GENERATING);
387 const errors = await generateInvites(values);
388 if (hasErrors(errors)) {
389 if (onlyHasWarning(errors)) {
390 setStatus(STATUS.CAN_SEND);
396 setStatus(STATUS.CAN_SEND);
401 const doSend = useCallback(async () => {
402 setGeneralError(null);
404 setStatus(STATUS.SENDING);
406 setStatus(STATUS.SUCCESS);
408 console.error(error);
409 setGeneralError(error.message);
410 setStatus(STATUS.FAILURE);
414 // when we transition to done, sync invites because we just sent some
415 // and therefore know that state has changed
420 }, [isDone, syncInvites, point]);
427 initialValues={INITIAL_VALUES}>
428 {({ handleSubmit }) => (
429 <FieldArray name="emails">
431 const sentInviteNames = Object.keys(receipts);
434 <Grid.Item full as={Flex} justify="end">
435 {/* use hidden class instead of removing component from dom */}
436 {/* in order to avoid janky reflow */}
438 onClick={() => fields.push('')}
439 disabled={!canInput || fields.length >= maxInvitesToSend}
440 className={cn({ hidden: isDone })}
448 <Grid.Item as={Text} className="f5" full>
450 {pluralize(sentInviteNames.length, 'invite')}
452 {pluralize(sentInviteNames.length, 'has', 'have')} been
456 {sentInviteNames.map(name => (
457 <Grid.Item as={HelpText} key={name} full>
459 {({ input: { value } }) => value}
466 {fields.map((name, i) => {
467 const isFirst = i === 0;
474 onMouseOver={() => setHovered({ [name]: true })}
475 onMouseLeave={() => setHovered({ [name]: false })}>
480 label={isFirst ? 'Email Address' : undefined}
481 accessory={accessoryFor(name)}
484 {({ meta: { active } }) => {
488 (active || hovered[name]) &&
495 onClick={() => fields.remove(i)}
514 handleSubmit={handleSubmit}
515 accessory={`${visualProgress}/${fields.length}`}>
516 {buttonText(status, fields.length)}
524 accessory={`${visualProgress}/${fields.length}`}
528 {buttonText(status, fields.length)}
534 <Highlighted warning>
535 Your ownership address {needFunds.address} needs at
536 least {fromWei(needFunds.minBalance)} ETH and
537 currently has {fromWei(needFunds.balance)} ETH.
538 Waiting until the account has enough funds.
543 <Grid.Item full as={FormError} />
546 <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