Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wire up liquidity stat on MarketStats #240

Merged
merged 6 commits into from
Jul 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions apps/hyperdrive-trading/src/ui/hyperdrive/hooks/useLiquidity.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
import { getLiquidityQuery } from "@hyperdrive/core";
import { useQuery, UseQueryResult } from "@tanstack/react-query";
import { QueryStatus, useQuery } from "@tanstack/react-query";
import { Address, usePublicClient } from "wagmi";

export type GetLiquidityResponse = {
marketLiquidity: string;
};
export function useLiquidity(hyperdriveAddress: Address): {
liquidity:
| {
liquidity: bigint;
formatted: string;
}
| undefined;
liquidityStatus: QueryStatus;
} {
const publicClient = usePublicClient();

export function useLiquidity(
hyperdriveAddress: Address,
): UseQueryResult<GetLiquidityResponse> {
const publicClient = usePublicClient() as any;
return useQuery(getLiquidityQuery({ hyperdriveAddress, publicClient }));
const { data, status } = useQuery(
getLiquidityQuery({
hyperdriveAddress,
publicClient: publicClient as any,
}),
);

return {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just return the useQuery itself? Then we have access to all the query helper methods from the hook if we need them.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a design decision @DannyDelott has made to reduce the return signature. If we change it here, we'd probably want to change it everywhere we're not returning the useQuery result.

liquidity: data,
liquidityStatus: status,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function MarketStats({
currentBlockNumber as bigint,
);

const { data: liquidity } = useLiquidity(hyperdrive.address);
const { liquidity } = useLiquidity(hyperdrive.address);
const { fixedAPR } = useCurrentFixedAPR(hyperdrive);
const { longPrice } = useCurrentLongPrice(hyperdrive);

Expand Down Expand Up @@ -62,7 +62,7 @@ export function MarketStats({
value={
<FormattedDaiValue
iconUrl={hyperdrive.baseToken.iconUrl as string}
value={liquidity?.marketLiquidity || "0"}
value={liquidity?.formatted || "0"}
/>
}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Row,
SortableGridTable,
} from "src/ui/base/components/tables/SortableGridTable";
import { formatBalance } from "src/ui/base/formatting/formatBalance";
import {
MarketTableRowData,
useMarketRowData,
Expand Down Expand Up @@ -96,7 +97,6 @@ function createMarketRow({
yieldSource,
liquidity,
}: MarketTableRowData): Row {
const formattedLiquidity = liquidity && parseInt(liquidity).toLocaleString();
return {
href: `/trade/${market.address}`,
cells: [
Expand All @@ -113,7 +113,7 @@ function createMarketRow({
className="flex flex-row items-center justify-start font-semibold"
>
<img className="mr-1 h-4" src={market.baseToken.iconUrl} />
{formattedLiquidity}
{formatBalance(liquidity)}
</span>,
<span key="apy" className="font-semibold">
1.25%
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ async function fetchMarketRowData(
);
const liquidityPromise = getLiquidity(hyperdrive.address, publicClient);

const [stats, { marketLiquidity }] = await Promise.all([
const [stats, liquidity] = await Promise.all([
statsPromise,
liquidityPromise,
]);

return {
market: hyperdrive,
liquidity: marketLiquidity,
liquidity: liquidity.formatted,
...stats,
};
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,33 @@ import { makeQueryKey } from "src/makeQueryKey";

import { QueryObserverOptions } from "@tanstack/query-core";
import { getPoolInfo } from "src/amm/getPoolInfo";
import { multiplyBigInt } from "src/base/multiplyBigInt";

interface GetLiquidityResult {
liquidity: bigint;
formatted: string;
}

/**
* This function retrieves the market liquidity by using the following formula:
* marketLiquidity = sharePrice * shareReserves - longsOutstanding
*
* @param hyperdriveAddress - The address of the hyperdrive
* @param publicClient - The public client
* @returns Promise that resolves with an object containing the market liquidity
*/
export async function getLiquidity(
hyperdriveAddress: Address,
publicClient: PublicClient<Transport, Chain>,
): Promise<{ marketLiquidity: string }> {
const poolInfo = await getPoolInfo({
): Promise<GetLiquidityResult> {
const { sharePrice, shareReserves, longsOutstanding } = await getPoolInfo({
hyperdriveAddress,
publicClient,
});

const sharePrice = parseFloat(formatUnits(poolInfo.sharePrice, 18));
const shareReserves = parseFloat(formatUnits(poolInfo.shareReserves, 18));
const longsOutstanding = parseFloat(
formatUnits(poolInfo.longsOutstanding, 18),
);

const marketLiquidity = sharePrice * shareReserves - longsOutstanding;
const liquidity =
multiplyBigInt([sharePrice, shareReserves], 18) - longsOutstanding;

return { marketLiquidity: marketLiquidity.toString() };
return { liquidity, formatted: formatUnits(liquidity, 18) };
}

interface GetLiquidityQueryOptions {
Expand All @@ -39,14 +39,22 @@ interface GetLiquidityQueryOptions {

type GetLiquidityReturnType = Awaited<ReturnType<typeof getLiquidity>>;

/**
* TODO: Move this to its own @hyperdrive/queries package eventually.
*/
export function getLiquidityQuery({
hyperdriveAddress,
publicClient,
}: GetLiquidityQueryOptions): QueryObserverOptions<GetLiquidityReturnType> {
const queryEnabled = !!hyperdriveAddress;

return {
enabled: queryEnabled,
queryKey: makeQueryKey("get-liquidity", {
hyperdriveAddress,
}),
queryFn: () => getLiquidity(hyperdriveAddress as Address, publicClient),
queryFn: queryEnabled
? () => getLiquidity(hyperdriveAddress, publicClient)
: undefined,
};
}
84 changes: 84 additions & 0 deletions packages/hyperdrive/src/base/multiplyBigInt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* Multiply an array of bigints together and preserve the correct scaling for
* decimals.
*
* @param options - The options to use.
* @param list - The bigints to multiply.
* @param decimals - The number of decimal places the bigints are scaled
* to. If a value in `values` has a `decimals` property, that value will be used
* instead. This is also the number of decimal places the result is scaled to.
*
* @example
*
* ```ts
* // 5.00 * .50 = 2.50
* multiplyBigInt([500n, 50n], 2);
* // 250n
*
* // With different decimals
* // 5.00 * .500 = 2.50
* multiplyBigInt(
* [
* 500n,
* {
* value: 500n,
* decimals: 3
* }
* ],
* 2
* );
* // 250n
* ```
*/
export function multiplyBigInt(
list: (
| bigint
| {
value: bigint;
decimals: number;
}
)[],
decimals: number,
): bigint {
if (list.length === 0) {
return 0n;
}

let totalValue: bigint;
let totalDecimals: number;

// Initialize the total value and decimals to the first value in the array.
if (typeof list[0] === "bigint") {
totalValue = list[0];
totalDecimals = decimals;
} else {
totalValue = list[0].value;
totalDecimals = list[0].decimals;
}

// Multiply the total value by each subsequent value in the array. And add the
// decimals together.
for (const value of list.slice(1)) {
if (typeof value === "bigint") {
totalValue *= value;
totalDecimals += decimals;
} else {
totalValue *= value.value;
totalDecimals += value.decimals;
}
}

// If the total decimals is less than the desired decimals, return 0.
if (totalDecimals < decimals) {
return 0n;
}

// If the total decimals is the same as the desired decimals, avoid doing any
// extra work and return the total value.
if (totalDecimals === decimals) {
return totalValue;
}

// Remove the extra decimal places.
return totalValue / 10n ** BigInt(totalDecimals - decimals);
}
9 changes: 5 additions & 4 deletions packages/hyperdrive/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ export {
export { getShorts } from "src/amm/shorts/getShortsOld";

// Liquidity
export {
getLiquidity,
getLiquidityQuery,
} from "src/amm/liquidity/getLiquidity";
export { getLiquidity, getLiquidityQuery } from "src/amm/getLiquidity";
export {
getClosedShorts,
getClosedShortsQuery,
Expand All @@ -62,3 +59,7 @@ export {
getWithdrawalSharesQuery,
} from "src/amm/lp/getWithdrawalShares";
export type { GetWithdrawalSharesOptions } from "src/amm/lp/getWithdrawalShares";

// Utils
export { sumBigInt } from "src/base/sumBigInt";
export { multiplyBigInt } from "src/base/multiplyBigInt";