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 } 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_PRICE_GWEI = 20; // we pay the premium for faster ux
47const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
48const INVITE_COST = toWei((GAS_PRICE_GWEI * GAS_LIMIT).toString(), 'gwei');
49const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
53 GENERATING: 'GENERATING',
61const buttonText = (status, count) => {
64 return `Generate ${pluralize(count, 'Invite')}`;
65 case STATUS.GENERATING:
66 return `Generating ${pluralize(count, 'Invite')}...`;
68 return `Send ${pluralize(count, 'Invite')}`;
70 return `Waiting on Funds...`;
72 return `Sending ${pluralize(count, 'Invite')}...`;
79// world's simplest uid
81const buildInputConfig = (extra = {}) =>
82 buildEmailInputConfig({
83 name: `email-${id++}`,
84 placeholder: 'Email Address',
88const buildAccessoryFor = (dones, errors) => name => {
89 if (dones[name]) return <AccessoryIcon.Success />;
90 if (errors[name]) return <AccessoryIcon.Failure />;
91 return <AccessoryIcon.Pending />;
94// TODO: test with tank, successful txs
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, getInvites } = usePointCache();
101 const { pointCursor } = usePointCursor();
102 const point = need.point(pointCursor);
103 const { getHasReceived, syncHasReceivedForEmail, sendMail } = useMailer();
105 const { availableInvites } = getInvites(point);
106 const maxInvitesToSend = availableInvites.matchWith({
111 // manage the array of input configs
114 { append: appendInput, removeAt: removeInputAt },
116 [buildInputConfig({ label: 'Email Address', autoFocus: true })],
120 // manage per-input state
121 const [hovered, setHovered] = useSetState();
122 const [invites, addInvite, clearInvites] = useSetState();
123 const [receipts, addReceipt, clearReceipts] = useSetState();
124 const [errors, addError] = useSetState();
126 // manage general state that affects the whole form
127 const [status, setStatus] = useState(STATUS.INPUT);
128 const [needFunds, setNeedFunds] = useState(null);
129 const [generalError, setGeneralError] = useState(null);
131 // derive booleans from status
132 const canInput = status === STATUS.INPUT;
133 const canSend = status === STATUS.CAN_SEND;
134 const isGenerating = status === STATUS.GENERATING;
135 const isSending = status === STATUS.SENDING;
136 const isFailed = status === STATUS.FAILURE;
137 const isDone = status === STATUS.SUCCESS;
139 // add disabled, error info to input configs
140 const dynamicConfigs = useMemo(
142 inputConfigs.map(config => {
143 config.disabled = !canInput;
144 const hasReceivedError = getHasReceived(config.name).matchWith({
145 Nothing: () => null, // loading
146 Just: p => p.value && HAS_RECEIVED_TEXT,
148 config.error = hasReceivedError || errors[config.name];
151 [inputConfigs, errors, canInput, getHasReceived]
154 // construct the state of the set of inputs we're rendering below
155 const { inputs, pass } = useForm(dynamicConfigs);
156 // did all of the inputs pass inspection (and there are no general errors)?
157 const allPass = pass && !generalError;
158 // the form is submittable iff passing and input is allowed
159 const canGenerate = allPass && canInput;
160 // additional inputs can be added iff input is allowed and we have enough
162 const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
164 // progress is [0, .length] of invites or receipts, as we're generating them
165 const progress = isGenerating
166 ? Object.keys(invites).length
168 ? Object.keys(receipts).length
170 const visualProgress = progress === null ? '-' : `${progress + 1}`;
172 // build a builder for the accessory to the input, depending on status
173 const accessoryFor = (() => {
174 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
175 if (isSending) return buildAccessoryFor(receipts, errors);
176 if (isFailed) return buildAccessoryFor({}, errors);
180 const generateInvites = useCallback(async () => {
181 const _contracts = contracts.getOrElse(null);
182 const _web3 = web3.getOrElse(null);
183 const _wallet = wallet.getOrElse(null);
184 if (!_contracts || !_web3 || !_wallet) {
185 // not using need because we want a custom error
186 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
189 //TODO want to do this on-input, but that gets weird. see #188
192 inputs.map(async input => {
193 const email = input.data;
194 const hasReceived = getHasReceived(email).matchWith({
195 Nothing: () => false, // loading
201 [input.name]: `${email} has already received an invite.`,
206 if (errorCount > 0) {
207 throw new Error(`Some of these already have a point!`);
210 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
211 const chainId = await _web3.eth.net.getId();
212 const planets = await azimuth.delegatedSending.getPlanetsToSend(
218 // account for the race condition where invites got used up while we were
219 // composing our target list
220 if (planets.length < inputs.length) {
221 // resync invites to the cache, since they're out of date
225 `Can currently only send ${planets.length} invites. ` +
226 `Please remove invites until you are within the limit.`
231 // NB(shrugs) - must be processed in serial because main thread, etc
232 for (let i = 0; i < inputs.length; i++) {
233 const input = inputs[i];
235 const { data: email, name } = inputs[i];
237 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
239 // we're always giving planets, so generate a ticket of the correct size
242 const inviteTx = azimuth.delegatedSending.sendPoint(
248 const signedTx = await signTransaction({
253 // TODO: ^ make a useTransactionSigner to encapsulate this logic
255 gasPrice: GAS_PRICE_GWEI.toString(),
256 gasLimit: GAS_LIMIT.toString(),
260 const rawTx = hexify(signedTx.serialize());
262 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
264 console.error(error);
266 addError({ [input.name]: `Wallet Error: ${input.email}` });
270 if (errorCount > 0) {
272 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
275 )} while generating wallets.`
294 const sendInvites = useCallback(async () => {
295 const _web3 = web3.getOrElse(null);
296 const _wallet = wallet.getOrElse(null);
297 if (!_web3 || !_wallet) {
298 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
301 setStatus(STATUS.FUNDING);
302 const tankWasUsed = await tank.ensureFundsFor(
306 INVITE_COST * inputs.length,
307 inputs.map(input => invites[input.name].rawTx),
308 (address, minBalance, balance) =>
309 setNeedFunds({ address, minBalance, balance }),
310 () => setNeedFunds(false)
313 setStatus(STATUS.SENDING);
317 const txAndMailings = inputs.map(async input => {
318 const invite = invites[input.name];
320 const txHash = await sendSignedTransaction(
326 // TODO: waitForTransactionConfirm never rejects
327 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
328 if (!didConfirm) throw new Error();
330 console.error(error);
333 [input.name]: `Transaction Failure for ${invite.email}`,
339 const success = await sendMail(
344 if (!success) throw new Error('Failed to send mail');
346 console.error(error);
348 //TODO make sure this actually gets displayed
350 [input.name]: `Mailing Failure for ${invite.email}, please send them this code manually: ${invite.ticket}`,
354 addReceipt({ [input.name]: true });
357 await Promise.all(txAndMailings);
358 // if there are any receipt errors, throw a general error
359 if (errorCount > 0) {
361 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
364 )} while sending transactions.`
379 const onClick = useCallback(async () => {
380 setGeneralError(null);
383 setStatus(STATUS.GENERATING);
384 await generateInvites();
385 setStatus(STATUS.CAN_SEND);
386 } else if (canSend) {
387 setStatus(STATUS.SENDING);
389 setStatus(STATUS.SUCCESS);
392 console.error(error);
393 setGeneralError(error);
394 setStatus(STATUS.FAILURE);
396 }, [canGenerate, canSend, generateInvites, sendInvites]);
398 // when inputs update, check to see if any of them are duplicates
400 // compute the list of valid emails
401 const emails = inputs.map(i => i.data).filter(d => !!d);
402 if (uniq(emails).length !== emails.length) {
403 setGeneralError(new Error(`Duplicate email.`));
405 setGeneralError(null);
409 // when we transition to done, sync invites because we just sent some
410 // and therefore know that state has changed
415 }, [isDone, syncInvites, point]);
418 for (const input of inputs) {
420 syncHasReceivedForEmail(input.data);
423 }, [inputs, syncHasReceivedForEmail]);
427 <Grid.Item as={Grid} full>
428 <Grid.Item as={Flex} cols={[1, 11]} align="center">
429 <MiniBackButton onClick={() => pop()} />
431 <Grid.Item cols={[11, 13]} justifySelf="end">
432 {/* use hidden class instead of removing component from dom */}
433 {/* in order to avoid janky reflow */}
435 onClick={() => appendInput()}
436 disabled={!canAddInvite}
437 className={cn({ hidden: isDone })}
446 <Grid.Item as={Text} className="f5" full>
447 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
448 {pluralize(inputs.length, 'has', 'have')} been successfully sent
450 {inputs.map(input => (
451 <Grid.Item as={HelpText} key={input.name} full>
452 {invites[input.name].email}
461 {inputs.map((input, i) => {
462 const isFirst = i === 0;
468 onMouseOver={() => setHovered({ [input.name]: true })}
469 onMouseLeave={() => setHovered({ [input.name]: false })}
475 accessory={accessoryFor(input.name)}
478 (input.focused || hovered[input.name]) &&
485 onClick={() => removeInputAt(i)}
499 disabled={!canGenerate && !canSend}
500 accessory={`${visualProgress}/${inputs.length}`}
504 {buttonText(status, inputs.length)}
510 Your ownership address {needFunds.address} needs at least{' '}
511 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
512 {fromWei(needFunds.balance)} ETH. Waiting until the account has
520 <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