1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import * as ob from 'urbit-ob';
4import * as azimuth from 'azimuth-js';
16import { uniq } from 'lodash';
17import { fromWei, toWei } from 'web3-utils';
19import { usePointCursor } from 'store/pointCursor';
20import { useNetwork } from 'store/network';
21import { usePointCache } from 'store/pointCache';
22import { useWallet } from 'store/wallet';
24// for transaction generation and signing
27 sendSignedTransaction,
28 waitForTransactionConfirm,
31import * as tank from 'lib/tank';
32import useArray from 'lib/useArray';
33import { buildEmailInputConfig } from 'lib/useInputs';
34import { MIN_PLANET, GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } from 'lib/constants';
35import * as need from 'lib/need';
36import * as wg from 'lib/walletgen';
37import useSetState from 'lib/useSetState';
38import pluralize from 'lib/pluralize';
39import useMailer from 'lib/useMailer';
41import LoadableButton from 'components/LoadableButton';
42import Highlighted from 'components/Highlighted';
44const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
45const INVITE_COST = toWei(
46 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
49const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
53 GENERATING: 'GENERATING',
61const buttonText = (status, count) => {
64 return `Generate ${pluralize(count, 'Invite')}`;
65 case STATUS.GENERATING:
66 return `Generating ${pluralize(count, 'Invite')}...`;
68 return `Send ${pluralize(count, 'Invite')}`;
70 return `Waiting on Funds...`;
72 return `Sending ${pluralize(count, 'Invite')}...`;
79// world's simplest uid
81const buildInputConfig = (extra = {}) =>
82 buildEmailInputConfig({
83 name: `email-${id++}`,
84 placeholder: 'Email Address',
88const buildAccessoryFor = (dones, errors) => name => {
89 if (dones[name]) return <AccessoryIcon.Success />;
90 if (errors[name]) return <AccessoryIcon.Failure />;
91 return <AccessoryIcon.Pending />;
94// TODO: test with tank, successful txs
95export default function InviteEmail() {
96 // TODO: resumption after error?
97 const { contracts, web3, networkType } = useNetwork();
98 const { wallet, walletType, walletHdPath } = useWallet();
99 const { syncInvites, getInvites } = usePointCache();
100 const { pointCursor } = usePointCursor();
101 const point = need.point(pointCursor);
102 const { getHasReceived, syncHasReceivedForEmail, sendMail } = useMailer();
104 const { availableInvites } = getInvites(point);
105 const maxInvitesToSend = availableInvites.matchWith({
110 // manage the array of input configs
113 { append: appendInput, removeAt: removeInputAt },
115 [buildInputConfig({ label: 'Email Address', autoFocus: true })],
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 // add disabled, error info to input configs
139 const dynamicConfigs = useMemo(
141 inputConfigs.map(config => {
142 config.disabled = !canInput;
143 const hasReceivedError = getHasReceived(config.name).matchWith({
144 Nothing: () => null, // loading
145 Just: p => p.value && HAS_RECEIVED_TEXT,
147 config.error = hasReceivedError || errors[config.name];
150 [inputConfigs, errors, canInput, getHasReceived]
153 // construct the state of the set of inputs we're rendering below
154 const { inputs, pass } = useForm(dynamicConfigs);
155 // did all of the inputs pass inspection (and there are no general errors)?
156 const allPass = pass && !generalError;
157 // the form is submittable iff passing and input is allowed
158 const canGenerate = allPass && canInput;
159 // additional inputs can be added iff input is allowed and we have enough
161 const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
163 // progress is [0, .length] of invites or receipts, as we're generating them
164 const progress = isGenerating
165 ? Object.keys(invites).length
167 ? Object.keys(receipts).length
169 const visualProgress = progress === null ? '-' : `${progress + 1}`;
171 // build a builder for the accessory to the input, depending on status
172 const accessoryFor = (() => {
173 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
174 if (isSending) return buildAccessoryFor(receipts, errors);
175 if (isFailed) return buildAccessoryFor({}, errors);
179 const generateInvites = useCallback(async () => {
180 const _contracts = contracts.getOrElse(null);
181 const _web3 = web3.getOrElse(null);
182 const _wallet = wallet.getOrElse(null);
183 if (!_contracts || !_web3 || !_wallet) {
184 // not using need because we want a custom error
185 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
188 //TODO want to do this on-input, but that gets weird. see #188
190 let alreadyReceived = [];
192 inputs.map(async input => {
193 const email = input.data;
194 getHasReceived(email).matchWith({
199 if (p.value) alreadyReceived.push(email);
205 throw new Error('No word yet from email service...');
207 if (alreadyReceived.length > 0) {
209 'The following recipients already own a point: ' +
210 alreadyReceived.join(', ')
214 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
215 const chainId = await _web3.eth.net.getId();
216 const planets = await azimuth.delegatedSending.getPlanetsToSend(
222 // account for the race condition where invites got used up while we were
223 // composing our target list
224 if (planets.length < inputs.length) {
225 // resync invites to the cache, since they're out of date
229 `Can currently only send ${planets.length} invites. ` +
230 `Please remove invites until you are within the limit.`
235 // NB(shrugs) - must be processed in serial because main thread, etc
237 for (let i = 0; i < inputs.length; i++) {
238 const input = inputs[i];
240 const { data: email, name } = inputs[i];
242 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
244 // we're always giving planets, so generate a ticket of the correct size
247 const inviteTx = azimuth.delegatedSending.sendPoint(
253 const signedTx = await signTransaction({
258 // TODO: ^ make a useTransactionSigner to encapsulate this logic
260 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
261 gasLimit: GAS_LIMIT.toString(),
265 const rawTx = hexify(signedTx.serialize());
267 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
269 console.error(error);
271 addError({ [input.name]: `Wallet Error: ${input.email}` });
275 if (errorCount > 0) {
277 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
280 )} while generating wallets.`
299 const sendInvites = useCallback(async () => {
300 const _web3 = web3.getOrElse(null);
301 const _wallet = wallet.getOrElse(null);
302 if (!_web3 || !_wallet) {
303 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
306 setStatus(STATUS.FUNDING);
307 const tankWasUsed = await tank.ensureFundsFor(
311 INVITE_COST * inputs.length,
312 inputs.map(input => invites[input.name].rawTx),
313 (address, minBalance, balance) =>
314 setNeedFunds({ address, minBalance, balance }),
315 () => setNeedFunds(undefined)
318 setStatus(STATUS.SENDING);
321 let unsentInvites = [];
322 let orphanedInvites = [];
323 const txAndMailings = inputs.map(async input => {
324 const invite = invites[input.name];
326 const txHash = await sendSignedTransaction(
332 // TODO: waitForTransactionConfirm never rejects
333 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
334 if (!didConfirm) throw new Error();
336 console.error(error);
337 unsentInvites.push(invite);
342 const success = await sendMail(
348 if (!success) throw new Error('Failed to send mail');
350 console.error(error);
351 orphanedInvites.push(invite);
354 addReceipt({ [input.name]: true });
357 await Promise.all(txAndMailings);
358 // if there are any receipt errors, throw a general error
359 let errorString = '';
360 if (orphanedInvites.length > 0) {
362 'Not all invite emails were sent. ' +
363 'Please send the following invite codes manually: ' +
364 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
367 if (unsentInvites.length > 0) {
370 'Not all invites were created. ' +
371 'Did not send invites for: ' +
372 unsentInvites.map(i => i.email).join(', ') +
375 if (errorString !== '') {
376 throw new Error(errorString);
389 const onClick = useCallback(async () => {
390 setGeneralError(null);
393 setStatus(STATUS.GENERATING);
394 await generateInvites();
395 setStatus(STATUS.CAN_SEND);
396 } else if (canSend) {
397 setStatus(STATUS.SENDING);
399 setStatus(STATUS.SUCCESS);
402 console.error(error);
403 setGeneralError(error);
404 setStatus(STATUS.FAILURE);
406 }, [canGenerate, canSend, generateInvites, sendInvites]);
408 // when inputs update, check to see if any of them are duplicates
410 // compute the list of valid emails
411 const emails = inputs.map(i => i.data).filter(d => !!d);
412 if (uniq(emails).length !== emails.length) {
413 setGeneralError(new Error(`Duplicate email.`));
415 setGeneralError(null);
416 setStatus(STATUS.INPUT);
420 // when we transition to done, sync invites because we just sent some
421 // and therefore know that state has changed
426 }, [isDone, syncInvites, point]);
429 for (const input of inputs) {
431 syncHasReceivedForEmail(input.data);
434 }, [inputs, syncHasReceivedForEmail]);
438 <Grid.Item full as={Flex} justify="end">
439 {/* use hidden class instead of removing component from dom */}
440 {/* in order to avoid janky reflow */}
442 onClick={() => appendInput()}
443 disabled={!canAddInvite}
444 className={cn({ hidden: isDone })}
452 <Grid.Item as={Text} className="f5" full>
453 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
454 {pluralize(inputs.length, 'has', 'have')} been successfully sent
456 {inputs.map(input => (
457 <Grid.Item as={HelpText} key={input.name} full>
458 {invites[input.name].email}
467 {inputs.map((input, i) => {
468 const isFirst = i === 0;
474 onMouseOver={() => setHovered({ [input.name]: true })}
475 onMouseLeave={() => setHovered({ [input.name]: false })}
481 accessory={accessoryFor(input.name)}
484 (input.focused || hovered[input.name]) &&
491 onClick={() => removeInputAt(i)}
505 disabled={!canGenerate && !canSend}
506 accessory={`${visualProgress}/${inputs.length}`}
510 {buttonText(status, inputs.length)}
515 <Highlighted warning>
516 Your ownership address {needFunds.address} needs at least{' '}
517 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
518 {fromWei(needFunds.balance)} ETH. Waiting until the account has
526 <ErrorText>{generalError.message.toString()}</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