1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import * as ob from 'urbit-ob';
4import * as azimuth from 'azimuth-js';
16import { uniq } from 'lodash';
17import { fromWei, toWei } from 'web3-utils';
19import { usePointCursor } from 'store/pointCursor';
20import { useNetwork } from 'store/network';
21import { usePointCache } from 'store/pointCache';
22import { useWallet } from 'store/wallet';
24// for transaction generation and signing
27 sendSignedTransaction,
28 waitForTransactionConfirm,
31import * as tank from 'lib/tank';
32import { useSuggestedGasPrice } from 'lib/useSuggestedGasPrice';
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 LoadableButton from 'components/LoadableButton';
43import Highlighted from 'components/Highlighted';
45const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
46const HAS_RECEIVED_TEXT = 'This email has already received an invite.';
50 GENERATING: 'GENERATING',
58const buttonText = (status, count) => {
61 return `Generate ${pluralize(count, 'Invite')}`;
62 case STATUS.GENERATING:
63 return `Generating ${pluralize(count, 'Invite')}...`;
65 return `Send ${pluralize(count, 'Invite')}`;
67 return `Waiting on Funds...`;
69 return `Sending ${pluralize(count, 'Invite')}...`;
76// world's simplest uid
78const buildInputConfig = (extra = {}) =>
79 buildEmailInputConfig({
80 name: `email-${id++}`,
81 placeholder: 'Email Address',
85const buildAccessoryFor = (dones, errors) => name => {
86 if (dones[name]) return <AccessoryIcon.Success />;
87 if (errors[name]) return <AccessoryIcon.Failure />;
88 return <AccessoryIcon.Pending />;
91// TODO: test with tank, successful txs
92export default function InviteEmail() {
93 // TODO: resumption after error?
94 const { contracts, web3, networkType } = useNetwork();
95 const { wallet, walletType, walletHdPath } = useWallet();
96 const { syncInvites, getInvites } = usePointCache();
97 const { pointCursor } = usePointCursor();
98 const point = need.point(pointCursor);
99 const { getHasReceived, syncHasReceivedForEmail, sendMail } = useMailer();
100 const { gasPrice } = useSuggestedGasPrice(networkType);
102 const { availableInvites } = getInvites(point);
103 const maxInvitesToSend = availableInvites.matchWith({
108 // manage the array of input configs
111 { append: appendInput, removeAt: removeInputAt },
113 [buildInputConfig({ label: 'Email Address', autoFocus: true })],
117 // manage per-input state
118 const [hovered, setHovered] = useSetState();
119 const [invites, addInvite, clearInvites] = useSetState();
120 const [receipts, addReceipt, clearReceipts] = useSetState();
121 const [errors, addError] = useSetState();
123 // manage general state that affects the whole form
124 const [status, setStatus] = useState(STATUS.INPUT);
125 const [needFunds, setNeedFunds] = useState(null);
126 const [generalError, setGeneralError] = useState(null);
128 // derive booleans from status
129 const canInput = status === STATUS.INPUT;
130 const canSend = status === STATUS.CAN_SEND;
131 const isGenerating = status === STATUS.GENERATING;
132 const isSending = status === STATUS.SENDING;
133 const isFailed = status === STATUS.FAILURE;
134 const isDone = status === STATUS.SUCCESS;
136 // add disabled, error info to input configs
137 const dynamicConfigs = useMemo(
139 inputConfigs.map(config => {
140 config.disabled = !canInput;
141 const hasReceivedError = getHasReceived(config.name).matchWith({
142 Nothing: () => null, // loading
143 Just: p => p.value && HAS_RECEIVED_TEXT,
145 config.error = hasReceivedError || errors[config.name];
148 [inputConfigs, errors, canInput, getHasReceived]
151 // construct the state of the set of inputs we're rendering below
152 const { inputs, pass } = useForm(dynamicConfigs);
153 // did all of the inputs pass inspection (and there are no general errors)?
154 const allPass = pass && !generalError;
155 // the form is submittable iff passing and input is allowed
156 const canGenerate = allPass && canInput;
157 // additional inputs can be added iff input is allowed and we have enough
159 const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
161 // progress is [0, .length] of invites or receipts, as we're generating them
162 const progress = isGenerating
163 ? Object.keys(invites).length
165 ? Object.keys(receipts).length
167 const visualProgress = progress === null ? '-' : `${progress + 1}`;
169 // build a builder for the accessory to the input, depending on status
170 const accessoryFor = (() => {
171 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
172 if (isSending) return buildAccessoryFor(receipts, errors);
173 if (isFailed) return buildAccessoryFor({}, errors);
177 const generateInvites = useCallback(async () => {
178 const _contracts = contracts.getOrElse(null);
179 const _web3 = web3.getOrElse(null);
180 const _wallet = wallet.getOrElse(null);
181 if (!_contracts || !_web3 || !_wallet) {
182 // not using need because we want a custom error
183 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
186 //TODO want to do this on-input, but that gets weird. see #188
188 let alreadyReceived = [];
190 inputs.map(async input => {
191 const email = input.data;
192 getHasReceived(email).matchWith({
197 if (p.value) alreadyReceived.push(email);
203 throw new Error('No word yet from email service...');
205 if (alreadyReceived.length > 0) {
207 'The following recipients already own a point: ' +
208 alreadyReceived.join(', ')
212 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
213 const chainId = await _web3.eth.net.getId();
214 const planets = await azimuth.delegatedSending.getPlanetsToSend(
220 // account for the race condition where invites got used up while we were
221 // composing our target list
222 if (planets.length < inputs.length) {
223 // resync invites to the cache, since they're out of date
227 `Can currently only send ${planets.length} invites. ` +
228 `Please remove invites until you are within the limit.`
233 // NB(shrugs) - must be processed in serial because main thread, etc
235 for (let i = 0; i < inputs.length; i++) {
236 const input = inputs[i];
238 const { data: email, name } = inputs[i];
240 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
242 // we're always giving planets, so generate a ticket of the correct size
245 const inviteTx = azimuth.delegatedSending.sendPoint(
251 const signedTx = await signTransaction({
256 // TODO: ^ make a useTransactionSigner to encapsulate this logic
258 gasPrice: gasPrice.toString(),
259 gasLimit: GAS_LIMIT.toString(),
263 const rawTx = hexify(signedTx.serialize());
265 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
267 console.error(error);
269 addError({ [input.name]: `Wallet Error: ${input.email}` });
273 if (errorCount > 0) {
275 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
278 )} while generating wallets.`
298 const sendInvites = useCallback(async () => {
299 const _web3 = web3.getOrElse(null);
300 const _wallet = wallet.getOrElse(null);
301 if (!_web3 || !_wallet) {
302 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
305 setStatus(STATUS.FUNDING);
306 const tankWasUsed = await tank.ensureFundsFor(
310 toWei((gasPrice * GAS_LIMIT * inputs.length).toString(), 'gwei'),
311 inputs.map(input => invites[input.name].rawTx),
312 (address, minBalance, balance) =>
313 setNeedFunds({ address, minBalance, balance }),
314 () => setNeedFunds(undefined)
317 setStatus(STATUS.SENDING);
320 let unsentInvites = [];
321 let orphanedInvites = [];
322 const txAndMailings = inputs.map(async input => {
323 const invite = invites[input.name];
325 const txHash = await sendSignedTransaction(
331 // TODO: waitForTransactionConfirm never rejects
332 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
333 if (!didConfirm) throw new Error();
335 console.error(error);
336 unsentInvites.push(invite);
341 const success = await sendMail(
347 if (!success) throw new Error('Failed to send mail');
349 console.error(error);
350 orphanedInvites.push(invite);
353 addReceipt({ [input.name]: true });
356 await Promise.all(txAndMailings);
357 // if there are any receipt errors, throw a general error
358 let errorString = '';
359 if (orphanedInvites.length > 0) {
361 'Not all invite emails were sent. ' +
362 'Please send the following invite codes manually: ' +
363 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
366 if (unsentInvites.length > 0) {
369 'Not all invites were created. ' +
370 'Did not send invites for: ' +
371 unsentInvites.map(i => i.email).join(', ') +
374 if (errorString !== '') {
375 throw new Error(errorString);
389 const onClick = useCallback(async () => {
390 setGeneralError(null);
393 setStatus(STATUS.GENERATING);
394 await generateInvites();
395 setStatus(STATUS.CAN_SEND);
396 } else if (canSend) {
397 setStatus(STATUS.SENDING);
399 setStatus(STATUS.SUCCESS);
402 console.error(error);
403 setGeneralError(error);
404 setStatus(STATUS.FAILURE);
406 }, [canGenerate, canSend, generateInvites, sendInvites]);
408 // when inputs update, check to see if any of them are duplicates
410 // compute the list of valid emails
411 const emails = inputs.map(i => i.data).filter(d => !!d);
412 if (uniq(emails).length !== emails.length) {
413 setGeneralError(new Error(`Duplicate email.`));
415 setGeneralError(null);
416 setStatus(STATUS.INPUT);
420 // when we transition to done, sync invites because we just sent some
421 // and therefore know that state has changed
426 }, [isDone, syncInvites, point]);
429 for (const input of inputs) {
431 syncHasReceivedForEmail(input.data);
434 }, [inputs, syncHasReceivedForEmail]);
438 <Grid.Item full as={Flex} justify="end">
439 {/* use hidden class instead of removing component from dom */}
440 {/* in order to avoid janky reflow */}
442 onClick={() => appendInput()}
443 disabled={!canAddInvite}
444 className={cn({ hidden: isDone })}
452 <Grid.Item as={Text} className="f5" full>
453 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
454 {pluralize(inputs.length, 'has', 'have')} been successfully sent
456 {inputs.map(input => (
457 <Grid.Item as={HelpText} key={input.name} full>
458 {invites[input.name].email}
467 {inputs.map((input, i) => {
468 const isFirst = i === 0;
474 onMouseOver={() => setHovered({ [input.name]: true })}
475 onMouseLeave={() => setHovered({ [input.name]: false })}
481 accessory={accessoryFor(input.name)}
484 (input.focused || hovered[input.name]) &&
491 onClick={() => removeInputAt(i)}
505 disabled={!canGenerate && !canSend}
506 accessory={`${visualProgress}/${inputs.length}`}
510 {buttonText(status, inputs.length)}
515 <Highlighted warning>
516 Your ownership address {needFunds.address} needs at least{' '}
517 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
518 {fromWei(needFunds.balance)} ETH. Waiting until the account has
526 <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