1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import * as azimuth from 'azimuth-js';
15import { uniq } from 'lodash';
17import { usePointCursor } from 'store/pointCursor';
18import { useNetwork } from 'store/network';
19import { usePointCache } from 'store/pointCache';
20import { useWallet } from 'store/wallet';
22// for transaction generation and signing
25 sendSignedTransaction,
26 waitForTransactionConfirm,
31import * as tank from 'lib/tank';
32import { useLocalRouter } from 'lib/LocalRouter';
33import useArray from 'lib/useArray';
34import { buildEmailInputConfig } from 'lib/useInputs';
35import { MIN_PLANET, GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } from 'lib/constants';
36import * as need from 'lib/need';
37import * as wg from 'lib/walletgen';
38import useSetState from 'lib/useSetState';
39import pluralize from 'lib/pluralize';
40import useMailer from 'lib/useMailer';
42import MiniBackButton from 'components/MiniBackButton';
43import LoadableButton from 'components/LoadableButton';
44import Highlighted from 'components/Highlighted';
46const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
47const INVITE_COST = toWei(
48 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
51const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
55 GENERATING: 'GENERATING',
63const buttonText = (status, count) => {
66 return `Generate ${pluralize(count, 'Invite')}`;
67 case STATUS.GENERATING:
68 return `Generating ${pluralize(count, 'Invite')}...`;
70 return `Send ${pluralize(count, 'Invite')}`;
72 return `Waiting on Funds...`;
74 return `Sending ${pluralize(count, 'Invite')}...`;
81// world's simplest uid
83const buildInputConfig = (extra = {}) =>
84 buildEmailInputConfig({
85 name: `email-${id++}`,
86 placeholder: 'Email Address',
90const buildAccessoryFor = (dones, errors) => name => {
91 if (dones[name]) return <AccessoryIcon.Success />;
92 if (errors[name]) return <AccessoryIcon.Failure />;
93 return <AccessoryIcon.Pending />;
96// TODO: test with tank, successful txs
97export default function InviteEmail() {
98 // TODO: resumption after error?
99 const { pop } = useLocalRouter();
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, syncHasReceivedForEmail, sendMail } = useMailer();
107 const { availableInvites } = getInvites(point);
108 const maxInvitesToSend = availableInvites.matchWith({
113 // manage the array of input configs
116 { append: appendInput, removeAt: removeInputAt },
118 [buildInputConfig({ label: 'Email Address', autoFocus: true })],
122 // manage per-input state
123 const [hovered, setHovered] = useSetState();
124 const [invites, addInvite, clearInvites] = useSetState();
125 const [receipts, addReceipt, clearReceipts] = useSetState();
126 const [errors, addError] = useSetState();
128 // manage general state that affects the whole form
129 const [status, setStatus] = useState(STATUS.INPUT);
130 const [needFunds, setNeedFunds] = useState(null);
131 const [generalError, setGeneralError] = useState(null);
133 // derive booleans from status
134 const canInput = status === STATUS.INPUT;
135 const canSend = status === STATUS.CAN_SEND;
136 const isGenerating = status === STATUS.GENERATING;
137 const isSending = status === STATUS.SENDING;
138 const isFailed = status === STATUS.FAILURE;
139 const isDone = status === STATUS.SUCCESS;
141 // add disabled, error info to input configs
142 const dynamicConfigs = useMemo(
144 inputConfigs.map(config => {
145 config.disabled = !canInput;
146 const hasReceivedError = getHasReceived(config.name).matchWith({
147 Nothing: () => null, // loading
148 Just: p => p.value && HAS_RECEIVED_TEXT,
150 config.error = hasReceivedError || errors[config.name];
153 [inputConfigs, errors, canInput, getHasReceived]
156 // construct the state of the set of inputs we're rendering below
157 const { inputs, pass } = useForm(dynamicConfigs);
158 // did all of the inputs pass inspection (and there are no general errors)?
159 const allPass = pass && !generalError;
160 // the form is submittable iff passing and input is allowed
161 const canGenerate = allPass && canInput;
162 // additional inputs can be added iff input is allowed and we have enough
164 const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
166 // progress is [0, .length] of invites or receipts, as we're generating them
167 const progress = isGenerating
168 ? Object.keys(invites).length
170 ? Object.keys(receipts).length
172 const visualProgress = progress === null ? '-' : `${progress + 1}`;
174 // build a builder for the accessory to the input, depending on status
175 const accessoryFor = (() => {
176 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
177 if (isSending) return buildAccessoryFor(receipts, errors);
178 if (isFailed) return buildAccessoryFor({}, errors);
182 const generateInvites = useCallback(async () => {
183 const _contracts = contracts.getOrElse(null);
184 const _web3 = web3.getOrElse(null);
185 const _wallet = wallet.getOrElse(null);
186 if (!_contracts || !_web3 || !_wallet) {
187 // not using need because we want a custom error
188 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
191 //TODO want to do this on-input, but that gets weird. see #188
194 inputs.map(async input => {
195 const email = input.data;
196 const hasReceived = getHasReceived(email).matchWith({
197 Nothing: () => false, // loading
203 [input.name]: `${email} has already received an invite.`,
208 if (errorCount > 0) {
209 throw new Error(`Some of these already have a point!`);
212 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
213 const chainId = await _web3.eth.net.getId();
214 const planets = await azimuth.delegatedSending.getPlanetsToSend(
220 // account for the race condition where invites got used up while we were
221 // composing our target list
222 if (planets.length < inputs.length) {
223 // resync invites to the cache, since they're out of date
227 `Can currently only send ${planets.length} invites. ` +
228 `Please remove invites until you are within the limit.`
233 // NB(shrugs) - must be processed in serial because main thread, etc
234 for (let i = 0; i < inputs.length; i++) {
235 const input = inputs[i];
237 const { data: email, name } = inputs[i];
239 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
241 // we're always giving planets, so generate a ticket of the correct size
244 const inviteTx = azimuth.delegatedSending.sendPoint(
250 const signedTx = await signTransaction({
255 // TODO: ^ make a useTransactionSigner to encapsulate this logic
257 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
258 gasLimit: GAS_LIMIT.toString(),
262 const rawTx = hexify(signedTx.serialize());
264 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
266 console.error(error);
268 addError({ [input.name]: `Wallet Error: ${input.email}` });
272 if (errorCount > 0) {
274 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
277 )} while generating wallets.`
296 const sendInvites = useCallback(async () => {
297 const _web3 = web3.getOrElse(null);
298 const _wallet = wallet.getOrElse(null);
299 if (!_web3 || !_wallet) {
300 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
303 setStatus(STATUS.FUNDING);
304 const tankWasUsed = await tank.ensureFundsFor(
308 INVITE_COST * inputs.length,
309 inputs.map(input => invites[input.name].rawTx),
310 (address, minBalance, balance) =>
311 setNeedFunds({ address, minBalance, balance }),
312 () => setNeedFunds(false)
315 setStatus(STATUS.SENDING);
319 const txAndMailings = inputs.map(async input => {
320 const invite = invites[input.name];
322 const txHash = await sendSignedTransaction(
328 // TODO: waitForTransactionConfirm never rejects
329 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
330 if (!didConfirm) throw new Error();
332 console.error(error);
335 [input.name]: `Transaction Failure for ${invite.email}`,
341 const success = await sendMail(
346 if (!success) throw new Error('Failed to send mail');
348 console.error(error);
350 //TODO make sure this actually gets displayed
352 [input.name]: `Mailing Failure for ${invite.email}, please send them this code manually: ${invite.ticket}`,
356 addReceipt({ [input.name]: true });
359 await Promise.all(txAndMailings);
360 // if there are any receipt errors, throw a general error
361 if (errorCount > 0) {
363 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
366 )} while sending transactions.`
381 const onClick = useCallback(async () => {
382 setGeneralError(null);
385 setStatus(STATUS.GENERATING);
386 await generateInvites();
387 setStatus(STATUS.CAN_SEND);
388 } else if (canSend) {
389 setStatus(STATUS.SENDING);
391 setStatus(STATUS.SUCCESS);
394 console.error(error);
395 setGeneralError(error);
396 setStatus(STATUS.FAILURE);
398 }, [canGenerate, canSend, generateInvites, sendInvites]);
400 // when inputs update, check to see if any of them are duplicates
402 // compute the list of valid emails
403 const emails = inputs.map(i => i.data).filter(d => !!d);
404 if (uniq(emails).length !== emails.length) {
405 setGeneralError(new Error(`Duplicate email.`));
407 setGeneralError(null);
411 // when we transition to done, sync invites because we just sent some
412 // and therefore know that state has changed
417 }, [isDone, syncInvites, point]);
420 for (const input of inputs) {
422 syncHasReceivedForEmail(input.data);
425 }, [inputs, syncHasReceivedForEmail]);
429 <Grid.Item as={Grid} full>
430 <Grid.Item as={Flex} cols={[1, 11]} align="center">
431 <MiniBackButton onClick={() => pop()} />
433 <Grid.Item cols={[11, 13]} justifySelf="end">
434 {/* use hidden class instead of removing component from dom */}
435 {/* in order to avoid janky reflow */}
437 onClick={() => appendInput()}
438 disabled={!canAddInvite}
439 className={cn({ hidden: isDone })}
448 <Grid.Item as={Text} className="f5" full>
449 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
450 {pluralize(inputs.length, 'has', 'have')} been successfully sent
452 {inputs.map(input => (
453 <Grid.Item as={HelpText} key={input.name} full>
454 {invites[input.name].email}
463 {inputs.map((input, i) => {
464 const isFirst = i === 0;
470 onMouseOver={() => setHovered({ [input.name]: true })}
471 onMouseLeave={() => setHovered({ [input.name]: false })}
477 accessory={accessoryFor(input.name)}
480 (input.focused || hovered[input.name]) &&
487 onClick={() => removeInputAt(i)}
501 disabled={!canGenerate && !canSend}
502 accessory={`${visualProgress}/${inputs.length}`}
506 {buttonText(status, inputs.length)}
512 Your ownership address {needFunds.address} needs at least{' '}
513 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
514 {fromWei(needFunds.balance)} ETH. Waiting until the account has
522 <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