Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Tor engine and Federation App #1207

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions frontend/src/basic/RobotPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const RobotPage = (): JSX.Element => {
const token = urlToken ?? garage.currentSlot;
if (token !== undefined && token !== null && page === 'robot') {
setInputToken(token);
if (window.NativeRobosats === undefined || torStatus === '"Done"') {
if (window.NativeRobosats === undefined || torStatus === 'ON') {
getGenerateRobot(token);
setView('profile');
}
Expand Down Expand Up @@ -83,7 +83,7 @@ const RobotPage = (): JSX.Element => {
garage.deleteSlot();
};

if (!(window.NativeRobosats === undefined) && !(torStatus === 'DONE' || torStatus === '"Done"')) {
if (!(window.NativeRobosats === undefined) && !(torStatus === 'ON')) {
return (
<Paper
elevation={12}
Expand Down
13 changes: 7 additions & 6 deletions frontend/src/components/BookTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,11 @@ const BookTable = ({
: orders;
}, [showControls, orders, fav, paymentMethods]);

const loadingPercentage =
((federation.exchange.enabledCoordinators - federation.exchange.loadingCoordinators) /
federation.exchange.enabledCoordinators) *
100;

if (!fullscreen) {
return (
<Paper
Expand Down Expand Up @@ -928,12 +933,8 @@ const BookTable = ({
setPaymentMethods,
},
loadingOverlay: {
variant: 'determinate',
value:
((federation.exchange.enabledCoordinators -
federation.exchange.loadingCoordinators) /
federation.exchange.enabledCoordinators) *
100,
variant: loadingPercentage === 0 ? 'indeterminate' : 'determinate',
value: loadingPercentage,
},
}}
paginationModel={paginationModel}
Expand Down
34 changes: 17 additions & 17 deletions frontend/src/components/RobotAvatar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import SmoothImage from 'react-smooth-image';
import { Avatar, Badge, Tooltip } from '@mui/material';
import { SendReceiveIcon } from '../Icons';
import placeholder from './placeholder.json';
import { robohash } from './RobohashGenerator';
// import { robohash } from './RobohashGenerator';
import { AppContext, type UseAppStoreType } from '../../contexts/AppContext';

interface Props {
Expand Down Expand Up @@ -53,22 +53,22 @@ const RobotAvatar: React.FC<Props> = ({
const backgroundImage = `url(data:${backgroundData.mime};base64,${backgroundData.data})`;
const className = placeholderType === 'loading' ? 'loadingAvatar' : 'generatingAvatar';

useEffect(() => {
// TODO: HANDLE ANDROID AVATARS TOO (when window.NativeRobosats !== undefined)
if (hashId !== undefined) {
robohash
.generate(hashId, small ? 'small' : 'large')
.then((avatar) => {
setAvatarSrc(avatar);
})
.catch(() => {
setAvatarSrc('');
});
setTimeout(() => {
setActiveBackground(false);
}, backgroundFadeTime);
}
}, [hashId]);
// useEffect(() => {
// // TODO: HANDLE ANDROID AVATARS TOO (when window.NativeRobosats !== undefined)
// if (hashId !== undefined) {
// robohash
// .generate(hashId, small ? 'small' : 'large')
// .then((avatar) => {
// setAvatarSrc(avatar);
// })
// .catch(() => {
// setAvatarSrc('');
// });
// setTimeout(() => {
// setActiveBackground(false);
// }, backgroundFadeTime);
// }
// }, [hashId]);

useEffect(() => {
if (shortAlias !== undefined) {
Expand Down
1 change: 0 additions & 1 deletion frontend/src/components/RobotInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ const RobotInfo: React.FC<Props> = ({ coordinator, onClose, disabled }: Props) =
(signedInvoice) => {
console.log('Signed message:', signedInvoice);
void coordinator.fetchReward(signedInvoice, garage, slot?.token).then((data) => {
console.log(data);
setBadInvoice(data.bad_invoice ?? '');
setShowRewardsSpinner(false);
setWithdrawn(data.successful_withdrawal);
Expand Down
1 change: 0 additions & 1 deletion frontend/src/components/SettingsForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,6 @@ const SettingsForm = ({ dense = false }: SettingsFormProps): JSX.Element => {
value={settings.network}
onChange={(e, network) => {
setSettings({ ...settings, network });
void federation.updateUrls(origin, { ...settings, network }, hostUrl);
systemClient.setItem('settings_network', network);
}}
>
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/TorConnection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const TorConnectionBadge = (): JSX.Element => {
return <></>;
}

if (torStatus === 'NOTINIT') {
if (torStatus === 'OFF' || torStatus === 'STOPPING') {
return (
<TorIndicator
color='primary'
Expand All @@ -80,7 +80,7 @@ const TorConnectionBadge = (): JSX.Element => {
title={t('Connecting to TOR network')}
/>
);
} else if (torStatus === '"Done"' || torStatus === 'DONE') {
} else if (torStatus === 'ON') {
return <TorIndicator color='success' progress={false} title={t('Connected to TOR network')} />;
} else {
return (
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/TorConnection/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const TorConnectionBadge = (): JSX.Element => {
return <></>;
}

if (torStatus === 'NOTINIT') {
if (torStatus === 'OFF' || torStatus === 'STOPING') {
return (
<TorIndicator
color='primary'
Expand All @@ -80,7 +80,7 @@ const TorConnectionBadge = (): JSX.Element => {
title={t('Connecting to TOR network')}
/>
);
} else if (torStatus === '"Done"' || torStatus === 'DONE') {
} else if (torStatus === 'ON') {
return <TorIndicator color='success' progress={false} title={t('Connected to TOR network')} />;
} else {
return (
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/contexts/AppContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export interface SlideDirection {
out: 'left' | 'right' | undefined;
}

export type TorStatus = 'NOTINIT' | 'STARTING' | '"Done"' | 'DONE';
export type TorStatus = 'ON' | 'STARTING' | 'STOPPING' | 'OFF';

export const isNativeRoboSats = !(window.NativeRobosats === undefined);

Expand Down Expand Up @@ -155,8 +155,8 @@ export interface UseAppStoreType {

export const initialAppContext: UseAppStoreType = {
theme: undefined,
torStatus: 'NOTINIT',
settings: getSettings(),
torStatus: 'STARTING',
settings: new Settings(),
setSettings: () => {},
page: entryPage,
setPage: () => {},
Expand Down Expand Up @@ -225,7 +225,7 @@ export const AppContextProvider = ({ children }: AppContextProviderProps): JSX.E
() => {
setTorStatus(event?.detail);
},
event?.detail === '"Done"' ? 5000 : 0,
event?.detail === 'ON' ? 5000 : 0,
);
});
}, []);
Expand Down
26 changes: 14 additions & 12 deletions frontend/src/contexts/FederationContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import React, {
type ReactNode,
} from 'react';

import { type Order, Federation } from '../models';
import { type Order, Federation, Settings } from '../models';

import { federationLottery } from '../utils';

import { AppContext, type UseAppStoreType } from './AppContext';
import { GarageContext, type UseGarageStoreType } from './GarageContext';
import NativeRobosats from '../services/Native';

// Refresh delays (ms) according to Order status
const defaultDelay = 5000;
Expand Down Expand Up @@ -61,7 +62,7 @@ export interface UseFederationStoreType {
}

export const initialFederationContext: UseFederationStoreType = {
federation: new Federation(),
federation: new Federation('onion', new Settings(), ''),
sortedCoordinators: [],
setDelay: () => {},
currentOrderId: { id: null, shortAlias: null },
Expand All @@ -79,7 +80,7 @@ export const FederationContextProvider = ({
const { settings, page, origin, hostUrl, open, torStatus } =
useContext<UseAppStoreType>(AppContext);
const { setMaker, garage, setBadOrder } = useContext<UseGarageStoreType>(GarageContext);
const [federation, setFederation] = useState(initialFederationContext.federation);
const [federation] = useState(new Federation(origin, settings, hostUrl));
const sortedCoordinators = useMemo(() => federationLottery(federation), []);
const [coordinatorUpdatedAt, setCoordinatorUpdatedAt] = useState<string>(
new Date().toISOString(),
Expand All @@ -101,19 +102,20 @@ export const FederationContextProvider = ({
setMaker((maker) => {
return { ...maker, coordinator: sortedCoordinators[0] };
}); // default MakerForm coordinator is decided via sorted lottery
}, []);

useEffect(() => {
// On bitcoin network change we reset book, limits and federation info and fetch everything again
const newFed = initialFederationContext.federation;
newFed.registerHook('onFederationUpdate', () => {
federation.registerHook('onFederationUpdate', () => {
setFederationUpdatedAt(new Date().toISOString());
});
newFed.registerHook('onCoordinatorUpdate', () => {
federation.registerHook('onCoordinatorUpdate', () => {
setCoordinatorUpdatedAt(new Date().toISOString());
});
void newFed.start(origin, settings, hostUrl);
setFederation(newFed);
}, []);

useEffect(() => {
// On bitcoin network change we reset book, limits and federation info and fetch everything again
if (window.NativeRobosats === undefined || torStatus === 'ON') {
void federation.updateUrl(origin, settings, hostUrl);
void federation.update();
}
}, [settings.network, torStatus]);

const onOrderReceived = (order: Order): void => {
Expand Down
33 changes: 8 additions & 25 deletions frontend/src/models/Coordinator.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { apiClient } from '../services/api';
import { validateTokenEntropy } from '../utils';
import { compareUpdateLimit } from './Limit.model';
import { defaultOrder } from './Order.model';
import { robohash } from '../components/RobotAvatar/RobohashGenerator';
// import { robohash } from '../components/RobotAvatar/RobohashGenerator';

export interface Contact {
nostr?: string | undefined;
Expand Down Expand Up @@ -97,7 +97,7 @@ function calculateSizeLimit(inputDate: Date): number {
}

export class Coordinator {
constructor(value: any) {
constructor(value: any, origin: Origin, settings: Settings, hostUrl: string) {
const established = new Date(value.established);
this.longAlias = value.longAlias;
this.shortAlias = value.shortAlias;
Expand All @@ -115,6 +115,8 @@ export class Coordinator {
this.testnetNodesPubkeys = value.testnetNodesPubkeys;
this.url = '';
this.basePath = '';

this.updateUrl(origin, settings, hostUrl);
}

// These properties are loaded from federation.json
Expand Down Expand Up @@ -145,32 +147,14 @@ export class Coordinator {
public loadingLimits: boolean = false;
public loadingRobot: boolean = true;

start = async (
origin: Origin,
settings: Settings,
hostUrl: string,
onUpdate: (shortAlias: string) => void = () => {},
): Promise<void> => {
if (this.enabled !== true) return;
void this.updateUrl(settings, origin, hostUrl, onUpdate);
};

updateUrl = async (
settings: Settings,
origin: Origin,
hostUrl: string,
onUpdate: (shortAlias: string) => void = () => {},
): Promise<void> => {
updateUrl = (origin: Origin, settings: Settings, hostUrl: string): void => {
if (settings.selfhostedClient && this.shortAlias !== 'local') {
this.url = hostUrl;
this.basePath = `/${settings.network}/${this.shortAlias}`;
} else {
this.url = String(this[settings.network][origin]);
this.basePath = '';
}
void this.update(() => {
onUpdate(this.shortAlias);
});
};

update = async (onUpdate: (shortAlias: string) => void = () => {}): Promise<void> => {
Expand All @@ -190,9 +174,9 @@ export class Coordinator {
};

generateAllMakerAvatars = async (data: [PublicOrder]): Promise<void> => {
for (const order of data) {
void robohash.generate(order.maker_hash_id, 'small');
}
// for (const order of data) {
// void robohash.generate(order.maker_hash_id, 'small');
// }
};

loadBook = (onDataLoad: () => void = () => {}): void => {
Expand Down Expand Up @@ -370,7 +354,6 @@ export class Coordinator {
return await apiClient
.get(this.url, `${this.basePath}/api/order/?order_id=${orderId}`, authHeaders)
.then((data) => {
console.log('data', data);
const order: Order = {
...defaultOrder,
...data,
Expand Down
Loading