Skip to content

Commit

Permalink
add data exchange
Browse files Browse the repository at this point in the history
  • Loading branch information
ljankoschek committed Jun 28, 2024
1 parent 68b1776 commit 0552338
Show file tree
Hide file tree
Showing 21 changed files with 270 additions and 65 deletions.
1 change: 0 additions & 1 deletion fe1-web/src/core/network/ingestion/Handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export function storeMessage(msg: ExtendedMessage) {
}

export function handleExtendedRpcRequests(req: ExtendedJsonRpcRequest) {
console.log(req);
if (req.request.method === JsonRpcMethod.BROADCAST) {
const broadcastParams = req.request.params as Broadcast;

Expand Down
1 change: 1 addition & 0 deletions fe1-web/src/core/network/jsonrpc/messages/MessageData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export enum ActionType {
FEDERATION_INIT = 'init',
FEDERATION_EXPECT = 'expect',
FEDERATION_RESULT = 'result',
TOKENS_EXCHANGE = 'tokens_exchange',
}

/** Enumeration of all possible signatures of a message */
Expand Down
2 changes: 2 additions & 0 deletions fe1-web/src/core/network/jsonrpc/messages/MessageRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const {
FEDERATION_INIT,
FEDERATION_EXPECT,
FEDERATION_RESULT,
TOKENS_EXCHANGE,
} = ActionType;
const { KEYPAIR, POP_TOKEN } = SignatureType;

Expand Down Expand Up @@ -109,6 +110,7 @@ export class MessageRegistry {
[k(FEDERATION, FEDERATION_INIT), { signature: KEYPAIR }],
[k(FEDERATION, FEDERATION_EXPECT), { signature: KEYPAIR }],
[k(FEDERATION, FEDERATION_RESULT), { signature: KEYPAIR }],
[k(FEDERATION, TOKENS_EXCHANGE), { signature: KEYPAIR }],
]);

/**
Expand Down
1 change: 1 addition & 0 deletions fe1-web/src/core/network/validation/Validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ const schemaIds: Record<ObjectType, Record<string, string>> = {
[ActionType.FEDERATION_INIT]: 'dataFederationInit',
[ActionType.FEDERATION_EXPECT]: 'dataFederationExpect',
[ActionType.FEDERATION_RESULT]: 'dataFederationResult',
[ActionType.TOKENS_EXCHANGE]: 'dataFederationTokensExchange',
},
};

Expand Down
2 changes: 2 additions & 0 deletions fe1-web/src/core/network/validation/schemas/dataSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import dataFederationChallengeRequest from 'protocol/query/method/message/data/d
import dataFederationExpect from 'protocol/query/method/message/data/dataFederationExpect.json';
import dataFederationInit from 'protocol/query/method/message/data/dataFederationInit.json';
import dataFederationResult from 'protocol/query/method/message/data/dataFederationResult.json';
import dataFederationTokensExchange from 'protocol/query/method/message/data/dataFederationTokensExchange.json';
/* eslint-enable import/order */

const dataSchemas = [
Expand Down Expand Up @@ -75,6 +76,7 @@ const dataSchemas = [
dataFederationExpect,
dataFederationInit,
dataFederationResult,
dataFederationTokensExchange,
];

export default dataSchemas;
3 changes: 2 additions & 1 deletion fe1-web/src/features/home/screens/ConnectConfirm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import ScreenWrapper from 'core/components/ScreenWrapper';
import { AppParamList } from 'core/navigation/typing/AppParamList';
import { ConnectParamList } from 'core/navigation/typing/ConnectParamList';
import { getNetworkManager, subscribeToChannel } from 'core/network';
import { Hash } from 'core/objects';
import { getFederationChannel, Hash } from 'core/objects';
import { Typography } from 'core/styles';
import containerStyles from 'core/styles/stylesheets/containerStyles';
import { FOUR_SECONDS } from 'resources/const';
Expand Down Expand Up @@ -63,6 +63,7 @@ const ConnectConfirm = () => {
} else {
// subscribe to the lao channel on the new connection
await subscribeToChannel(laoId, dispatch, laoChannel, [connection]);
await subscribeToChannel(laoId, dispatch, getFederationChannel(laoId));
}

navigation.navigate(STRINGS.navigation_app_lao, {
Expand Down
3 changes: 2 additions & 1 deletion fe1-web/src/features/home/screens/ConnectScan.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import QrCodeScanOverlay from 'core/components/QrCodeScanOverlay';
import { AppParamList } from 'core/navigation/typing/AppParamList';
import { ConnectParamList } from 'core/navigation/typing/ConnectParamList';
import { getNetworkManager, subscribeToChannel } from 'core/network';
import { Channel } from 'core/objects';
import { Channel, getFederationChannel } from 'core/objects';
import { Spacing, Typography } from 'core/styles';
import { FOUR_SECONDS } from 'resources/const';
import STRINGS from 'resources/strings';
Expand Down Expand Up @@ -164,6 +164,7 @@ const ConnectScan = () => {
);

await connectToLaoAndSubscribe(connectToLao, laoChannel);
await subscribeToChannel(connectToLao.lao, dispatch, getFederationChannel(connectToLao.lao));

isProcessingScan.current = false;
setIsConnecting(false);
Expand Down
1 change: 0 additions & 1 deletion fe1-web/src/features/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import * as rollCall from './rollCall';
import * as social from './social';
import * as wallet from './wallet';
import * as witness from './witness';
import { getRollCallById } from './rollCall/functions/RollCall';

export function configureFeatures() {
const messageRegistry = new MessageRegistry();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const AddLinkedOrganizationModal = () => {
const navigation = useNavigation<NavigationProps['navigation']>();
const toast = useToast();
const laoId = LinkedOrganizationsHooks.useCurrentLaoId();
const isOrganizer = LinkedOrganizationsHooks.useIsLaoOrganizer(laoId);
const lao = LinkedOrganizationsHooks.useCurrentLao();
const challengeSelector = useMemo(() => makeChallengeSelector(laoId), [laoId]);
const challengeState = useSelector(challengeSelector);
Expand Down Expand Up @@ -121,6 +122,7 @@ const AddLinkedOrganizationModal = () => {
console.log('Expect Federation successfull');
})
.catch((err) => {
console.log(err);
toast.show(`Could not expect Federation, error: ${err}`, {
type: 'danger',
placement: 'bottom',
Expand All @@ -139,6 +141,7 @@ const AddLinkedOrganizationModal = () => {
console.log('Init Federation successfull');
})
.catch((err) => {
console.log(err);
toast.show(`Could not init Federation, error: ${err}`, {
type: 'danger',
placement: 'bottom',
Expand Down Expand Up @@ -180,7 +183,7 @@ const AddLinkedOrganizationModal = () => {
};

useEffect(() => {
if (challengeState) {
if (challengeState && isOrganizer) {
const challenge = Challenge.fromState(challengeState);
const jsonObj = {
lao_id: laoId,
Expand All @@ -193,7 +196,7 @@ const AddLinkedOrganizationModal = () => {
};
setQRCodeData(JSON.stringify(jsonObj));
}
}, [challengeState, laoId, lao.organizer, lao.server_addresses]);
}, [challengeState, laoId, lao.organizer, lao.server_addresses, isOrganizer]);

return (
<>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,44 +1,53 @@
import React, { useEffect } from 'react';
import { Hash } from 'core/objects';
import { LinkedOrganizationsHooks } from '../hooks';
import { catchup, subscribeToChannel } from 'core/network';
import { dispatch } from 'core/redux';
import React from 'react';
import { useToast } from 'react-native-toast-notifications';

import { Hash } from 'core/objects';
import { FOUR_SECONDS } from 'resources/const';

import { LinkedOrganizationsHooks } from '../hooks';
import { tokensExchange } from '../network';

interface BroadcastLinkedOrgInfoProps {
linkedLaoId: Hash,
linkedLaoId: Hash;
}



const BroadcastLinkedOrgInfo: React.FC<BroadcastLinkedOrgInfoProps> = ({
linkedLaoId
}) => {
const BroadcastLinkedOrgInfo: React.FC<BroadcastLinkedOrgInfoProps> = ({ linkedLaoId }) => {
const laoId = LinkedOrganizationsHooks.useCurrentLaoId();
console.log(LinkedOrganizationsHooks.useGetLaoById(laoId))
const isOrganizer = LinkedOrganizationsHooks.useIsLaoOrganizer(laoId);
const toast = useToast();
const fetchedLao = LinkedOrganizationsHooks.useGetLaoById(linkedLaoId);
if (fetchedLao?.last_roll_call_id === undefined) {
toast.show(`Data Exchange failed: Linked Organization has no last roll call id`, {
const fetchedRollCall = LinkedOrganizationsHooks.useGetRollCallById(
fetchedLao!.last_roll_call_id!,
);

if (fetchedRollCall === undefined) {
toast.show(`Data Exchange failed: RollCall ID is undefined`, {
type: 'danger',
placement: 'bottom',
duration: FOUR_SECONDS,
});
return (null);
return null;
}
const fetchedRollCall = LinkedOrganizationsHooks.useGetRollCallById(fetchedLao.last_roll_call_id);
if (fetchedRollCall === undefined) {
toast.show(`Data Exchange failed: RollCall ID is undefined`, {
if (fetchedRollCall.attendees === undefined) {
toast.show(`Data Exchange failed: RollCall Attendees is undefined`, {
type: 'danger',
placement: 'bottom',
duration: FOUR_SECONDS,
});
return (null);
return null;
}
console.log(fetchedRollCall.attendees)
return (null);
tokensExchange(laoId, linkedLaoId, fetchedRollCall.id, fetchedRollCall.attendees)
.then(() => {
console.log('Data Exchange successfull');
})
.catch((err) => {
console.log(err);
toast.show(`Could not exchange Tokens, error: ${err}`, {
type: 'danger',
placement: 'bottom',
duration: FOUR_SECONDS,
});
});
return null;
};

export default BroadcastLinkedOrgInfo;
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ export namespace LinkedOrganizationsHooks {
*/
export const useGetLaoById = (laoId: Hash) => useLinkedOrganizationsContext().getLaoById(laoId);

/**
/**
* Gets the function to retrieve a rollcall by its id
*/
export const useGetRollCallById = (id: Hash) => useLinkedOrganizationsContext().getRollCallById(id);
export const useGetRollCallById = (id: Hash) =>
useLinkedOrganizationsContext().getRollCallById(id);

/**
* Gets whether the current user is organizer of the given lao
Expand Down
3 changes: 2 additions & 1 deletion fe1-web/src/features/linked-organizations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import { challengeReducer, linkedOrganizationsReducer } from './reducer';
export function configure(
configuration: LinkedOrganizationsConfiguration,
): LinkedOrganizationsInterface {
const { useCurrentLao, useCurrentLaoId, useIsLaoOrganizer, getLaoById, getRollCallById } = configuration;
const { useCurrentLao, useCurrentLaoId, useIsLaoOrganizer, getLaoById, getRollCallById } =
configuration;
configureNetwork(configuration);
return {
identifier: LINKED_ORGANIZATIONS_FEATURE_IDENTIFIER,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import { subscribeToChannel } from 'core/network';
import { ActionType, ObjectType, ProcessableMessage } from 'core/network/jsonrpc/messages';
import { Base64UrlData } from 'core/objects';
import { Base64UrlData, getReactionChannel, getUserSocialChannel } from 'core/objects';
import { dispatch } from 'core/redux';

import { LinkedOrganizationsConfiguration } from '../interface';
import { Challenge } from '../objects/Challenge';
import { addReceivedChallenge, setChallenge } from '../reducer';
import { addLinkedLaoId } from '../reducer/LinkedOrganizationsReducer';
import {
ChallengeRequest,
ChallengeMessage,
FederationExpect,
FederationInit,
FederationResult,
} from './messages';
import { TokensExchange } from './messages/TokensExchange';

/**
* Handler for linked organization messages
Expand All @@ -28,7 +31,6 @@ export const handleChallengeMessage = () => (msg: ProcessableMessage) => {
console.warn('handleRequestChallengeMessage was called to process an unsupported message');
return false;
}

const makeErr = (err: string) => `challenge was not processed: ${err}`;

// obtain the lao id from the channel
Expand Down Expand Up @@ -64,7 +66,6 @@ export const handleChallengeRequestMessage =
console.warn('handleRequestChallengeMessage was called to process an unsupported message');
return false;
}

const makeErr = (err: string) => `challenge/request was not processed: ${err}`;

const laoId = getCurrentLaoId();
Expand Down Expand Up @@ -94,7 +95,6 @@ export const handleFederationInitMessage =
console.warn('handleFederationInitMessage was called to process an unsupported message');
return false;
}

const makeErr = (err: string) => `federation/init was not processed: ${err}`;

const laoId = getCurrentLaoId();
Expand Down Expand Up @@ -130,7 +130,6 @@ export const handleFederationExpectMessage =
console.warn('handleFederationExpectMessage was called to process an unsupported message');
return false;
}

const makeErr = (err: string) => `federation/expect was not processed: ${err}`;

const laoId = getCurrentLaoId();
Expand Down Expand Up @@ -159,16 +158,13 @@ export const handleFederationExpectMessage =
export const handleFederationResultMessage =
(getCurrentLaoId: LinkedOrganizationsConfiguration['getCurrentLaoId']) =>
(msg: ProcessableMessage) => {
console.log('HANLDE FEDRES');
console.log(msg);
if (
msg.messageData.object !== ObjectType.FEDERATION ||
msg.messageData.action !== ActionType.FEDERATION_RESULT
) {
console.warn('handleFederationResultMessage was called to process an unsupported message');
return false;
}

const makeErr = (err: string) => `federation/result was not processed: ${err}`;

const laoId = getCurrentLaoId();
Expand Down Expand Up @@ -203,3 +199,72 @@ export const handleFederationResultMessage =
}
return false;
};

/**
* Handles an tokensExchange message.
*/
export const handleTokensExchangeMessage =
(getCurrentLaoId: LinkedOrganizationsConfiguration['getCurrentLaoId']) =>
(msg: ProcessableMessage) => {
if (
msg.messageData.object !== ObjectType.FEDERATION ||
msg.messageData.action !== ActionType.TOKENS_EXCHANGE
) {
console.warn('handleTokensExchangeMessage was called to process an unsupported message');
return false;
}
const makeErr = (err: string) => `federation/tokensExchange was not processed: ${err}`;

const laoId = getCurrentLaoId();
if (!laoId) {
console.warn(makeErr('no Lao is currently active'));
return false;
}

if (msg.messageData instanceof TokensExchange) {
const tokensExchange = msg.messageData as TokensExchange;
if (
tokensExchange.lao_id &&
tokensExchange.roll_call_id &&
tokensExchange.tokens &&
tokensExchange.timestamp
) {
dispatch(addLinkedLaoId(laoId, tokensExchange.lao_id));
const subscribeChannels = async (): Promise<void> => {
const subscribePromises = tokensExchange.tokens.map(async (attendee) => {
try {
await subscribeToChannel(
tokensExchange.lao_id,
dispatch,
getUserSocialChannel(tokensExchange.lao_id, attendee),
);
} catch (err) {
console.error(
`Could not subscribe to social channel of attendee with public key '${attendee}', error:`,
err,
);
}
});

try {
await Promise.all(subscribePromises);
} catch (err) {
console.error('Error subscribing to one or more social channels:', err);
}

try {
await subscribeToChannel(
tokensExchange.lao_id,
dispatch,
getReactionChannel(tokensExchange.lao_id),
);
} catch (err) {
console.error('Could not subscribe to reaction channel, error:', err);
}
};
subscribeChannels();
return true;
}
}
return false;
};
Loading

0 comments on commit 0552338

Please sign in to comment.