1import { useCallback, useEffect, useMemo, useState } from 'react';
2import * as azimuth from 'azimuth-js';
3import * as need from 'lib/need';
4import SecureLS from 'secure-ls';
7 deriveNetworkSeedFromUrbitWallet,
8 attemptNetworkSeedDerivation,
11import { useNetwork } from 'store/network';
12import { usePointCursor } from 'store/pointCursor';
13import { EMPTY_POINT, useRollerStore } from 'store/rollerStore';
14import { useWallet } from 'store/wallet';
15import { usePointCache } from 'store/pointCache';
17import { getUpdatedPointMessage, isPlanet, toL1Details } from './utils/point';
18import { convertToInt } from './convertToInt';
19import { isDevelopment } from './flags';
24} from './utils/roller';
25import { TEN_SECONDS } from './constants';
33} from '@urbit/roller-api';
35import Point, { PointField, Points } from './types/Point';
36import { ReticketParams, SendL2Params } from './types/L2Transaction';
37import { L1Point } from './types/L1Point';
38import { ddmmmYYYY } from './utils/date';
39import { showNotification } from './utils/notifications';
40import { useWalletConnect } from './useWalletConnect';
41import { PendingL1Txn } from './types/PendingL1Transaction';
42import { TRANSACTION_PROGRESS } from './reticket';
43import { useRollerOptions } from './useRollerOptions';
44import { useTimerStore } from 'store/timerStore';
46interface UpdateParams {
52 intervalTime?: number;
55export default function useRoller() {
63 const { connector } = useWalletConnect();
64 const { pointCursor }: any = usePointCursor();
65 const { web3, contracts }: any = useNetwork();
66 const allPoints: any = usePointCache();
67 const getDetails = allPoints?.getDetails;
74 setPendingTransactions,
81 const { setNextBatchTime } = useTimerStore();
82 const [config, setConfig] = useState<Config | null>(null);
84 const { options } = useRollerOptions();
86 const api = useMemo(() => {
87 return new RollerRPCAPI(options);
94 encryptionSecret: authToken.getOrElse('default'),
99 const getNextQuotaTime = useCallback(
100 (nextSlice: number) => {
105 setNextQuotaTime(next);
106 getNextQuotaTime(next);
108 .catch(err => console.warn(err));
109 }, nextSlice - new Date().getTime());
111 [api, setNextQuotaTime]
114 const fetchConfig = useCallback(async () => {
115 getNextQuotaTime(Date.now() + 1000);
120 setNextBatchTime(config.nextBatch);
123 // TODO: more elegant error handling
125 '[fetchConfig:failed] check the roller connection?\n',
129 }, [api, getNextQuotaTime, setNextBatchTime]);
131 const quotaReached = useCallback(() => {
132 if (point.l2Quota <= 0) {
134 `You have reached your weekly L2 transaction limit. You will get another
135 ${point.l2Allowance} transactions on ${ddmmmYYYY(nextQuotaTime)}.`
139 return point.l2Quota <= 0;
140 }, [nextQuotaTime, point, setModalText]);
142 const initPoint = useCallback(
143 async (point: string | number) => {
144 const _wallet = wallet.getOrElse(null);
145 const _contracts = contracts.getOrElse(null);
147 if (!_wallet || !_contracts) {
151 const pointNum = Number(point);
153 const rawDetails = await api.getPoint(pointNum);
154 const isL2 = isL2Spawn(rawDetails?.dominion);
155 const l2Quota = isL2 ? await api.getRemainingQuota(pointNum) : 0;
156 const l2Allowance = isL2 ? await api.getAllowance(pointNum) : 0;
158 const details = isL2Spawn(rawDetails?.dominion)
159 ? toL1Details(rawDetails)
160 : await azimuth.azimuth.getPoint(_contracts, point);
165 address: _wallet.address,
172 // Try getting the details from L1
174 const _contracts = need.contracts(contracts);
175 const details = await azimuth.azimuth.getPoint(_contracts, point);
179 address: _wallet.address,
183 // Just return a placeholder Point
184 const details: L1Point = toL1Details();
188 address: _wallet.address,
194 [api, wallet, contracts]
197 const getAndUpdatePoint = useCallback(
198 async (point: number) => {
199 const updatedPoint = await initPoint(point);
200 updatePoint(updatedPoint);
202 [initPoint, updatePoint]
205 const checkForUpdates = useCallback(
212 intervalTime = TEN_SECONDS,
213 }: UpdateParams) => {
214 if (l1Txn) storePendingL1Txn(l1Txn);
217 const check = async () => {
218 const updatedPoint = await initPoint(point);
219 const changedField = !points[point]
221 : updatedPoint.getChangedField(points[point], field);
224 console.log(`CHECKING FOR ${changedField} UPDATES:`, updatedPoint);
227 if (!updatedPoint.isPlaceholder && changedField) {
228 updatePoint(updatedPoint);
230 clearInterval(interval);
233 if (l1Txn) deletePendingL1Txn(l1Txn);
236 `${message || getUpdatedPointMessage(updatedPoint, changedField)}`
242 interval = setInterval(check, intervalTime);
245 [points, initPoint, updatePoint, storePendingL1Txn, deletePendingL1Txn]
248 const spawnPoint = useCallback(
249 async (pointToSpawn: number, destinationAddress: string) => {
250 if (quotaReached()) {
254 const _point = need.point(pointCursor);
255 const _contracts = contracts.getOrElse(null);
256 const _web3 = web3.getOrElse(null);
257 const _wallet = wallet.getOrElse(null);
258 const _authToken = authToken.getOrElse(null);
260 if (!_contracts || !_web3 || !_wallet || !_authToken) {
261 // not using need because we want a custom error
262 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
265 const proxy = point.getSpawnProxy();
267 if (proxy === undefined)
268 throw new Error("Error: Address doesn't match proxy");
270 const nonce = await api.getNonce({
275 await submitL2Transaction({
277 address: destinationAddress,
303 const getPoints = useCallback(
304 async (proxy: Proxy, address: EthAddress) => {
305 const points: Ship[] =
307 ? await api.getOwnedPoints(address)
309 ? await api.getManagerFor(address)
311 ? await api.getVotingFor(address)
312 : proxy === 'transfer'
313 ? await api.getTransferringFor(address)
315 ? await api.getSpawningFor(address)
323 const getPendingTransactions = useCallback(async () => {
325 if (!point.isDefault) {
326 const newPending = await api.getPendingByShip(point.value);
327 setPendingTransactions(newPending);
330 console.warn('ERROR GETTING PENDING', error);
332 }, [api, setPendingTransactions, point]);
334 interface ConfigureKeysParams {
336 customNetworkSeed?: string;
339 const configureNetworkKeys = useCallback(
340 async ({ breach, customNetworkSeed }: ConfigureKeysParams) => {
341 if (quotaReached()) {
344 const _wallet = wallet.getOrElse(null);
345 const _web3 = web3.getOrElse(null);
346 if (!_wallet || !_web3 || point.isDefault) {
347 // not using need because we want a custom error
348 throw new Error('Internal Error: Missing Wallet/Details');
351 const proxy = point.getManagerProxy();
353 if (proxy === undefined)
354 throw new Error("Error: Address doesn't match proxy");
356 const nonce = await api.getNonce({
361 const nextRevision = point.keyRevisionNumber + 1;
362 const networkSeed = customNetworkSeed
364 : await attemptNetworkSeedDerivation({
371 revision: nextRevision,
373 const txHash = await submitL2Transaction({
380 type: 'configureKeys',
387 return api.getPendingTx(txHash);
390 // eslint-disable-line
404 const performL2Reticket = async ({
411 }: ReticketParams) => {
412 const azimuthPoint = await api.getPoint(point);
414 const _web3 = web3.getOrElse(null);
415 let nonce = await api.getNonce({ ship: point, proxy });
416 const progress = onUpdate
417 ? (state: number) => onUpdate({ type: 'progress', state })
422 // 1. Update networking keys
423 progress(TRANSACTION_PROGRESS.GENERATING);
424 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
425 const nextRevision = networkRevision + 1;
426 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
430 const configureKeysRequest = await submitL2Transaction({
438 type: 'configureKeys',
443 requests.push(configureKeysRequest);
445 // 2. Set Management Proxy
446 progress(TRANSACTION_PROGRESS.SIGNING);
447 const registerMgmtRequest = await registerProxyAddress(
460 requests.push(registerMgmtRequest);
462 // 3. Set Spawn Proxy
463 progress(TRANSACTION_PROGRESS.FUNDING);
464 if (!isPlanet(Number(point))) {
465 const registerSpawnRequest = await registerProxyAddress(
472 toWallet?.spawn?.keys?.address || to,
478 requests.push(registerSpawnRequest);
482 progress(TRANSACTION_PROGRESS.TRANSFERRING);
483 const transferTxRequest = await submitL2Transaction({
488 type: 'transferPoint',
495 requests.push(transferTxRequest);
497 progress(TRANSACTION_PROGRESS.CLEANING);
498 const hashes = await Promise.all(requests);
500 progress(TRANSACTION_PROGRESS.DONE);
504 const setProxyAddress = useCallback(
505 async (proxyType: Proxy, address: EthAddress) => {
506 if (quotaReached()) {
510 const _wallet = wallet.getOrElse(null);
511 const _web3 = web3.getOrElse(null);
514 // not using need because we want a custom error
515 throw new Error('Internal Error: Missing Wallet');
518 if (point.isDefault) {
519 // not using need because we want a custom error
520 throw new Error('Internal Error: Invalid point');
523 const proxy = point.getAddressProxy(proxyType);
525 if (proxy === undefined)
526 throw new Error("Error: Address doesn't match expected proxy");
528 const nonce = await api.getNonce({ ship: point.value, proxy });
530 const txHash = await registerProxyAddress(
543 return api.getPendingTx(txHash);
545 [api, connector, point, wallet, web3, walletType, quotaReached]
548 const changeSponsorship = useCallback(
551 type: 'adopt' | 'detach' | 'reject',
552 skipQuotaCheck = false
554 if (!skipQuotaCheck && quotaReached()) {
558 const _wallet = wallet.getOrElse(null);
559 const _web3 = web3.getOrElse(null);
560 const ship = point.value;
562 const proxy = point.getManagerProxy();
564 if (proxy === undefined)
565 throw new Error("Error: Address doesn't match expected proxy");
567 const nonce = await api.getNonce({ ship, proxy });
568 // const txHash = await adopt(api, _wallet, point.value, proxy, nonce, ship);
569 const txHash = await submitL2Transaction({
576 address: _wallet.address,
583 return api.getPendingTx(txHash);
585 [api, point, wallet, walletType, web3, connector, quotaReached]
588 const transferPoint = useCallback(
589 async (address: EthAddress, reset?: boolean) => {
590 if (quotaReached()) {
594 const _point = need.point(pointCursor);
595 const _wallet = wallet.getOrElse(null);
596 const _web3 = web3.getOrElse(null);
599 // not using need because we want a custom error
600 throw new Error('Internal Error: Missing Wallet');
603 const proxy = point.getTransferProxy();
605 if (proxy === undefined)
606 throw new Error("Error: Address doesn't match proxy");
608 const nonce = await api.getNonce({ ship: _point, proxy });
610 const txHash = await submitL2Transaction({
617 type: 'transferPoint',
624 return api.getPendingTx(txHash);
626 [api, connector, point, pointCursor, wallet, web3, walletType, quotaReached]
629 const sendL2Transaction = useCallback(
630 async (params: SendL2Params) => {
631 if (quotaReached()) {
635 const _wallet = wallet.getOrElse(null);
636 const _web3 = web3.getOrElse(null);
638 if (!_wallet || point.isDefault) {
639 // not using need because we want a custom error
640 throw new Error('Internal Error: Missing Wallet or Point Info');
643 return submitL2Transaction({
653 [api, connector, point, wallet, web3, walletType, quotaReached]
656 const changeSponsor = useCallback(
657 async (newSponsor: number) => {
658 if (point.isDefault) {
659 throw new Error('Internal Error: point is default');
662 const curPoint = point.value;
663 const _wallet = wallet.getOrElse(null);
666 // not using need because we want a custom error
667 throw new Error('Internal Error: Missing Wallet');
670 const proxy = point.getManagerProxy();
672 if (proxy === undefined)
673 throw new Error("Error: Address doesn't match proxy");
675 const nonce = await api.getNonce({ ship: curPoint, proxy });
677 return sendL2Transaction({
685 [api, point, sendL2Transaction, wallet]
688 const cancelEscape = useCallback(async () => {
689 if (point.isDefault) {
690 throw new Error('Internal Error: point is default');
693 const curPoint = point.value;
694 const _wallet = wallet.getOrElse(null);
697 // not using need because we want a custom error
698 throw new Error('Internal Error: Missing Wallet');
701 const proxy = point.getManagerProxy();
703 if (proxy === undefined)
704 throw new Error("Error: Address doesn't match proxy");
706 const nonce = await api.getNonce({ ship: curPoint, proxy });
708 return sendL2Transaction({
711 type: 'cancelEscape',
714 }, [api, point, sendL2Transaction, wallet]);
716 const getPointsDetails = useCallback(
718 ownedPoints: number[],
719 incomingPoints: number[],
720 managingPoints: number[],
721 votingPoints: number[],
722 spawningPoints: number[]
726 await Promise.all(ownedPoints.map(initPoint)),
727 await Promise.all(incomingPoints.map(initPoint)),
728 await Promise.all(managingPoints.map(initPoint)),
729 await Promise.all(votingPoints.map(initPoint)),
730 await Promise.all(spawningPoints.map(initPoint)),
734 allPoints.reduce((acc: Points, cur: (Point | undefined)[]) => {
747 [setPoints, initPoint]
750 // On load, get initial config
757 }, [config, fetchConfig]);
766 configureNetworkKeys,
770 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