on 74b4047 help sign in
bridge/src/lib/useInviter.js
224 lines 6.3 kB history raw
1import { useState, useCallback, useEffect } from 'react';
2import { toBN } from 'web3-utils';
3import * as azimuth from 'azimuth-js';
4import { FORM_ERROR } from 'final-form';
6import * as wg from 'lib/walletgen';
7import * as tank from 'lib/tank';
8import * as need from 'lib/need';
9import pluralize from 'lib/pluralize';
10import { GAS_LIMITS } from 'lib/constants';
11import {
12 signTransaction,
13 sendSignedTransaction,
14 waitForTransactionConfirm,
15 hexify,
16} from 'lib/txn';
17import useGasPrice from 'lib/useGasPrice';
18import { MIN_PLANET } from 'lib/constants';
19import { safeToWei } from 'lib/lib';
21import { useNetwork } from 'store/network';
22import { useWallet } from 'store/wallet';
23import { usePointCursor } from 'store/pointCursor';
24import { usePointCache } from 'store/pointCache';
26import { WARNING } from 'form/helpers';
28const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
29const STATUS = {
30 INPUT: 'INPUT',
31 SENDING: 'SENDING',
32 SUCCESS: 'SUCCESS',
33 FAILURE: 'FAILURE',
34};
36const useInviter = () => {
37 const { contracts, web3, networkType } = useNetwork();
38 const { wallet, walletType, walletHdPath, authToken } = useWallet();
39 const { pointCursor } = usePointCursor();
40 const { syncInvites } = usePointCache();
41 const { gasPrice } = useGasPrice();
43 const point = need.point(pointCursor);
45 const [needFunds, setNeedFunds] = useState(null);
46 const [invites, setInvites] = useState([]);
48 const [progress, setProgress] = useState(0);
49 const [txStatus, setTxStatus] = useState(STATUS.INPUT);
51 const isDone = txStatus === STATUS.SUCCESS;
52 useEffect(() => {
53 if (isDone) {
54 syncInvites(point);
55 }
56 }, [isDone, syncInvites, point]);
58 const resetInvites = useCallback(() => {
59 setProgress(0);
60 setInvites([]);
61 setTxStatus(STATUS.INPUT);
62 }, [setProgress, setInvites, setTxStatus]);
64 //TODO split this out into smaller callbacks within useInviter
65 const generateInvites = useCallback(
66 async numInvites => {
67 const _contracts = contracts.getOrElse(null);
68 const _web3 = web3.getOrElse(null);
69 const _wallet = wallet.getOrElse(null);
70 const _authToken = authToken.getOrElse(null);
71 if (!_contracts || !_web3 || !_wallet || !_authToken) {
72 // not using need because we want a custom error
73 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
74 }
76 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
77 const chainId = await _web3.eth.net.getId();
78 const planets = await azimuth.delegatedSending.getPlanetsToSend(
79 _contracts,
80 point,
81 numInvites
82 );
84 setTxStatus(STATUS.SENDING);
85 // account for the race condition where invites got used up while we were
86 // composing our target list
87 if (planets.length < numInvites) {
88 // resync invites to the cache, since they're out of date
89 syncInvites(point);
91 setTxStatus(STATUS.FAILURE);
93 return {
94 errors: {
95 [FORM_ERROR]:
96 `Can currently only send ${planets.length} invites. ` +
97 `Please remove invites until you are within the limit.`,
98 },
99 };
100 }
102 // NB(shrugs) - must be processed in serial because main thread, etc
103 let signedInvites = [];
104 for (let i = 0; i < numInvites; i++) {
105 setProgress(x => x + 1);
106 try {
107 const planet = planets[i];
109 const {
110 ticket,
111 owner,
112 } = await wg.generateTemporaryDeterministicWallet(planet, _authToken);
114 const inviteTx = azimuth.delegatedSending.sendPoint(
115 _contracts,
116 point,
117 planet,
118 owner.keys.address
119 );
121 const signedTx = await signTransaction({
122 wallet: _wallet,
123 walletType,
124 walletHdPath,
125 networkType,
126 chainId,
127 nonce: nonce + i,
128 // TODO: ^ make a useTransactionSigner to encapsulate this logic
129 txn: inviteTx,
130 gasPrice: gasPrice.toFixed(), // expects string gwei
131 gasLimit: GAS_LIMIT.toFixed(),
132 });
134 const rawTx = hexify(signedTx.serialize());
136 signedInvites.push({ ticket, signedTx, rawTx });
137 } catch (error) {
138 console.error(error);
139 return {
140 errors: {
141 [WARNING]: `There was an error while generating wallets.`,
142 },
143 };
144 }
145 }
147 const totalCost = toBN(GAS_LIMIT)
148 .mul(toBN(gasPrice))
149 .mul(toBN(numInvites));
150 const tankWasUsed = await tank.ensureFundsFor(
151 _web3,
152 point,
153 _wallet.address,
154 walletType,
155 safeToWei(totalCost, 'gwei'),
156 signedInvites.map(si => si.rawTx),
157 (address, minBalance, balance) =>
158 setNeedFunds({ address, minBalance, balance }),
159 () => setNeedFunds(undefined)
160 );
162 let inviteErrors = [];
163 let confirmedInvites = [];
164 const txAndMailings = signedInvites.map(async invite => {
165 try {
166 const txHash = await sendSignedTransaction(
167 _web3,
168 invite.signedTx,
169 tankWasUsed
170 );
172 await waitForTransactionConfirm(_web3, txHash);
173 confirmedInvites.push(invite);
174 } catch (error) {
175 console.error('Error sending invite tx:', error);
176 if (typeof error === 'string') {
177 inviteErrors.push(error);
178 } else if (typeof error === 'object' && error.message) {
179 inviteErrors.push(error.message);
180 }
181 return;
182 }
183 });
185 await Promise.all(txAndMailings);
187 setTxStatus(STATUS.SUCCESS);
188 setInvites(confirmedInvites);
190 if (inviteErrors.length > 0) {
191 return {
192 errors: {
193 [FORM_ERROR]: ['Error sending invites: ', ...inviteErrors],
194 },
195 };
196 }
198 return { invites: confirmedInvites };
199 },
200 [
201 authToken,
202 contracts,
203 gasPrice,
204 networkType,
205 point,
206 syncInvites,
207 wallet,
208 walletHdPath,
209 walletType,
210 web3,
211 ]
212 );
214 return {
215 progress,
216 txStatus,
217 needFunds,
218 invites,
219 generateInvites,
220 resetInvites,
221 };
222};
224export default useInviter;