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 * as wg from 'lib/walletgen';
11// for transaction generation and signing
14 sendSignedTransaction,
15 waitForTransactionConfirm,
20import * as tank from 'lib/tank';
21import { useLocalRouter } from 'lib/LocalRouter';
23import MiniBackButton from 'components/MiniBackButton';
24import useInvites from 'lib/useInvites';
25import { usePointCursor } from 'store/pointCursor';
26import LoadableButton from 'components/LoadableButton';
27import useArray from 'lib/useArray';
28import useForm from 'indigo-react/lib/useForm';
29import { buildEmailInputConfig } from 'components/Inputs';
30import { MIN_PLANET } from 'lib/constants';
31import Highlighted from 'components/Highlighted';
32import { useNetwork } from 'store/network';
33import { usePointCache } from 'store/pointCache';
34import { useWallet } from 'store/wallet';
35import useSetState from 'lib/useSetState';
36import pluralize from 'lib/pluralize';
37import useMailer from 'lib/useMailer';
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: how to handle dependency loop between inputConfigs and hasReceived?
93// TODO: test with tank, successful txs
94// TODO: put accessory inside of input
95export default function InviteEmail() {
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 config.error = errors[config.name];
142 [inputConfigs, errors, canInput]
144 const { inputs, pass } = useForm(dynamicConfigs);
145 const emails = useMemo(() => inputs.map(i => i.data).filter(d => !!d), [
148 const { getHasRecieved, sendMail } = useMailer(emails);
150 const canAddInvite = canInput && inputs.length < maxInvitesToSend;
151 const allPass = pass && !generalError;
152 const canGenerate = allPass && status === STATUS.INPUT;
154 const progress = isGenerating
155 ? Object.keys(invites).length
157 ? Object.keys(receipts).length
159 const visualProgress = progress === null ? '-' : `${progress + 1}`;
161 const accessoryFor = (() => {
162 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
163 if (isSending) return buildAccessoryFor(receipts, errors);
164 if (isFailed) return buildAccessoryFor({}, errors);
168 const generateInvites = useCallback(async () => {
169 const _contracts = contracts.getOrElse(null);
170 const _web3 = web3.getOrElse(null);
171 const _wallet = wallet.getOrElse(null);
172 if (!_contracts || !_web3 || !_wallet) {
173 // not using need because we want a custom error
174 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
177 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
178 const chainId = await _web3.eth.net.getId();
179 const planets = await azimuth.delegatedSending.getPlanetsToSend(
185 // account for the race condition where invites got used up while we were
186 // composing our target list
187 if (planets.length < inputs.length) {
188 // resync invites to the cache, since they're out of date
192 `Can currently only send ${planets.length} invites. ` +
193 `Please remove invites until you are within the limit.`
199 // NB(shrugs) - must be processed in serial because main thread, etc
200 for (let i = 0; i < inputs.length; i++) {
201 const input = inputs[i];
203 const { data: email, name } = inputs[i];
205 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
207 // we're always giving planets, so generate a ticket of the correct size
210 const inviteTx = azimuth.delegatedSending.sendPoint(
216 const signedTx = await signTransaction({
221 // TODO: ^ make a useTransactionSigner to encapsulate this logic
222 txn: Maybe.Just(inviteTx),
223 gasPrice: GAS_PRICE_GWEI.toString(),
224 gasLimit: GAS_LIMIT.toString(),
229 const rawTx = hexify(signedTx.serialize());
231 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
233 console.error(error);
235 addError({ [input.name]: `Wallet Error: ${input.email}` });
239 if (errorCount > 0) {
241 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
244 )} while generating wallets.`
262 const sendInvites = useCallback(async () => {
263 const _web3 = web3.getOrElse(null);
264 const _wallet = wallet.getOrElse(null);
265 if (!_web3 || !_wallet) {
266 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
269 setStatus(STATUS.FUNDING);
270 const tankWasUsed = await tank.ensureFundsFor(
274 INVITE_COST * inputs.length,
275 inputs.map(input => invites[input.name].rawTx),
276 (address, minBalance, balance) =>
277 setNeedFunds({ address, minBalance, balance }),
278 () => setNeedFunds(false)
281 setStatus(STATUS.SENDING);
285 const txAndMailings = inputs.map(async input => {
286 const invite = invites[input.name];
288 const txHash = await sendSignedTransaction(
290 Maybe.Just(invite.signedTx),
295 // TODO: waitForTransactionConfirm never rejects
296 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
297 if (!didConfirm) throw new Error();
299 console.error(error);
302 [input.name]: `Transaction Failure for ${invite.email}`,
308 console.log(`${invite.email} - ${invite.ticket}`);
312 const mailSuccess = await sendMail(
317 if (!mailSuccess) throw new Error();
319 console.error(error);
322 [input.name]: `Mailing Failure for ${invite.email}`,
326 addReceipt({ [input.name]: true });
329 await Promise.all(txAndMailings);
330 // if there are any receipt errors, throw a general error
331 if (errorCount > 0) {
333 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
336 )} while sending transactions.`
350 const onClickGenerate = useCallback(async () => {
351 setGeneralError(null);
352 setStatus(STATUS.GENERATING);
354 await generateInvites();
355 setStatus(STATUS.CAN_SEND);
357 console.error(error);
358 setGeneralError(error);
359 setStatus(STATUS.FAILURE);
361 }, [setStatus, setGeneralError, generateInvites]);
363 const onClickSend = useCallback(async () => {
364 setGeneralError(null);
365 setStatus(STATUS.SENDING);
368 setStatus(STATUS.SUCCESS);
370 console.error(error);
371 setGeneralError(error);
372 setStatus(STATUS.FAILURE);
374 }, [setStatus, sendInvites, setGeneralError]);
376 const onClick = useCallback(() => {
379 } else if (canSend) {
382 }, [canGenerate, canSend, onClickGenerate, onClickSend]);
385 if (uniq(emails).length !== emails.length) {
386 setGeneralError(new Error(`Duplicate email.`));
388 setGeneralError(null);
394 <Grid.Item as={Grid} full>
395 <Grid.Item as={Flex} cols={[1, 11]} align="center">
396 <MiniBackButton onClick={() => pop()} />
398 <Grid.Item cols={[11, 13]} justifySelf="end">
399 {/* use hidden class instead of removing component from dom */}
400 {/* in order to avoid janky reflow */}
402 onClick={() => appendInput()}
403 disabled={!canAddInvite}
404 className={cn({ hidden: isDone })}
413 <Grid.Item as={Text} full>
414 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
415 {pluralize(inputs.length, 'has', 'have')} been successfully sent
417 {inputs.map(input => (
418 <Grid.Item as={HelpText} key={input.name} full>
419 {invites[input.name].email}
428 {inputs.map((input, i) => {
429 const isFirst = i === 0;
435 onMouseOver={() => setHovered({ [input.name]: true })}
436 onMouseLeave={() => setHovered({ [input.name]: false })}
442 accessory={accessoryFor(input.name)}
445 (input.focused || hovered[input.name]) &&
452 onClick={() => removeInputAt(i)}
466 disabled={!canGenerate && !canSend}
467 accessory={`${visualProgress}/${inputs.length}`}
471 {buttonText(status, inputs.length)}
477 Your ownership address {needFunds.address} needs at least{' '}
478 {fromWei(needFunds.minBalance)}ETH and currently has{' '}
479 {fromWei(needFunds.balance)}.
486 <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