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 {
47 point?: Point | number;
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): Promise<Point> => {
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) => {
216 const p = (typeof point === 'number' ? await initPoint(point) : point) as Point
218 if (l1Txn) storePendingL1Txn(l1Txn);
221 const check = async () => {
222 const changedField = !points[p.value]
224 : p.getChangedField(points[p.value], field);
227 console.log(`CHECKING FOR ${changedField} UPDATES:`, p.patp);
230 if (!p.isPlaceholder && changedField) {
233 clearInterval(interval);
236 if (l1Txn) deletePendingL1Txn(l1Txn);
239 `${message || getUpdatedPointMessage(p, changedField)}`
245 interval = setInterval(check, intervalTime);
248 [points, initPoint, updatePoint, storePendingL1Txn, deletePendingL1Txn]
251 const spawnPoint = useCallback(
252 async (pointToSpawn: number, destinationAddress: string) => {
253 if (quotaReached()) {
257 const _point = need.point(pointCursor);
258 const _contracts = contracts.getOrElse(null);
259 const _web3 = web3.getOrElse(null);
260 const _wallet = wallet.getOrElse(null);
261 const _authToken = authToken.getOrElse(null);
263 if (!_contracts || !_web3 || !_wallet || !_authToken) {
264 // not using need because we want a custom error
265 throw new Error('Internal Error: Missing Contracts/Web3/Wallet');
268 const proxy = point.getSpawnProxy();
270 if (proxy === undefined)
271 throw new Error("Error: Address doesn't match proxy");
273 const nonce = await api.getNonce({
278 await submitL2Transaction({
280 address: destinationAddress,
306 const getPoints = useCallback(
307 async (proxy: Proxy, address: EthAddress) => {
308 const points: Ship[] =
310 ? await api.getOwnedPoints(address)
312 ? await api.getManagerFor(address)
314 ? await api.getVotingFor(address)
315 : proxy === 'transfer'
316 ? await api.getTransferringFor(address)
318 ? await api.getSpawningFor(address)
326 const getPendingTransactions = useCallback(async () => {
328 if (!point.isDefault) {
329 const newPending = await api.getPendingByShip(point.value);
330 setPendingTransactions(newPending);
333 console.warn('ERROR GETTING PENDING', error);
335 }, [api, setPendingTransactions, point]);
337 interface ConfigureKeysParams {
339 customNetworkSeed?: string;
342 const configureNetworkKeys = useCallback(
343 async ({ breach, customNetworkSeed }: ConfigureKeysParams) => {
344 if (quotaReached()) {
347 const _wallet = wallet.getOrElse(null);
348 const _web3 = web3.getOrElse(null);
349 if (!_wallet || !_web3 || point.isDefault) {
350 // not using need because we want a custom error
351 throw new Error('Internal Error: Missing Wallet/Details');
354 const proxy = point.getManagerProxy();
356 if (proxy === undefined)
357 throw new Error("Error: Address doesn't match proxy");
359 const nonce = await api.getNonce({
364 const nextRevision = point.keyRevisionNumber + 1;
365 const networkSeed = customNetworkSeed
367 : await attemptNetworkSeedDerivation({
374 revision: nextRevision,
376 const txHash = await submitL2Transaction({
383 type: 'configureKeys',
390 return api.getPendingTx(txHash);
393 // eslint-disable-line
407 const performL2Reticket = async ({
414 }: ReticketParams) => {
415 const azimuthPoint = await api.getPoint(point);
417 const _web3 = web3.getOrElse(null);
418 let nonce = await api.getNonce({ ship: point, proxy });
419 const progress = onUpdate
420 ? (state: number) => onUpdate({ type: 'progress', state })
425 // 1. Update networking keys
426 progress(TRANSACTION_PROGRESS.GENERATING);
427 const networkRevision = convertToInt(azimuthPoint.network.keys.life, 10);
428 const nextRevision = networkRevision + 1;
429 const networkSeed = await deriveNetworkSeedFromUrbitWallet(
433 const configureKeysRequest = await submitL2Transaction({
441 type: 'configureKeys',
446 requests.push(configureKeysRequest);
448 // 2. Set Management Proxy
449 progress(TRANSACTION_PROGRESS.SIGNING);
450 const registerMgmtRequest = await registerProxyAddress(
463 requests.push(registerMgmtRequest);
465 // 3. Set Spawn Proxy
466 progress(TRANSACTION_PROGRESS.FUNDING);
467 if (!isPlanet(Number(point))) {
468 const registerSpawnRequest = await registerProxyAddress(
475 toWallet?.spawn?.keys?.address || to,
481 requests.push(registerSpawnRequest);
485 progress(TRANSACTION_PROGRESS.TRANSFERRING);
486 const transferTxRequest = await submitL2Transaction({
491 type: 'transferPoint',
498 requests.push(transferTxRequest);
500 progress(TRANSACTION_PROGRESS.CLEANING);
501 const hashes = await Promise.all(requests);
503 progress(TRANSACTION_PROGRESS.DONE);
507 const setProxyAddress = useCallback(
508 async (proxyType: Proxy, address: EthAddress) => {
509 if (quotaReached()) {
513 const _wallet = wallet.getOrElse(null);
514 const _web3 = web3.getOrElse(null);
517 // not using need because we want a custom error
518 throw new Error('Internal Error: Missing Wallet');
521 if (point.isDefault) {
522 // not using need because we want a custom error
523 throw new Error('Internal Error: Invalid point');
526 const proxy = point.getAddressProxy(proxyType);
528 if (proxy === undefined)
529 throw new Error("Error: Address doesn't match expected proxy");
531 const nonce = await api.getNonce({ ship: point.value, proxy });
533 const txHash = await registerProxyAddress(
546 return api.getPendingTx(txHash);
548 [api, connector, point, wallet, web3, walletType, quotaReached]
551 const changeSponsorship = useCallback(
554 type: 'adopt' | 'detach' | 'reject',
555 skipQuotaCheck = false
557 if (!skipQuotaCheck && quotaReached()) {
561 const _wallet = wallet.getOrElse(null);
562 const _web3 = web3.getOrElse(null);
563 const ship = point.value;
565 const proxy = point.getManagerProxy();
567 if (proxy === undefined)
568 throw new Error("Error: Address doesn't match expected proxy");
570 const nonce = await api.getNonce({ ship, proxy });
571 // const txHash = await adopt(api, _wallet, point.value, proxy, nonce, ship);
572 const txHash = await submitL2Transaction({
579 address: _wallet.address,
586 return api.getPendingTx(txHash);
588 [api, point, wallet, walletType, web3, connector, quotaReached]
591 const transferPoint = useCallback(
592 async (address: EthAddress, reset?: boolean) => {
593 if (quotaReached()) {
597 const _point = need.point(pointCursor);
598 const _wallet = wallet.getOrElse(null);
599 const _web3 = web3.getOrElse(null);
602 // not using need because we want a custom error
603 throw new Error('Internal Error: Missing Wallet');
606 const proxy = point.getTransferProxy();
608 if (proxy === undefined)
609 throw new Error("Error: Address doesn't match proxy");
611 const nonce = await api.getNonce({ ship: _point, proxy });
613 const txHash = await submitL2Transaction({
620 type: 'transferPoint',
627 return api.getPendingTx(txHash);
629 [api, connector, point, pointCursor, wallet, web3, walletType, quotaReached]
632 const sendL2Transaction = useCallback(
633 async (params: SendL2Params) => {
634 if (quotaReached()) {
638 const _wallet = wallet.getOrElse(null);
639 const _web3 = web3.getOrElse(null);
641 if (!_wallet || point.isDefault) {
642 // not using need because we want a custom error
643 throw new Error('Internal Error: Missing Wallet or Point Info');
646 return submitL2Transaction({
656 [api, connector, point, wallet, web3, walletType, quotaReached]
659 const changeSponsor = useCallback(
660 async (newSponsor: number) => {
661 if (point.isDefault) {
662 throw new Error('Internal Error: point is default');
665 const curPoint = point.value;
666 const _wallet = wallet.getOrElse(null);
669 // not using need because we want a custom error
670 throw new Error('Internal Error: Missing Wallet');
673 const proxy = point.getManagerProxy();
675 if (proxy === undefined)
676 throw new Error("Error: Address doesn't match proxy");
678 const nonce = await api.getNonce({ ship: curPoint, proxy });
680 return sendL2Transaction({
688 [api, point, sendL2Transaction, wallet]
691 const cancelEscape = useCallback(async () => {
692 if (point.isDefault) {
693 throw new Error('Internal Error: point is default');
696 const curPoint = point.value;
697 const _wallet = wallet.getOrElse(null);
700 // not using need because we want a custom error
701 throw new Error('Internal Error: Missing Wallet');
704 const proxy = point.getManagerProxy();
706 if (proxy === undefined)
707 throw new Error("Error: Address doesn't match proxy");
709 const nonce = await api.getNonce({ ship: curPoint, proxy });
711 return sendL2Transaction({
714 type: 'cancelEscape',
717 }, [api, point, sendL2Transaction, wallet]);
719 const getPointsDetails = useCallback(
721 ownedPoints: number[],
722 incomingPoints: number[],
723 managingPoints: number[],
724 votingPoints: number[],
725 spawningPoints: number[]
729 await Promise.all(ownedPoints.map(initPoint)),
730 await Promise.all(incomingPoints.map(initPoint)),
731 await Promise.all(managingPoints.map(initPoint)),
732 await Promise.all(votingPoints.map(initPoint)),
733 await Promise.all(spawningPoints.map(initPoint)),
737 allPoints.reduce((acc: Points, cur: (Point | undefined)[]) => {
750 [setPoints, initPoint]
753 // On load, get initial config
760 }, [config, fetchConfig]);
769 configureNetworkKeys,
773 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