1import { Just, Nothing } from 'folktale/maybe';
2import React from 'react';
3import * as azimuth from 'azimuth-js';
4import * as need from 'lib/need';
6import { hasReceived, sendMail } from 'lib/inviteMail';
7import { Button, Input, H3, Warning } from 'components/old/Base';
9// for wallet generation
10import * as wg from '_walletgen/lib/lib';
12// for transaction generation and signing
15 sendSignedTransaction,
16 waitForTransactionConfirm,
21import * as tank from 'lib/tank';
22import { withNetwork } from 'store/network';
23import { compose } from 'lib/lib';
24import { withWallet } from 'store/wallet';
25import { withPointCursor } from 'store/pointCursor';
26import View from 'components/View';
28const GAS_PRICE_GWEI = 20; // we pay the premium for faster ux
29const GAS_LIMIT = 350000;
30const INVITE_COST = toWei((GAS_PRICE_GWEI * GAS_LIMIT).toString(), 'gwei');
33 INPUT: 'Generate invites',
34 GENERATING: 'Generating invites',
35 CAN_SEND: 'Send invites',
36 FUNDING: 'Funding invites',
37 SENDING: 'Sending invites',
48class InviteEmail extends React.Component {
53 invitesAvailable: Nothing(),
55 targets: [{ email: '', hasReceived: Nothing(), status: Nothing() }],
59 fundingMessage: Nothing(),
63 this.findInvited = this.findInvited.bind(this);
64 this.generateInvites = this.generateInvites.bind(this);
65 this.sendInvites = this.sendInvites.bind(this);
66 this.canSend = this.canSend.bind(this);
67 this.addError = this.addError.bind(this);
68 this.handleEmailInput = this.handleEmailInput.bind(this);
69 this.addTarget = this.addTarget.bind(this);
70 this.removeTarget = this.removeTarget.bind(this);
71 this.setEmailStatus = this.setEmailStatus.bind(this);
72 this.askForFunding = this.askForFunding.bind(this);
76 this.point = need.pointCursor(this.props.pointCursor);
77 this.address = need.addressFromWallet(this.props.wallet);
78 this.contracts = need.contracts(this.props.contracts);
79 this.web3 = need.web3(this.props.web3);
81 console.log(azimuth.delegatedSending);
82 azimuth.delegatedSending
83 .getTotalUsableInvites(this.contracts, this.point)
85 this.setState({ invitesAvailable: Just(count) });
90 componentDidUpdate(prevProps) {
95 let invited = await azimuth.delegatedSending.getInvited(
99 invited = invited.map(async point => {
100 const active = await azimuth.azimuth.isActive(this.contracts, point);
101 const res = { point: Number(point), active: active };
104 invited = await Promise.all(invited);
105 const total = invited.length;
106 const accepted = invited.filter(i => i.active).length;
107 this.setState({ invited: Just({ total, accepted }) });
110 async getTemporaryWallet() {
111 const ticket = await wg.makeTicket(0x10000); // planet-sized ticket
112 const owner = await wg.generateOwnershipWallet(0, ticket);
113 return { ticket, owner: owner.keys.address };
116 async generateInvites() {
117 this.setState({ status: STATUS.GENERATING });
119 const web3 = this.web3;
120 const targets = this.state.targets;
121 const planets = await azimuth.delegatedSending.getPlanetsToSend(
127 // account for the race condition where invites got used up while we were
128 // composing our target list
129 if (planets.length < targets.length) {
130 this.addError('Can currently only send ' + planets.length + ' invites!');
134 const nonce = await web3.eth.getTransactionCount(this.address);
135 const chainId = await web3.eth.net.getId();
137 // create invite wallets and transactions
138 let invites = []; // { email, ticket, signedTx, rawTx }
139 for (let i = 0; i < targets.length; i++) {
140 console.log('generating email', i, targets[i].email);
141 this.setEmailStatus(i, EMAIL_STATUS.BUSY);
143 const email = targets[i].email;
144 const wallet = await this.getTemporaryWallet();
146 let inviteTx = azimuth.delegatedSending.sendPoint(
152 const signedTx = await signTransaction({
155 gasPrice: GAS_PRICE_GWEI.toString(),
156 gasLimit: GAS_LIMIT.toString(),
161 const rawTx = hexify(signedTx.serialize());
163 invites.push({ email, ticket: wallet.ticket, signedTx, rawTx });
164 this.setEmailStatus(i, EMAIL_STATUS.DONE);
167 this.setState({ wipInvites: invites, status: STATUS.CAN_SEND });
170 async sendInvites() {
171 const invites = this.state.wipInvites;
172 const web3 = this.web3;
174 //TODO invite status isn't changing/re-rendering... why?
176 status: STATUS.FUNDING,
177 invites: invites.map(i => {
178 return { ...i, status: Nothing() };
182 const tankWasUsed = await tank.ensureFundsFor(
186 INVITE_COST * invites.length,
187 invites.map(i => i.rawTx),
190 this.setState({ fundingMessage: Nothing() });
194 this.setState({ status: STATUS.SENDING });
196 //TODO nasty loop, probably move into lib... but so many callbacks!
198 for (let i = 0; i < invites.length; i++) {
199 const invite = invites[i];
201 // send transaction. if it fails, inform the user and skip to next
204 txHash = await sendSignedTransaction(
206 Just(invite.signedTx),
211 console.error('invite tx sending failed', err);
212 this.addError('Invite transaction not sent for ' + invite.email);
213 this.setEmailStatus(i, EMAIL_STATUS.FAIL);
217 // ask the email sender to send this. we can do this prior to tx confirm,
218 // because the sender service waits for confirm & success for us.
219 // if this fails, inform the user and skip to next
221 const mailSuccess = await sendMail(
226 if (!mailSuccess) throw new Error();
227 this.setEmailStatus(i, EMAIL_STATUS.DONE);
229 console.log('email send failed');
230 //NOTE this assumes that the transaction succeeds, but we don't know
231 // that for a fact yet...
233 'Invite email failed to send for ' +
235 '. Please give them this ticket: ' +
238 this.setEmailStatus(i, EMAIL_STATUS.FAIL);
242 // update status on transaction confirm, but don't block on it
244 waitForTransactionConfirm(web3, txHash).then(success => {
246 this.setEmailStatus(i, EMAIL_STATUS.DONE);
248 console.log('invite tx rejected');
249 this.addError('Invite transaction failed for ' + invite.email);
250 this.setEmailStatus(i, EMAIL_STATUS.FAIL);
257 const txStatus = await Promise.all(promises);
258 if (txStatus.every(e => e)) {
259 this.setState({ status: STATUS.DONE });
261 this.setState({ status: STATUS.FAIL });
265 setEmailStatus(i, status) {
266 const targets = this.state.targets;
267 targets[i].status = Just(status);
268 this.setState({ targets });
272 const newError = this.state.errors.matchWith({
273 Nothing: () => [error],
275 errs.value.push(error);
279 this.setState({ errors: Just(newError) });
282 askForFunding(address, minBalance, balance) {
284 fundingMessage: Just(
285 `Please make sure ${address} has at least ${fromWei(minBalance)} ETH,` +
286 `we'll continue once that's true. Current balance: ${fromWei(
294 handleEmailInput(i, email) {
295 let targets = this.state.targets;
296 targets[i].email = email;
298 // if it's a valid address, check if it has received an invite before
299 if (email.match(/.*@.*\...+/)) {
300 hasReceived(email).then(res => {
301 targets[i].hasReceived = Just(res);
302 this.setState({ targets });
305 targets[i].hasReceived = Nothing();
308 this.setState({ targets });
312 const targets = this.state.targets;
314 // may not have duplicate targets
315 if (new Set(targets.map(t => t.email)).size !== targets.length)
318 // none may have received invites already
319 for (let i = 0; i < targets.length; i++) {
320 const target = targets[i];
321 const res = target.hasReceived.matchWith({
323 Just: has => has.value,
325 if (res) return false;
328 return this.state.invitesAvailable.matchWith({
329 Nothing: () => false,
330 Just: invites => invites.value > 0,
335 let targets = this.state.targets;
336 targets.push({ email: '', hasReceived: Nothing(), status: Nothing() });
337 this.setState({ targets });
341 let targets = this.state.targets;
342 targets.length = targets.length - 1;
343 this.setState({ targets });
348 this.state.status === STATUS.DONE ? this.state.targets.length : null;
350 const invitesAvailable = this.state.invitesAvailable.matchWith({
351 Nothing: () => 'Loading...',
353 const dia = dif ? `(-${dif})` : '';
354 return `You currently have ${invites.value}${dia} invitations left.`;
358 const invitesSent = this.state.invited.matchWith({
359 Nothing: () => <>{'Loading...'}</>,
361 const dit = dif ? `(+${dif})` : '';
365 {invited.value.total + dit}
366 {' invites you sent, '}
367 {invited.value.accepted}
368 {' have been accepted.'}
374 const error = this.state.errors.matchWith({
377 <Warning className={'mt-8'}>
378 <H3 style={{ marginTop: 0, paddingTop: 0 }}>
379 {'Something went wrong!'}
381 {errors.value.map(err => (
388 const fundingMessage = this.state.fundingMessage.matchWith({
390 Just: msg => <Warning className={'mt-8'}>{msg.value}</Warning>,
394 if (this.state.status === STATUS.DONE) {
395 //TODO proper clickable router thing
396 inputs = '<- Back to Home';
398 const inputDisabled = this.state.status !== STATUS.INPUT;
402 prop-size={'s narrow'}
404 disabled={inputDisabled || this.state.targets.length === 1}
405 onClick={this.removeTarget}>
412 prop-size={'s narrow'}
416 this.state.invitesAvailable.matchWith({
418 Just: inv => inv.value <= this.state.targets.length,
421 onClick={this.addTarget}>
426 let targetInputs = [];
427 for (let i = 0; i < this.state.targets.length; i++) {
428 const target = this.state.targets[i];
429 let progress = target.status.matchWith({
431 Just: status => status.value,
438 this.handleEmailInput(i, value);
440 placeholder={'Email address'}
441 disabled={inputDisabled}
443 {target.hasReceived.matchWith({
446 has.value ? <span>{'×'}</span> : <span>{'°'}</span>,
453 const submitButton = (
455 prop-size={'xl wide'}
458 (inputDisabled && this.state.status !== STATUS.CAN_SEND) ||
462 if (this.state.status === STATUS.INPUT) this.generateInvites();
463 if (this.state.status === STATUS.CAN_SEND) this.sendInvites();
481 <p>{'send invites here, for planets'}</p>
483 <p>{invitesAvailable}</p>
485 <ul>{invitesSent}</ul>
497export default compose(
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