on c2ab9d2 help sign in
bridge/src/lib/useInviter.js
229 lines 6.4 kB history raw
1import { useState, useCallback, useEffect } from 'react';
2import { toWei, 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';
20import { useNetwork } from 'store/network';
21import { useWallet } from 'store/wallet';
22import { usePointCursor } from 'store/pointCursor';
23import { usePointCache } from 'store/pointCache';
25import { WARNING } from 'form/helpers';
27const GAS_LIMIT = GAS_LIMITS.GIFT_PLANET;
28const STATUS = {
29 INPUT: 'INPUT',
30 SENDING: 'SENDING',
31 SUCCESS: 'SUCCESS',
32 FAILURE: 'FAILURE',
33};
35const useInviter = () => {
36 const { contracts, web3, networkType } = useNetwork();
37 const { wallet, walletType, walletHdPath } = useWallet();
38 const { pointCursor } = usePointCursor();
39 const { syncInvites } = usePointCache();
40 const { gasPrice } = useGasPrice();
41 const point = need.point(pointCursor);
43 const [needFunds, setNeedFunds] = useState(null);
44 const [invites, setInvites] = useState([]);
46 const [progress, setProgress] = useState(0);
47 const [txStatus, setTxStatus] = useState(STATUS.INPUT);
49 const isDone = txStatus === STATUS.SUCCESS;
50 useEffect(() => {
51 if (isDone) {
52 syncInvites(point);
53 }
54 }, [isDone, syncInvites, point]);
56 const resetInvites = useCallback(() => {
57 setProgress(0);
58 setInvites([]);
59 setTxStatus(STATUS.INPUT);
60 }, [setProgress, setInvites, setTxStatus]);
62 const generateInvites = useCallback(
63 async numInvites => {
64 const _contracts = contracts.getOrElse(null);
65 const _web3 = web3.getOrElse(null);
66 const _wallet = wallet.getOrElse(null);
67 if (!_contracts || !_web3 || !_wallet) {
68 // not using need because we want a custom error
69 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
70 }
72 const nonce = await _web3.eth.getTransactionCount(_wallet.address);
73 const chainId = await _web3.eth.net.getId();
74 debugger;
75 const planets = await azimuth.delegatedSending.getPlanetsToSend(
76 _contracts,
77 point,
78 numInvites
79 );
81 setTxStatus(STATUS.SENDING);
82 // account for the race condition where invites got used up while we were
83 // composing our target list
84 if (planets.length < numInvites) {
85 // resync invites to the cache, since they're out of date
86 syncInvites(point);
88 setTxStatus(STATUS.FAILURE);
90 return {
91 errors: {
92 [FORM_ERROR]:
93 `Can currently only send ${planets.length} invites. ` +
94 `Please remove invites until you are within the limit.`,
95 },
96 };
97 }
99 // NB(shrugs) - must be processed in serial because main thread, etc
100 let signedInvites = [];
101 let errorCount = 0;
102 for (let i = 0; i < numInvites; i++) {
103 setProgress(x => x + 1);
104 try {
105 const planet = planets[i];
107 const { ticket, owner } = await wg.generateTemporaryTicketAndWallet(
108 MIN_PLANET
109 // we're always giving planets, so generate a ticket of the correct size
110 );
112 const inviteTx = azimuth.delegatedSending.sendPoint(
113 _contracts,
114 point,
115 planet,
116 owner.keys.address
117 );
119 const signedTx = await signTransaction({
120 wallet: _wallet,
121 walletType,
122 walletHdPath,
123 networkType,
124 chainId,
125 nonce: nonce + i,
126 // TODO: ^ make a useTransactionSigner to encapsulate this logic
127 txn: inviteTx,
128 gasPrice: gasPrice.toFixed(), // expects string gwei
129 gasLimit: GAS_LIMIT.toFixed(),
130 });
132 const rawTx = hexify(signedTx.serialize());
134 signedInvites.push({ ticket, signedTx, rawTx });
135 } catch (error) {
136 console.error(error);
137 return {
138 errors: {
139 [WARNING]: `There was an error while generating wallets.`,
140 },
141 };
142 }
143 }
145 const totalCost = toBN(GAS_LIMIT)
146 .mul(toBN(gasPrice))
147 .mul(toBN(numInvites));
148 const tankWasUsed = await tank.ensureFundsFor(
149 _web3,
150 point,
151 _wallet.address,
152 toWei(totalCost.toString(), 'gwei'),
153 Object.keys(invites).map(name => invites[name].rawTx),
154 (address, minBalance, balance) =>
155 setNeedFunds({ address, minBalance, balance }),
156 () => setNeedFunds(undefined)
157 );
159 let unsentInvites = [];
160 let confirmedInvites = [];
161 const txAndMailings = signedInvites.map(async invite => {
162 try {
163 const txHash = await sendSignedTransaction(
164 _web3,
165 invite.signedTx,
166 tankWasUsed
167 );
169 await waitForTransactionConfirm(_web3, txHash);
170 confirmedInvites.push(invite);
171 } catch (error) {
172 console.error(error);
173 unsentInvites.push(invite);
174 return;
175 }
176 });
178 await Promise.all(txAndMailings);
180 setTxStatus(STATUS.SUCCESS);
181 setInvites(confirmedInvites);
182 console.log(unsentInvites);
183 console.log(confirmedInvites);
185 if (unsentInvites.length > 0) {
186 return { errors: { [FORM_ERROR]: unsentInvites } };
187 }
189 if (errorCount > 0) {
190 return {
191 errors: {
192 [WARNING]: `There ${pluralize(
193 errorCount,
194 'was',
195 'were'
196 )} ${pluralize(
197 errorCount,
198 'error'
199 )} while generating wallets. You can still send the invites that generated correctly.`,
200 },
201 };
202 }
203 return { invites: confirmedInvites };
204 },
205 [
206 contracts,
207 gasPrice,
208 invites,
209 networkType,
210 point,
211 syncInvites,
212 wallet,
213 walletHdPath,
214 walletType,
215 web3,
216 ]
217 );
219 return {
220 progress,
221 txStatus,
222 needFunds,
223 invites,
224 generateInvites,
225 resetInvites,
226 };
227};
229export default useInviter;