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 useArray from 'lib/useArray';
33import { buildEmailInputConfig } from 'lib/useInputs';
34import { MIN_PLANET, GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } from 'lib/constants';
35import * as need from 'lib/need';
36import * as wg from 'lib/walletgen';
37import useSetState from 'lib/useSetState';
38import pluralize from 'lib/pluralize';
39import useMailer from 'lib/useMailer';
41import LoadableButton from 'components/LoadableButton';
42import Highlighted from 'components/Highlighted';
44const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
45const INVITE_COST = toWei(
46 (DEFAULT_GAS_PRICE_GWEI * GAS_LIMIT).toString(),
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 { contracts, web3, networkType } = useNetwork();
98 const { wallet, walletType, walletHdPath } = useWallet();
99 const { syncInvites, getInvites } = usePointCache();
100 const { pointCursor } = usePointCursor();
101 const point = need.point(pointCursor);
102 const { getHasReceived, syncHasReceivedForEmail, sendMail } = useMailer();
104 const { availableInvites } = getInvites(point);
105 const maxInvitesToSend = availableInvites.matchWith({
110 // manage the array of input configs
113 { append: appendInput, removeAt: removeInputAt },
115 [buildInputConfig({ label: 'Email Address', autoFocus: true })],
119 // manage per-input state
120 const [hovered, setHovered] = useSetState();
121 const [invites, addInvite, clearInvites] = useSetState();
122 const [receipts, addReceipt, clearReceipts] = useSetState();
123 const [errors, addError] = useSetState();
125 // manage general state that affects the whole form
126 const [status, setStatus] = useState(STATUS.INPUT);
127 const [needFunds, setNeedFunds] = useState(null);
128 const [generalError, setGeneralError] = useState(null);
130 // derive booleans from status
131 const canInput = status === STATUS.INPUT;
132 const canSend = status === STATUS.CAN_SEND;
133 const isGenerating = status === STATUS.GENERATING;
134 const isSending = status === STATUS.SENDING;
135 const isFailed = status === STATUS.FAILURE;
136 const isDone = status === STATUS.SUCCESS;
138 // add disabled, error info to input configs
139 const dynamicConfigs = useMemo(
141 inputConfigs.map(config => {
142 config.disabled = !canInput;
143 const hasReceivedError = getHasReceived(config.name).matchWith({
144 Nothing: () => null, // loading
145 Just: p => p.value && HAS_RECEIVED_TEXT,
147 config.error = hasReceivedError || errors[config.name];
150 [inputConfigs, errors, canInput, getHasReceived]
153 // construct the state of the set of inputs we're rendering below
154 const { inputs, pass } = useForm(dynamicConfigs);
155 // did all of the inputs pass inspection (and there are no general errors)?
156 const allPass = pass && !generalError;
157 // the form is submittable iff passing and input is allowed
158 const canGenerate = allPass && canInput;
159 // additional inputs can be added iff input is allowed and we have enough
161 const canAddInvite = canInput && inputConfigs.length < maxInvitesToSend;
163 // progress is [0, .length] of invites or receipts, as we're generating them
164 const progress = isGenerating
165 ? Object.keys(invites).length
167 ? Object.keys(receipts).length
169 const visualProgress = progress === null ? '-' : `${progress + 1}`;
171 // build a builder for the accessory to the input, depending on status
172 const accessoryFor = (() => {
173 if (isGenerating || canSend) return buildAccessoryFor(invites, errors);
174 if (isSending) return buildAccessoryFor(receipts, errors);
175 if (isFailed) return buildAccessoryFor({}, errors);
179 const generateInvites = useCallback(async () => {
180 const _contracts = contracts.getOrElse(null);
181 const _web3 = web3.getOrElse(null);
182 const _wallet = wallet.getOrElse(null);
183 if (!_contracts || !_web3 || !_wallet) {
184 // not using need because we want a custom error
185 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
188 //TODO want to do this on-input, but that gets weird. see #188
191 inputs.map(async input => {
192 const email = input.data;
193 const hasReceived = getHasReceived(email).matchWith({
194 Nothing: () => false, // loading
200 [input.name]: `${email} has already received an invite.`,
205 if (errorCount > 0) {
206 throw new Error(`Some of these already have a point!`);
209 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
210 const chainId = await _web3.eth.net.getId();
211 const planets = await azimuth.delegatedSending.getPlanetsToSend(
217 // account for the race condition where invites got used up while we were
218 // composing our target list
219 if (planets.length < inputs.length) {
220 // resync invites to the cache, since they're out of date
224 `Can currently only send ${planets.length} invites. ` +
225 `Please remove invites until you are within the limit.`
230 // NB(shrugs) - must be processed in serial because main thread, etc
231 for (let i = 0; i < inputs.length; i++) {
232 const input = inputs[i];
234 const { data: email, name } = inputs[i];
236 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
238 // we're always giving planets, so generate a ticket of the correct size
241 const inviteTx = azimuth.delegatedSending.sendPoint(
247 const signedTx = await signTransaction({
252 // TODO: ^ make a useTransactionSigner to encapsulate this logic
254 gasPrice: DEFAULT_GAS_PRICE_GWEI.toString(),
255 gasLimit: GAS_LIMIT.toString(),
259 const rawTx = hexify(signedTx.serialize());
261 addInvite({ [name]: { email, ticket, signedTx, rawTx } });
263 console.error(error);
265 addError({ [input.name]: `Wallet Error: ${input.email}` });
269 if (errorCount > 0) {
271 `There ${pluralize(errorCount, 'was', 'were')} ${pluralize(
274 )} while generating wallets.`
293 const sendInvites = useCallback(async () => {
294 const _web3 = web3.getOrElse(null);
295 const _wallet = wallet.getOrElse(null);
296 if (!_web3 || !_wallet) {
297 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
300 setStatus(STATUS.FUNDING);
301 const tankWasUsed = await tank.ensureFundsFor(
305 INVITE_COST * inputs.length,
306 inputs.map(input => invites[input.name].rawTx),
307 (address, minBalance, balance) =>
308 setNeedFunds({ address, minBalance, balance }),
309 () => setNeedFunds(undefined)
312 setStatus(STATUS.SENDING);
316 const txAndMailings = inputs.map(async input => {
317 const invite = invites[input.name];
319 const txHash = await sendSignedTransaction(
325 // TODO: waitForTransactionConfirm never rejects
326 const didConfirm = await waitForTransactionConfirm(_web3, txHash);
327 if (!didConfirm) throw new Error();
329 console.error(error);
332 [input.name]: `Transaction Failure for ${invite.email}`,
338 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 full as={Flex} justify="end">
428 {/* use hidden class instead of removing component from dom */}
429 {/* in order to avoid janky reflow */}
431 onClick={() => appendInput()}
432 disabled={!canAddInvite}
433 className={cn({ hidden: isDone })}
441 <Grid.Item as={Text} className="f5" full>
442 <Highlighted>{pluralize(inputs.length, 'invite')}</Highlighted>{' '}
443 {pluralize(inputs.length, 'has', 'have')} been successfully sent
445 {inputs.map(input => (
446 <Grid.Item as={HelpText} key={input.name} full>
447 {invites[input.name].email}
456 {inputs.map((input, i) => {
457 const isFirst = i === 0;
463 onMouseOver={() => setHovered({ [input.name]: true })}
464 onMouseLeave={() => setHovered({ [input.name]: false })}
470 accessory={accessoryFor(input.name)}
473 (input.focused || hovered[input.name]) &&
480 onClick={() => removeInputAt(i)}
494 disabled={!canGenerate && !canSend}
495 accessory={`${visualProgress}/${inputs.length}`}
499 {buttonText(status, inputs.length)}
504 <Highlighted warning>
505 Your ownership address {needFunds.address} needs at least{' '}
506 {fromWei(needFunds.minBalance)} ETH and currently has{' '}
507 {fromWei(needFunds.balance)} ETH. Waiting until the account has
515 <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