Skip to content

Commit

Permalink
Merge pull request #1541 from Itheum/buy-ith
Browse files Browse the repository at this point in the history
feature: put the buy ITH modal everywhere where we say ITH is not enough
  • Loading branch information
newbreedofgeek authored Dec 12, 2024
2 parents fd2e138 + 2dd8983 commit 7b664c0
Show file tree
Hide file tree
Showing 6 changed files with 125 additions and 77 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "data-dex",
"version": "1.18.24",
"version": "1.18.25",
"description": "The Itheum Data DEX enables you to trade your data using web3 tech",
"dependencies": {
"@ashswap/ash-sdk-js": "2.2.0",
Expand Down
96 changes: 45 additions & 51 deletions src/components/BuyItheumModal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useEffect, useState } from "react";
import { Aggregator, ChainId, SorSwapResponse } from "@ashswap/ash-sdk-js/out";
import {
Modal,
ModalOverlay,
Expand All @@ -15,25 +16,15 @@ import {
Box,
Text,
Flex,
useToast,
FormErrorMessage,
} from "@chakra-ui/react";
import { Aggregator, ChainId, SorSwapResponse } from "@ashswap/ash-sdk-js/out";
import { itheumTokenIdentifier, networkConfiguration } from "@itheum/sdk-mx-data-nft/out";
import {
Address,
ApiNetworkProvider,
DefinitionOfFungibleTokenOnNetwork,
ITransactionOnNetwork,
ProxyNetworkProvider,
Transaction,
TransactionWatcher,
} from "@multiversx/sdk-core";
import BigNumber from "bignumber.js";
import { getAccountTokenFromApi, getMvxRpcApi } from "libs/MultiversX/api";
import { sendTransactions } from "@multiversx/sdk-dapp/services";
import { Address, ApiNetworkProvider, DefinitionOfFungibleTokenOnNetwork, ProxyNetworkProvider, Transaction } from "@multiversx/sdk-core";
import { useGetAccountInfo, useGetPendingTransactions } from "@multiversx/sdk-dapp/hooks";
import { sendTransactions } from "@multiversx/sdk-dapp/services";
import BigNumber from "bignumber.js";
import { contractsForChain } from "libs/config";
import { getAccountTokenFromApi, getMvxRpcApi } from "libs/MultiversX/api";
import { convertWeiToEsdt } from "libs/utils";
import { useAccountStore } from "store";

Expand All @@ -59,7 +50,6 @@ const TransactionModal: React.FC<TransactionModalProps> = ({ isOpen, onClose, ad
const [sessionId, setSessionId] = useState<string>();
const { pendingTransactions } = useGetPendingTransactions();
const updateItheumBalance = useAccountStore((state) => state.updateItheumBalance);

const isError = Number(amount) <= 0 || amount === "" || Number(amount) > new BigNumber(account.balance).shiftedBy(-18).toNumber();

useEffect(() => {
Expand All @@ -68,7 +58,9 @@ const TransactionModal: React.FC<TransactionModalProps> = ({ isOpen, onClose, ad
setSwapAmount(BigNumber(0));
return;
}

const numericAmount = new BigNumber(amount).shiftedBy(18);

setFeeAmount(numericAmount.multipliedBy(FEE_PERCENTAGE));
setSwapAmount(numericAmount.multipliedBy(1 - FEE_PERCENTAGE));
}, [amount]);
Expand All @@ -90,13 +82,6 @@ const TransactionModal: React.FC<TransactionModalProps> = ({ isOpen, onClose, ad
fetchTokenDetails();
}, [isOpen]);

const handleClose = () => {
setAmount("1");
onClose();
setIsLoading(false);
setTx(null);
};

useEffect(() => {
const fetchAggregatorResponse = async () => {
if (!swapAmount) return;
Expand Down Expand Up @@ -127,28 +112,6 @@ const TransactionModal: React.FC<TransactionModalProps> = ({ isOpen, onClose, ad
fetchAggregatorResponse();
}, [swapAmount, address, amount]);

const handleSwapTransaction = async () => {
try {
const feeTransaction = new Transaction({
sender: new Address(address),
receiver: new Address(FEE_ADDRESS),
value: feeAmount,
gasLimit: 60000,
chainID: networkConfiguration.mainnet.chainID,
});

const txSent = await sendTransactions({
transactions: [tx, feeTransaction],
});

setIsLoading(true);

setSessionId(txSent["sessionId"]);
} catch (error) {
console.error("Error executing transaction:", error);
}
};

useEffect(() => {
if (!pendingTransactions[sessionId]) return;

Expand Down Expand Up @@ -199,18 +162,47 @@ const TransactionModal: React.FC<TransactionModalProps> = ({ isOpen, onClose, ad
handleTransactionCompletion();
}, [pendingTransactions, sessionId, onClose]);

const handleClose = () => {
setAmount("1");
onClose();
setIsLoading(false);
setTx(null);
};

const handleSwapTransaction = async () => {
try {
const feeTransaction = new Transaction({
sender: new Address(address),
receiver: new Address(FEE_ADDRESS),
value: feeAmount,
gasLimit: 60000,
chainID: networkConfiguration.mainnet.chainID,
});

const txSent = await sendTransactions({
transactions: [tx, feeTransaction],
});

setIsLoading(true);

setSessionId(txSent["sessionId"]);
} catch (error) {
console.error("Error executing transaction:", error);
}
};

return (
<Modal isOpen={isOpen} onClose={() => handleClose()}>
<ModalOverlay backdropFilter="blur(10px)" />
<ModalContent bgColor={colorMode === "dark" ? "#181818" : "bgWhite"}>
<ModalHeader>
<Flex justifyContent="space-between" alignItems="center">
<Text fontSize="large" fontWeight="bold">
Buy $ITHEUM
Buy $ITHEUM with EGLD
</Text>
{itheumTokenDetails?.assets?.svgUrl && <Image src={itheumTokenDetails.assets.svgUrl} alt="Itheum Token" boxSize="60px" ml="8px" />}
</Flex>
<Text fontSize="xs" color="teal.400">
<Text fontSize="xs" color="teal.200" mt="-2">
Powered by AshSwap Aggregator
</Text>
</ModalHeader>
Expand All @@ -227,8 +219,9 @@ const TransactionModal: React.FC<TransactionModalProps> = ({ isOpen, onClose, ad
borderRadius="md"
fontWeight="bold"
fontSize="md"
backgroundColor={colorMode === "dark" ? "teal.400" : "teal.100"}
backgroundColor={colorMode === "dark" ? "teal.200" : "teal.100"}
textAlign="center"
color="black"
display="inline-block">
$EGLD
</Box>{" "}
Expand Down Expand Up @@ -267,20 +260,21 @@ const TransactionModal: React.FC<TransactionModalProps> = ({ isOpen, onClose, ad
Swapped Amount:{" "}
<b>{swapAmount.shiftedBy(-18).toNumber() < 0.1 ? swapAmount.shiftedBy(-18).toFixed(6) : swapAmount.shiftedBy(-18).toFixed(2)} EGLD</b>
</Text>
<Text fontSize="lg" mt={2}>
<Text fontSize="lg" mt={5}>
You will get approximately:
</Text>
<Box
mt={2}
px="40px"
py="5px"
py="8px"
borderRadius="md"
fontWeight="bold"
fontSize="md"
backgroundColor={colorMode === "dark" ? "teal.400" : "teal.100"}
fontSize="lg"
backgroundColor={colorMode === "dark" ? "teal.200" : "teal.100"}
textAlign="center"
display="flex"
alignItems="center"
color="black"
justifyContent="center">
{isNaN(Number(swapDetails?.minReturnAmount)) ? "0.00" : Number(swapDetails?.minReturnAmount).toFixed(2)} $ITHEUM
</Box>
Expand Down
47 changes: 32 additions & 15 deletions src/components/Sections/AppHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { TiArrowSortedDown } from "react-icons/ti";
import { Link as ReactRouterLink, useLocation, useNavigate } from "react-router-dom";
import logoSmlL from "assets/img/logo-icon-b.png";
import logoSmlD from "assets/img/logo-sml-d.png";
import BuyItheumModal from "components/BuyItheumModal";
import ClaimsHistory from "components/ClaimsHistory";
import Countdown from "components/CountDown";
import InteractionsHistory from "components/Tables/InteractionHistory";
Expand All @@ -59,12 +60,6 @@ import ShortAddress from "components/UtilComps/ShortAddress";
import { CHAIN_TOKEN_SYMBOL, CHAINS, MENU, EXPLORER_APP_FOR_TOKEN } from "libs/config";
import { formatNumberRoundFloor } from "libs/utils";
import { useAccountStore } from "store";
import { Aggregator, ChainId } from "@ashswap/ash-sdk-js/out";
import { itheumTokenIdentifier } from "@itheum/sdk-mx-enterprise/out";
import BigNumber from "bignumber.js";
import { Address } from "@multiversx/sdk-core/out";
import { sendTransactions } from "@multiversx/sdk-dapp/services";
import TransactionModal from "components/BuyItheumModal";

const exploreRouterMenu = [
{
Expand Down Expand Up @@ -139,7 +134,7 @@ const exploreRouterMenu = [
menuEnum: MENU.LIVELINESS,
path: "/datanfts/wallet/liveliness",
label: "Liveliness Staking",
shortLbl: "Liveliness",
shortLbl: "Staking",
Icon: FaTachometerAlt,
needToBeLoggedIn: true,
isHidden: false,
Expand All @@ -162,9 +157,9 @@ const AppHeader = ({ onShowConnectWalletModal, setMenuItem, handleLogout }: { on
const [mxShowInteractionsHistory, setMxInteractionsHistory] = useState(false);
const bitzBalance = useAccountStore((state) => state.bitzBalance);
const cooldown = useAccountStore((state) => state.cooldown);
const connectBtnTitle = useBreakpointValue({ base: "Connect Wallet", md: "Connect MultiversX Wallet" });
const connectBtnTitle = useBreakpointValue({ base: "Connect Wallet", md: "Login via Wallet" });
const navigate = useNavigate();
const [isModalOpen, setIsModalOpen] = useState(false);
const [buyItheumModalOpen, setIsBuyItheumModalOpen] = useState(false);

const navigateToDiscover = (menuEnum: number) => {
setMenuItem(menuEnum);
Expand Down Expand Up @@ -262,9 +257,9 @@ const AppHeader = ({ onShowConnectWalletModal, setMenuItem, handleLogout }: { on
const { path, menuEnum, shortLbl, isHidden, Icon } = quickMenuItem;
return (
<Link
ml={"3px"}
as={ReactRouterLink}
to={path}
mx={"4px"}
style={{ textDecoration: "none" }}
key={path}
display={shouldDisplayQuickMenuItem(quickMenuItem, isMxLoggedIn)}>
Expand Down Expand Up @@ -294,20 +289,21 @@ const AppHeader = ({ onShowConnectWalletModal, setMenuItem, handleLogout }: { on
fontSize="md"
variant="outline"
h={"12"}
display={isMxLoggedIn ? "initial" : "none"}
isDisabled={hasPendingTransactions}
ml={"8px"}
isDisabled={hasPendingTransactions || !isMxLoggedIn}
title="Login via Wallet to Buy $ITHEUM using EGLD"
key={"buy_itheum"}
size={isMxLoggedIn ? "sm" : "md"}
onClick={() => setIsModalOpen(true)}>
<Text pl={2} fontSize={{ base: isMxLoggedIn ? "sm" : "md", "2xl": "lg" }} color={colorMode === "dark" ? "white" : "black"}>
onClick={() => setIsBuyItheumModalOpen(true)}>
<Text fontSize={{ base: isMxLoggedIn ? "sm" : "md", "2xl": "lg" }} color={colorMode === "dark" ? "white" : "black"}>
Buy $ITHEUM
</Text>
</Button>
</HStack>
{isMxLoggedIn && (
<>
<ItheumTokenBalanceBadge displayParams={["none", null, "block"]} />
<TransactionModal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} address={mxAddress} />
<BuyItheumModal isOpen={buyItheumModalOpen} onClose={() => setIsBuyItheumModalOpen(false)} address={mxAddress} />
<LoggedInChainBadge chain={chainFriendlyName} displayParams={["none", null, "block"]} />
<Box display={{ base: "none", md: "block" }} zIndex="11">
{exploreRouterMenu.map((menu) => (
Expand Down Expand Up @@ -362,6 +358,14 @@ const AppHeader = ({ onShowConnectWalletModal, setMenuItem, handleLogout }: { on
</MenuGroup>

<MenuGroup>
<MenuItem
onClick={() => setIsBuyItheumModalOpen(true)}
fontSize="lg"
fontWeight="500"
isDisabled={hasPendingTransactions}
backgroundColor={colorMode === "dark" ? "#181818" : "bgWhite"}>
Buy $ITHEUM
</MenuItem>
{isMxLoggedIn && (
<ChainSupportedComponent feature={MENU.CLAIMS}>
<MenuItem
Expand Down Expand Up @@ -683,6 +687,18 @@ const AppHeader = ({ onShowConnectWalletModal, setMenuItem, handleLogout }: { on
);
})}

<ListItem
as={Button}
variant={"ghost"}
w={"full"}
borderRadius={"0"}
display={"flex"}
justifyContent={"start"}
p={3}
onClick={() => setIsBuyItheumModalOpen(true)}>
Buy $ITHEUM
</ListItem>

<ListItem
as={Button}
variant={"ghost"}
Expand All @@ -694,6 +710,7 @@ const AppHeader = ({ onShowConnectWalletModal, setMenuItem, handleLogout }: { on
onClick={() => setMxShowClaimsHistory(true)}>
View Claims History
</ListItem>

<ListItem
as={Button}
variant={"ghost"}
Expand Down
4 changes: 2 additions & 2 deletions src/libs/language.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const labels = {
"The Data Marshal is unavailable to provide a status check on this Data Stream URL. This may mean that the Data Stream is unavailable. Do not proceed with the transaction. (ER-16)",
"ERR_MARKET_REQ_FAIL": "Could not fetch marketplace requirements. (ER-17)",
"ERR_MARKET_OFFERS_FAIL": "Could not fetch marketplace offers. (ER-18)",
"ERR_MINT_FORM_NOT_ENOUGH_TAX": "You have insufficient ITHEUM tokens for the Anti-Spam Tax. (ER-19)",
"ERR_MINT_FORM_NOT_ENOUGH_TAX": "You have insufficient $ITHEUM tokens for the Anti-Spam Tax. (ER-19)",
"ERR_MINT_FORM_GEN_IMG_API_DOWN": "Generative image generation service is not responding. (ER-20)",
"ERR_CONTRACT_PARAM_READ": "Could not fetch parameters from the smart contract. (ER-21)",
"ERR_API_ISSUE_DATA_NFT_DETAILS": "Could not fetch Data NFT-FT details. (ER-22)",
Expand Down Expand Up @@ -49,5 +49,5 @@ export const labels = {
"ADD_FAVORITE_FAILS": "Could not add to favorites. (ER-27)",
"REMOVE_FAVORITE_FAILS": "Could not remove from favorites. (ER-28)",
"ERR_MARKET_NR_OFFERS_FAIL": "Could not fetch number of marketplace offers. (ER-29)",
"ERR_MINT_FORM_NOT_ENOUGH_BOND": "You have insufficient ITHEUM tokens for the Liveness Bonding.",
"ERR_MINT_FORM_NOT_ENOUGH_BOND": "You have insufficient $ITHEUM tokens for the Liveness Bonding.",
};
Loading

0 comments on commit 7b664c0

Please sign in to comment.