1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import Maybe from 'folktale/maybe';
4import * as azimuth from 'azimuth-js';
5import { Grid, Flex, Input, IconButton, HelpText, Text } from 'indigo-react';
6import { uniq } from 'lodash';
8import * as need from 'lib/need';
9import { hasReceived, sendMail } from 'lib/inviteMail';
10import * as wg from 'lib/walletgen';
12// for transaction generation and signing
15 sendSignedTransaction,
16 waitForTransactionConfirm,
21import * as tank from 'lib/tank';
22import { useLocalRouter } from 'lib/LocalRouter';
24import MiniBackButton from 'components/MiniBackButton';
25import useInvites from 'lib/useInvites';
26import { usePointCursor } from 'store/pointCursor';
27import LoadableButton from 'components/LoadableButton';
28import useArray from 'lib/useArray';
29import useForm from 'indigo-react/lib/useForm';
30import { buildEmailInputConfig } from 'components/Inputs';
31import { MIN_PLANET } from 'lib/constants';
32import Highlighted from 'components/Highlighted';
33import { useNetwork } from 'store/network';
34import { usePointCache } from 'store/pointCache';
35import { useWallet } from 'store/wallet';
36import useSetState from 'lib/useSetState';
37import pluralize from 'lib/pluralize';
39const kStubMailer = process.env.REACT_APP_STUB_MAILER === 'true';
41const GAS_PRICE_GWEI = 20; // we pay the premium for faster ux
42const GAS_LIMIT = 350000;
43const INVITE_COST = toWei((GAS_PRICE_GWEI * GAS_LIMIT).toString(), 'gwei');
47 GENERATING: 'GENERATING',
55const buttonText = (status, count) => {
58 return `Generate ${pluralize(count, 'Invite')}`;
59 case STATUS.GENERATING:
60 return `Generating ${pluralize(count, 'Invite')}...`;
62 return `Send ${pluralize(count, 'Invite')}`;
64 return `Waiting on Funds...`;
66 return `Sending ${pluralize(count, 'Invite')}...`;
73const kPendingAccessory = '⋯';
74const kSuccessAccessory = '✔';
75const kFailureAccessory = '×';
77// world's simplest uid
79const buildInputConfig = (extra = {}) =>
80 buildEmailInputConfig({ name: `email-${id++}`, ...extra });
82const buildAccessoryFor = (dones, errors) => name => (
83 <Flex justify="center" align="center" style={{ height: '100%' }}>
85 if (dones[name]) return kSuccessAccessory;
86 if (errors[name]) return kFailureAccessory;
87 return kPendingAccessory;
92// TODO: refactor transactions + mailer into hooks
93// TODO: put accessory inside of input
94// TODO: implement hasReceived cache with useHasReceived
95export default function NewInviteEmail() {
96 // TODO: resumption after error?
97 const { pop } = useLocalRouter();
98 const { contracts, web3, networkType } = useNetwork();
99 const { wallet, walletType, walletHdPath } = useWallet();
100 const { syncInvites } = usePointCache();
101 const { pointCursor } = usePointCursor();
102 const point = need.pointCursor(pointCursor);
104 const { availableInvites } = useInvites(point);
105 const maxInvitesToSend = availableInvites.matchWith({
112 { append: appendInput, removeAt: removeInputAt },
114 [buildInputConfig({ placeholder: 'Email Addresss' })],
118 const [hovered, setHovered] = useSetState({});
119 const [invites, addInvite, clearInvites] = useSetState({});
120 const [receipts, addReceipt, clearReceipts] = useSetState({});
121 const [errors, addError, clearError] = useSetState({});
123 const [status, setStatus] = useState(STATUS.INPUT);
124 const [needFunds, setNeedFunds] = useState(null);
125 const [generalError, setGeneralError] = useState(null);
127 const canInput = status === STATUS.INPUT;
128 const canSend = status === STATUS.CAN_SEND;
129 const isGenerating = status === STATUS.GENERATING;
130 const isSending = status === STATUS.SENDING;
131 const isFunding = status === STATUS.FUNDING;
132 const isFailed = status === STATUS.FAILURE;
133 const isDone = status === STATUS.SUCCESS;
135 const dynamicConfigs = useMemo(
137 inputConfigs.map(config => {
138 config.disabled = !canInput;
139 console.log(config.name, errors[config.name]);
140 config.error = errors[config.name];
143 [inputConfigs, errors, canInput]
145 const { inputs, pass } = useForm(dynamicConfigs);
147 const canAddInvite = canInput && inputs.length < maxInvitesToSend;
148 const allPass = pass && !generalError;
149 const canGenerate = allPass && status === STATUS.INPUT;
151 const progress = isGenerating
152 ? Object.keys(invites).length
154 ? Object.keys(receipts).length
156 const visualProgress = progress === null ? '-' : `${progress + 1}`;
158 const accessoryFor = (() => {
159 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
160 if (isSending) return buildAccessoryFor(receipts, errors);
161 if (isFailed) return buildAccessoryFor({}, errors);
165 const generateInvites = useCallback(async () => {
166 const _contracts = contracts.getOrElse(null);
167 const _web3 = web3.getOrElse(null);
168 const _wallet = wallet.getOrElse(null);
169 if (!_contracts || !_web3 || !_wallet) {
170 // not using need because we want a custom error
171 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
174 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
175 const chainId = await _web3.eth.net.getId();
176 const planets = await azimuth.delegatedSending.getPlanetsToSend(
182 // account for the race condition where invites got used up while we were
183 // composing our target list
184 if (planets.length < inputs.length) {
185 // resync invites to the cache, since they're out of date
189 `Can currently only send ${planets.length} invites. ` +
190 `Please remove invites until you are within the limit.`
196 // NB(shrugs) - must be processed in serial because main thread, etc
197 for (let i = 0; i < inputs.length; i++) {
198 const input = inputs[i];
200 const { data: email, name } = inputs[i];
202 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
204 // we're always giving planets, so generate a ticket of the correct size
207 const inviteTx = azimuth.delegatedSending.sendPoint(
213 const signedTx = await signTransaction({
218 // TODO: ^ make a useTransactionSigner to encapsulate this logic
219 txn: Maybe.Just(inviteTx),
220 gasPrice: GAS_PRICE_GWEI.toString(),
221 gasLimit: GAS_LIMIT.toString(),
226 const rawTx = hexify(signedTx.serialize());
228 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
230 console.error(error);
232 addError({ [input.name]: `Wallet Error: ${input.email}` });
236 if (errorCount > 0) {
238 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
241 )} while generating wallets.`
259 const sendInvites = useCallback(async () => {
260 const _web3 = web3.getOrElse(null);
261 const _wallet = wallet.getOrElse(null);
262 if (!_web3 || !_wallet) {
263 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
266 setStatus(STATUS.FUNDING);
267 const tankWasUsed = await tank.ensureFundsFor(
271 INVITE_COST * inputs.length,
272 inputs.map(input => invites[input.name].rawTx),
273 (address, minBalance, balance) =>
274 setNeedFunds({ address, minBalance, balance }),
275 () => setNeedFunds(false)
278 setStatus(STATUS.SENDING);
282 const txAndMailings = inputs.map(async input => {
283 const invite = invites[input.name];
285 const txHash = await sendSignedTransaction(
287 Maybe.Just(invite.signedTx),
292 // TODO: waitForTransactionConfirm never rejects
293 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
294 if (!didConfirm) throw new Error();
296 console.error(error);
299 [input.name]: `Transaction Failure for ${invite.email}`,
305 console.log(`${invite.email} - ${invite.ticket}`);
309 const mailSuccess = await sendMail(
314 if (!mailSuccess) throw new Error();
316 console.error(error);
319 [input.name]: `Mailing Failure for ${invite.email}`,
323 addReceipt({ [input.name]: true });
326 await Promise.all(txAndMailings);
327 // if there are any receipt errors, throw a general error
328 if (errorCount > 0) {
330 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
333 )} while sending transactions.`
347 const onClickGenerate = useCallback(async () => {
348 setGeneralError(null);
349 setStatus(STATUS.GENERATING);
351 await generateInvites();
352 setStatus(STATUS.CAN_SEND);
354 console.error(error);
355 setGeneralError(error);
356 setStatus(STATUS.FAILURE);
358 }, [setStatus, setGeneralError, generateInvites]);
360 const onClickSend = useCallback(async () => {
361 setGeneralError(null);
362 setStatus(STATUS.SENDING);
365 setStatus(STATUS.SUCCESS);
367 console.error(error);
368 setGeneralError(error);
369 setStatus(STATUS.FAILURE);
371 }, [setStatus, sendInvites, setGeneralError]);
373 const onClick = useCallback(() => {
376 } else if (canSend) {
379 }, [canGenerate, canSend, onClickGenerate, onClickSend]);
382 const emails = inputs.map(i => i.data).filter(d => !!d);
383 if (uniq(emails).length !== emails.length) {
384 setGeneralError(new Error(`Duplicate email.`));
386 setGeneralError(null);
392 <Grid.Item as={Grid} full>
393 <Grid.Item as={Flex} cols={[1, 11]} align="center">
394 <MiniBackButton onClick={() => pop()} />
396 <Grid.Item cols={[11, 13]} justifySelf="end">
397 {/* use hidden class instead of removing component from dom */}
398 {/* in order to avoid janky reflow */}
400 onClick={() => appendInput()}
401 disabled={!canAddInvite}
402 className={cn({ hidden: isDone })}
411 <Grid.Item as={Text} full>
412 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
413 {pluralize(inputs.length, 'has', 'have')} been successfully sent
415 {inputs.map(input => (
416 <Grid.Item as={HelpText} key={input.name} full>
417 {invites[input.name].email}
426 {inputs.map((input, i) => {
427 const isFirst = i === 0;
433 onMouseOver={() => setHovered({ [input.name]: true })}
434 onMouseLeave={() => setHovered({ [input.name]: false })}
440 accessory={accessoryFor(input.name)}
443 (input.focused || hovered[input.name]) &&
450 onClick={() => removeInputAt(i)}
464 disabled={!canGenerate && !canSend}
465 accessory={`${visualProgress}/${inputs.length}`}
469 {buttonText(status, inputs.length)}
475 Your ownership address {needFunds.address} needs at least{' '}
476 {fromWei(needFunds.minBalance)}ETH and currently has{' '}
477 {fromWei(needFunds.balance)}.
484 <Highlighted>{generalError.message.toString()}</Highlighted>
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