Skip to content

Commit

Permalink
fix: fixed page crash when storing bank data in persistent storage
Browse files Browse the repository at this point in the history
  • Loading branch information
k0beLeenders committed Jan 7, 2025
1 parent 018a02c commit 7d3df02
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { QuoteResponse } from "@jup-ag/api";
import { ActiveBankInfo } from "@mrgnlabs/marginfi-v2-ui-state";
import { shortenAddress, usdFormatter } from "@mrgnlabs/mrgn-common";
import { composeExplorerUrl } from "@mrgnlabs/mrgn-utils";
import BigNumber from "bignumber.js";

interface Props {
depositBank: ActiveBankInfo;
Expand Down Expand Up @@ -35,6 +36,24 @@ export const TradingScreen = ({
}: Props) => {
const tokenBank = React.useMemo(() => (type === "long" ? depositBank : borrowBank), [type, depositBank, borrowBank]);

const borrowBankOraclePrice = React.useMemo(() => {
const oraclePrice = borrowBank.info.oraclePrice.priceRealtime.price;
if (BigNumber.isBigNumber(oraclePrice)) {
return oraclePrice.toNumber();
} else {
return Number(oraclePrice);
}
}, [borrowBank]);

const depositBankOraclePrice = React.useMemo(() => {
const oraclePrice = depositBank.info.oraclePrice.priceRealtime.price;
if (BigNumber.isBigNumber(oraclePrice)) {
return oraclePrice.toNumber();
} else {
return Number(oraclePrice);
}
}, [depositBank]);

if (!tokenBank) {
return <></>;
}
Expand All @@ -43,13 +62,15 @@ export const TradingScreen = ({
<>
<div className="flex flex-col items-center gap-4 border-b border-border pb-10">
<div className="flex items-center">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className="rounded-full"
src={depositBank.meta.tokenLogoUri}
alt={(depositBank?.meta.tokenSymbol || "Token") + " logo"}
width={48}
height={48}
/>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className="rounded-full -ml-5 relative z-10"
src={borrowBank.meta.tokenLogoUri}
Expand Down Expand Up @@ -82,8 +103,8 @@ export const TradingScreen = ({
<dt>Size</dt>
<dd className="text-right">
{type === "long"
? usdFormatter.format(depositAmount * depositBank.info.oraclePrice.priceRealtime.price.toNumber())
: usdFormatter.format(borrowAmount * borrowBank.info.oraclePrice.priceRealtime.price.toNumber())}
? usdFormatter.format(depositAmount * depositBankOraclePrice)
: usdFormatter.format(borrowAmount * borrowBankOraclePrice)}
</dd>
<dt>Leverage</dt>
<dd className="text-right">{`${leverage}x`}</dd>
Expand Down
24 changes: 10 additions & 14 deletions apps/marginfi-v2-trading/src/pages/api/oracle/priceV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { Connection, PublicKey } from "@solana/web3.js";
import BigNumber from "bignumber.js";
import { NextApiRequest, NextApiResponse } from "next";
import config from "~/config/marginfi";
import { PoolListApiResponse } from "~/types/api.types";
import { OraclePriceString, PoolListApiResponse } from "~/types/api.types";

const SWITCHBOARD_CROSSSBAR_API = process.env.SWITCHBOARD_CROSSSBAR_API || "https://crossbar.switchboard.xyz";
const IS_SWB_STAGE = SWITCHBOARD_CROSSSBAR_API === "https://staging.crossbar.switchboard.xyz";
Expand All @@ -40,19 +40,6 @@ interface OracleDataWithTimestamp extends OracleData {
timestamp: BigNumber;
}

interface PriceWithConfidenceString {
price: string;
confidence: string;
lowestPrice: string;
highestPrice: string;
}

interface OraclePriceString {
priceRealtime: PriceWithConfidenceString;
priceWeighted: PriceWithConfidenceString;
timestamp?: string;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
let host = extractHost(req.headers.origin) || extractHost(req.headers.referer);

Expand Down Expand Up @@ -201,6 +188,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
const bankPkMap = new Map<string, OraclePrice>();

try {
updatedOraclePrices.forEach((value, key) => {
console.log("key", key);
console.log("value", value.priceRealtime.price.toNumber());
});
} catch {
console.log("error");
}

requestedOraclesData.forEach((oracleData) => {
const oraclePrice = updatedOraclePrices.get(oracleData.oracleKey)!;
bankPkMap.set(oracleData.bankPk.toBase58(), oraclePrice);
Expand Down
2 changes: 1 addition & 1 deletion apps/marginfi-v2-trading/src/pages/api/pool/oracle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
queueKey: queueKey.toBase58(),
} as PoolOracleApiResponse);
} catch (error) {
console.error("Error fetching pool data:", error);
console.log("Error fetching oracle data for oracle creation:", error);
return res.status(500).json({
error: "Internal server error",
message: process.env.NODE_ENV === "development" ? error : undefined,
Expand Down
3 changes: 2 additions & 1 deletion apps/marginfi-v2-trading/src/store/tradeStoreV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
BankData,
GroupStatus,
} from "~/types/trade-store.types";
import { OraclePriceV2ApiResponse } from "~/types/api.types";

export enum TradePoolFilterStates {
TIMESTAMP = "timestamp",
Expand Down Expand Up @@ -852,7 +853,7 @@ async function fetchOraclePrices() {
throw new Error("Failed to fetch oracle prices");
}

const responseBody: Record<string, any> = await response.json();
const responseBody: OraclePriceV2ApiResponse = await response.json();

if (!responseBody) {
throw new Error("Failed to fetch oracle prices");
Expand Down
20 changes: 20 additions & 0 deletions apps/marginfi-v2-trading/src/types/api.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,23 @@ export type BirdeyeMarketDataResponse = {
circulating_supply: number;
circulating_marketcap: number;
};

/**
* Type definitions for the /api/oracle/priceV2 endpoint
*/
interface PriceWithConfidenceString {
price: string;
confidence: string;
lowestPrice: string;
highestPrice: string;
}

export interface OraclePriceString {
priceRealtime: PriceWithConfidenceString;
priceWeighted: PriceWithConfidenceString;
timestamp?: string;
}

export type OraclePriceV2ApiResponse = {
[key: string]: OraclePriceString;
};

0 comments on commit 7d3df02

Please sign in to comment.