Skip to content

Commit

Permalink
Merge branch 'main' into feature/stake-box
Browse files Browse the repository at this point in the history
  • Loading branch information
borcherd committed Oct 11, 2024
2 parents c1ea5c5 + 6f07e46 commit 8cc4090
Show file tree
Hide file tree
Showing 15 changed files with 135 additions and 149 deletions.
Binary file added apps/marginfi-v2-trading/public/phantom.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -482,12 +482,13 @@ function canBeLooped(activeGroup: GroupData, loopingObject: LoopingObject, trade
}
}

if (
(activeGroup.pool.token && isBankOracleStale(activeGroup.pool.token)) ||
(activeGroup.pool.quoteTokens[0] && isBankOracleStale(activeGroup.pool.quoteTokens[0]))
) {
checks.push(STATIC_SIMULATION_ERRORS.STALE_TRADING);
}
// Banks will always be stale for now
// if (
// (activeGroup.pool.token && isBankOracleStale(activeGroup.pool.token)) ||
// (activeGroup.pool.quoteTokens[0] && isBankOracleStale(activeGroup.pool.quoteTokens[0]))
// ) {
// checks.push(STATIC_SIMULATION_ERRORS.STALE_TRADING);
// }

return checks;
}
76 changes: 0 additions & 76 deletions apps/marginfi-v2-trading/src/context/MrgnlendProvider.tsx

This file was deleted.

1 change: 0 additions & 1 deletion apps/marginfi-v2-trading/src/context/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export * from "./MrgnlendProvider";
export * from "./TradeProvider";
48 changes: 23 additions & 25 deletions apps/marginfi-v2-trading/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { AuthDialog } from "@mrgnlabs/mrgn-ui";

import config from "~/config";
import { useTradeStore } from "~/store";
import { MrgnlendProvider, TradePovider } from "~/context";
import { TradePovider } from "~/context";
import { WALLET_ADAPTERS } from "~/config/wallets";
import { BANK_METADATA_MAP } from "~/config/trade";
import { WalletProvider as MrgnWalletProvider } from "~/components/wallet-v2/hooks/use-wallet.hook";
Expand Down Expand Up @@ -53,33 +53,31 @@ export default function MrgnApp({ Component, pageProps, path, bank }: AppProps &
<TipLinkWalletAutoConnect isReady={isReady} query={query}>
<WalletProvider wallets={WALLET_ADAPTERS} autoConnect={true}>
<MrgnWalletProvider>
<MrgnlendProvider>
<TradePovider>
<div className="mrgn-bg-gradient">
<Header />

<Desktop>
<WalletModalProvider>
<div className="w-full flex flex-col justify-center items-center">
<Component {...pageProps} />
</div>
<Footer />
</WalletModalProvider>
</Desktop>

<Mobile>
<MobileNavbar />
<TradePovider>
<div className="mrgn-bg-gradient">
<Header />

<Desktop>
<WalletModalProvider>
<div className="w-full flex flex-col justify-center items-center">
<Component {...pageProps} />
</div>
</Mobile>
<Analytics />

<AuthDialog onboardingEnabled={false} />
<ToastContainer position="bottom-left" theme="light" />
</div>
</TradePovider>
</MrgnlendProvider>
<Footer />
</WalletModalProvider>
</Desktop>

<Mobile>
<MobileNavbar />
<div className="w-full flex flex-col justify-center items-center">
<Component {...pageProps} />
</div>
</Mobile>
<Analytics />

<AuthDialog onboardingEnabled={false} />
<ToastContainer position="bottom-left" theme="light" />
</div>
</TradePovider>
</MrgnWalletProvider>
</WalletProvider>
</TipLinkWalletAutoConnect>
Expand Down
19 changes: 12 additions & 7 deletions apps/marginfi-v2-trading/src/pages/api/oracle/price.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ interface OracleData {
maxAge: number;
}

interface OracleDataWithTimestamp extends OracleData {
timestamp: BigNumber;
}

interface PriceWithConfidenceString {
price: string;
confidence: string;
Expand Down Expand Up @@ -77,9 +81,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (!host) {
return res.status(400).json({ error: "Invalid input: expected a valid host." });
}
const feedIdMapRaw: Record<string, string> = await fetch(`${host}/api/oracle/pythFeedMap`).then((response) =>
response.json()
);
const feedIdMapRaw: Record<string, string> = await fetch(
`${host}/api/oracle/pythFeedMap?groupPk=${banksMap[0].data.group.toBase58()}`
).then((response) => response.json());
const feedIdMap: Map<string, PublicKey> = new Map(
Object.entries(feedIdMapRaw).map(([key, value]) => [key, new PublicKey(value)])
);
Expand All @@ -94,7 +98,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const oracleAis = await chunkedGetRawMultipleAccountInfoOrdered(connection, [
...requestedOraclesData.map((oracleData) => oracleData.oracleKey),
]);
let swbPullOraclesStale: { data: OracleData; feedHash: string }[] = [];
let swbPullOraclesStale: { data: OracleDataWithTimestamp; feedHash: string }[] = [];
for (const index in requestedOraclesData) {
const oracleData = requestedOraclesData[index];
const priceDataRaw = oracleAis[index];
Expand All @@ -107,7 +111,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// If on-chain data is recent enough, use it even for SwitchboardPull oracles
if (oracleData.oracleSetup === OracleSetup.SwitchboardPull && isStale) {
swbPullOraclesStale.push({
data: oracleData,
data: { ...oracleData, timestamp: oraclePrice.timestamp },
feedHash: Buffer.from(decodeSwitchboardPullFeedData(priceDataRaw.data).feed_hash).toString("hex"),
});
continue;
Expand All @@ -122,15 +126,16 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const crossbarPrices = await fetchCrossbarPrices(feedHashes);

for (const {
data: { oracleKey },
data: { oracleKey, timestamp },
feedHash,
} of swbPullOraclesStale) {
const crossbarPrice = crossbarPrices.get(feedHash);
if (!crossbarPrice) {
throw new Error(`Crossbar didn't return data for ${feedHash}`);
}
const updatedOraclePrice = { ...crossbarPrice, timestamp } as OraclePrice;

updatedOraclePrices.set(oracleKey, crossbarPrice);
updatedOraclePrices.set(oracleKey, updatedOraclePrice);
}
}

Expand Down
9 changes: 7 additions & 2 deletions apps/marginfi-v2-trading/src/pages/api/oracle/pythFeedMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@ import { Connection, PublicKey } from "@solana/web3.js";
import { NextApiRequest, NextApiResponse } from "next";
import config from "~/config/marginfi";

export default async function handler(_req: NextApiRequest, res: NextApiResponse) {
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const groupPk = req.query.groupPk;
if (!groupPk || typeof groupPk !== "string") {
return res.status(400).json({ error: "Invalid input: expected a groupPk string." });
}

const connection = new Connection(
process.env.PRIVATE_RPC_ENDPOINT_OVERRIDE || process.env.NEXT_PUBLIC_MARGINFI_RPC_ENDPOINT_OVERRIDE || ""
);
Expand All @@ -26,7 +31,7 @@ export default async function handler(_req: NextApiRequest, res: NextApiResponse

let bankAddresses = (
await connection.getProgramAccounts(config.mfiConfig.programId, {
filters: [{ memcmp: { offset: 8 + 32 + 1, bytes: config.mfiConfig.groupPk.toBase58() } }],
filters: [{ memcmp: { offset: 8 + 32 + 1, bytes: groupPk } }],
dataSlice: { length: 0, offset: 0 },
})
).map((bank) => bank.pubkey.toBase58());
Expand Down
2 changes: 2 additions & 0 deletions apps/marginfi-v2-trading/src/store/tradeStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
computeAccountSummary,
DEFAULT_ACCOUNT_SUMMARY,
AccountSummary,
fetchGroupData,
} from "@mrgnlabs/marginfi-v2-ui-state";
import {
MarginfiClient,
Expand Down Expand Up @@ -526,6 +527,7 @@ async function getGroupData({
connection,
{
preloadedBankAddresses: bankKeys,
fetchGroupDataOverride: fetchGroupData,
}
);

Expand Down
Binary file added apps/marginfi-v2-ui/public/phantom.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 5 additions & 5 deletions packages/marginfi-v2-ui-state/src/lib/mrgnlend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ function computeAccountSummary(marginfiAccount: MarginfiAccountWrapper, banks: E

function makeBankInfo(bank: Bank, oraclePrice: OraclePrice, emissionTokenData?: TokenPrice): BankState {
const { lendingRate, borrowingRate } = bank.computeInterestRates();
const totalDeposits = nativeToUi(bank.getTotalAssetQuantity(), bank.mintDecimals);
const totalBorrows = nativeToUi(bank.getTotalLiabilityQuantity(), bank.mintDecimals);
const totalDeposits = nativeToUi(bank.totalAssetShares, bank.mintDecimals);
const totalBorrows = nativeToUi(bank.totalLiabilityShares, bank.mintDecimals);
const liquidity = totalDeposits - totalBorrows;
const utilizationRate = bank.computeUtilizationRate().times(100).toNumber();

Expand Down Expand Up @@ -552,9 +552,9 @@ async function fetchGroupData(
}

async function fetchPythFeedMap() {
const feedIdMapRaw: Record<string, string> = await fetch(`/api/oracle/pythFeedMap`).then((response) =>
response.json()
);
const feedIdMapRaw: Record<string, string> = await fetch(
`/api/oracle/pythFeedMap?groupPk=${groupAddress.toBase58()}`
).then((response) => response.json());
const feedIdMap: Map<string, PublicKey> = new Map(
Object.entries(feedIdMapRaw).map(([key, value]) => [key, new PublicKey(value)])
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const AuthDialog = ({ mrgnState, onboardingEnabled = true }: AuthDialogPr
const [isLoading, setIsLoading] = React.useState<boolean>(false);
const [isActiveLoading, setIsActiveLoading] = React.useState<string>("");
const [progress, setProgress] = React.useState<number>(0);
const { loginWeb3Auth, connecting, connected, walletContextState } = useWallet();
const { loginWeb3Auth, connecting, connected, select, walletContextState } = useWallet();
const { query, replace, pathname } = useRouter();

// if user has PWA force social login
Expand Down Expand Up @@ -112,7 +112,7 @@ export const AuthDialog = ({ mrgnState, onboardingEnabled = true }: AuthDialogPr

setIsLoading(true);
setIsActiveLoading(selectedWallet);
walletContextState.select(selectedWallet as any);
select(selectedWallet as any);

const newQuery = { ...query };
delete newQuery.onramp;
Expand All @@ -126,7 +126,7 @@ export const AuthDialog = ({ mrgnState, onboardingEnabled = true }: AuthDialogPr
{ shallow: true }
);
}
}, [pathname, query, query.onramp, replace, walletContextState.select]);
}, [pathname, query, query.onramp, replace, select, walletContextState]);

// reset on force close
React.useEffect(() => {
Expand All @@ -145,7 +145,7 @@ export const AuthDialog = ({ mrgnState, onboardingEnabled = true }: AuthDialogPr
if (!selectedWallet) return;
setIsLoading(true);
setIsActiveLoading(selectedWallet);
walletContextState.select(selectedWallet as any);
select(selectedWallet as any);
localStorage.setItem("isOnboarded", "true");
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const web3AuthIconMap: { [key in Web3AuthProvider]: { icon: JSX.Element } } = {
};

export const WalletButton = () => {
const { connected, isLoading, loginWeb3Auth, walletContextState } = useWallet();
const { connected, isLoading, loginWeb3Auth, select, walletContextState } = useWallet();
const [setIsWalletSignUpOpen] = useWalletStore((state) => [state.setIsWalletSignUpOpen]);

const walletInfo = useMemo(() => JSON.parse(localStorage.getItem("walletInfo") ?? "null") as WalletInfo, []);
Expand Down Expand Up @@ -64,12 +64,12 @@ export const WalletButton = () => {
loginWeb3Auth(walletInfo.name);
}
} else {
walletContextState.select(walletInfo.name as any);
select(walletInfo.name as any);
}
} catch (error) {
setIsWalletSignUpOpen(true);
}
}, [walletInfo, setIsWalletSignUpOpen, walletContextState.select, loginWeb3Auth]);
}, [walletInfo, setIsWalletSignUpOpen, select, loginWeb3Auth]);

return (
<Button className={`gap-1.5 py-0 ${walletInfo ? "pr-2" : "pr-4"}`}>
Expand Down
Loading

0 comments on commit 8cc4090

Please sign in to comment.