Skip to content

Commit

Permalink
Show estimated usd value based on query data
Browse files Browse the repository at this point in the history
  • Loading branch information
dkildar committed Nov 9, 2024
1 parent f6d3957 commit 7d791cd
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 189 deletions.
128 changes: 0 additions & 128 deletions src/api/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1422,134 +1422,6 @@ export const updatePassword = (
ownerKey: PrivateKey
): Promise<TransactionConfirmation> => hiveClient.broadcast.updateAccount(update, ownerKey);

// HE Hive Signer Operations
export const transferHiveEngineHs = (
from: string,
to: string,
symbol: string,
amount: string,
memo: string
): any => {
const params = {
authority: "active",
required_auths: `["${from}"]`,
required_posting_auths: "[]",
id: "ssc-mainnet-hive",
json: JSON.stringify({
contractName: "tokens",
contractAction: "transfer",
contractPayload: {
symbol,
to,
quantity: amount.toString(),
memo
}
})
};

return hotSign("custom-json", params, `@${from}/engine`);
};

export const delegateHiveEngineHs = (
from: string,
to: string,
symbol: string,
amount: string
): any => {
const params = {
authority: "active",
required_auths: `["${from}"]`,
required_posting_auths: "[]",
id: "ssc-mainnet-hive",
json: JSON.stringify({
contractName: "tokens",
contractAction: "delegate",
contractPayload: {
symbol,
to,
quantity: amount.toString()
}
})
};

return hotSign("custom-json", params, `@${from}/engine`);
};

export const undelegateHiveEngineHs = (
from: string,
to: string,
symbol: string,
amount: string
): any => {
const params = {
authority: "active",
required_auths: `["${from}"]`,
required_posting_auths: "[]",
id: "ssc-mainnet-hive",
json: JSON.stringify({
contractName: "tokens",
contractAction: "undelegate",
contractPayload: {
symbol,
from: to,
quantity: amount.toString()
}
})
};

return hotSign("custom-json", params, `@${from}/engine`);
};

export const stakeHiveEngineHs = (
from: string,
to: string,
symbol: string,
amount: string
): any => {
const params = {
authority: "active",
required_auths: `["${from}"]`,
required_posting_auths: "[]",
id: "ssc-mainnet-hive",
json: JSON.stringify({
contractName: "tokens",
contractAction: "stake",
contractPayload: {
symbol,
to,
quantity: amount.toString()
}
})
};

return hotSign("custom-json", params, `@${from}/engine`);
};

export const unstakeHiveEngineHs = (
from: string,
to: string,
symbol: string,
amount: string
): any => {
const params = {
authority: "active",
required_auths: `["${from}"]`,
required_posting_auths: "[]",
id: "ssc-mainnet-hive",
json: JSON.stringify({
contractName: "tokens",
contractAction: "unstake",
contractPayload: {
symbol,
to,
quantity: amount.toString()
}
})
};

return hotSign("custom-json", params, `@${from}/engine`);
};

export const Revoke = (
account: string,
weight_threshold: number,
Expand Down
17 changes: 10 additions & 7 deletions src/api/queries/engine/get-hive-engine-balances-query.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EcencyQueriesManager, QueryIdentifiers } from "@/core/react-query";
import { QueryIdentifiers } from "@/core/react-query";
import { TokenMetadata } from "@/entities";
import { HiveEngineToken } from "@/utils";
import { getTokenBalances, getTokens } from "@/api/hive-engine";
Expand All @@ -9,19 +9,21 @@ import {
getAllHiveEngineTokensQuery,
getDynamicPropsQuery
} from "@/api/queries";
import { useQuery } from "@tanstack/react-query";

export const getHiveEngineBalancesQuery = (account?: string) =>
EcencyQueriesManager.generateClientServerQuery({
queryKey: [QueryIdentifiers.HIVE_ENGINE_TOKEN_BALANCES],
export function useGetHiveEngineBalancesQuery(account?: string) {
const { data: dynamicProps = DEFAULT_DYNAMIC_PROPS } = getDynamicPropsQuery().useClientQuery();
const { data: allTokens } = getAllHiveEngineTokensQuery().useClientQuery();

return useQuery({
queryKey: [QueryIdentifiers.HIVE_ENGINE_TOKEN_BALANCES, account, dynamicProps, allTokens],
queryFn: async () => {
if (!account) {
throw new Error("[HiveEngine] No account in a balances query");
}

const balances = await getTokenBalances(account);
const tokens = await getTokens(balances.map((t) => t.symbol));
const dynamicProps = (await getDynamicPropsQuery().prefetch()) ?? DEFAULT_DYNAMIC_PROPS;
const allTokens = (await getAllHiveEngineTokensQuery(account).prefetch()) ?? [];

return balances.map((balance) => {
const token = tokens.find((t) => t.symbol == balance.symbol);
Expand All @@ -48,10 +50,11 @@ export const getHiveEngineBalancesQuery = (account?: string) =>
},
enabled: !!account
});
}

export function useHiveEngineAssetWallet(asset: string) {
const activeUser = useGlobalStore((s) => s.activeUser);
const { data: wallets } = getHiveEngineBalancesQuery(activeUser?.username).useClientQuery();
const { data: wallets } = useGetHiveEngineBalancesQuery(activeUser?.username);

return useMemo(() => wallets?.find((w) => w.symbol === asset), [wallets, asset]);
}
Original file line number Diff line number Diff line change
@@ -1,52 +1,26 @@
import React, { useCallback, useEffect, useState } from "react";
import { getMetrics } from "@/api/hive-engine";
import React, { useMemo } from "react";
import i18next from "i18next";
import { DEFAULT_DYNAMIC_PROPS, getDynamicPropsQuery } from "@/api/queries";

export const EngineTokensEstimated = (props: any) => {
const { tokens: userTokens } = props;

const { data: dynamicProps } = getDynamicPropsQuery().useClientQuery();
const [estimated, setEstimated] = useState(`${i18next.t("wallet.calculating")}...`);

const getEstimatedUsdValue = useCallback(async () => {
const AllMarketTokens = await getMetrics();

const pricePerHive =
(dynamicProps ?? DEFAULT_DYNAMIC_PROPS).base / (dynamicProps ?? DEFAULT_DYNAMIC_PROPS).quote;

let mappedBalanceMetrics = userTokens.map((item: any) => {
let eachMetric = AllMarketTokens.find((m: any) => m.symbol === item.symbol);
return {
...item,
...eachMetric
};
});

// const walletTokens = mappedBalanceMetrics.filter((w: any) => w.balance !== 0 || w.stakedBalance !== 0)

const tokens_usd_prices = mappedBalanceMetrics.map((w: any) => {
return w.symbol === "SWAP.HIVE"
? Number(pricePerHive * w.balance)
: w.lastPrice === 0
? 0
: Number((w.lastPrice ?? 0) * pricePerHive * w.balance);
});

const totalWalletUsdValue = tokens_usd_prices.reduce(
(x: any, y: any) => +(x + y).toFixed(3),
0
);
const usd_total_value = totalWalletUsdValue.toLocaleString("en-US", {
style: "currency",
currency: "USD"
});
setEstimated(usd_total_value);
}, [dynamicProps, userTokens]);

useEffect(() => {
getEstimatedUsdValue();
}, [getEstimatedUsdValue, userTokens]);
import { HiveEngineToken } from "@/utils";

interface Props {
tokens: HiveEngineToken[];
}

export const EngineTokensEstimated = ({ tokens }: Props) => {
const estimated = useMemo(() => {
if (tokens.length > 0) {
const totalWalletUsdValue = +tokens
.map((item) => +item.usdValue)
.reduce((acc, item) => +(acc + item), 0)
.toFixed(3);
return totalWalletUsdValue.toLocaleString("en-US", {
style: "currency",
currency: "USD"
});
}

return `${i18next.t("wallet.calculating")}...`;
}, [tokens]);

return (
<div className="balance-row estimated alternative">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { SortEngineTokens } from "./sort-hive-engine-tokens";
import { EngineTokensEstimated } from "./engine-tokens-estimated";
import { Account, TokenStatus } from "@/entities";
import { useGlobalStore } from "@/core/global-store";
import { getHiveEngineBalancesQuery } from "@/api/queries";
import { useGetHiveEngineBalancesQuery } from "@/api/queries";
import { formatError } from "@/api/operations";
import useMount from "react-use/lib/useMount";
import { WalletMenu } from "../../_components/wallet-menu";
Expand All @@ -36,9 +36,7 @@ export function WalletHiveEngine({ account }: Props) {
"delegationIn" | "asc" | "desc" | "balance" | "stake" | "delegationOut" | "usdValue"
>();

const { data: balancesData, isFetching } = getHiveEngineBalancesQuery(
account.name
).useClientQuery();
const { data: balancesData, isFetching } = useGetHiveEngineBalancesQuery(account.name);

const tokens = useMemo(
() =>
Expand Down Expand Up @@ -206,7 +204,7 @@ export function WalletHiveEngine({ account }: Props) {
</div>
</div>

<EngineTokensEstimated tokens={balancesData} />
<EngineTokensEstimated tokens={balancesData ?? []} />

{tokens.length >= 3 && (
<div className="wallet-info">
Expand Down
3 changes: 2 additions & 1 deletion src/app/(dynamicPages)/profile/[username]/engine/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getAccountFullQuery } from "@/api/queries";
import { getAccountFullQuery, getDynamicPropsQuery } from "@/api/queries";
import { notFound } from "next/navigation";
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { getQueryClient } from "@/core/react-query";
Expand All @@ -18,6 +18,7 @@ export async function generateMetadata(props: Props, parent: ResolvingMetadata):
export default async function EnginePage({ params }: Props) {
const { username } = await params;
const account = await getAccountFullQuery(username.replace("%40", "")).prefetch();
await getDynamicPropsQuery().prefetch();

if (!account) {
return notFound();
Expand Down

0 comments on commit 7d791cd

Please sign in to comment.