1import { useCallback, useEffect, useMemo, useState } from 'react';
2import * as azimuth from 'azimuth-js';
3import * as need from 'lib/need';
4import * as ob from 'urbit-ob';
5import * as wg from 'lib/walletgen';
7import { convertToInt } from './convertToInt';
8import { ensureHexPrefix } from 'form/formatters';
9import { getOutgoingPoints, maybeGetResult } from 'views/Points';
10import { isDevelopment, isRopsten } from './flags';
11import { isPlanet } from './utils/point';
12import { ROLLER_HOSTS } from './constants';
13import { signTransactionHash } from './authToken';
14import { useNetwork } from 'store/network';
15import { usePointCache } from 'store/pointCache';
16import { usePointCursor } from 'store/pointCursor';
17import { useRollerStore } from 'store/roller';
18import { useWallet } from 'store/wallet';
23 deriveNetworkSeedFromUrbitWallet,
37} from '@urbit/roller-api';
44} from './utils/roller';
50} from 'store/storage/roller';
52const getProxyAndNonce = (
55): { proxy?: string; nonce?: number } => {
56 return point.ownership?.managementProxy?.address === address
57 ? { proxy: 'manage', nonce: point.ownership?.managementProxy.nonce }
58 : point.ownership?.owner?.address === address
59 ? { proxy: 'own', nonce: point.ownership?.owner.nonce }
60 : point.ownership?.spawnProxy?.address === address
61 ? { proxy: 'spawn', nonce: point.ownership?.spawn?.owner.nonce }
62 : point.ownership?.votingProxy?.address === address
63 ? { proxy: 'vote', nonce: point.ownership?.votingProxy?.owner.nonce }
64 : point.ownership?.transferProxy?.address === address
67 nonce: point.transferProxy?.votingProxy?.owner.nonce,
69 : { proxy: undefined, nonce: undefined };
72export default function useRoller() {
73 const { wallet, authToken, authMnemonic, urbitWallet }: any = useWallet();
74 const { pointCursor }: any = usePointCursor();
75 const { web3, contracts }: any = useNetwork();
76 const allPoints: any = usePointCache();
77 const controlledPoints = allPoints?.controlledPoints;
78 const getDetails = allPoints?.getDetails;
84 setPendingTransactions,
88 const [config, setConfig] = useState<Config | null>(null);
90 const options: Options = useMemo(() => {
91 const type = isRopsten || !isDevelopment ? 'https' : 'http';
92 const host = isRopsten
93 ? ROLLER_HOSTS.ROPSTEN
96 : ROLLER_HOSTS.MAINNET;
97 const port = isDevelopment ? 8080 : 80;
98 const path = '/v1/roller';
110 const api = useMemo(() => {
111 return new RollerRPCAPI(options);
114 const fetchConfig = useCallback(async () => {
119 setNextBatchTime(response.nextBatch);
122 // TODO: more elegant error handling
124 '[fetchConfig:failed] check the roller connection?\n',
128 }, [api]); // eslint-disable-line react-hooks/exhaustive-deps
130 const generateInviteCodes = useCallback(
131 async (numInvites: number) => {
132 const _point = need.point(pointCursor);
133 const _contracts = contracts.getOrElse(null);
134 const _web3 = web3.getOrElse(null);
135 const _wallet = wallet.getOrElse(null);
136 const _authToken = authToken.getOrElse(null);
137 const _details = getDetails(_point);
138 if (!_contracts || !_web3 || !_wallet || !_authToken || !_details) {
139 // not using need because we want a custom error
140 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
143 const planets: UnspawnedPoints = await api.getUnspawned(_point);
144 const starInfo = await api.getPoint(_point);
146 const tickets: { ticket: string; planet: number; owner: string }[] = [];
147 const requests: Promise<string>[] = [];
149 const { proxy, nonce } = getProxyAndNonce(starInfo, _wallet.address);
151 if (!(proxy === 'own' || proxy === 'spawn') || nonce === undefined)
152 throw new Error("Error: Address doesn't match proxy");
154 for (let i = 0; i < numInvites && planets[i]; i++) {
155 const planet = planets[i];
156 const nonceInc = i + nonce;
158 const { ticket, owner } = await wg.generateTemporaryDeterministicWallet(
163 const spawnRequest = await spawn(
172 const configureKeysRequest = await configureKeys(
185 const transferPointRequest = await transferPoint(
194 requests.push(spawnRequest, configureKeysRequest, transferPointRequest);
198 owner: owner.keys.address,
202 const hashes = await Promise.all(requests);
204 const pendingInvites = tickets.map((ticket, ind) => ({
206 hash: hashes[ind * 3 + 2],
210 setPendingInvites(_point, pendingInvites);
227 const getPoints = useCallback(
228 async (proxy: Proxy, address: EthAddress) => {
229 const points: Ship[] =
231 ? await api.getOwnedPoints(address)
233 ? await api.getManagerFor(address)
235 ? await api.getVotingFor(address)
236 : proxy === 'transfer'
237 ? await api.getTransferringFor(address)
239 ? await api.getSpawningFor(address)
247 const getPendingTransactions = useCallback(async () => {
249 const curPoint = Number(need.point(pointCursor));
250 const newPending = await api.getPendingByShip(curPoint);
251 setPendingTransactions(newPending);
253 // const allTransactions = await api.getHistory()
255 console.warn('ERROR GETTING PENDING', error);
257 }, [api, setPendingTransactions, pointCursor]);
259 const getInvites = useCallback(
260 async (isL2: boolean) => {
262 const curPoint: number = Number(need.point(pointCursor));
263 const invites = getStoredInvites(curPoint);
264 const availableInvites = invites.available;
266 const pendingTransactions = await api.getPendingByShip(curPoint);
268 console.log('PENDING', pendingTransactions);
270 setPendingTransactions(pendingTransactions);
272 const stillPending = invites.pending.filter(invite => {
273 const completed = !pendingTransactions.find(
274 p => `~${p?.rawTx?.tx?.data?.ship}` === ob.patp(invite.planet)
279 !availableInvites.find(({ ship }) => invite.ship === ship)
281 availableInvites.push({ ...invite, status: 'available' });
287 setStoredInvites(curPoint, {
288 available: availableInvites,
289 pending: stillPending,
291 setInvites(availableInvites);
293 const _authToken = authToken.getOrElse(null);
294 const _contracts = contracts.getOrElse(null);
296 if (_authToken && _contracts) {
297 let possibleMissingInvites: number[] = [];
299 const allSpawned = await api.getSpawned(curPoint);
300 const ownedPoints = maybeGetResult(
305 possibleMissingInvites = allSpawned.filter(
306 (p: number) => ownedPoints.includes(p) && isPlanet(p)
310 const outgoingPoints = getOutgoingPoints(
315 const availablePoints = await azimuth.azimuth.getUnspawnedChildren(
320 possibleMissingInvites = possibleMissingInvites.concat(
321 outgoingPoints.filter(
322 (p: number) => isPlanet(p) && availablePoints.includes(p)
326 // Iterate over all spawned and controlled planets
327 // If the planet is not in available invites, generate the ticket and add it
329 console.log('POSSIBLE MISSING', possibleMissingInvites);
332 for (let i = 0; i < possibleMissingInvites.length; i++) {
333 const planet = possibleMissingInvites[i];
336 !availableInvites.find(hasPoint(planet)) &&
337 !(await azimuth.azimuth.isActive(_contracts, planet))
339 console.log('MISSING IN AVAILABLE', planet);
343 } = await wg.generateTemporaryDeterministicWallet(
348 availableInvites.push({
353 owner: owner.keys.address,
358 setStoredInvites(curPoint, {
359 available: availableInvites.filter(({ planet }) =>
360 possibleMissingInvites.includes(planet)
362 pending: stillPending,
364 setInvites(availableInvites);
367 console.warn('ERROR GETTING INVITES', error);
374 setPendingTransactions,
382 // TODO: extract from #transferPoint
383 // interface ConfigureKeysParams {
387 // const configureKeys = async () => {
391 interface AcceptInviteParams {
394 fromWallet: any; // TODO: wallet type
395 toWallet: any; // TODO: wallet type
398 const acceptInvite = async ({
403 }: AcceptInviteParams) => {
404 const azimuthPoint = await api.getPoint(point);
405 const spawnerPatp = ob.patp(azimuthPoint?.network?.sponsor?.who);
406 console.log('azimuthPoint', azimuthPoint);
407 const ownerAddress = azimuthPoint?.ownership?.owner?.address!;
409 const { nonce } = getProxyAndNonce(azimuthPoint, ownerAddress);
410 if (nonce === undefined) {
411 throw new Error('Nonce unavailable');
414 // 1. Update networking keys
415 // TODO: extract this to a useRoller#configureKeys function?
416 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
417 const nextRevision = networkRevision + 1;
418 const fromOwnerProxy: From = {
423 const seed = await deriveNetworkSeedFromUrbitWallet(toWallet, nextRevision);
424 const keys = deriveNetworkKeys(seed.value);
426 auth: ensureHexPrefix(keys.auth.public),
428 cryptoSuite: CRYPTO_SUITE_VERSION.toString(),
429 encrypt: ensureHexPrefix(keys.crypt.public),
432 const keysHash: Hash = await api.hashTransaction(
439 const keysSigningKey = fromWallet.privateKey;
440 await api.configureKeys(
441 signTransactionHash(keysHash, Buffer.from(keysSigningKey, 'hex')),
448 const transferData = { address: ownerAddress, reset: false };
449 const transferHash: Hash = await api.hashTransaction(
456 const transferSigningKey = toWallet.ownership.keys.private;
457 const transferTxHash = await api.transferPoint(
458 signTransactionHash(transferHash, Buffer.from(transferSigningKey, 'hex')),
464 return transferTxHash;
467 // On load, get initial config
474 }, [config, fetchConfig]);
477 const interval = setInterval(() => {
478 const nextRoll = getTimeToNextBatch(nextBatchTime, new Date().getTime());
479 setNextRoll(nextRoll);
481 if (nextBatchTime <= new Date().getTime()) {
482 api.getRollerConfig().then(response => {
483 setNextBatchTime(response.nextBatch);
486 getInvites(currentL2);
490 return () => clearInterval(interval);
491 }, [nextBatchTime, getPendingTransactions, currentL2]); // eslint-disable-line react-hooks/exhaustive-deps
499 getPendingTransactions,
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