Skip to content

Commit

Permalink
Merge pull request #593 from EYBlockchain/liju.jose/nightfall-browser…
Browse files Browse the repository at this point in the history
…/websocket-bug-fix

(nightfall-browser) bug fixed - websocket initiating at all page
  • Loading branch information
Westlad authored Apr 21, 2022
2 parents 0de9a5d + 88ccd6c commit 81ad115
Showing 1 changed file with 29 additions and 12 deletions.
41 changes: 29 additions & 12 deletions wallet/src/hooks/User/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ export const UserProvider = ({ children }) => {
};

const setupWebSocket = () => {
if (state.compressedPkd === '') return;
const socket = new WebSocket(eventWsUrl);

// Connection opened
Expand All @@ -69,11 +68,28 @@ export const UserProvider = ({ children }) => {
socket.send(JSON.stringify({ type: 'sync', lastBlock }));
});

setState(previousState => {
return {
...previousState,
socket,
};
});
};

let messageEventHandler;
const configureMessageListener = () => {
const { compressedPkd, socket } = state;
if (compressedPkd === '') return;

if (messageEventHandler) {
socket.removeEventListener('message', messageEventHandler);
}

// Listen for messages
socket.addEventListener('message', async function (event) {
messageEventHandler = async function (event) {
console.log('Message from server ', JSON.parse(event.data));
const parsed = JSON.parse(event.data);
const { ivk, nsk } = await retrieveAndDecrypt(state.compressedPkd);
const { ivk, nsk } = await retrieveAndDecrypt(compressedPkd);
if (parsed.type === 'sync') {
await parsed.historicalData
.sort((a, b) => a.block.blockNumberL2 - b.block.blockNumberL2)
Expand All @@ -93,17 +109,18 @@ export const UserProvider = ({ children }) => {
}),
);
}
} else if (parsed.type === 'blockProposed') await blockProposedEventHandler(parsed.data, [ivk], [nsk]);
} else if (parsed.type === 'blockProposed')
await blockProposedEventHandler(parsed.data, [ivk], [nsk]);
// TODO Rollback Handler
});
setState(previousState => {
return {
...previousState,
socket,
};
});
};

socket.addEventListener('message', messageEventHandler);
};

React.useEffect(() => {
setupWebSocket();
}, []);

React.useEffect(async () => {
if (location.pathname !== '/' && state.compressedPkd === '') {
await syncState();
Expand All @@ -112,7 +129,7 @@ export const UserProvider = ({ children }) => {
}, [location]);

React.useEffect(() => {
setupWebSocket();
configureMessageListener();
}, [state.compressedPkd]);

/*
Expand Down

0 comments on commit 81ad115

Please sign in to comment.