Skip to content

Commit

Permalink
fix: marginfi client state & portfolio bug & cleanup console.log
Browse files Browse the repository at this point in the history
  • Loading branch information
k0beLeenders committed Aug 11, 2024
1 parent 601b305 commit 3ae3eb0
Show file tree
Hide file tree
Showing 13 changed files with 82 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,16 @@ export const ActionBox = ({
isTokenSelectable,
handleCloseDialog,
}: ActionBoxProps) => {
const [isInitialized, setIsRefreshingStore, activeGroupPk, groupMap, mfiClient, nativeSolBalance, refreshGroup] =
useTradeStore((state) => [
const [isInitialized, setIsRefreshingStore, activeGroupPk, groupMap, nativeSolBalance, refreshGroup] = useTradeStore(
(state) => [
state.initialized,
state.setIsRefreshingStore,
state.activeGroup,
state.groupMap,
state.marginfiClient,
state.nativeSolBalance,
state.refreshGroup,
]);
]
);

const activeGroup = React.useMemo(() => {
const group = activeGroupPk ? groupMap.get(activeGroupPk.toBase58()) || null : null;
Expand Down Expand Up @@ -363,6 +363,7 @@ export const ActionBox = ({
setIsActionComplete,
setPreviousTxn,
setIsRefreshingStore,
refreshGroup,
connection,
wallet,
activeGroup?.groupPk,
Expand Down Expand Up @@ -443,7 +444,7 @@ export const ActionBox = ({
};

const handleLstAction = React.useCallback(async () => {
if ((!selectedBank && !selectedStakingAccount) || !mfiClient || !lstData) {
if ((!selectedBank && !selectedStakingAccount) || !activeGroup?.client || !lstData) {
return;
}

Expand Down Expand Up @@ -473,7 +474,7 @@ export const ActionBox = ({

const txnSig = await executeLstAction({
actionMode,
marginfiClient: mfiClient,
marginfiClient: activeGroup.client,
amount,
connection,
wallet,
Expand Down Expand Up @@ -538,7 +539,8 @@ export const ActionBox = ({
}, [
selectedBank,
selectedStakingAccount,
mfiClient,
activeGroup?.client,
activeGroup?.groupPk,
lstData,
lstQuoteMeta,
setIsLoading,
Expand All @@ -553,17 +555,18 @@ export const ActionBox = ({
setIsActionComplete,
setPreviousTxn,
setIsRefreshingStore,
activeGroup?.groupPk,
refreshGroup,
]);

const handleLendingAction = React.useCallback(async () => {
if (!actionMode || !selectedBank || (!amount && !repayAmount)) {
console.log({ activeGroup });
if (!actionMode || !activeGroup?.client || !selectedBank || (!amount && !repayAmount)) {
return;
}

const action = async () => {
const params = {
mfiClient,
mfiClient: activeGroup.client,
actionType: actionMode,
bank: selectedBank,
amount,
Expand All @@ -589,10 +592,10 @@ export const ActionBox = ({
await action();
}, [
actionMode,
activeGroup?.client,
selectedBank,
amount,
repayAmount,
mfiClient,
nativeSolBalance,
selectedAccount,
walletContextState,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,8 @@ export const LendingPreview = ({
addAdditionalsPopup,
children,
}: ActionBoxPreviewProps) => {
const [marginfiClient] = useTradeStore((state) => [state.marginfiClient]);

const { preview, previewStats, isLoading, actionMethod } = useLendingPreview({
marginfiClient: activeGroup?.client ?? marginfiClient,
marginfiClient: activeGroup?.client ?? null,
accountSummary: activeGroup?.accountSummary ?? DEFAULT_ACCOUNT_SUMMARY,
actionMode,
account: activeGroup?.selectedAccount ?? null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@ import { useTradeStore } from "~/store";
import { Button } from "~/components/ui/button";

export const ActiveGroup = () => {
const [activeGroupPk, groupMap, marginfiClient] = useTradeStore((state) => [
state.activeGroup,
state.groupMap,
state.marginfiClient,
]);
const [activeGroupPk, groupMap] = useTradeStore((state) => [state.activeGroup, state.groupMap]);

const activeGroup = React.useMemo(() => {
return (activeGroupPk ? groupMap.get(activeGroupPk.toBase58()) : null) ?? null;
Expand All @@ -31,8 +27,8 @@ export const ActiveGroup = () => {

return (
<div className="fixed bottom-14 left-6 bg-secondary/90 max-w-fit p-4 rounded-xl text-sm z-50">
{(!activeGroup || !activeGroup.pool.token || !marginfiClient) && <p>No active group</p>}
{activeGroup && activeGroup.pool.token && marginfiClient && isOpen && (
{(!activeGroup || !activeGroup.pool.token || !activeGroup.client) && <p>No active group</p>}
{activeGroup && activeGroup.pool.token && activeGroup.client && isOpen && (
<>
<Button variant="ghost" className="absolute top-2 right-2 h-auto p-1" onClick={() => setIsOpen(false)}>
<IconX size={14} />
Expand All @@ -52,12 +48,12 @@ export const ActiveGroup = () => {
<li>
<strong className="font-medium">Active group</strong>:{" "}
<Link
href={`https://solana.fm/address/${marginfiClient.groupAddress.toBase58()}`}
href={`https://solana.fm/address/${activeGroup.client.groupAddress.toBase58()}`}
target="_blank"
rel="noreferrer"
className="text-chartreuse"
>
{shortenAddress(marginfiClient.groupAddress)}
{shortenAddress(activeGroup.client.groupAddress)}
</Link>
</li>
<li>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@ import { ActionType, ExtendedBankInfo } from "@mrgnlabs/marginfi-v2-ui-state";
import { numeralFormatter, usdFormatter, tokenPriceFormatter } from "@mrgnlabs/mrgn-common";

import { getTokenImageURL } from "~/utils";
import { useTradeStore } from "~/store";
import { GroupData } from "~/store/tradeStore";
import { useAssetItemData } from "~/hooks/useAssetItemData";

import { ActionBoxDialog } from "~/components/common/ActionBox";
import { Button } from "~/components/ui/button";

type BankCardProps = {
activeGroup: GroupData;
bank: ExtendedBankInfo;
};

export const BankCard = ({ bank }: BankCardProps) => {
export const BankCard = ({ activeGroup, bank }: BankCardProps) => {
const { rateAP } = useAssetItemData({ bank, isInLendingMode: true });
return (
<div className="bg-background border p-4 rounded-lg space-y-4 flex flex-col justify-between">
Expand Down Expand Up @@ -75,6 +76,7 @@ export const BankCard = ({ bank }: BankCardProps) => {
<div className="flex justify-between w-full gap-4 mt-auto">
{bank.isActive && (
<ActionBoxDialog
activeGroupArg={activeGroup}
requestedAction={bank.position.isLending ? ActionType.Withdraw : ActionType.Repay}
requestedBank={bank}
>
Expand All @@ -83,7 +85,7 @@ export const BankCard = ({ bank }: BankCardProps) => {
</Button>
</ActionBoxDialog>
)}
<ActionBoxDialog requestedAction={ActionType.Deposit} requestedBank={bank}>
<ActionBoxDialog activeGroupArg={activeGroup} requestedAction={ActionType.Deposit} requestedBank={bank}>
<Button className="h-12 w-1/2 ml-auto" variant="default">
Supply {bank.isActive && "more"}
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,17 @@ export const PositionActionButtons = ({
collateralBank,
marginfiClient,
bank.meta.tokenSymbol,
borrowBank,
depositBanks,
borrowBank,
slippageBps,
connection,
priorityFee,
platformFeeBps,
groupsCache,
wallet,
setIsRefreshingStore,
refreshGroup,
activeGroup?.groupPk,
]);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,22 @@ import { PositionActionButtons } from "~/components/common/Portfolio";
import { Table, TableBody, TableHead, TableCell, TableHeader, TableRow } from "~/components/ui/table";
import { Badge } from "~/components/ui/badge";
import { GroupData } from "~/store/tradeStore";
import { PublicKey } from "@solana/web3.js";

export const PositionList = () => {
export const PositionList = ({ activeGroupPk }: { activeGroupPk: PublicKey }) => {
const [portfolio] = useTradeStore((state) => [state.portfolio]);

const portfolioCombined = React.useMemo(() => {
if (!portfolio) return [];

const isActiveGroupPosition = (item: GroupData) => item.pool.token.isActive;
const isActiveGroupPosition = (item: GroupData) => item.groupPk.equals(activeGroupPk);

const activeGroupPosition = [...portfolio.long, ...portfolio.short].find(isActiveGroupPosition);

const sortedLongs = portfolio.long.filter((item) => !isActiveGroupPosition(item));
const sortedShorts = portfolio.short.filter((item) => !isActiveGroupPosition(item));

return [...(activeGroupPosition ? [activeGroupPosition] : []), ...sortedLongs, ...sortedShorts];
}, [portfolio]);
}, [activeGroupPk, portfolio]);

if (!portfolio) return null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,16 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
}
}, [tradeState, loopingObject]);

const [activeGroupPk, setActiveGroup, marginfiClient, groupMap, setIsRefreshingStore, refreshGroup, fetchTradeState] =
useTradeStore((state) => [
const [activeGroupPk, setActiveGroup, groupMap, setIsRefreshingStore, refreshGroup, fetchTradeState] = useTradeStore(
(state) => [
state.activeGroup,
state.setActiveGroup,
state.marginfiClient,
state.groupMap,
state.setIsRefreshingStore,
state.refreshGroup,
state.fetchTradeState,
]);
]
);

const [slippageBps, priorityFee, platformFeeBps, setSlippageBps, setIsActionComplete, setPreviousTxn] = useUiStore(
(state) => [
Expand Down Expand Up @@ -157,7 +157,7 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {

const loadStats = React.useCallback(
async (simulationResult: SimulationResult | null, looping: LoopingObject, isAccountInitialized: boolean) => {
if (!marginfiClient || !activeGroup) {
if (!activeGroup?.client || !activeGroup) {
return;
}
setStats(
Expand All @@ -171,19 +171,19 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
)
);
},
[activeGroup, marginfiClient]
[activeGroup]
);

const handleSimulation = React.useCallback(
async (looping: LoopingObject, bank: ExtendedBankInfo, selectedAccount: MarginfiAccountWrapper | null) => {
if (!marginfiClient) {
if (!activeGroup?.client) {
return;
}

let simulationResult: SimulationResult | null = null;
try {
simulationResult = await simulateLooping({
marginfiClient,
marginfiClient: activeGroup.client,
account: selectedAccount,
bank: bank,
loopingTxn: looping.loopingTxn,
Expand All @@ -200,11 +200,11 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
loadStats(simulationResult, looping, !!selectedAccount);
}
},
[loadStats, marginfiClient]
[loadStats, activeGroup?.client]
);

const loadLoopingVariables = React.useCallback(async () => {
if (marginfiClient && activeGroup) {
if (activeGroup?.client && activeGroup) {
try {
if (Number(amount) === 0 || leverage <= 1) {
throw new Error("Amount is 0");
Expand All @@ -226,7 +226,7 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
const amountParsed = isNaN(Number.parseFloat(strippedAmount)) ? 0 : Number.parseFloat(strippedAmount);

const result = await calculateLoopingParams({
marginfiClient,
marginfiClient: activeGroup?.client,
marginfiAccount: activeGroup.selectedAccount,
depositBank,
borrowBank,
Expand Down Expand Up @@ -260,7 +260,6 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
}
}
}, [
marginfiClient,
activeGroup,
amount,
leverage,
Expand Down Expand Up @@ -291,7 +290,7 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
const leverageActionCb = React.useCallback(
async (depositBank: ExtendedBankInfo, borrowBank: ExtendedBankInfo) => {
const sig = await executeLeverageAction({
marginfiClient,
marginfiClient: activeGroup?.client ?? null,
marginfiAccount: activeGroup?.selectedAccount ?? null,
depositBank,
borrowBank,
Expand All @@ -306,21 +305,11 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {

return sig;
},
[
amount,
connection,
loopingObject,
marginfiClient,
priorityFee,
activeGroup,
slippageBps,
tradeState,
walletContextState,
]
[amount, connection, loopingObject, priorityFee, activeGroup, slippageBps, tradeState, walletContextState]
);

const handleLeverageAction = React.useCallback(async () => {
if (loopingObject && marginfiClient && collateralBank) {
if (loopingObject && activeGroup?.client && collateralBank) {
try {
setIsLoading(true);
let depositBank: ExtendedBankInfo, borrowBank: ExtendedBankInfo;
Expand Down Expand Up @@ -389,7 +378,7 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
leverage,
leverageActionCb,
loopingObject,
marginfiClient,
refreshGroup,
setIsActionComplete,
setIsRefreshingStore,
setPreviousTxn,
Expand Down Expand Up @@ -544,6 +533,7 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
<p>{actionMethod.description}</p>
{actionMethod.action && (
<ActionBoxDialog
activeGroupArg={activeGroup}
requestedAction={actionMethod.action.type}
requestedBank={actionMethod.action.bank}
>
Expand Down Expand Up @@ -601,7 +591,11 @@ export const TradingBox = ({ side = "long" }: TradingBoxProps) => {
{Stats}
</>
) : (
<ActionBoxDialog requestedAction={ActionType.Deposit} requestedBank={activeGroup.pool.quoteTokens[0]}>
<ActionBoxDialog
activeGroupArg={activeGroup}
requestedAction={ActionType.Deposit}
requestedBank={activeGroup.pool.quoteTokens[0]}
>
<Button className="w-full">Deposit Collateral</Button>
</ActionBoxDialog>
)}
Expand Down
1 change: 0 additions & 1 deletion apps/marginfi-v2-trading/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,5 @@ MrgnApp.getInitialProps = async (appContext: AppContext): Promise<AppInitialProp
bank = data.find((bank: BankMetadataRaw) => bank.groupAddress === groupAddress);
}

console.log(path);
return { ...appProps, path: path || "/", bank };
};
4 changes: 2 additions & 2 deletions apps/marginfi-v2-trading/src/pages/pools/[symbol].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ export default function TradeSymbolPage() {
</div>

<div className="grid grid-cols-1 gap-4 w-full mx-auto mt-8 md:grid-cols-2 md:gap-8">
<BankCard bank={activeGroup.pool.token} />
<BankCard bank={activeGroup.pool.quoteTokens[0]} />
<BankCard activeGroup={activeGroup} bank={activeGroup.pool.token} />
<BankCard activeGroup={activeGroup} bank={activeGroup.pool.quoteTokens[0]} />
</div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion apps/marginfi-v2-trading/src/pages/trade/[symbol].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ export default function TradeSymbolPage() {
</div>
</div>
<div className="pt-4">
<PositionList />
<PositionList activeGroupPk={activeGroup.groupPk} />
</div>
</div>
</div>
Expand Down
Loading

0 comments on commit 3ae3eb0

Please sign in to comment.