1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import Maybe from 'folktale/maybe';
4import * as azimuth from 'azimuth-js';
14import { uniq } from 'lodash';
16import * as need from 'lib/need';
17import * as wg from 'lib/walletgen';
19// for transaction generation and signing
22 sendSignedTransaction,
23 waitForTransactionConfirm,
28import * as tank from 'lib/tank';
29import { useLocalRouter } from 'lib/LocalRouter';
31import MiniBackButton from 'components/MiniBackButton';
32import useInvites from 'lib/useInvites';
33import { usePointCursor } from 'store/pointCursor';
34import LoadableButton from 'components/LoadableButton';
35import useArray from 'lib/useArray';
36import useForm from 'indigo-react/lib/useForm';
37import { buildEmailInputConfig } from 'components/Inputs';
38import { MIN_PLANET } from 'lib/constants';
39import Highlighted from 'components/Highlighted';
40import { useNetwork } from 'store/network';
41import { usePointCache } from 'store/pointCache';
42import { useWallet } from 'store/wallet';
43import useSetState from 'lib/useSetState';
44import pluralize from 'lib/pluralize';
45import useMailer from 'lib/useMailer';
46import useRenderCount from 'lib/useRenderCount';
48const GAS_PRICE_GWEI = 20; // we pay the premium for faster ux
49const GAS_LIMIT = 400000;
50const INVITE_COST = toWei((GAS_PRICE_GWEI * GAS_LIMIT).toString(), 'gwei');
54 GENERATING: 'GENERATING',
62const buttonText = (status, count) => {
65 return `Generate ${pluralize(count, 'Invite')}`;
66 case STATUS.GENERATING:
67 return `Generating ${pluralize(count, 'Invite')}...`;
69 return `Send ${pluralize(count, 'Invite')}`;
71 return `Waiting on Funds...`;
73 return `Sending ${pluralize(count, 'Invite')}...`;
80const kPendingAccessory = '⋯';
81const kSuccessAccessory = '✔';
82const kFailureAccessory = '×';
84// world's simplest uid
86const buildInputConfig = (extra = {}) =>
87 buildEmailInputConfig({ name: `email-${id++}`, ...extra });
89const buildAccessoryFor = (dones, errors) => name => (
90 <Flex justify="center" align="center" style={{ height: '100%' }}>
92 if (dones[name]) return kSuccessAccessory;
93 if (errors[name]) return kFailureAccessory;
94 return kPendingAccessory;
99// TODO: test with tank, successful txs
100// TODO: put accessory inside of input
101export default function InviteEmail() {
102 // TODO: resumption after error?
103 const { pop } = useLocalRouter();
104 const { contracts, web3, networkType } = useNetwork();
105 const { wallet, walletType, walletHdPath } = useWallet();
106 const { syncInvites } = usePointCache();
107 const { pointCursor } = usePointCursor();
108 const point = need.pointCursor(pointCursor);
110 const { availableInvites } = useInvites(point);
111 const maxInvitesToSend = availableInvites.matchWith({
118 { append: appendInput, removeAt: removeInputAt },
120 [buildInputConfig({ placeholder: 'Email Address' })],
124 const { getHasRecieved, syncHasReceivedForEmail, sendMail } = useMailer();
125 const [hovered, setHovered] = useSetState();
126 const [invites, addInvite, clearInvites] = useSetState();
127 const [receipts, addReceipt, clearReceipts] = useSetState();
128 const [errors, addError, clearError] = useSetState();
130 const [status, setStatus] = useState(STATUS.INPUT);
131 const [needFunds, setNeedFunds] = useState(null);
132 const [generalError, setGeneralError] = useState(null);
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 isFunding = status === STATUS.FUNDING;
139 const isFailed = status === STATUS.FAILURE;
140 const isDone = status === STATUS.SUCCESS;
142 const dynamicConfigs = useMemo(
144 inputConfigs.map(config => {
145 config.disabled = !canInput;
146 const hasReceivedError = getHasRecieved(config.name).matchWith({
147 Nothing: () => null, // loading
148 Just: p => p.value && 'This email has already received an invite.',
150 config.error = hasReceivedError || errors[config.name];
153 [inputConfigs, errors, canInput, getHasRecieved]
155 const { inputs, pass } = useForm(dynamicConfigs);
156 const emails = useMemo(() => inputs.map(i => i.data).filter(d => !!d), [
160 const canAddInvite = canInput && inputs.length < maxInvitesToSend;
161 const allPass = pass && !generalError;
162 const canGenerate = allPass && status === STATUS.INPUT;
164 const progress = isGenerating
165 ? Object.keys(invites).length
167 ? Object.keys(receipts).length
169 const visualProgress = progress === null ? '-' : `${progress + 1}`;
171 const accessoryFor = (() => {
172 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
173 if (isSending) return buildAccessoryFor(receipts, errors);
174 if (isFailed) return buildAccessoryFor({}, errors);
178 const generateInvites = useCallback(async () => {
179 const _contracts = contracts.getOrElse(null);
180 const _web3 = web3.getOrElse(null);
181 const _wallet = wallet.getOrElse(null);
182 if (!_contracts || !_web3 || !_wallet) {
183 // not using need because we want a custom error
184 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
187 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
188 const chainId = await _web3.eth.net.getId();
189 const planets = await azimuth.delegatedSending.getPlanetsToSend(
195 // account for the race condition where invites got used up while we were
196 // composing our target list
197 if (planets.length < inputs.length) {
198 // resync invites to the cache, since they're out of date
202 `Can currently only send ${planets.length} invites. ` +
203 `Please remove invites until you are within the limit.`
209 // NB(shrugs) - must be processed in serial because main thread, etc
210 for (let i = 0; i < inputs.length; i++) {
211 const input = inputs[i];
213 const { data: email, name } = inputs[i];
215 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
217 // we're always giving planets, so generate a ticket of the correct size
220 const inviteTx = azimuth.delegatedSending.sendPoint(
226 const signedTx = await signTransaction({
231 // TODO: ^ make a useTransactionSigner to encapsulate this logic
232 txn: Maybe.Just(inviteTx),
233 gasPrice: GAS_PRICE_GWEI.toString(),
234 gasLimit: GAS_LIMIT.toString(),
239 const rawTx = hexify(signedTx.serialize());
241 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
243 console.error(error);
245 addError({ [input.name]: `Wallet Error: ${input.email}` });
249 if (errorCount > 0) {
251 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
254 )} while generating wallets.`
272 const sendInvites = useCallback(async () => {
273 const _web3 = web3.getOrElse(null);
274 const _wallet = wallet.getOrElse(null);
275 if (!_web3 || !_wallet) {
276 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
279 setStatus(STATUS.FUNDING);
280 const tankWasUsed = await tank.ensureFundsFor(
284 INVITE_COST * inputs.length,
285 inputs.map(input => invites[input.name].rawTx),
286 (address, minBalance, balance) =>
287 setNeedFunds({ address, minBalance, balance }),
288 () => setNeedFunds(false)
291 setStatus(STATUS.SENDING);
295 const txAndMailings = inputs.map(async input => {
296 const invite = invites[input.name];
298 const txHash = await sendSignedTransaction(
300 Maybe.Just(invite.signedTx),
305 // TODO: waitForTransactionConfirm never rejects
306 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
307 if (!didConfirm) throw new Error();
309 console.error(error);
312 [input.name]: `Transaction Failure for ${invite.email}`,
318 await sendMail(invite.email, invite.ticket, invite.rawTx);
320 console.error(error);
323 [input.name]: `Mailing Failure for ${invite.email}`,
327 addReceipt({ [input.name]: true });
330 await Promise.all(txAndMailings);
331 // if there are any receipt errors, throw a general error
332 if (errorCount > 0) {
334 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
337 )} while sending transactions.`
352 const onClickGenerate = useCallback(async () => {
353 setGeneralError(null);
354 setStatus(STATUS.GENERATING);
356 await generateInvites();
357 setStatus(STATUS.CAN_SEND);
359 console.error(error);
360 setGeneralError(error);
361 setStatus(STATUS.FAILURE);
363 }, [setStatus, setGeneralError, generateInvites]);
365 const onClickSend = useCallback(async () => {
366 setGeneralError(null);
367 setStatus(STATUS.SENDING);
370 setStatus(STATUS.SUCCESS);
372 console.error(error);
373 setGeneralError(error);
374 setStatus(STATUS.FAILURE);
376 }, [setStatus, sendInvites, setGeneralError]);
378 const onClick = useCallback(() => {
381 } else if (canSend) {
384 }, [canGenerate, canSend, onClickGenerate, onClickSend]);
387 if (uniq(emails).length !== emails.length) {
388 setGeneralError(new Error(`Duplicate email.`));
390 setGeneralError(null);
394 // when we transition to done, sync invites because we just sent some
399 }, [isDone, syncInvites, point]);
403 <Grid.Item as={Grid} full>
404 <Grid.Item as={Flex} cols={[1, 11]} align="center">
405 <MiniBackButton onClick={() => pop()} />
407 <Grid.Item cols={[11, 13]} justifySelf="end">
408 {/* use hidden class instead of removing component from dom */}
409 {/* in order to avoid janky reflow */}
411 onClick={() => appendInput()}
412 disabled={!canAddInvite}
413 className={cn({ hidden: isDone })}
422 <Grid.Item as={Text} full>
423 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
424 {pluralize(inputs.length, 'has', 'have')} been successfully sent
426 {inputs.map(input => (
427 <Grid.Item as={HelpText} key={input.name} full>
428 {invites[input.name].email}
437 {inputs.map((input, i) => {
438 const isFirst = i === 0;
444 onMouseOver={() => setHovered({ [input.name]: true })}
445 onMouseLeave={() => setHovered({ [input.name]: false })}
451 onValue={email => syncHasReceivedForEmail(email)}
452 // NB(shrugs): ^ this feels like a hack?
453 accessory={accessoryFor(input.name)}
456 (input.focused || hovered[input.name]) &&
463 onClick={() => removeInputAt(i)}
477 disabled={!canGenerate && !canSend}
478 accessory={`${visualProgress}/${inputs.length}`}
482 {buttonText(status, inputs.length)}
488 Your ownership address {needFunds.address} needs at least{' '}
489 {fromWei(needFunds.minBalance)}ETH and currently has{' '}
490 {fromWei(needFunds.balance)}.
497 <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