on 2fec545 help sign in
bridge/src/views/Invite/useInvites.ts
376 lines 10 kB history raw
1import { SpawnedPoints, UnspawnedPoints } from '@urbit/roller-api';
2import { POINT_DOMINIONS } from 'lib/constants';
3import { deriveNetworkSeedFromUrbitWallet } from 'lib/keys';
4import * as need from 'lib/need';
5import * as azimuth from 'azimuth-js';
6import { Invite, Invites } from 'lib/types/Invite';
7import useRoller from 'lib/useRoller';
8import { useWalletConnect } from 'lib/useWalletConnect';
9import { showNotification } from 'lib/utils/notifications';
10import {
11 generateInviteWallet,
12 getPendingSpawns,
13 submitL2Transaction,
14 registerProxyAddress,
15} from 'lib/utils/roller';
16import { useCallback, useRef } from 'react';
17import { useNetwork } from 'store/network';
18import { usePointCursor } from 'store/pointCursor';
19import { useRollerStore } from 'store/rollerStore';
20import {
21 getStoredInvites,
22 setStoredInvite,
23 setStoredInvites,
24} from 'store/storage/roller';
25import { useWallet } from 'store/wallet';
26import { usePointCache } from 'store/pointCache';
27import create from 'zustand';
28import { generateCsvLine } from 'lib/utils/invite';
29import Point from 'lib/types/Point';
31const inviteTemplate = (
32 planet: number,
33 ticket = '',
34 owner = '',
35 hash = ''
36): Invite => ({
37 planet,
38 ticket,
39 owner,
40 hash,
41});
43export type InviteGeneratingStatus =
44 | 'initial'
45 | 'generating'
46 | 'finished'
47 | 'errored';
49interface InviteJob {
50 generatingNum: number;
51 status: InviteGeneratingStatus;
54interface InviteStore {
55 invites: Invites;
56 inviteJobs: {
57 [point: number]: InviteJob;
58 };
59 addInvite: (point: number, invite: Invite) => void;
60 setInvites: (points: number, invites: Invite[]) => void;
61 updateJob: (point: number, updates: Partial<InviteJob>) => void;
64export const useInviteStore = create<InviteStore>((set, get) => ({
65 invites: {},
66 inviteJobs: {},
67 addInvite: (point: number, invite: Invite) => {
68 set(state => {
69 const newInvites: Invites = {};
70 const invites = state.invites[point];
72 if (!invites.find(inv => inv.planet === invite.planet)) {
73 newInvites[point] = [...invites, invite];
74 }
75 return { invites: Object.assign(state.invites, newInvites) };
76 });
77 },
78 setInvites: (point: number, invites: Invite[]) =>
79 set(state => {
80 const newInvites: Invites = {};
81 newInvites[point] = invites;
82 return { invites: Object.assign(state.invites, newInvites) };
83 }),
84 updateJob: (point: number, updates: Partial<InviteJob>) => {
85 const jobs = get().inviteJobs;
86 const job = jobs[point] || { status: 'initial', generatingNum: 0 };
87 const newJob = Object.assign({}, job, updates);
88 jobs[point] = newJob;
90 set({ inviteJobs: jobs });
91 },
92}));
94export function useInvites() {
95 const { wallet, authToken, walletType }: any = useWallet();
96 const { connector } = useWalletConnect();
97 const { pointCursor }: any = usePointCursor();
98 const { web3, contracts }: any = useNetwork();
99 const allPoints: any = usePointCache();
100 const getDetails = allPoints?.getDetails;
101 const { api, ls, performL2Reticket } = useRoller();
102 const { point, pointList, setPendingTransactions } = useRollerStore();
103 const {
104 invites,
105 inviteJobs,
106 addInvite,
107 setInvites,
108 updateJob,
109 } = useInviteStore();
111 const generateInviteInfo = async (planet: number, _authToken: string) => {
112 const { ticket, inviteWallet } = await generateInviteWallet(
113 planet,
114 _authToken
115 );
117 return inviteTemplate(planet, ticket, inviteWallet.ownership.keys.address);
118 };
120 const getInvites = useCallback(async () => {
121 const inviteJob = inviteJobs[point.value];
122 if (inviteJob?.status === 'generating') {
123 return;
124 }
126 try {
127 updateJob(point.value, { status: 'generating' });
129 const curPoint: number = Number(need.point(pointCursor));
130 const _authToken = authToken.getOrElse(null);
131 const _contracts = contracts.getOrElse(null);
133 if (_authToken && _contracts) {
134 const spawnedPoints = point.isL2Spawn
135 ? await api.getSpawned(curPoint)
136 : [];
138 const newPending = await api.getPendingByShip(curPoint);
139 setPendingTransactions(newPending);
140 const pendingSpawns = getPendingSpawns(newPending);
142 const availablePoints = await azimuth.azimuth.getUnspawnedChildren(
143 _contracts,
144 curPoint
145 );
147 const outgoingPoints = pointList
148 .filter(
149 ({ value, isPlanet }) => isPlanet && availablePoints.includes(value)
150 )
151 .map(({ value }) => value);
153 const invitePlanets = spawnedPoints
154 .concat(
155 outgoingPoints.filter((p: number) => !spawnedPoints.includes(p))
156 )
157 .filter((p: number) => !pendingSpawns.has(p))
158 .sort();
160 setInvites(curPoint, []);
162 const newInvites: Invite[] = [];
163 // Iterate over all of the stored invites, generating wallet info as necessary
164 const storedInvites = getStoredInvites(ls);
166 for (let i = 0; i < invitePlanets.length; i++) {
167 updateJob(point.value, { generatingNum: i + 1 });
168 const planet = invitePlanets[i];
169 const storedInvite = storedInvites[planet];
170 const invite =
171 storedInvite || (await generateInviteInfo(planet, _authToken));
173 // TODO: check if the invite point's owner still matches the deterministic wallet address
174 const planetInfo = await api.getPoint(planet);
175 setStoredInvite(ls, invite);
177 if (
178 invite.owner.toLowerCase() ===
179 planetInfo.ownership?.owner?.address &&
180 planetInfo.dominion === POINT_DOMINIONS.L2
181 ) {
182 addInvite(curPoint, invite);
183 newInvites.push(invite);
184 }
186 if (storedInvite) {
187 setStoredInvite(ls, invite);
188 }
189 }
191 updateJob(point.value, { status: 'finished', generatingNum: 0 });
192 return newInvites;
193 }
194 } catch (error) {
195 console.warn('ERROR GETTING INVITES', error);
196 updateJob(point.value, { status: 'errored', generatingNum: 0 });
197 }
198 }, [
199 api,
200 authToken,
201 contracts,
202 pointCursor,
203 ls,
204 point,
205 pointList,
206 addInvite,
207 setInvites,
208 setPendingTransactions,
209 updateJob,
210 ]);
212 const generateInviteCodes = useCallback(
213 async (
214 point: Point,
215 planets: SpawnedPoints | UnspawnedPoints,
216 spawn: boolean = true
217 ) => {
218 const _contracts = contracts.getOrElse(null);
219 const _web3 = web3.getOrElse(null);
220 const _wallet = wallet.getOrElse(null);
221 const _authToken = authToken.getOrElse(null);
223 if (!_contracts || !_web3 || !_wallet || !_authToken) {
224 // not using need because we want a custom error
225 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
226 }
228 // TODO: remove when UI disables management proxy from spawning invites
229 // if (Just.hasInstance(authMnemonic)) {
230 // throw new Error(
231 // "Auth key Error: A management mnemonic can't create invite codes"
232 // );
233 // }
235 const invites: Invite[] = [];
237 const proxy = point.getSpawnProxy();
239 if (proxy === undefined)
240 throw new Error("Error: Address doesn't match proxy");
242 const nonce = await api.getNonce({
243 ship: point.value,
244 proxy,
245 });
247 for (let i = 0; i < planets.length; i++) {
248 updateJob(point.value, { generatingNum: i + 1 });
249 const planet = planets[i];
250 const nonceInc = i + nonce;
252 const { ticket, inviteWallet } = await generateInviteWallet(
253 planet,
254 _authToken
255 );
257 if (!spawn) {
258 await performL2Reticket({
259 point: planet,
260 to: inviteWallet.ownership.keys.address,
261 manager: inviteWallet.management.keys.address,
262 fromWallet: _wallet,
263 toWallet: inviteWallet,
264 });
265 } else {
266 await submitL2Transaction({
267 api,
268 address: _wallet.address,
269 wallet: _wallet,
270 ship: point.value,
271 proxy,
272 nonce: nonceInc,
273 pointToSpawn: planet,
274 type: 'spawn',
275 walletType,
276 web3: _web3,
277 connector,
278 });
280 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
281 inviteWallet,
282 1
283 );
284 await submitL2Transaction({
285 api,
286 wallet: _wallet,
287 ship: planet,
288 proxy: 'own',
289 nonce: 0,
290 networkSeed,
291 type: 'configureKeys',
292 walletType,
293 web3: _web3,
294 connector,
295 });
297 await registerProxyAddress(
298 api,
299 _wallet,
300 planet,
301 'own',
302 'manage',
303 1,
304 inviteWallet.management.keys.address,
305 walletType,
306 _web3,
307 connector
308 );
310 await submitL2Transaction({
311 api,
312 wallet: _wallet,
313 ship: planet,
314 proxy: 'own',
315 type: 'transferPoint',
316 nonce: 2,
317 address: inviteWallet.ownership.keys.address,
318 walletType,
319 web3: _web3,
320 connector,
321 });
322 }
324 invites.push({
325 hash: '',
326 ticket,
327 planet,
328 owner: inviteWallet.ownership.keys.address,
329 });
330 }
332 setStoredInvites(ls, invites);
333 console.log('getting invites from code generation');
334 getInvites();
335 showNotification(
336 `Your invite${invites.length > 1 ? 's have' : ' has'} been generated!`
337 );
338 },
339 [
340 api,
341 authToken,
342 connector,
343 contracts,
344 pointCursor,
345 point,
346 wallet,
347 walletType,
348 web3,
349 getDetails,
350 ls,
351 getInvites,
352 updateJob,
353 performL2Reticket,
354 ]
355 );
357 const generateCsv = useCallback(() => {
358 const pointInvites = invites[point.value];
360 if (!pointInvites) {
361 throw new Error('There was an error creating the CSV');
362 }
364 return pointInvites.reduce(
365 (csvData, { ticket, planet }, ind) =>
366 (csvData += generateCsvLine(ind, ticket, planet)),
367 'Number,Planet,Invite URL,Point,Ticket\n'
368 );
369 }, [invites, point]);
371 return {
372 getInvites,
373 generateCsv,
374 generateInviteCodes,
375 };