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 { Just } from 'folktale/maybe';
7import { Invite } from 'lib/types/Invite';
8import { convertToInt } from './convertToInt';
9import { ensureHexPrefix } from 'form/formatters';
10import { getOutgoingPoints } from 'views/Points';
11import { isDevelopment, isRopsten } from './flags';
12import { isPlanet } from './utils/point';
13import { hasPoint, generateInviteWallet } from './utils/roller';
14import { ROLLER_HOSTS } from './constants';
15import { signTransactionHash } from './authToken';
16import { useNetwork } from 'store/network';
17import { usePointCache } from 'store/pointCache';
18import { usePointCursor } from 'store/pointCursor';
19import { useRollerStore } from 'store/roller';
20import { useWallet } from 'store/wallet';
25 deriveNetworkSeedFromUrbitWallet,
39} from '@urbit/roller-api';
46} from './utils/roller';
52} from 'store/storage/roller';
54const getProxyAndNonce = (
57): { proxy?: string; nonce?: number } => {
58 return point.ownership?.managementProxy?.address === address
59 ? { proxy: 'manage', nonce: point.ownership?.managementProxy.nonce }
60 : point.ownership?.owner?.address === address
61 ? { proxy: 'own', nonce: point.ownership?.owner.nonce }
62 : point.ownership?.spawnProxy?.address === address
63 ? { proxy: 'spawn', nonce: point.ownership?.spawn?.owner.nonce }
64 : point.ownership?.votingProxy?.address === address
65 ? { proxy: 'vote', nonce: point.ownership?.votingProxy?.owner.nonce }
66 : point.ownership?.transferProxy?.address === address
69 nonce: point.transferProxy?.votingProxy?.owner.nonce,
71 : { proxy: undefined, nonce: undefined };
74export default function useRoller() {
75 const { wallet, authToken, authMnemonic, urbitWallet }: any = useWallet();
76 const { pointCursor }: any = usePointCursor();
77 const { web3, contracts }: any = useNetwork();
78 const allPoints: any = usePointCache();
79 const controlledPoints = allPoints?.controlledPoints;
80 const getDetails = allPoints?.getDetails;
86 setPendingTransactions,
90 const [config, setConfig] = useState<Config | null>(null);
92 const options: Options = useMemo(() => {
93 const type = isRopsten || !isDevelopment ? 'https' : 'http';
94 const host = isRopsten
95 ? ROLLER_HOSTS.ROPSTEN
98 : ROLLER_HOSTS.MAINNET;
99 const port = isRopsten ? 443 : 8080;
100 const path = '/v1/roller';
112 const api = useMemo(() => {
113 return new RollerRPCAPI(options);
116 const fetchConfig = useCallback(async () => {
121 setNextBatchTime(response.nextBatch);
124 // TODO: more elegant error handling
126 '[fetchConfig:failed] check the roller connection?\n',
130 }, [api]); // eslint-disable-line react-hooks/exhaustive-deps
132 const generateInviteCodes = useCallback(
133 async (numInvites: number) => {
134 const _point = need.point(pointCursor);
135 const _contracts = contracts.getOrElse(null);
136 const _web3 = web3.getOrElse(null);
137 const _wallet = wallet.getOrElse(null);
138 const _authToken = authToken.getOrElse(null);
139 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');
145 if (Just.hasInstance(authMnemonic)) {
147 "Auth key Error: A management mnemonic can't create invite codes"
150 const planets: UnspawnedPoints = await api.getUnspawned(_point);
151 const starInfo = await api.getPoint(_point);
158 const requests: Promise<string>[] = [];
160 // TODO: replace with "currentNonce" from store, that would reflect the latest nonce
161 // Bridge has used for the star _wallet.address
163 const { proxy, nonce } = getProxyAndNonce(starInfo, _wallet.address);
165 if (!(proxy === 'own' || proxy === 'spawn') || nonce === undefined)
166 throw new Error("Error: Address doesn't match proxy");
168 for (let i = 0; i < numInvites && planets[i]; i++) {
169 const planet = planets[i];
170 const nonceInc = i + nonce;
172 const { ticket, owner } = await generateInviteWallet(
177 const spawnRequest = await spawn(
186 const configureKeysRequest = await configureKeys(
199 const transferPointRequest = await transferPoint(
208 requests.push(spawnRequest, configureKeysRequest, transferPointRequest);
212 owner: owner.keys.address,
216 const hashes = await Promise.all(requests);
218 const pendingInvites: Invite[] = tickets.map((ticket, ind) => ({
220 hash: hashes[ind * 3 + 2],
224 setPendingInvites(_point, pendingInvites);
239 const getPoints = useCallback(
240 async (proxy: Proxy, address: EthAddress) => {
241 const points: Ship[] =
243 ? await api.getOwnedPoints(address)
245 ? await api.getManagerFor(address)
247 ? await api.getVotingFor(address)
248 : proxy === 'transfer'
249 ? await api.getTransferringFor(address)
251 ? await api.getSpawningFor(address)
259 const getPendingTransactions = useCallback(async () => {
261 const curPoint = Number(need.point(pointCursor));
262 const newPending = await api.getPendingByShip(curPoint);
263 setPendingTransactions(newPending);
265 // const allTransactions = await api.getHistory()
267 console.warn('ERROR GETTING PENDING', error);
269 }, [api, setPendingTransactions, pointCursor]);
271 const getInvites = useCallback(
272 async (isL2: boolean) => {
274 const curPoint: number = Number(need.point(pointCursor));
275 const invites = getStoredInvites(curPoint);
276 const availableInvites = invites.available;
277 const pendingTransactions = await api.getPendingByShip(curPoint);
279 console.log('PENDING', pendingTransactions);
281 setPendingTransactions(pendingTransactions);
283 const stillPending = invites.pending.filter(invite => {
284 const completed = !pendingTransactions.find(
285 p => `~${p?.rawTx?.tx?.data?.ship}` === ob.patp(invite.planet)
290 !availableInvites.find(({ planet }) => invite.planet === planet)
292 availableInvites.push({ ...invite, status: 'available' });
298 setStoredInvites(curPoint, {
299 available: availableInvites,
300 pending: stillPending,
302 setInvites(availableInvites);
304 const _authToken = authToken.getOrElse(null);
305 const _contracts = contracts.getOrElse(null);
307 if (_authToken && _contracts) {
308 let possibleMissingInvites: number[] = [];
309 let availablePoints: number[] = [];
311 possibleMissingInvites = await api.getSpawned(curPoint);
312 availablePoints = await api.getUnspawned(curPoint);
314 // TODO: should it be removed?
315 availablePoints = await azimuth.azimuth.getUnspawnedChildren(
321 const outgoingPoints = getOutgoingPoints(
326 possibleMissingInvites = possibleMissingInvites.concat(
327 outgoingPoints.filter(
328 (p: number) => isPlanet(p) && availablePoints.includes(p)
332 // Iterate over all spawned and controlled planets
333 // If the planet is not in available invites, generate the ticket and add it
335 console.log('POSSIBLE MISSING', possibleMissingInvites);
337 // TODO: this can be verym slow, so best to allow the user to manually
338 // reveal the ticket, after checking if the invite is still "active"
339 // (i.e. if the address inferred from the derived inviteWallet corresponds to
340 // to the address the point has as owner)
342 for (let i = 0; i < possibleMissingInvites.length; i++) {
343 const planet = possibleMissingInvites[i];
344 if (!availableInvites.find(hasPoint(planet))) {
345 console.log('MISSING IN AVAILABLE', planet);
346 const { ticket, owner } = await generateInviteWallet(
351 availableInvites.push({
356 owner: owner.keys.address,
361 setStoredInvites(curPoint, {
362 available: availableInvites.filter(({ planet }) =>
363 possibleMissingInvites.includes(planet)
365 pending: stillPending,
367 setInvites(availableInvites);
370 console.warn('ERROR GETTING INVITES', error);
377 setPendingTransactions,
385 // TODO: extract from #transferPoint
386 // interface ConfigureKeysParams {
390 // const configureKeys = async () => {
394 interface AcceptInviteParams {
397 fromWallet: any; // TODO: wallet type
398 toWallet: any; // TODO: wallet type
401 const acceptInvite = async ({
406 }: AcceptInviteParams) => {
407 const azimuthPoint = await api.getPoint(point);
408 console.log('azimuthPoint', azimuthPoint);
409 const ownerAddress = azimuthPoint?.ownership?.owner?.address!;
411 const { nonce } = getProxyAndNonce(azimuthPoint, ownerAddress);
412 if (nonce === undefined) {
413 throw new Error('Nonce unavailable');
416 // 1. Update networking keys
417 // TODO: extract this to a useRoller#configureKeys function?
418 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
419 const nextRevision = networkRevision + 1;
420 const fromOwnerProxy: From = {
425 const seed = await deriveNetworkSeedFromUrbitWallet(toWallet, nextRevision);
426 const keys = deriveNetworkKeys(seed.value);
428 auth: ensureHexPrefix(keys.auth.public),
430 cryptoSuite: CRYPTO_SUITE_VERSION.toString(),
431 encrypt: ensureHexPrefix(keys.crypt.public),
434 const keysHash: Hash = await api.hashTransaction(
441 const keysSigningKey = fromWallet.privateKey;
442 await api.configureKeys(
443 signTransactionHash(keysHash, Buffer.from(keysSigningKey, 'hex')),
450 const transferData = { address: to, reset: false };
451 const transferHash: Hash = await api.hashTransaction(
458 const transferTxHash = await api.transferPoint(
459 signTransactionHash(transferHash, Buffer.from(keysSigningKey, 'hex')),
465 return transferTxHash;
468 // On load, get initial config
475 }, [config, fetchConfig]);
478 const interval = setInterval(() => {
479 const nextRoll = getTimeToNextBatch(nextBatchTime, new Date().getTime());
480 setNextRoll(nextRoll);
482 if (nextBatchTime <= new Date().getTime()) {
483 api.getRollerConfig().then(response => {
484 setNextBatchTime(response.nextBatch);
487 getInvites(currentL2);
491 return () => clearInterval(interval);
492 }, [nextBatchTime, getPendingTransactions, currentL2]); // eslint-disable-line react-hooks/exhaustive-deps
500 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