on 4f027ea help sign in
bridge/src/lib/useRoller.ts
681 lines 18 kB history raw
1import { useCallback, useEffect, useMemo, useState } from 'react';
2import * as azimuth from 'azimuth-js';
3import * as need from 'lib/need';
4import SecureLS from 'secure-ls';
6import { Invite } from 'lib/types/Invite';
7import { convertToInt } from './convertToInt';
8import { isDevelopment, isRopsten } from './flags';
9import { generateInviteWallet, getPendingSpawns } from './utils/roller';
10import { ROLLER_HOSTS } from './constants';
12import { useNetwork } from 'store/network';
13import { usePointCursor } from 'store/pointCursor';
14import { useRollerStore } from 'store/roller';
15import { useWallet } from 'store/wallet';
16import { getStoredInvites, setStoredInvites } from 'store/storage/roller';
17import { usePointCache } from 'store/pointCache';
18import { getOutgoingPoints } from 'views/Points';
19import {
20 getSpawnProxy,
21 getManagerProxy,
22 getAddressProxy,
23 getTransferProxy,
24} from './utils/proxy';
25import { isPlanet } from './utils/point';
27import {
28 deriveNetworkSeedFromUrbitWallet,
29 attemptNetworkSeedDerivation,
30} from 'lib/keys';
32import {
33 Config,
34 Ship,
35 Proxy,
36 RollerRPCAPI,
37 Options,
38 EthAddress,
39 UnspawnedPoints,
40} from '@urbit/roller-api';
42import {
43 configureKeys,
44 getTimeToNextBatch,
45 spawn,
46 transferPointRequest,
47 registerProxyAddress,
48} from './utils/roller';
50const ONE_SECOND = 1000;
52const inviteTemplate = (
53 planet: number,
54 ticket = '',
55 owner = '',
56 hash = ''
57): Invite => ({
58 planet,
59 ticket,
60 owner,
61 hash,
62});
64export default function useRoller() {
65 const { wallet, authToken, authMnemonic, urbitWallet }: any = useWallet();
66 const { pointCursor }: any = usePointCursor();
67 const { web3, contracts }: any = useNetwork();
68 const allPoints: any = usePointCache();
69 const controlledPoints = allPoints?.controlledPoints;
70 const getDetails = allPoints?.getDetails;
72 const {
73 nextBatchTime,
74 currentL2,
75 invitePoints,
76 invites,
77 setNextBatchTime,
78 setNextRoll,
79 setPendingTransactions,
80 setInvites,
81 setInvitePoints,
82 setInviteGeneratingNum,
83 } = useRollerStore();
84 const [config, setConfig] = useState<Config | null>(null);
86 const options: Options = useMemo(() => {
87 const type = isRopsten || !isDevelopment ? 'https' : 'http';
88 const host = isRopsten
89 ? ROLLER_HOSTS.ROPSTEN
90 : isDevelopment
91 ? ROLLER_HOSTS.LOCAL
92 : ROLLER_HOSTS.MAINNET;
93 const port = isRopsten ? 443 : 8080;
94 const path = '/v1/roller';
96 return {
97 transport: {
98 type,
99 host,
100 port,
101 path,
102 },
103 };
104 }, []);
106 const api = useMemo(() => {
107 return new RollerRPCAPI(options);
108 }, [options]);
110 const fetchConfig = useCallback(async () => {
111 api
112 .getRollerConfig()
113 .then(response => {
114 setConfig(response);
115 setNextBatchTime(response.nextBatch);
116 })
117 .catch(err => {
118 // TODO: more elegant error handling
119 console.warn(
120 '[fetchConfig:failed] check the roller connection?\n',
121 err
122 );
123 });
124 }, [api]); // eslint-disable-line react-hooks/exhaustive-deps
126 const ls = new SecureLS({
127 isCompression: false,
128 encryptionSecret: authToken.getOrElse('default'),
129 });
131 const generateInviteCodes = useCallback(
132 async (numInvites: number) => {
133 const _point = need.point(pointCursor);
134 const _contracts = contracts.getOrElse(null);
135 const _web3 = web3.getOrElse(null);
136 const _wallet = wallet.getOrElse(null);
137 const _authToken = authToken.getOrElse(null);
138 const _details = getDetails(_point);
140 if (!_contracts || !_web3 || !_wallet || !_authToken || !_details) {
141 // not using need because we want a custom error
142 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
143 }
145 // if (Just.hasInstance(authMnemonic)) {
146 // throw new Error(
147 // "Auth key Error: A management mnemonic can't create invite codes"
148 // );
149 // }
150 let planets: UnspawnedPoints = await api.getUnspawned(_point);
152 const pendingTxs = await api.getPendingByShip(_point);
154 const pendingSpawns = getPendingSpawns(pendingTxs);
156 planets = planets.filter((point: number) => !pendingSpawns.has(point));
158 const starInfo = await api.getPoint(_point);
159 const invites: Invite[] = [];
160 const requests: Promise<string>[] = [];
162 const proxy = getSpawnProxy(starInfo.ownership!, _wallet.address);
164 if (proxy === undefined)
165 throw new Error("Error: Address doesn't match proxy");
167 const nonce = await api.getNonce({
168 ship: _point,
169 proxy,
170 });
172 for (let i = 0; i < numInvites && planets[i]; i++) {
173 setInviteGeneratingNum(i + 1);
174 const planet = planets[i];
175 const nonceInc = i + nonce;
177 const { ticket, inviteWallet } = await generateInviteWallet(
178 planet,
179 _authToken
180 );
182 const spawnRequest = spawn(
183 api,
184 _wallet,
185 _point,
186 proxy,
187 nonceInc,
188 planet
189 );
191 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
192 inviteWallet,
193 1
194 );
195 const configureKeysRequest = configureKeys(
196 api,
197 _wallet,
198 planet,
199 'own',
200 0,
201 networkSeed
202 );
204 const setManagementProxyRequest = registerProxyAddress(
205 api,
206 _wallet,
207 planet,
208 'own',
209 'manage',
210 1,
211 inviteWallet.management.keys.address
212 );
214 const transferRequest = transferPointRequest(
215 api,
216 _wallet,
217 planet,
218 'own',
219 2,
220 inviteWallet.ownership.keys.address
221 );
223 requests.push(
224 spawnRequest,
225 configureKeysRequest,
226 setManagementProxyRequest,
227 transferRequest
228 );
229 await Promise.all(requests);
231 invites.push({
232 hash: '',
233 ticket,
234 planet,
235 owner: inviteWallet.ownership.keys.address,
236 });
237 }
239 setStoredInvites(ls, invites);
240 },
241 [
242 api,
243 authToken,
244 contracts,
245 pointCursor,
246 wallet,
247 web3,
248 getDetails,
249 ls,
250 setInviteGeneratingNum,
251 ]
252 );
254 const getPoints = useCallback(
255 async (proxy: Proxy, address: EthAddress) => {
256 const points: Ship[] =
257 proxy === 'own'
258 ? await api.getOwnedPoints(address)
259 : proxy === 'manage'
260 ? await api.getManagerFor(address)
261 : proxy === 'vote'
262 ? await api.getVotingFor(address)
263 : proxy === 'transfer'
264 ? await api.getTransferringFor(address)
265 : proxy === 'spawn'
266 ? await api.getSpawningFor(address)
267 : [];
269 return points;
270 },
271 [api]
272 );
274 const getPendingTransactions = useCallback(async () => {
275 try {
276 const curPoint = Number(need.point(pointCursor));
277 const newPending = await api.getPendingByShip(curPoint);
279 setPendingTransactions(newPending);
280 } catch (error) {
281 console.warn('ERROR GETTING PENDING', error);
282 }
283 }, [api, setPendingTransactions, pointCursor]);
285 const generateInviteInfo = async (planet: number, _authToken: string) => {
286 const { ticket, inviteWallet } = await generateInviteWallet(
287 planet,
288 _authToken
289 );
291 return inviteTemplate(planet, ticket, inviteWallet.ownership.keys.address);
292 };
294 const getInvites = useCallback(
295 async (isL2: boolean, getAll = false) => {
296 try {
297 const curPoint: number = Number(need.point(pointCursor));
298 setInvites(invitePoints.map(p => inviteTemplate(p)));
300 const _authToken = authToken.getOrElse(null);
301 const _contracts = contracts.getOrElse(null);
303 if (_authToken && _contracts) {
304 const spawnedPoints = isL2 ? await api.getSpawned(curPoint) : [];
306 const availablePoints = await azimuth.azimuth.getUnspawnedChildren(
307 _contracts,
308 curPoint
309 );
311 const outgoingPoints = getOutgoingPoints(
312 controlledPoints,
313 getDetails
314 ).filter((p: number) => isPlanet(p) && availablePoints.includes(p));
316 const invitePlanets = spawnedPoints.concat(
317 outgoingPoints.filter((p: number) => !spawnedPoints.includes(p))
318 );
320 if (isDevelopment) {
321 console.log('INVITED PLANETS', invitePlanets);
322 }
324 const newInvites: Invite[] = [];
325 // Iterate over all of the stored invites, generating wallet info as necessary
326 const storedInvites = getStoredInvites(ls);
328 for (let i = 0; i < invitePlanets.length; i++) {
329 setInviteGeneratingNum(i + 1);
330 const planet = invitePlanets[i];
331 const invite = storedInvites[planet];
333 if (invite?.ticket) {
334 newInvites.push(invite);
335 } else if (getAll) {
336 if (isDevelopment) {
337 console.log('MISSING INVITE INFO', planet);
338 }
339 const newInvite = await generateInviteInfo(planet, _authToken);
340 newInvites.push(newInvite);
341 } else {
342 newInvites.push(inviteTemplate(planet));
343 }
344 }
346 setStoredInvites(ls, newInvites);
347 setInvites(newInvites);
349 return newInvites;
350 }
351 } catch (error) {
352 console.warn('ERROR GETTING INVITES', error);
353 }
354 },
355 [
356 api,
357 authToken,
358 contracts,
359 controlledPoints,
360 getDetails,
361 pointCursor,
362 invitePoints,
363 ls,
364 setInvites,
365 setInviteGeneratingNum,
366 ]
367 );
369 const showInvite = useCallback(
370 async (planet: number) => {
371 const _authToken = authToken.getOrElse(null);
373 if (_authToken) {
374 const newInvite = await generateInviteInfo(planet, _authToken);
375 const newInvites = invites.map(invite =>
376 invite.planet === planet ? newInvite : invite
377 );
378 setInvites(newInvites);
379 setStoredInvites(ls, newInvites);
380 }
381 },
382 [authToken, invites, ls, setInvites]
383 );
385 const getNumInvites = useCallback(
386 async (isL2: boolean) => {
387 try {
388 const curPoint: number = Number(need.point(pointCursor));
389 const _authToken = authToken.getOrElse(null);
390 const _contracts = contracts.getOrElse(null);
392 if (_authToken && _contracts) {
393 let invitePoints = isL2 ? await api.getSpawned(curPoint) : [];
395 const availablePoints = await azimuth.azimuth.getUnspawnedChildren(
396 _contracts,
397 curPoint
398 );
400 const newPending = await api.getPendingByShip(curPoint);
401 const pendingSpawns = getPendingSpawns(newPending);
403 const outgoingPoints = getOutgoingPoints(
404 controlledPoints,
405 getDetails
406 ).filter((p: number) => isPlanet(p) && availablePoints.includes(p));
408 setPendingTransactions(newPending);
409 setInvitePoints(
410 invitePoints
411 .concat(
412 outgoingPoints.filter((p: number) => !invitePoints.includes(p))
413 )
414 .filter((p: number) => !pendingSpawns.has(p))
415 );
416 }
417 } catch (e) {
418 if (isDevelopment) {
419 console.warn(e);
420 }
421 }
422 },
423 [
424 api,
425 pointCursor,
426 authToken,
427 contracts,
428 controlledPoints,
429 getDetails,
430 setInvitePoints,
431 setPendingTransactions,
432 ]
433 );
435 interface ConfigureKeysParams {
436 breach: boolean;
437 customNetworkSeed?: string;
438 }
440 const configureNetworkingKeys = async ({
441 breach,
442 customNetworkSeed,
443 }: ConfigureKeysParams) => {
444 const _point = need.point(pointCursor);
445 const azimuthPoint = await api.getPoint(_point);
446 const _wallet = wallet.getOrElse(null);
447 const _details = getDetails(_point);
448 if (!_wallet || !_details) {
449 // not using need because we want a custom error
450 throw new Error('Internal Error: Missing Wallet/Details');
451 }
453 const proxy = getManagerProxy(azimuthPoint.ownership!, _wallet.address);
455 if (proxy === undefined)
456 throw new Error("Error: Address doesn't match proxy");
458 const nonce = await api.getNonce({
459 ship: _point,
460 proxy,
461 });
463 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
464 const nextRevision = networkRevision + 1;
465 const networkSeed = customNetworkSeed
466 ? customNetworkSeed
467 : await attemptNetworkSeedDerivation({
468 urbitWallet,
469 wallet,
470 authMnemonic,
471 details: _details,
472 point: _point,
473 authToken,
474 revision: nextRevision,
475 });
476 const txHash = await configureKeys(
477 api,
478 _wallet,
479 _point,
480 proxy!,
481 nonce,
482 networkSeed,
483 breach
484 );
485 const pendingTx = await api.getPendingTx(txHash);
487 return pendingTx;
488 };
490 interface ReticketParams {
491 point: Ship;
492 to: EthAddress;
493 manager: EthAddress;
494 fromWallet: any; // TODO: wallet type
495 toWallet: any; // TODO: wallet type
496 }
498 const performL2Reticket = async ({
499 point,
500 to,
501 manager,
502 fromWallet,
503 toWallet,
504 }: ReticketParams) => {
505 const azimuthPoint = await api.getPoint(point);
506 const proxy = 'own';
507 let nonce = await api.getNonce({ ship: point, proxy });
509 let requests = [];
511 // 1. Update networking keys
512 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
513 const nextRevision = networkRevision + 1;
514 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
515 toWallet,
516 nextRevision
517 );
518 const configureKeysRequest = await configureKeys(
519 api,
520 fromWallet,
521 point,
522 proxy,
523 nonce,
524 networkSeed
525 );
526 nonce = nonce + 1;
527 requests.push(configureKeysRequest);
529 // 2. Set Management Proxy
530 const registerMgmtRequest = await registerProxyAddress(
531 api,
532 fromWallet,
533 point,
534 proxy,
535 'manage',
536 nonce,
537 manager
538 );
539 nonce = nonce + 1;
540 requests.push(registerMgmtRequest);
542 // 3. Set Spawn Proxy
543 if (!isPlanet(Number(point))) {
544 const registerSpawnRequest = await registerProxyAddress(
545 api,
546 fromWallet,
547 point,
548 proxy,
549 'spawn',
550 nonce,
551 toWallet.spawn.keys.address
552 );
553 nonce = nonce + 1;
554 requests.push(registerSpawnRequest);
555 }
556 // 4. Transfer point
557 const transferTxRequest = await transferPointRequest(
558 api,
559 fromWallet,
560 point,
561 proxy,
562 nonce,
563 to
564 );
565 requests.push(transferTxRequest);
567 const hashes = await Promise.all(requests);
568 return hashes;
569 };
571 const setProxyAddress = useCallback(
572 async (proxyType: Proxy, address: EthAddress) => {
573 const _point = need.point(pointCursor);
574 const _wallet = wallet.getOrElse(null);
576 if (!_wallet) {
577 // not using need because we want a custom error
578 throw new Error('Internal Error: Missing Wallet');
579 }
581 const pointDetails = await api.getPoint(_point);
582 const ownership = pointDetails.ownership!;
583 const proxy = getAddressProxy(ownership, _wallet.address, proxyType);
585 if (proxy === undefined)
586 throw new Error("Error: Address doesn't match expected proxy");
588 const nonce = await api.getNonce({ ship: _point, proxy });
590 const txHash = await registerProxyAddress(
591 api,
592 _wallet,
593 _point,
594 proxy,
595 proxyType,
596 nonce,
597 address
598 );
600 const pendingTx = await api.getPendingTx(txHash);
602 return pendingTx;
603 },
604 [api, pointCursor, wallet]
605 );
607 const transferPoint = useCallback(
608 async (address: EthAddress, reset?: boolean) => {
609 const _point = need.point(pointCursor);
610 const _wallet = wallet.getOrElse(null);
612 if (!_wallet) {
613 // not using need because we want a custom error
614 throw new Error('Internal Error: Missing Wallet');
615 }
617 const pointDetails = await api.getPoint(_point);
618 const proxy = getTransferProxy(pointDetails.ownership!, _wallet.address);
620 if (proxy === undefined)
621 throw new Error("Error: Address doesn't match proxy");
623 const nonce = await api.getNonce({ ship: _point, proxy });
625 const txHash = await transferPointRequest(
626 api,
627 _wallet,
628 _point,
629 proxy,
630 nonce,
631 address,
632 reset || false
633 );
634 const pendingTx = await api.getPendingTx(txHash);
636 return pendingTx;
637 },
638 [api, pointCursor, wallet]
639 );
641 // On load, get initial config
642 useEffect(() => {
643 if (config) {
644 return;
645 }
647 fetchConfig();
648 }, [config, fetchConfig]);
650 useEffect(() => {
651 const interval = setInterval(() => {
652 const nextRoll = getTimeToNextBatch(nextBatchTime, new Date().getTime());
653 setNextRoll(nextRoll);
655 if (nextBatchTime - ONE_SECOND <= new Date().getTime()) {
656 api.getRollerConfig().then(response => {
657 setNextBatchTime(response.nextBatch);
658 getNumInvites(currentL2);
659 });
660 }
661 }, 1000);
663 return () => clearInterval(interval);
664 }, [nextBatchTime, getPendingTransactions, currentL2]); // eslint-disable-line react-hooks/exhaustive-deps
666 return {
667 api,
668 performL2Reticket,
669 config,
670 getPoints,
671 getInvites,
672 getPendingTransactions,
673 generateInviteCodes,
674 transferPoint,
675 setProxyAddress,
676 configureNetworkingKeys,
677 getNumInvites,
678 showInvite,
679 ls,
680 };