import {
Alert,
AppBar,
Box,
Button,
Card,
Container,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Divider,
IconButton,
Paper,
Snackbar,
Tab,
Tabs,
Toolbar,
Typography,
useTheme,
} from '@mui/material';
import Grid from '@mui/material/Grid';
import {
SyntheticEvent,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import CloseIcon from '@mui/icons-material/Close';
import { getBaseApiReact } from '../../App';
import {
executeEvent,
subscribeToEvent,
unsubscribeFromEvent,
} from '../../utils/events';
import { getFee } from '../../background/background.ts';
import { Spacer } from '../../common/Spacer';
import { FidgetSpinner } from 'react-loader-spinner';
import { useModal } from '../../hooks/useModal.tsx';
import { useAtom, useSetAtom } from 'jotai';
import { memberGroupsAtom, txListAtom } from '../../atoms/global';
import { Trans, useTranslation } from 'react-i18next';
import { TransitionUp } from '../../common/Transitions.tsx';
import {
nextLevel,
averageBlockDay,
averageBlockTime,
dayReward,
levelUpBlocks,
levelUpDays,
mintingStatus,
} from './MintingStats.tsx';
export const Minting = ({ setIsOpenMinting, myAddress, show }) => {
const setTxList = useSetAtom(txListAtom);
const [groups] = useAtom(memberGroupsAtom);
const [mintingAccounts, setMintingAccounts] = useState([]);
const [accountInfo, setAccountInfo] = useState(null);
const [mintingKey, setMintingKey] = useState('');
const [rewardShares, setRewardShares] = useState([]);
const [adminInfo, setAdminInfo] = useState({});
const [nodeStatus, setNodeStatus] = useState({});
const [addressLevel, setAddressLevel] = useState({});
const [tier4Online, setTier4Online] = useState(0);
const [openSnack, setOpenSnack] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [nodeHeightBlock, setNodeHeightBlock] = useState({});
const [valueMintingTab, setValueMintingTab] = useState(0);
const { isShow: isShowNext, onOk, show: showNext } = useModal();
const theme = useTheme();
const { t } = useTranslation([
'auth',
'core',
'group',
'question',
'tutorial',
]);
const [info, setInfo] = useState(null);
const [names, setNames] = useState({});
const [accountInfos, setAccountInfos] = useState({});
const [showWaitDialog, setShowWaitDialog] = useState(false);
const isPartOfMintingGroup = useMemo(() => {
if (groups?.length === 0) return false;
return !!groups?.find((item) => item?.groupId?.toString() === '694');
}, [groups]);
const getMintingAccounts = useCallback(async () => {
try {
const url = `${getBaseApiReact()}/admin/mintingaccounts`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('network error');
}
const data = await response.json();
setMintingAccounts(data);
} catch (error) {
console.log(error);
}
}, []);
const accountIsMinting = useMemo(() => {
return !!mintingAccounts?.find(
(item) => item?.recipientAccount === myAddress
);
}, [mintingAccounts, myAddress]);
const getName = async (address) => {
try {
const url = `${getBaseApiReact()}/names/primary/${address}`;
const response = await fetch(url);
const nameData = await response.json();
if (nameData?.name) {
setNames((prev) => {
return {
...prev,
[address]: nameData?.name,
};
});
} else {
setNames((prev) => {
return {
...prev,
[address]: null,
};
});
}
} catch (error) {
console.log(error);
}
};
function a11yProps(index: number) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
const getAccountInfo = async (address: string, others?: boolean) => {
try {
if (!others) {
setIsLoading(true);
}
const url = `${getBaseApiReact()}/addresses/${address}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('network error');
}
const data = await response.json();
if (others) {
setAccountInfos((prev) => {
return {
...prev,
[address]: data,
};
});
} else {
setAccountInfo(data);
}
} catch (error) {
console.log(error);
} finally {
if (!others) {
setIsLoading(false);
}
}
};
const daysToNextLevel = levelUpDays(
accountInfo,
adminInfo,
nodeHeightBlock,
nodeStatus
);
const refreshRewardShare = () => {
if (!myAddress) return;
getRewardShares(myAddress);
};
useEffect(() => {
subscribeToEvent('refresh-rewardshare-list', refreshRewardShare);
return () => {
unsubscribeFromEvent('refresh-rewardshare-list', refreshRewardShare);
};
}, [myAddress]);
const handleNames = (address) => {
if (!address) return undefined;
if (names[address]) return names[address];
if (names[address] === null) return address;
getName(address);
return address;
};
const getAdminInfo = useCallback(async () => {
try {
const url = `${getBaseApiReact()}/admin/info`;
const response = await fetch(url);
const data = await response.json();
setAdminInfo(data);
setTimeout(getAdminInfo, 30000);
} catch (error) {
console.log(error);
}
}, []);
const getNodeStatus = useCallback(async () => {
try {
const url = `${getBaseApiReact()}/admin/status`;
const response = await fetch(url);
const data = await response.json();
setNodeStatus(data);
setTimeout(getNodeStatus, 30000);
} catch (error) {
console.error('Request failed', error);
}
}, []);
useEffect(() => {
if (nodeStatus?.height) {
const getNodeHeightBlock = async () => {
try {
const nodeBlock = nodeStatus.height - 1440;
const url = `${getBaseApiReact()}/blocks/byheight/${nodeBlock}`;
const response = await fetch(url);
const data = await response.json();
setNodeHeightBlock(data);
} catch (error) {
console.error('Request failed', error);
}
};
getNodeHeightBlock();
}
}, [nodeStatus]);
const getAddressLevel = useCallback(async () => {
try {
const url = `${getBaseApiReact()}/addresses/online/levels`;
const response = await fetch(url);
const data = await response.json();
setAddressLevel(data);
setTier4Online(
parseFloat(data.addressLevel[7].count) +
parseFloat(data.addressLevel[8].count)
);
} catch (error) {
console.error('Request failed', error);
}
}, []);
const getRewardShares = useCallback(async (address) => {
try {
const url = `${getBaseApiReact()}/addresses/rewardshares?involving=${address}`; // TODO check API (still useful?)
const response = await fetch(url);
if (!response.ok) {
throw new Error('network error');
}
const data = await response.json();
setRewardShares(data);
return data;
} catch (error) {
console.log(error);
}
}, []);
const addMintingAccount = useCallback(async (val) => {
try {
setIsLoading(true);
return await new Promise((res, rej) => {
window
.sendMessage(
'ADMIN_ACTION',
{
type: 'addmintingaccount',
value: val,
},
180000,
true
)
.then((response) => {
if (!response?.error) {
res(response);
setMintingKey('');
setTimeout(() => {
getMintingAccounts();
}, 300);
return;
}
rej({ message: response.error });
})
.catch((error) => {
rej({
message:
error.message ||
t('core:message.error.generic', {
postProcess: 'capitalizeFirstChar',
}),
});
});
});
} catch (error) {
setInfo({
type: 'error',
message:
error?.message ||
t('core:message.error.minting_account_add', {
postProcess: 'capitalizeFirstChar',
}),
});
setOpenSnack(true);
} finally {
setIsLoading(false);
}
}, []);
const removeMintingAccount = useCallback(async (val, acct) => {
try {
setIsLoading(true);
return await new Promise((res, rej) => {
window
.sendMessage(
'ADMIN_ACTION',
{
type: 'removemintingaccount',
value: val,
},
180000,
true
)
.then((response) => {
if (!response?.error) {
res(response);
setTimeout(() => {
getMintingAccounts();
}, 300);
return;
}
rej({ message: response.error });
})
.catch((error) => {
rej({
message:
error.message ||
t('core:message.error.generic', {
postProcess: 'capitalizeFirstChar',
}),
});
});
});
} catch (error) {
setInfo({
type: 'error',
message:
error?.message ||
t('core:message.error.minting_account_remove', {
postProcess: 'capitalizeFirstChar',
}),
});
setOpenSnack(true);
} finally {
setIsLoading(false);
}
}, []);
const createRewardShare = useCallback(async (publicKey, recipient) => {
const fee = await getFee('REWARD_SHARE');
await show({
message: t('core:message.question.perform_transaction', {
action: 'REWARD_SHARE',
postProcess: 'capitalizeFirstChar',
}),
publishFee: fee.fee + ' QORT',
});
return await new Promise((res, rej) => {
window
.sendMessage('createRewardShare', {
recipientPublicKey: publicKey,
})
.then((response) => {
if (!response?.error) {
setTxList((prev) => [
{
recipient,
...response,
type: 'add-rewardShare',
label: t('group:message.success.rewardshare_add', {
postProcess: 'capitalizeFirstChar',
}),
labelDone: t('group:message.success.rewardshare_add_label', {
postProcess: 'capitalizeFirstChar',
}),
done: false,
},
...prev,
]);
res(response);
return;
}
rej({ message: response.error });
})
.catch((error) => {
rej({
message:
error.message ||
t('core:message.error.generic', {
postProcess: 'capitalizeFirstChar',
}),
});
});
});
}, []);
const getRewardSharePrivateKey = useCallback(async (publicKey) => {
return await new Promise((res, rej) => {
window
.sendMessage('getRewardSharePrivateKey', {
recipientPublicKey: publicKey,
})
.then((response) => {
if (!response?.error) {
res(response);
return;
}
rej({ message: response.error });
})
.catch((error) => {
rej({
message:
error.message ||
t('core:message.error.generic', {
postProcess: 'capitalizeFirstChar',
}),
});
});
});
}, []);
const waitUntilRewardShareIsConfirmed = async (timeoutMs = 600000) => {
const pollingInterval = 30000;
const startTime = Date.now();
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
while (Date.now() - startTime < timeoutMs) {
const rewardShares = await getRewardShares(myAddress);
const findRewardShare = rewardShares?.find(
(item) =>
item?.recipient === myAddress && item?.mintingAccount === myAddress
);
if (findRewardShare) {
return true; // Exit early if found
}
await sleep(pollingInterval); // Wait before the next poll
}
throw new Error(
t('group:message.error.timeout_reward', {
postProcess: 'capitalizeFirstChar',
})
);
};
const startMinting = async () => {
try {
setIsLoading(true);
const findRewardShare = rewardShares?.find(
(item) =>
item?.recipient === myAddress && item?.mintingAccount === myAddress
);
if (findRewardShare) {
const privateRewardShare = await getRewardSharePrivateKey(
accountInfo?.publicKey
);
addMintingAccount(privateRewardShare);
} else {
await createRewardShare(accountInfo?.publicKey, myAddress);
setShowWaitDialog(true);
await waitUntilRewardShareIsConfirmed();
await showNext({
message: '',
});
const privateRewardShare = await getRewardSharePrivateKey(
accountInfo?.publicKey
);
setShowWaitDialog(false);
addMintingAccount(privateRewardShare);
}
} catch (error) {
setShowWaitDialog(false);
setInfo({
type: 'error',
message:
error?.message ||
t('group:message.error:minting', {
postProcess: 'capitalizeFirstChar',
}),
});
setOpenSnack(true);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
getAddressLevel();
getAdminInfo();
getMintingAccounts();
getNodeStatus();
}, []);
useEffect(() => {
if (!myAddress) return;
getRewardShares(myAddress);
getAccountInfo(myAddress);
}, [myAddress]);
const handleClose = () => {
setOpenSnack(false);
setTimeout(() => {
setInfo(null);
}, 250);
};
const StatCard = ({ label, value }: { label: string; value: string }) => (
{label}
{value}
);
const handleChange = (event: SyntheticEvent, newValue: number) => {
setValueMintingTab(newValue);
};
return (
);
};