Skip to content

Commit

Permalink
cleanup and added update boolean to lst data
Browse files Browse the repository at this point in the history
  • Loading branch information
k0beLeenders committed Oct 16, 2024
1 parent 10d7111 commit fcdb8c2
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,7 @@ import {
VersionedTransaction,
} from "@solana/web3.js";

import {
Bank,
makeBundleTipIx,
MarginfiAccount,
MarginfiAccountWrapper,
MarginfiClient,
SimulationResult,
} from "@mrgnlabs/marginfi-client-v2";
import { makeBundleTipIx, MarginfiAccountWrapper, MarginfiClient } from "@mrgnlabs/marginfi-client-v2";
import { AccountSummary, ExtendedBankInfo, ActionType } from "@mrgnlabs/marginfi-v2-ui-state";
import {
ActionMethod,
Expand All @@ -32,7 +25,7 @@ import {
TOKEN_2022_MINTS,
usePrevious,
} from "@mrgnlabs/mrgn-utils";
import { calculateSummary, getAdressLookupTableAccounts, getSimulationResult } from "../utils";
import { calculateSummary, fetchLstData, getAdressLookupTableAccounts, getSimulationResult } from "../utils";
import {
createAssociatedTokenAccountIdempotentInstruction,
getAssociatedTokenAddressSync,
Expand All @@ -42,9 +35,10 @@ import {
uiToNative,
Wallet,
} from "@mrgnlabs/mrgn-common";
import { createJupiterApiClient, QuoteResponse } from "@jup-ag/api";
import { createJupiterApiClient } from "@jup-ag/api";
import * as solanaStakePool from "@solana/spl-stake-pool";
import { AddressLookupTableAccount } from "@solana/web3.js";

import { useActionBoxStore } from "../../../store"; //always import actionbox like this

type StakeSimulationProps = {
debouncedAmount: number;
Expand All @@ -55,9 +49,8 @@ type StakeSimulationProps = {
actionTxns: StakeActionTxns;
simulationResult: any | null;
isRefreshTxn: boolean;
slippageBps: number;
marginfiClient: MarginfiClient | null;
lstData: LstData | null;
solPriceUsd: number;

setSimulationResult: (result: any | null) => void;
setActionTxns: (actionTxns: StakeActionTxns) => void;
Expand All @@ -74,15 +67,39 @@ export function useStakeSimulation({
actionTxns,
simulationResult,
isRefreshTxn,
slippageBps,
marginfiClient,
solPriceUsd,

setSimulationResult,
lstData,
setActionTxns,
setErrorMessage,
setIsLoading,
}: StakeSimulationProps) {
const [slippageBps, priorityFee] = useActionBoxStore((state) => [state.slippageBps, state.priorityFee]);

const prevDebouncedAmount = usePrevious(debouncedAmount);
const [lstData, setLstData] = React.useState<LstData | null>(null);

const actionSummary = React.useMemo(() => {
if (lstData && solPriceUsd) {
return {
commission: lstData.solDepositFee,
currentPrice: lstData.lstSolValue,
projectedApy: lstData.projectedApy,
supply: lstData.tvl * solPriceUsd,
};
}
}, [lstData, solPriceUsd]);

const handleFetchLstData = React.useCallback(async () => {
// TODO: this is more of a refactor across all actionboxes, find a better way to feed connection
const connection = new Connection(process.env.NEXT_PUBLIC_MARGINFI_RPC_ENDPOINT_OVERRIDE!, "confirmed");

if (connection) {
const lstData = await fetchLstData(connection);
setLstData(lstData);
}
}, [setLstData]);

const handleSimulation = React.useCallback(
async (txns: (VersionedTransaction | Transaction)[]) => {
Expand All @@ -106,34 +123,14 @@ export function useStakeSimulation({
[selectedAccount, selectedBank, marginfiClient, setSimulationResult, simulationResult]
);

// const handleActionSummary = React.useCallback(
// (summary?: AccountSummary, result?: SimulationResult) => {
// if (selectedAccount && summary && selectedBank) {
// return calculateSummary({
// simulationResult: result ?? undefined,
// bank: selectedBank,
// accountSummary: summary,
// actionTxns: actionTxns,
// });
// }
// },
// [selectedAccount, selectedBank, actionTxns]
// );

const fetchStakeTxs = React.useCallback(
async (amount: number) => {
const connection = marginfiClient?.provider.connection;

console.log("fetchStakeTxs1");

console.log({ amount });

if (amount === 0 || !selectedBank || !connection || !lstData) {
return;
}

console.log("fetchStakeTxs");

try {
const swapObject = await getSwapQuoteWithRetry({
amount: uiToNative(amount, selectedBank.info.state.mintDecimals).toNumber(),
Expand Down Expand Up @@ -196,10 +193,6 @@ export function useStakeSimulation({
});
const swapTx = new VersionedTransaction(swapMessage.compileToV0Message(AddressLookupAccounts));

const simulation = await connection.simulateTransaction(swapTx);
// console.log({ simulation });

// console.log("swapTx", swapTx);
const userSolTransfer = new Keypair();
const signers: Signer[] = [userSolTransfer];
const stakeIxs: TransactionInstruction[] = [];
Expand All @@ -218,8 +211,6 @@ export function useStakeSimulation({
true
);
const ataData = await connection.getAccountInfo(destinationTokenAccount);
console.log({ destinationTokenAccount });
console.log({ poolmint: lstData.accountData.poolMint.toString() });

if (!ataData) {
stakeIxs.push(
Expand All @@ -232,16 +223,11 @@ export function useStakeSimulation({
);
}

console.log("destinationTokenAccount", destinationTokenAccount);

const [withdrawAuthority] = PublicKey.findProgramAddressSync(
[lstData.poolAddress.toBuffer(), Buffer.from("withdraw")],
solanaStakePool.STAKE_POOL_PROGRAM_ID
);

console.log({ poolAddress: lstData.poolAddress });
console.log("withdrawAuthority", withdrawAuthority);

stakeIxs.push(
solanaStakePool.StakePoolInstruction.depositSol({
stakePool: lstData.poolAddress,
Expand All @@ -256,11 +242,8 @@ export function useStakeSimulation({
})
);

console.log("stakeIx", stakeIxs);

const bundleTipIx = makeBundleTipIx(marginfiClient.wallet.publicKey);

console.log("bundleTipIx", bundleTipIx);
const stakeMessage = new TransactionMessage({
payerKey: marginfiClient.wallet.publicKey,
recentBlockhash: blockhash,
Expand All @@ -270,10 +253,8 @@ export function useStakeSimulation({
const stakeTx = new VersionedTransaction(stakeMessage.compileToV0Message([]));
stakeTx.sign(signers);

console.log("stakeTx", stakeTx);
setActionTxns({
actionTxn: stakeTx,
// additionalTxns: [],
actionQuote: swapObject, // TODO: update name
additionalTxns: [swapTx],
});
Expand Down Expand Up @@ -354,6 +335,10 @@ export function useStakeSimulation({
]
);

React.useEffect(() => {
handleFetchLstData();
}, [handleFetchLstData]);

React.useEffect(() => {
if (prevDebouncedAmount !== debouncedAmount) {
if (actionMode === ActionType.MintLST) {
Expand All @@ -369,13 +354,14 @@ export function useStakeSimulation({
...(actionTxns?.additionalTxns ?? []),
...(actionTxns?.actionTxn ? [actionTxns?.actionTxn] : []),
]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [actionTxns]);

// const actionSimulationSummary = React.useMemo(() => {
// return handleActionSummary(accountSummary, simulationResult ?? undefined);
// }, [accountSummary, simulationResult, handleActionSummary]);

return {
actionSimulationSummary: undefined, // TODO: in future we can return lstAta data to display exact lst output amount
actionSummary, // TODO: in future we can return lstAta data to display exact lst output amount
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ export const StakeBox = ({
actionTxns,
errorMessage,
isLoading,
lstData,
refreshState,
refreshSelectedBanks,
fetchActionBoxState,
Expand All @@ -70,7 +69,6 @@ export const StakeBox = ({
setSelectedBank,
setIsLoading,
setErrorMessage,
setLstData,
] = useStakeBoxStore(isDialog)((state) => [
state.amountRaw,
state.actionMode,
Expand All @@ -79,7 +77,6 @@ export const StakeBox = ({
state.actionTxns,
state.errorMessage,
state.isLoading,
state.lstData,
state.refreshState,
state.refreshSelectedBanks,
state.fetchActionBoxState,
Expand All @@ -90,7 +87,6 @@ export const StakeBox = ({
state.setSelectedBank,
state.setIsLoading,
state.setErrorMessage,
state.setLstData,
]);

const { amount, debouncedAmount, walletAmount, maxAmount } = useActionAmounts({
Expand All @@ -100,46 +96,18 @@ export const StakeBox = ({
actionMode,
});

const [slippage, setIsSettingsDialogOpen, setPreviousTxn, setIsActionComplete] = useActionBoxStore((state) => [
state.slippageBps,
const [setIsSettingsDialogOpen, setPreviousTxn, setIsActionComplete] = useActionBoxStore((state) => [
state.setIsSettingsDialogOpen,
state.setPreviousTxn,
state.setIsActionComplete,
]);

const solUsdValue = React.useMemo(() => {
const solPriceUsd = React.useMemo(() => {
const bank = banks.find((bank) => bank.info.state.mint.equals(SOL_MINT));
return bank ? getPriceWithConfidence(bank.info.oraclePrice, false).price.toNumber() : 0;
}, [banks]);

useEffect(() => {
const _fetchLstData = async (connection: Connection) => {
setLstData(await fetchLstData(connection));
};

const connection = new Connection(process.env.NEXT_PUBLIC_MARGINFI_RPC_ENDPOINT_OVERRIDE!, "confirmed");
if (connection) _fetchLstData(connection);
}, [setLstData]);

const [actionSummary, setActionSummary] = React.useState<{
supply: number;
projectedApy: number;
currentPrice: number;
commission: number;
}>();

useEffect(() => {
if (lstData && solUsdValue) {
setActionSummary({
commission: lstData.solDepositFee,
currentPrice: lstData.lstSolValue,
projectedApy: lstData.projectedApy,
supply: lstData.tvl * solUsdValue,
});
}
}, [lstData, solUsdValue]);

const { actionSimulationSummary } = useStakeSimulation({
const { actionSummary } = useStakeSimulation({
debouncedAmount: debouncedAmount ?? 0,
selectedAccount,
selectedBank,
Expand All @@ -151,9 +119,8 @@ export const StakeBox = ({
setErrorMessage,
setIsLoading,
isRefreshTxn: true, // TODO: fill, see repay-collat-box
slippageBps: slippage,
marginfiClient,
lstData: lstData ?? null,
solPriceUsd,
});

const handleStakeAction = React.useCallback(async () => {
Expand Down Expand Up @@ -215,9 +182,6 @@ export const StakeBox = ({
setIsLoading,
setPreviousTxn,
]);
React.useEffect(() => {
console.log(actionSimulationSummary);
}, [actionSimulationSummary]);

React.useEffect(() => {
fetchActionBoxState({ requestedLendType: requestedActionType, requestedBank });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ interface StateBoxState {

errorMessage: ActionMethod | null;
isLoading: boolean;
lstData: LstData | null;

// Actions
refreshState: (actionMode?: ActionType) => void;
Expand All @@ -29,7 +28,6 @@ interface StateBoxState {
setSelectedBank: (bank: ExtendedBankInfo | null) => void;
setIsLoading: (isLoading: boolean) => void;
setErrorMessage: (errorMessage: ActionMethod | null) => void;
setLstData: (lstData: LstData | null) => void;
}

function createStakeBoxStore() {
Expand Down Expand Up @@ -151,10 +149,6 @@ const stateCreator: StateCreator<StateBoxState, [], []> = (set, get) => ({
setErrorMessage(errorMessage) {
set({ errorMessage });
},

setLstData(lstData) {
set({ lstData });
},
});

export { createStakeBoxStore };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,7 @@ export async function fetchLstData(connection: Connection): Promise<LstData> {
solDepositFee,
accountData: stakePool,
validatorList: stakePoolInfo.validatorList.map((v) => new PublicKey(v.voteAccountAddress)),
updateRequired: stakePoolInfo.details.updateRequired,
lastUpdateEpoch: stakePoolInfo.lastUpdateEpoch,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export const getSimulationResult = async ({

if (!lstAta) throw new Error("Failed to simulate stake transaction");

return;
return true;

// const previewBanks = marginfiClient.banks;
// previewBanks.set(
Expand Down
2 changes: 2 additions & 0 deletions packages/mrgn-utils/src/actions/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export interface LstData {
solDepositFee: number;
accountData: solanaStakePool.StakePool;
validatorList: PublicKey[];
updateRequired: boolean;
lastUpdateEpoch: string;
}

export interface ActionTxns {
Expand Down

0 comments on commit fcdb8c2

Please sign in to comment.