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 { useLocalRouter } from 'lib/LocalRouter';
33import useArray from 'lib/useArray';
34import { buildEmailInputConfig } from 'lib/useInputs';
35import { MIN_PLANET, GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } 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_LIMIT = GAS_LIMITS.GIFT_PLANET;
47const INVITE_COST = toWei(
48 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
51const HAS_RECEIVED_TEXT = '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.point(pointCursor);
105 const { getHasReceived, 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', autoFocus: true })],
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] = 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 = getHasReceived(config.name).matchWith({
147 Nothing: () => null, // loading
148 Just: p => p.value && HAS_RECEIVED_TEXT,
150 config.error = hasReceivedError || errors[config.name];
153 [inputConfigs, errors, canInput, getHasReceived]
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 //TODO want to do this on-input, but that gets weird. see #188
193 let alreadyReceived = [];
195 inputs.map(async input => {
196 const email = input.data;
197 getHasReceived(email).matchWith({
202 if (p.value) alreadyReceived.push(email);
208 throw new Error('No word yet from email service...');
210 if (alreadyReceived.length > 0) {
212 'The following recipients already own a point: ' +
213 alreadyReceived.join(', ')
217 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
218 const chainId = await _web3.eth.net.getId();
219 const planets = await azimuth.delegatedSending.getPlanetsToSend(
225 // account for the race condition where invites got used up while we were
226 // composing our target list
227 if (planets.length < inputs.length) {
228 // resync invites to the cache, since they're out of date
232 `Can currently only send ${planets.length} invites. ` +
233 `Please remove invites until you are within the limit.`
238 // NB(shrugs) - must be processed in serial because main thread, etc
240 for (let i = 0; i < inputs.length; i++) {
241 const input = inputs[i];
243 const { data: email, name } = inputs[i];
245 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
247 // we're always giving planets, so generate a ticket of the correct size
250 const inviteTx = azimuth.delegatedSending.sendPoint(
256 const signedTx = await signTransaction({
261 // TODO: ^ make a useTransactionSigner to encapsulate this logic
263 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
264 gasLimit: GAS_LIMIT.toString(),
268 const rawTx = hexify(signedTx.serialize());
270 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
272 console.error(error);
274 addError({ [input.name]: `Wallet Error: ${input.email}` });
278 if (errorCount > 0) {
280 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
283 )} while generating wallets.`
302 const sendInvites = useCallback(async () => {
303 const _web3 = web3.getOrElse(null);
304 const _wallet = wallet.getOrElse(null);
305 if (!_web3 || !_wallet) {
306 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
309 setStatus(STATUS.FUNDING);
310 const tankWasUsed = await tank.ensureFundsFor(
314 INVITE_COST * inputs.length,
315 inputs.map(input => invites[input.name].rawTx),
316 (address, minBalance, balance) =>
317 setNeedFunds({ address, minBalance, balance }),
318 () => setNeedFunds(undefined)
321 setStatus(STATUS.SENDING);
324 let unsentInvites = [];
325 let orphanedInvites = [];
326 const txAndMailings = inputs.map(async input => {
327 const invite = invites[input.name];
329 const txHash = await sendSignedTransaction(
335 // TODO: waitForTransactionConfirm never rejects
336 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
337 if (!didConfirm) throw new Error();
339 console.error(error);
340 unsentInvites.push(invite);
345 const success = await sendMail(
351 if (!success) throw new Error('Failed to send mail');
353 console.error(error);
354 orphanedInvites.push(invite);
357 addReceipt({ [input.name]: true });
360 await Promise.all(txAndMailings);
361 // if there are any receipt errors, throw a general error
362 let errorString = '';
363 if (orphanedInvites.length > 0) {
365 'Not all invite emails were sent. ' +
366 'Please send the following invite codes manually: ' +
367 orphanedInvites.map(i => `${i.email}: ${i.ticket}`).join(', ') +
370 if (unsentInvites.length > 0) {
373 'Not all invites were created. ' +
374 'Did not send invites for: ' +
375 unsentInvites.map(i => i.email).join(', ') +
378 if (errorString !== '') {
379 throw new Error(errorString);
392 const onClick = useCallback(async () => {
393 setGeneralError(null);
396 setStatus(STATUS.GENERATING);
397 await generateInvites();
398 setStatus(STATUS.CAN_SEND);
399 } else if (canSend) {
400 setStatus(STATUS.SENDING);
402 setStatus(STATUS.SUCCESS);
405 console.error(error);
406 setGeneralError(error);
407 setStatus(STATUS.FAILURE);
409 }, [canGenerate, canSend, generateInvites, sendInvites]);
411 // when inputs update, check to see if any of them are duplicates
413 // compute the list of valid emails
414 const emails = inputs.map(i => i.data).filter(d => !!d);
415 if (uniq(emails).length !== emails.length) {
416 setGeneralError(new Error(`Duplicate email.`));
418 setGeneralError(null);
419 setStatus(STATUS.INPUT);
423 // when we transition to done, sync invites because we just sent some
424 // and therefore know that state has changed
429 }, [isDone, syncInvites, point]);
432 for (const input of inputs) {
434 syncHasReceivedForEmail(input.data);
437 }, [inputs, syncHasReceivedForEmail]);
441 <Grid.Item as={Grid} full>
442 <Grid.Item as={Flex} cols={[1, 11]} align="center">
443 <MiniBackButton onClick={() => pop()} />
445 <Grid.Item cols={[11, 13]} justifySelf="end">
446 {/* use hidden class instead of removing component from dom */}
447 {/* in order to avoid janky reflow */}
449 onClick={() => appendInput()}
450 disabled={!canAddInvite}
451 className={cn({ hidden: isDone })}
460 <Grid.Item as={Text} className="f5" full>
461 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
462 {pluralize(inputs.length, 'has', 'have')} been successfully sent
464 {inputs.map(input => (
465 <Grid.Item as={HelpText} key={input.name} full>
466 {invites[input.name].email}
475 {inputs.map((input, i) => {
476 const isFirst = i === 0;
482 onMouseOver={() => setHovered({ [input.name]: true })}
483 onMouseLeave={() => setHovered({ [input.name]: false })}
489 accessory={accessoryFor(input.name)}
492 (input.focused || hovered[input.name]) &&
499 onClick={() => removeInputAt(i)}
513 disabled={!canGenerate && !canSend}
514 accessory={`${visualProgress}/${inputs.length}`}
518 {buttonText(status, inputs.length)}
524 Your ownership address {needFunds.address} needs at least{' '}
525 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
526 {fromWei(needFunds.balance)} ETH. Waiting until the account has
534 <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