Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelPretorius committed Mar 6, 2024
1 parent c89da65 commit e71edc2
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 59 deletions.
16 changes: 13 additions & 3 deletions components/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,18 +58,28 @@ function Modal({ onClose, children, title, className, ...other }: ModalProps) {

export default Modal;

// Function to render modal
/**
* Render a modal with the given content
* @param content The content to render in the modal
* @param onClose Function to execute when manually close the modal through clicking the close button or backdrop
* @returns Function to close the modal, only removing the React component, not executing the onClose function
*/
export const renderModal = (content: ReactNode, onClose: () => void) => {
const modalDiv = document.getElementById('custom-root') as HTMLElement;
const root = createRoot(modalDiv);

// Function to execute when manually close the modal
const handleManualClose = () => {
handleClose();
onClose();
};

const handleClose = () => {
root.unmount(); // Unmount the React component
onClose();
};

// Render your Modal component into the div
root.render(<Modal onClose={handleClose}>{content}</Modal>);
root.render(<Modal onClose={handleManualClose}>{content}</Modal>);

return handleClose;
};
15 changes: 8 additions & 7 deletions components/SignX/SignX.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HTMLAttributes, useEffect, useRef } from 'react';
import { FC, HTMLAttributes, useEffect, useRef } from 'react';
import QRCode from 'react-qr-code';
import { CountdownCircleTimer } from 'react-countdown-circle-timer';
import { isMobile, isIOS, isMacOs } from 'react-device-detect';
Expand All @@ -10,16 +10,18 @@ import { getCSSVariable } from '@utils/styles';
type SignXProps = {
title: string;
subtitle?: string;
data: string;
data: any;
timeout: number;
transactSequence?: number;
isNewSession?: boolean;
} & HTMLAttributes<HTMLDivElement>;

const SignX = ({ title, subtitle, data, timeout, isNewSession = true }: SignXProps) => {
const SignX: FC<SignXProps> = ({ title, subtitle, data, timeout, transactSequence }) => {
const isNewSession = transactSequence === 1;
const firstLoad = useRef(false);
const timeoutFull = (timeout - 1000) / 1000;
const timeoutThird = timeoutFull / 3;
const deeplink = convertDataToDeeplink(isNewSession ? JSON.parse(data) : { type: SIGN_X_CLEAN_DEEPLINK });
const deeplink = convertDataToDeeplink(isNewSession ? data : { type: SIGN_X_CLEAN_DEEPLINK });
const downloadLink =
isIOS || isMacOs
? `https://apps.apple.com/app/impacts-x/id6444948058`
Expand All @@ -29,7 +31,6 @@ const SignX = ({ title, subtitle, data, timeout, isNewSession = true }: SignXPro
if (firstLoad.current) return;
firstLoad.current = true;

console.log({ deeplink });
if (isMobile) {
console.log('isMobile');
setTimeout(() => {
Expand All @@ -48,7 +49,7 @@ const SignX = ({ title, subtitle, data, timeout, isNewSession = true }: SignXPro
<a href={downloadLink} rel='noopener noreferrer' target='_blank'>
Impacts X App
</a>{' '}
and sign the transaction
and sign transaction #{transactSequence}
</p>
) : subtitle ? (
<p>{subtitle}</p>
Expand Down Expand Up @@ -79,7 +80,7 @@ const SignX = ({ title, subtitle, data, timeout, isNewSession = true }: SignXPro
</div>
{isNewSession && (
<>
<QRCode value={data} size={250} />
<QRCode value={JSON.stringify(data)} size={250} />
<p className={styles.deeplink}>
If you are on a mobile device please install the{' '}
<a href={downloadLink} rel='noopener noreferrer' target='_blank'>
Expand Down
Binary file removed ixo-signx-sdk-1.0.1.tgz
Binary file not shown.
Binary file added ixo-signx-sdk-1.0.17.tgz
Binary file not shown.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"@ixo/cosmos-chain-resolver": "0.0.6",
"@ixo/impactxclient-sdk": "1.1.22",
"@ixo/jambo-wallet-sdk": "0.0.3",
"@ixo/signx-sdk": "./ixo-signx-sdk-1.0.1.tgz",
"@ixo/signx-sdk": "./ixo-signx-sdk-1.0.17.tgz",
"@keplr-wallet/cosmos": "0.11.11",
"@keplr-wallet/types": "0.11.10",
"@keplr-wallet/wc-client": "0.11.11",
Expand Down
83 changes: 38 additions & 45 deletions utils/signX.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const initializeSignX = async (
if (signXInitializing) return;
signXInitializing = true;

let handleClose: () => void;
let removeModal: () => void;
try {
if (walletUser?.chainId && walletUser?.chainId !== chainInfo.chainId)
throw new Error('Chains changed, please logout and login again');
Expand All @@ -38,7 +38,7 @@ export const initializeSignX = async (

signXClient = new SignX({
endpoint: SIGN_X_RELAYERS[chainInfo.chainNetwork || 'mainnet'],
// endpoint: 'http://localhost:3000',
// endpoint: 'http://localhost:8000',
network: chainInfo.chainNetwork || 'mainnet',
sitename: config.siteName ?? 'JAMBO dApp',
});
Expand All @@ -47,33 +47,25 @@ export const initializeSignX = async (
if (walletUser?.address || walletUser?.pubKey) return walletUser;

// get login data from client to display QR code and start polling
const data = await signXClient.login({ pollingInterval: 2000 });
const data = await signXClient.login({ pollingInterval: 1000 });

const closeModal = () => {
signXClient.off(SIGN_X_LOGIN_ERROR, () => {});
signXClient.off(SIGN_X_LOGIN_SUCCESS, () => {});
// callback for when modal is closed manually
const onManualCloseModal = () => {
signXClient.stopPolling('Login cancelled', SIGN_X_LOGIN_ERROR);
};

handleClose = renderModal(
<SignXModal title='SignX Login' data={JSON.stringify(data)} timeout={signXClient.timeout} />,
closeModal,
removeModal = renderModal(
<SignXModal title='SignX Login' data={data} timeout={signXClient.timeout} transactSequence={1} />,
onManualCloseModal,
);

const eventData: any = await new Promise((resolve, reject) => {
const handleSuccess = (data: any) => {
signXClient.off(SIGN_X_LOGIN_ERROR, handleError); // Remove error listener once successful
resolve(data);
};
const handleError = (error: any) => {
signXClient.off(SIGN_X_LOGIN_SUCCESS, handleSuccess); // Remove success listener on error
reject(error);
};

const handleSuccess = (data: any) => resolve(data);
const handleError = (error: any) => reject(error);
signXClient.on(SIGN_X_LOGIN_SUCCESS, handleSuccess);
signXClient.on(SIGN_X_LOGIN_ERROR, handleError);
});
handleClose();
// removeModal();

return {
name: eventData.data.name,
Expand All @@ -90,7 +82,10 @@ export const initializeSignX = async (
} finally {
signXInitializing = false;
// @ts-ignore
if (handleClose) handleClose();
if (removeModal) removeModal();
// remove event listeners
signXClient.removeAllListeners(SIGN_X_LOGIN_ERROR);
signXClient.removeAllListeners(SIGN_X_LOGIN_SUCCESS);
}
};

Expand All @@ -106,7 +101,12 @@ export const signXBroadCastMessage = async (
if (signXBroadCastMessageBusy) return null;
signXBroadCastMessageBusy = true;

let handleClose: () => void;
let removeModal: () => void;
// callback for when modal is closed manually
let onManualCloseModal = (clearSession = true) => {
signXClient.stopPolling('Transaction cancelled', SIGN_X_TRANSACT_ERROR, clearSession);
};

try {
if (!chainInfo || !chainInfo.chainId) throw new Error('No chain info found');
if (chainInfo.chainName !== 'ixo') throw new Error('SignX only works on ixo chain');
Expand All @@ -115,7 +115,6 @@ export const signXBroadCastMessage = async (
if (!signXClient) throw new Error('No signXClient found to broadcast transaction');

const registry = createRegistry();

const txBody = toHex(registry.encodeTxBody({ messages: msgs as any, memo }));

// get transact data from client to start polling, display QR code if new session
Expand All @@ -126,40 +125,29 @@ export const signXBroadCastMessage = async (
timestamp: new Date().toISOString(),
transactions: [{ sequence: 1, txBodyHex: txBody }],
});
const isNewSession = !!data?.sessionHash;

const closeModal = () => {
signXClient.off(SIGN_X_TRANSACT_ERROR, () => {});
signXClient.off(SIGN_X_TRANSACT_SUCCESS, () => {});
signXClient.stopPolling('Transaction cancelled', SIGN_X_TRANSACT_ERROR, false);
};
// if already active session(aka no sessionHash), start polling for next transaction that was just added
if (!data?.sessionHash) {
signXClient.pollNextTransaction();
}

handleClose = renderModal(
removeModal = renderModal(
<SignXModal
title='SignX Transaction'
data={JSON.stringify(data)}
data={data}
timeout={signXClient.timeout}
isNewSession={isNewSession}
transactSequence={signXClient.transactSequence}
/>,
closeModal,
onManualCloseModal,
);

// wait for transaction to be broadcasted and SignX to emit success or fail event
const eventData: any = await new Promise((resolve, reject) => {
const handleSuccess = (data: any) => {
signXClient.off(SIGN_X_TRANSACT_ERROR, handleError); // Remove error listener once successful
resolve(data);
};
const handleError = (error: any) => {
signXClient.off(SIGN_X_TRANSACT_SUCCESS, handleSuccess); // Remove success listener on error
reject(error);
};

const handleSuccess = (data: any) => resolve(data);
const handleError = (error: any) => reject(error);
signXClient.on(SIGN_X_TRANSACT_SUCCESS, handleSuccess);
signXClient.on(SIGN_X_TRANSACT_ERROR, handleError);
});
handleClose();

console.log({ eventData });

return eventData.data?.transactionHash;
} catch (e) {
Expand All @@ -169,6 +157,11 @@ export const signXBroadCastMessage = async (
} finally {
signXBroadCastMessageBusy = false;
// @ts-ignore
if (handleClose) handleClose();
if (removeModal) removeModal();
// @ts-ignore
if (onManualCloseModal) onManualCloseModal(false);
// remove event listeners
signXClient.removeAllListeners(SIGN_X_TRANSACT_ERROR);
signXClient.removeAllListeners(SIGN_X_TRANSACT_SUCCESS);
}
};
6 changes: 3 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1827,9 +1827,9 @@
bech32 "2.0.0"
bs58 "5.0.0"

"@ixo/signx-sdk@./ixo-signx-sdk-1.0.1.tgz":
version "1.0.1"
resolved "./ixo-signx-sdk-1.0.1.tgz#14307dba481cbd9798e9d4a32b37af5c74ce0a0e"
"@ixo/signx-sdk@./ixo-signx-sdk-1.0.17.tgz":
version "1.0.17"
resolved "./ixo-signx-sdk-1.0.17.tgz#1cf31cc15f0799988788a86362a40c7d669f78b9"
dependencies:
"@babel/runtime" "7.19.4"
axios "1.3.4"
Expand Down

0 comments on commit e71edc2

Please sign in to comment.