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';
24} from './utils/proxy';
25import { isPlanet } from './utils/point';
28 deriveNetworkSeedFromUrbitWallet,
29 attemptNetworkSeedDerivation,
40} from '@urbit/roller-api';
48} from './utils/roller';
50const ONE_SECOND = 1000;
52const inviteTemplate = (
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;
79 setPendingTransactions,
82 setInviteGeneratingNum,
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
92 : ROLLER_HOSTS.MAINNET;
93 const port = isDevelopment && !isRopsten ? 8080 : 443;
94 const path = '/v1/roller';
106 const api = useMemo(() => {
107 return new RollerRPCAPI(options);
110 const fetchConfig = useCallback(async () => {
115 setNextBatchTime(response.nextBatch);
118 // TODO: more elegant error handling
120 '[fetchConfig:failed] check the roller connection?\n',
124 }, [api]); // eslint-disable-line react-hooks/exhaustive-deps
129 isCompression: false,
130 encryptionSecret: authToken.getOrElse('default'),
135 const generateInviteCodes = useCallback(
136 async (numInvites: number) => {
137 const _point = need.point(pointCursor);
138 const _contracts = contracts.getOrElse(null);
139 const _web3 = web3.getOrElse(null);
140 const _wallet = wallet.getOrElse(null);
141 const _authToken = authToken.getOrElse(null);
142 const _details = getDetails(_point);
144 if (!_contracts || !_web3 || !_wallet || !_authToken || !_details) {
145 // not using need because we want a custom error
146 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
149 // if (Just.hasInstance(authMnemonic)) {
151 // "Auth key Error: A management mnemonic can't create invite codes"
154 let planets: UnspawnedPoints = await api.getUnspawned(_point);
156 const pendingTxs = await api.getPendingByShip(_point);
158 const pendingSpawns = getPendingSpawns(pendingTxs);
160 planets = planets.filter((point: number) => !pendingSpawns.has(point));
162 const starInfo = await api.getPoint(_point);
163 const invites: Invite[] = [];
164 const requests: Promise<string>[] = [];
166 const proxy = getSpawnProxy(starInfo.ownership!, _wallet.address);
168 if (proxy === undefined)
169 throw new Error("Error: Address doesn't match proxy");
171 const nonce = await api.getNonce({
176 for (let i = 0; i < numInvites && planets[i]; i++) {
177 setInviteGeneratingNum(i + 1);
178 const planet = planets[i];
179 const nonceInc = i + nonce;
181 const { ticket, inviteWallet } = await generateInviteWallet(
186 const spawnRequest = spawn(
195 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
199 const configureKeysRequest = configureKeys(
208 const setManagementProxyRequest = registerProxyAddress(
215 inviteWallet.management.keys.address
218 const transferRequest = transferPointRequest(
224 inviteWallet.ownership.keys.address
229 configureKeysRequest,
230 setManagementProxyRequest,
233 await Promise.all(requests);
239 owner: inviteWallet.ownership.keys.address,
243 setStoredInvites(ls, invites);
254 setInviteGeneratingNum,
258 const getPoints = useCallback(
259 async (proxy: Proxy, address: EthAddress) => {
260 const points: Ship[] =
262 ? await api.getOwnedPoints(address)
264 ? await api.getManagerFor(address)
266 ? await api.getVotingFor(address)
267 : proxy === 'transfer'
268 ? await api.getTransferringFor(address)
270 ? await api.getSpawningFor(address)
278 const getPendingTransactions = useCallback(async () => {
280 const curPoint = Number(need.point(pointCursor));
281 const newPending = await api.getPendingByShip(curPoint);
283 setPendingTransactions(newPending);
285 console.warn('ERROR GETTING PENDING', error);
287 }, [api, setPendingTransactions, pointCursor]);
289 const generateInviteInfo = async (planet: number, _authToken: string) => {
290 const { ticket, inviteWallet } = await generateInviteWallet(
295 return inviteTemplate(planet, ticket, inviteWallet.ownership.keys.address);
298 const getInvites = useCallback(
299 async (isL2: boolean, getAll = false) => {
301 const curPoint: number = Number(need.point(pointCursor));
302 setInvites(invitePoints.map(p => inviteTemplate(p)));
304 const _authToken = authToken.getOrElse(null);
305 const _contracts = contracts.getOrElse(null);
307 if (_authToken && _contracts) {
308 const spawnedPoints = isL2 ? await api.getSpawned(curPoint) : [];
310 const availablePoints = await azimuth.azimuth.getUnspawnedChildren(
315 const outgoingPoints = getOutgoingPoints(
318 ).filter((p: number) => isPlanet(p) && availablePoints.includes(p));
320 const invitePlanets = spawnedPoints.concat(
321 outgoingPoints.filter((p: number) => !spawnedPoints.includes(p))
325 console.log('INVITED PLANETS', invitePlanets);
328 const newInvites: Invite[] = [];
329 // Iterate over all of the stored invites, generating wallet info as necessary
330 const storedInvites = getStoredInvites(ls);
332 for (let i = 0; i < invitePlanets.length; i++) {
333 setInviteGeneratingNum(i + 1);
334 const planet = invitePlanets[i];
335 const invite = storedInvites[planet];
337 if (invite?.ticket) {
338 newInvites.push(invite);
341 console.log('MISSING INVITE INFO', planet);
343 const newInvite = await generateInviteInfo(planet, _authToken);
344 newInvites.push(newInvite);
346 newInvites.push(inviteTemplate(planet));
350 setStoredInvites(ls, newInvites);
351 setInvites(newInvites);
356 console.warn('ERROR GETTING INVITES', error);
369 setInviteGeneratingNum,
373 const showInvite = useCallback(
374 async (planet: number) => {
375 const _authToken = authToken.getOrElse(null);
378 const newInvite = await generateInviteInfo(planet, _authToken);
379 const newInvites = invites.map(invite =>
380 invite.planet === planet ? newInvite : invite
382 setInvites(newInvites);
383 setStoredInvites(ls, newInvites);
386 [authToken, invites, ls, setInvites]
389 const getNumInvites = useCallback(
390 async (isL2: boolean) => {
392 const curPoint: number = Number(need.point(pointCursor));
393 const _authToken = authToken.getOrElse(null);
394 const _contracts = contracts.getOrElse(null);
396 if (_authToken && _contracts) {
397 let invitePoints = isL2 ? await api.getSpawned(curPoint) : [];
399 const availablePoints = await azimuth.azimuth.getUnspawnedChildren(
404 const newPending = await api.getPendingByShip(curPoint);
405 const pendingSpawns = getPendingSpawns(newPending);
407 const outgoingPoints = getOutgoingPoints(
410 ).filter((p: number) => isPlanet(p) && availablePoints.includes(p));
412 setPendingTransactions(newPending);
416 outgoingPoints.filter((p: number) => !invitePoints.includes(p))
418 .filter((p: number) => !pendingSpawns.has(p))
435 setPendingTransactions,
439 interface ConfigureKeysParams {
441 customNetworkSeed?: string;
444 const configureNetworkingKeys = async ({
447 }: ConfigureKeysParams) => {
448 const _point = need.point(pointCursor);
449 const azimuthPoint = await api.getPoint(_point);
450 const _wallet = wallet.getOrElse(null);
451 const _details = getDetails(_point);
452 if (!_wallet || !_details) {
453 // not using need because we want a custom error
454 throw new Error('Internal Error: Missing Wallet/Details');
457 const proxy = getManagerProxy(azimuthPoint.ownership!, _wallet.address);
459 if (proxy === undefined)
460 throw new Error("Error: Address doesn't match proxy");
462 const nonce = await api.getNonce({
467 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
468 const nextRevision = networkRevision + 1;
469 const networkSeed = customNetworkSeed
471 : await attemptNetworkSeedDerivation({
478 revision: nextRevision,
480 const txHash = await configureKeys(
489 const pendingTx = await api.getPendingTx(txHash);
494 interface ReticketParams {
498 fromWallet: any; // TODO: wallet type
499 toWallet: any; // TODO: wallet type
502 const performL2Reticket = async ({
508 }: ReticketParams) => {
509 const azimuthPoint = await api.getPoint(point);
511 let nonce = await api.getNonce({ ship: point, proxy });
515 // 1. Update networking keys
516 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
517 const nextRevision = networkRevision + 1;
518 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
522 const configureKeysRequest = await configureKeys(
531 requests.push(configureKeysRequest);
533 // 2. Set Management Proxy
534 const registerMgmtRequest = await registerProxyAddress(
544 requests.push(registerMgmtRequest);
546 // 3. Set Spawn Proxy
547 if (!isPlanet(Number(point))) {
548 const registerSpawnRequest = await registerProxyAddress(
555 toWallet.spawn.keys.address
558 requests.push(registerSpawnRequest);
561 const transferTxRequest = await transferPointRequest(
569 requests.push(transferTxRequest);
571 const hashes = await Promise.all(requests);
575 const setProxyAddress = useCallback(
576 async (proxyType: Proxy, address: EthAddress) => {
577 const _point = need.point(pointCursor);
578 const _wallet = wallet.getOrElse(null);
581 // not using need because we want a custom error
582 throw new Error('Internal Error: Missing Wallet');
585 const pointDetails = await api.getPoint(_point);
586 const ownership = pointDetails.ownership!;
587 const proxy = getAddressProxy(ownership, _wallet.address, proxyType);
589 if (proxy === undefined)
590 throw new Error("Error: Address doesn't match expected proxy");
592 const nonce = await api.getNonce({ ship: _point, proxy });
594 const txHash = await registerProxyAddress(
604 const pendingTx = await api.getPendingTx(txHash);
608 [api, pointCursor, wallet]
611 const transferPoint = useCallback(
612 async (address: EthAddress, reset?: boolean) => {
613 const _point = need.point(pointCursor);
614 const _wallet = wallet.getOrElse(null);
617 // not using need because we want a custom error
618 throw new Error('Internal Error: Missing Wallet');
621 const pointDetails = await api.getPoint(_point);
622 const proxy = getTransferProxy(pointDetails.ownership!, _wallet.address);
624 if (proxy === undefined)
625 throw new Error("Error: Address doesn't match proxy");
627 const nonce = await api.getNonce({ ship: _point, proxy });
629 const txHash = await transferPointRequest(
638 const pendingTx = await api.getPendingTx(txHash);
642 [api, pointCursor, wallet]
645 // On load, get initial config
652 }, [config, fetchConfig]);
655 const interval = setInterval(() => {
656 const nextRoll = getTimeToNextBatch(nextBatchTime, new Date().getTime());
657 setNextRoll(nextRoll);
659 if (nextBatchTime - ONE_SECOND <= new Date().getTime()) {
660 api.getRollerConfig().then(response => {
661 setNextBatchTime(response.nextBatch);
662 getNumInvites(currentL2);
667 return () => clearInterval(interval);
668 }, [nextBatchTime, getPendingTransactions, currentL2]); // eslint-disable-line react-hooks/exhaustive-deps
676 getPendingTransactions,
680 configureNetworkingKeys,
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list