1import { useCallback, useEffect, useMemo, useState } from 'react';
3import * as azimuth from 'azimuth-js';
4import * as need from 'lib/need';
5import * as ob from 'urbit-ob';
6import { Just } from 'folktale/maybe';
8import { Invite } from 'lib/types/Invite';
9import { convertToInt } from './convertToInt';
10import { isDevelopment, isRopsten } from './flags';
11import { hasPoint, generateInviteWallet } from './utils/roller';
12import { ROLLER_HOSTS } from './constants';
14import { useNetwork } from 'store/network';
15import { usePointCursor } from 'store/pointCursor';
16import { useRollerStore } from 'store/roller';
17import { useWallet } from 'store/wallet';
22} from 'store/storage/roller';
23import { usePointCache } from 'store/pointCache';
24import { getOutgoingPoints } from 'views/Points';
30} from './utils/nonce';
31import { isPlanet } from './utils/point';
34 deriveNetworkSeedFromUrbitWallet,
35 attemptNetworkSeedDerivation,
48} from '@urbit/roller-api';
56} from './utils/roller';
58function isSpawn(tx: L2Data | undefined): tx is SpawnParams {
59 return (tx as SpawnParams) !== undefined;
62function isShipNumber(ship: number | string | undefined): ship is number {
63 return (ship as number) !== undefined;
66export default function useRoller() {
67 const { wallet, authToken, authMnemonic, urbitWallet }: any = useWallet();
68 const { pointCursor }: any = usePointCursor();
69 const { web3, contracts }: any = useNetwork();
70 const allPoints: any = usePointCache();
71 const controlledPoints = allPoints?.controlledPoints;
72 const getDetails = allPoints?.getDetails;
78 setPendingTransactions,
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 = isRopsten ? 443 : 8080;
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
126 const generateInviteCodes = useCallback(
127 async (numInvites: number) => {
128 const _point = need.point(pointCursor);
129 const _contracts = contracts.getOrElse(null);
130 const _web3 = web3.getOrElse(null);
131 const _wallet = wallet.getOrElse(null);
132 const _authToken = authToken.getOrElse(null);
133 const _details = getDetails(_point);
135 if (!_contracts || !_web3 || !_wallet || !_authToken || !_details) {
136 // not using need because we want a custom error
137 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
140 if (Just.hasInstance(authMnemonic)) {
142 "Auth key Error: A management mnemonic can't create invite codes"
145 let planets: UnspawnedPoints = await api.getUnspawned(_point);
147 const pendingTxs = await api.getPendingByShip(_point);
149 const pendingSpawns = _.reduce(
152 return isSpawn(pending.rawTx?.tx) &&
153 isShipNumber(pending.rawTx?.tx.data.ship)
154 ? acc.add(pending.rawTx?.tx.data.ship!)
160 console.log(pendingTxs, pendingSpawns);
162 planets = planets.filter((point: number) => !pendingSpawns.has(point));
164 const starInfo = nonces[_point];
165 console.log(starInfo);
171 const requests: Promise<string>[] = [];
174 getSpawnNonce(starInfo, _wallet.address) ||
175 getOwnerNonce(starInfo, _wallet.address);
177 if (operator === undefined)
178 throw new Error("Error: Address doesn't match proxy");
179 console.log('operator', operator);
180 for (let i = 0; i < numInvites && planets[i]; i++) {
181 const planet = planets[i];
182 const nonceInc = i + operator.nonce!;
184 const { ticket, inviteWallet } = await generateInviteWallet(
189 const spawnRequest = await spawn(
197 increaseNonce(_point, operator.proxy!);
199 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
203 const configureKeysRequest = await configureKeys(
212 const setManagementProxyRequest = await registerProxyAddress(
219 inviteWallet.management.keys.address
222 const transferRequest = await transferPointRequest(
228 inviteWallet.ownership.keys.address
233 configureKeysRequest,
234 setManagementProxyRequest,
240 owner: inviteWallet.ownership.keys.address,
244 const hashes = await Promise.all(requests);
246 const pendingInvites: Invite[] = tickets.map((ticket, ind) => ({
248 hash: hashes[ind * 3 + 2],
252 console.log('latest update', nonces[_point]);
253 setPendingInvites(_point, pendingInvites);
269 const getPoints = useCallback(
270 async (proxy: Proxy, address: EthAddress) => {
271 const points: Ship[] =
273 ? await api.getOwnedPoints(address)
275 ? await api.getManagerFor(address)
277 ? await api.getVotingFor(address)
278 : proxy === 'transfer'
279 ? await api.getTransferringFor(address)
281 ? await api.getSpawningFor(address)
289 const getPendingTransactions = useCallback(async () => {
291 const curPoint = Number(need.point(pointCursor));
292 const newPending = await api.getPendingByShip(curPoint);
293 setPendingTransactions(newPending);
295 // const allTransactions = await api.getHistory()
297 console.warn('ERROR GETTING PENDING', error);
299 }, [api, setPendingTransactions, pointCursor]);
301 const getInvites = useCallback(
302 async (isL2: boolean) => {
304 const curPoint: number = Number(need.point(pointCursor));
305 const invites = getStoredInvites(curPoint);
306 const availableInvites = invites.available;
307 const pendingTransactions = await api.getPendingByShip(curPoint);
309 console.log('PENDING', pendingTransactions);
311 setPendingTransactions(pendingTransactions);
313 const stillPending = invites.pending.filter(invite => {
314 const completed = !pendingTransactions.find(
315 p => `~${p?.rawTx?.tx?.data?.ship}` === ob.patp(invite.planet)
320 !availableInvites.find(({ planet }) => invite.planet === planet)
322 availableInvites.push({ ...invite, status: 'available' });
328 setStoredInvites(curPoint, {
329 available: availableInvites,
330 pending: stillPending,
332 setInvites(availableInvites);
334 const _authToken = authToken.getOrElse(null);
335 const _contracts = contracts.getOrElse(null);
337 if (_authToken && _contracts) {
338 let possibleMissingInvites: number[] = [];
339 let availablePoints: number[] = [];
341 possibleMissingInvites = await api.getSpawned(curPoint);
342 availablePoints = await api.getUnspawned(curPoint);
344 // TODO: should it be removed?
345 availablePoints = await azimuth.azimuth.getUnspawnedChildren(
351 const outgoingPoints = getOutgoingPoints(
356 possibleMissingInvites = possibleMissingInvites.concat(
357 outgoingPoints.filter(
358 (p: number) => isPlanet(p) && availablePoints.includes(p)
362 // Iterate over all spawned and controlled planets
363 // If the planet is not in available invites, generate the ticket and add it
365 console.log('POSSIBLE MISSING', possibleMissingInvites);
367 // TODO: this can be verym slow, so best to allow the user to manually
368 // reveal the ticket, after checking if the invite is still "active"
369 // (i.e. if the address inferred from the derived inviteWallet corresponds to
370 // to the address the point has as owner)
372 for (let i = 0; i < possibleMissingInvites.length; i++) {
373 const planet = possibleMissingInvites[i];
374 if (!availableInvites.find(hasPoint(planet))) {
375 console.log('MISSING IN AVAILABLE', planet);
376 const { ticket, inviteWallet } = await generateInviteWallet(
381 availableInvites.push({
386 owner: inviteWallet.ownership.keys.address,
391 setStoredInvites(curPoint, {
392 available: availableInvites.filter(({ planet }) =>
393 possibleMissingInvites.includes(planet)
395 pending: stillPending,
397 setInvites(availableInvites);
400 console.warn('ERROR GETTING INVITES', error);
411 setPendingTransactions,
415 interface ConfigureKeysParams {
417 customNetworkSeed?: string;
420 const configureNetworkingKeys = async ({
423 }: ConfigureKeysParams) => {
424 const _point = need.point(pointCursor);
425 const azimuthPoint = await api.getPoint(_point);
426 const _wallet = wallet.getOrElse(null);
427 const _details = getDetails(_point);
428 if (!_wallet || !_details) {
429 // not using need because we want a custom error
430 throw new Error('Internal Error: Missing Wallet/Details');
433 const pointDetails = nonces[_point];
435 getManagementNonce(pointDetails, _wallet.address) ||
436 getOwnerNonce(pointDetails, _wallet.address);
437 if (operator === undefined)
438 throw new Error("Error: Address doesn't match proxy");
439 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
440 const nextRevision = networkRevision + 1;
441 const networkSeed = customNetworkSeed
443 : await attemptNetworkSeedDerivation({
450 revision: nextRevision,
452 const txHash = await configureKeys(
461 const pendingTx = await api.getPendingTx(txHash);
466 interface AcceptInviteParams {
470 fromWallet: any; // TODO: wallet type
471 toWallet: any; // TODO: wallet type
474 const acceptInvite = async ({
480 }: AcceptInviteParams) => {
481 const azimuthPoint = await api.getPoint(point);
482 console.log('azimuthPoint', azimuthPoint);
483 const ownerAddress = azimuthPoint?.ownership?.owner?.address!;
486 azimuthPoint.ownership &&
487 getOwnerNonce(azimuthPoint.ownership, ownerAddress);
489 if (operator === undefined)
490 throw new Error("Error: Address doesn't match proxy");
492 const nonce = operator.nonce!;
494 // 1. Update networking keys
495 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
496 const nextRevision = networkRevision + 1;
497 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
501 const configureKeysRequest = await configureKeys(
510 // TODO: not needed? next time we operate with this point we will login, and get
511 // the latest nonce (updated with any nonce increase from possible pending txs)
512 // increaseNonce(point, operator.proxy!);
514 // 2. Set Management Proxy
515 const registerProxyAddressRequest = await registerProxyAddress(
526 const transferTxRequest = await transferPointRequest(
534 const hashes = await Promise.all([
535 configureKeysRequest,
536 registerProxyAddressRequest,
542 const setProxyAddress = useCallback(
543 async (proxyType: Proxy, address: EthAddress) => {
544 const _point = need.point(pointCursor);
545 const _wallet = wallet.getOrElse(null);
548 // not using need because we want a custom error
549 throw new Error('Internal Error: Missing Wallet');
552 const pointDetails = nonces[_point];
554 getManagementNonce(pointDetails, _wallet.address) ||
555 getOwnerNonce(pointDetails, _wallet.address);
557 if (operator === undefined)
558 throw new Error("Error: Address doesn't match proxy");
560 const txHash = await registerProxyAddress(
570 const pendingTx = await api.getPendingTx(txHash);
574 [api, pointCursor, wallet, nonces]
577 const transferPoint = useCallback(
578 async (address: EthAddress, reset?: boolean) => {
579 const _point = need.point(pointCursor);
580 const _wallet = wallet.getOrElse(null);
583 // not using need because we want a custom error
584 throw new Error('Internal Error: Missing Wallet');
587 const pointDetails = nonces[_point];
589 getTransferNonce(pointDetails, _wallet.address) ||
590 getOwnerNonce(pointDetails, _wallet.address);
592 if (operator === undefined)
593 throw new Error("Error: Address doesn't match proxy");
595 const txHash = await transferPointRequest(
604 const pendingTx = await api.getPendingTx(txHash);
608 [api, pointCursor, wallet, nonces]
611 // On load, get initial config
618 }, [config, fetchConfig]);
621 const interval = setInterval(() => {
622 const nextRoll = getTimeToNextBatch(nextBatchTime, new Date().getTime());
623 setNextRoll(nextRoll);
625 if (nextBatchTime <= new Date().getTime()) {
626 api.getRollerConfig().then(response => {
627 setNextBatchTime(response.nextBatch);
630 getInvites(currentL2);
634 return () => clearInterval(interval);
635 }, [nextBatchTime, getPendingTransactions, currentL2]); // eslint-disable-line react-hooks/exhaustive-deps
643 getPendingTransactions,
647 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