forked from cerc-io/snowballtools-base
Part of https://www.notion.so/Laconic-Mainnet-Plan-1eca6b22d47280569cd0d1e6d711d949 Co-authored-by: Shreerang Kale <shreerangkale@gmail.com> Co-authored-by: Prathamesh Musale <prathamesh.musale0@gmail.com> Reviewed-on: cerc-io/snowballtools-base#59 Co-authored-by: Nabarun <nabarun@deepstacksoft.com> Co-committed-by: Nabarun <nabarun@deepstacksoft.com>
51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
|
|
import { useAddNetwork } from './useAddNetwork';
|
|
|
|
const useCheckBalance = (amount: string, iframeId: string) => {
|
|
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
|
|
|
|
const { networkData } = useAddNetwork()
|
|
|
|
const checkBalance = useCallback(() => {
|
|
if (!networkData) {
|
|
return;
|
|
}
|
|
|
|
const iframe = document.getElementById(iframeId) as HTMLIFrameElement;
|
|
|
|
if (!iframe || !iframe.contentWindow) {
|
|
console.error(`Iframe with ID "${iframeId}" not found or not loaded`);
|
|
return;
|
|
}
|
|
|
|
iframe.contentWindow.postMessage(
|
|
{
|
|
type: 'CHECK_BALANCE',
|
|
chainId: networkData.chainId,
|
|
amount,
|
|
},
|
|
import.meta.env.VITE_WALLET_IFRAME_URL
|
|
);
|
|
}, [iframeId, amount, networkData]);
|
|
|
|
useEffect(() => {
|
|
const handleMessage = (event: MessageEvent) => {
|
|
if (event.origin !== import.meta.env.VITE_WALLET_IFRAME_URL) return;
|
|
|
|
if (event.data.type !== 'IS_SUFFICIENT') return;
|
|
|
|
setIsBalanceSufficient(event.data.data);
|
|
};
|
|
|
|
window.addEventListener('message', handleMessage);
|
|
return () => {
|
|
window.removeEventListener('message', handleMessage);
|
|
};
|
|
}, []);
|
|
|
|
return { isBalanceSufficient, checkBalance };
|
|
};
|
|
|
|
export default useCheckBalance;
|