1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import Maybe from 'folktale/maybe';
4import * as azimuth from 'azimuth-js';
15import { uniq } from 'lodash';
17import * as need from 'lib/need';
18import * as wg from 'lib/walletgen';
20// for transaction generation and signing
23 sendSignedTransaction,
24 waitForTransactionConfirm,
29import * as tank from 'lib/tank';
30import { useLocalRouter } from 'lib/LocalRouter';
32import MiniBackButton from 'components/MiniBackButton';
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';
47const GAS_PRICE_GWEI = 20; // we pay the premium for faster ux
48const GAS_LIMIT = 400000;
49const INVITE_COST = toWei((GAS_PRICE_GWEI * GAS_LIMIT).toString(), 'gwei');
51const kHasReceivedText = '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.pointCursor(pointCursor);
105 const { getHasRecieved, 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' })],
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, clearErrors] = 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 = getHasRecieved(config.name).matchWith({
147 Nothing: () => null, // loading
148 Just: p => p.value && kHasReceivedText,
150 config.error = hasReceivedError || errors[config.name];
153 [inputConfigs, errors, canInput, getHasRecieved]
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 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
192 const chainId = await _web3.eth.net.getId();
193 const planets = await azimuth.delegatedSending.getPlanetsToSend(
199 // account for the race condition where invites got used up while we were
200 // composing our target list
201 if (planets.length < inputs.length) {
202 // resync invites to the cache, since they're out of date
206 `Can currently only send ${planets.length} invites. ` +
207 `Please remove invites until you are within the limit.`
213 // NB(shrugs) - must be processed in serial because main thread, etc
214 for (let i = 0; i < inputs.length; i++) {
215 const input = inputs[i];
217 const { data: email, name } = inputs[i];
219 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
221 // we're always giving planets, so generate a ticket of the correct size
224 const inviteTx = azimuth.delegatedSending.sendPoint(
230 const signedTx = await signTransaction({
235 // TODO: ^ make a useTransactionSigner to encapsulate this logic
236 txn: Maybe.Just(inviteTx),
237 gasPrice: GAS_PRICE_GWEI.toString(),
238 gasLimit: GAS_LIMIT.toString(),
243 const rawTx = hexify(signedTx.serialize());
245 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
247 console.error(error);
249 addError({ [input.name]: `Wallet Error: ${input.email}` });
253 if (errorCount > 0) {
255 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
258 )} while generating wallets.`
276 const sendInvites = useCallback(async () => {
277 const _web3 = web3.getOrElse(null);
278 const _wallet = wallet.getOrElse(null);
279 if (!_web3 || !_wallet) {
280 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
283 setStatus(STATUS.FUNDING);
284 const tankWasUsed = await tank.ensureFundsFor(
288 INVITE_COST * inputs.length,
289 inputs.map(input => invites[input.name].rawTx),
290 (address, minBalance, balance) =>
291 setNeedFunds({ address, minBalance, balance }),
292 () => setNeedFunds(false)
295 setStatus(STATUS.SENDING);
299 const txAndMailings = inputs.map(async input => {
300 const invite = invites[input.name];
302 const txHash = await sendSignedTransaction(
304 Maybe.Just(invite.signedTx),
309 // TODO: waitForTransactionConfirm never rejects
310 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
311 if (!didConfirm) throw new Error();
313 console.error(error);
316 [input.name]: `Transaction Failure for ${invite.email}`,
322 await sendMail(invite.email, invite.ticket, invite.rawTx);
324 console.error(error);
327 [input.name]: `Mailing Failure for ${invite.email}`,
331 addReceipt({ [input.name]: true });
334 await Promise.all(txAndMailings);
335 // if there are any receipt errors, throw a general error
336 if (errorCount > 0) {
338 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
341 )} while sending transactions.`
356 const onClick = useCallback(async () => {
357 setGeneralError(null);
360 setStatus(STATUS.GENERATING);
361 await generateInvites();
362 setStatus(STATUS.CAN_SEND);
363 } else if (canSend) {
364 setStatus(STATUS.SENDING);
366 setStatus(STATUS.SUCCESS);
369 console.error(error);
370 setGeneralError(error);
371 setStatus(STATUS.FAILURE);
373 }, [canGenerate, canSend, generateInvites, sendInvites]);
375 // when inputs update, check to see if any of them are duplicates
377 // compute the list of valid emails
378 const emails = inputs.map(i => i.data).filter(d => !!d);
379 if (uniq(emails).length !== emails.length) {
380 setGeneralError(new Error(`Duplicate email.`));
382 setGeneralError(null);
386 // when we transition to done, sync invites because we just sent some
387 // and therefore know that state has changed
392 }, [isDone, syncInvites, point]);
396 <Grid.Item as={Grid} full>
397 <Grid.Item as={Flex} cols={[1, 11]} align="center">
398 <MiniBackButton onClick={() => pop()} />
400 <Grid.Item cols={[11, 13]} justifySelf="end">
401 {/* use hidden class instead of removing component from dom */}
402 {/* in order to avoid janky reflow */}
404 onClick={() => appendInput()}
405 disabled={!canAddInvite}
406 className={cn({ hidden: isDone })}
415 <Grid.Item as={Text} full>
416 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
417 {pluralize(inputs.length, 'has', 'have')} been successfully sent
419 {inputs.map(input => (
420 <Grid.Item as={HelpText} key={input.name} full>
421 {invites[input.name].email}
430 {inputs.map((input, i) => {
431 const isFirst = i === 0;
437 onMouseOver={() => setHovered({ [input.name]: true })}
438 onMouseLeave={() => setHovered({ [input.name]: false })}
444 onValue={email => syncHasReceivedForEmail(email)}
445 // NB(shrugs): ^ this feels like a hack?
446 accessory={accessoryFor(input.name)}
449 (input.focused || hovered[input.name]) &&
456 onClick={() => removeInputAt(i)}
470 disabled={!canGenerate && !canSend}
471 accessory={`${visualProgress}/${inputs.length}`}
475 {buttonText(status, inputs.length)}
481 Your ownership address {needFunds.address} needs at least{' '}
482 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
483 {fromWei(needFunds.balance)} ETH. Waiting until the account has
491 <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