Skip to content

Commit

Permalink
Merge pull request #1262 from RoboSats/new-tor-engine
Browse files Browse the repository at this point in the history
Fix Federation Android App
  • Loading branch information
Reckless-Satoshi authored May 1, 2024
2 parents 8d2ca28 + 3b18f6a commit 0f41a61
Show file tree
Hide file tree
Showing 49 changed files with 935 additions and 256 deletions.
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
*.py[cod]
__pycache__

# C extensions
*.so

# Packages
*.egg
*.egg-info
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/basic/RobotPage/Onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ const Onboarding = ({
/>
</Grid>

{slot?.hashId ? (
{slot?.nickname ? (
<Grid item>
<Typography align='center'>{t('Hi! My name is')}</Typography>
<Typography component='h5' variant='h5'>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/basic/RobotPage/RobotProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ const RobotProfile = ({
sx={{ width: '100%' }}
>
<Grid item sx={{ height: '2.3em', position: 'relative' }}>
{slot?.hashId ? (
{slot?.nickname ? (
<Typography align='center' component='h5' variant='h5'>
<div
style={{
Expand Down
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
16 changes: 9 additions & 7 deletions frontend/src/components/BookTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const ClickThroughDataGrid = styled(DataGrid)({
'& .MuiDataGrid-overlayWrapperInner': {
pointerEvents: 'none',
},
...{ headerStyleFix },
});

const premiumColor = function (baseColor: string, accentColor: string, point: number): string {
Expand Down Expand Up @@ -897,6 +896,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 All @@ -908,6 +912,7 @@ const BookTable = ({
}
>
<ClickThroughDataGrid
sx={headerStyleFix}
localeText={localeText}
rowHeight={3.714 * theme.typography.fontSize}
headerHeight={3.25 * theme.typography.fontSize}
Expand All @@ -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 All @@ -949,6 +950,7 @@ const BookTable = ({
<Dialog open={fullscreen} fullScreen={true}>
<Paper style={{ width: '100%', height: '100%', overflow: 'auto' }}>
<ClickThroughDataGrid
sx={headerStyleFix}
localeText={localeText}
rowHeight={3.714 * theme.typography.fontSize}
headerHeight={3.25 * theme.typography.fontSize}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Dialogs/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const ProfileDialog = ({ open = false, onClose }: Props): JSX.Element => {
<ListItem className='profileNickname'>
<ListItemText>
<Typography component='h6' variant='h6'>
{garage.getSlot()?.nickname !== undefined && (
{!garage.getSlot()?.nickname && (
<div style={{ position: 'relative', left: '-7px' }}>
<div
style={{
Expand Down
11 changes: 4 additions & 7 deletions frontend/src/components/RobotAvatar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ 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 { AppContext, type UseAppStoreType } from '../../contexts/AppContext';
import { roboidentitiesClient } from '../../services/Roboidentities/Web';

interface Props {
shortAlias?: string | undefined;
Expand Down Expand Up @@ -54,10 +54,9 @@ const RobotAvatar: React.FC<Props> = ({
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')
roboidentitiesClient
.generateRobohash(hashId, small ? 'small' : 'large')
.then((avatar) => {
setAvatarSrc(avatar);
})
Expand All @@ -78,9 +77,7 @@ const RobotAvatar: React.FC<Props> = ({
);
} else {
setAvatarSrc(
`file:///android_asset/Web.bundle/assets/federation/avatars/${shortAlias}${
small ? ' .small' : ''
}.webp`,
`file:///android_asset/Web.bundle/assets/federation/avatars/${shortAlias}.webp`,
);
}
setTimeout(() => {
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
29 changes: 6 additions & 23 deletions frontend/src/models/Coordinator.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import {
type Order,
type Garage,
} from '.';
import { roboidentitiesClient } from '../services/Roboidentities/Web';
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';

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 @@ -191,7 +175,7 @@ export class Coordinator {

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

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

0 comments on commit 0f41a61

Please sign in to comment.