on a0efefc help sign in
bridge/src/lib/useInviter.js
230 lines 6.4 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 const generateInvites = useCallback(
65 async numInvites => {
66 const _contracts = contracts.getOrElse(null);
67 const _web3 = web3.getOrElse(null);
68 const _wallet = wallet.getOrElse(null);
69 const _authToken = authToken.getOrElse(null);
70 if (!_contracts || !_web3 || !_wallet || !_authToken) {
71 // not using need because we want a custom error
72 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
73 }
75 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
76 const chainId = await _web3.eth.net.getId();
77 const planets = await azimuth.delegatedSending.getPlanetsToSend(
78 _contracts,
79 point,
80 numInvites
81 );
83 setTxStatus(STATUS.SENDING);
84 // account for the race condition where invites got used up while we were
85 // composing our target list
86 if (planets.length < numInvites) {
87 // resync invites to the cache, since they're out of date
88 syncInvites(point);
90 setTxStatus(STATUS.FAILURE);
92 return {
93 errors: {
94 [FORM_ERROR]:
95 `Can currently only send ${planets.length} invites. ` +
96 `Please remove invites until you are within the limit.`,
97 },
98 };
99 }
101 // NB(shrugs) - must be processed in serial because main thread, etc
102 let signedInvites = [];
103 let errorCount = 0;
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 unsentInvites = [];
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);
176 unsentInvites.push(invite);
177 return;
178 }
179 });
181 await Promise.all(txAndMailings);
183 setTxStatus(STATUS.SUCCESS);
184 setInvites(confirmedInvites);
186 if (unsentInvites.length > 0) {
187 return { errors: { [FORM_ERROR]: unsentInvites } };
188 }
190 if (errorCount > 0) {
191 return {
192 errors: {
193 [WARNING]: `There ${pluralize(
194 errorCount,
195 'was',
196 'were'
197 )} ${pluralize(
198 errorCount,
199 'error'
200 )} while generating wallets. You can still send the invites that generated correctly.`,
201 },
202 };
203 }
204 return { invites: confirmedInvites };
205 },
206 [
207 authToken,
208 contracts,
209 gasPrice,
210 networkType,
211 point,
212 syncInvites,
213 wallet,
214 walletHdPath,
215 walletType,
216 web3,
217 ]
218 );
220 return {
221 progress,
222 txStatus,
223 needFunds,
224 invites,
225 generateInvites,
226 resetInvites,
227 };
228};
230export default useInviter;