Skip to content

Commit

Permalink
fix: cleanup & improved toasts
Browse files Browse the repository at this point in the history
  • Loading branch information
k0beLeenders committed Nov 20, 2024
1 parent 846e536 commit 2062010
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export const Navbar: FC = () => {
</PopoverTrigger>
<PopoverContent className="w-80">
<Settings
onChange={setTransactionSettings}
onChange={(settings) => setTransactionSettings(settings, connection)}
broadcastType={broadcastType}
priorityType={priorityType}
maxCap={maxCap}
Expand Down
8 changes: 1 addition & 7 deletions apps/marginfi-v2-ui/src/context/MrgnlendProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,7 @@ export const MrgnlendProvider: React.FC<{
state.resetUserData,
state.userDataFetched,
]);
const [priorityType, broadcastType, maxCapType, maxCap, fetchPriorityFee] = useUiStore((state) => [
state.priorityType,
state.broadcastType,
state.maxCapType,
state.maxCap,
state.fetchPriorityFee,
]);
const [fetchPriorityFee] = useUiStore((state) => [state.fetchPriorityFee]);

// identify user if logged in
React.useEffect(() => {
Expand Down
13 changes: 8 additions & 5 deletions apps/marginfi-v2-ui/src/store/uiStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ interface UiState {
setPoolFilter: (poolType: PoolTypes) => void;
setSortOption: (sortOption: SortAssetOption) => void;
setAssetListSearch: (search: string) => void;
setTransactionSettings: (settings: TransactionSettings) => void;
fetchPriorityFee: (connection: Connection) => void;
setTransactionSettings: (settings: TransactionSettings, connection: Connection) => void;
fetchPriorityFee: (connection: Connection, settings?: TransactionSettings) => void;
}

function createUiStore() {
Expand Down Expand Up @@ -106,9 +106,12 @@ const stateCreator: StateCreator<UiState, [], []> = (set, get) => ({
setPoolFilter: (poolType: PoolTypes) => set({ poolFilter: poolType }),
setSortOption: (sortOption: SortAssetOption) => set({ sortOption: sortOption }),
setAssetListSearch: (search: string) => set({ assetListSearch: search }),
setTransactionSettings: (settings: TransactionSettings) => set({ ...settings }),
fetchPriorityFee: async (connection: Connection) => {
const { maxCapType, maxCap, broadcastType, priorityType } = get();
setTransactionSettings: (settings: TransactionSettings, connection: Connection) => {
set({ ...settings });
get().fetchPriorityFee(connection, settings);
},
fetchPriorityFee: async (connection: Connection, settings?: TransactionSettings) => {
const { maxCapType, maxCap, broadcastType, priorityType } = settings ?? get();
try {
const priorityFees = await fetchPriorityFee(maxCapType, maxCap, broadcastType, priorityType, connection);
set({ priorityFees });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ function getFlashloanIndex(transactions: SolanaTransaction[]): number | null {
return null;
}

const uiToMicroLamports = (ui: number, limitCU: number = 1_400_000) => {
const priorityFeeMicroLamports = ui * LAMPORTS_PER_SOL * 1_000_000;
return priorityFeeMicroLamports / limitCU;
};

const microLamportsToUi = (microLamports: number, limitCU: number = 1_400_000) => {
const priorityFeeMicroLamports = microLamports * limitCU;
const priorityFeeUi = priorityFeeMicroLamports / (LAMPORTS_PER_SOL * 1_000_000);
Expand All @@ -94,11 +99,23 @@ export function formatTransactions(
});

const txSizes: number[] = transactions.map((tx) => getTxSize(tx));
const dummyPriorityFeeIx = makePriorityFeeMicroIx(1);

const priorityIxs = transactions.map((tx) => {
if (broadcastType === "BUNDLE") {
return dummyPriorityFeeIx;
}

const cu = getComputeBudgetUnits(tx);
const priorityFeeUi = microLamportsToUi(priorityFeeMicro, cu);
return makePriorityFeeMicroIx(priorityFeeMicro, cu);

let updatedFees = priorityFeeMicro;
// don't want to pay more than 0.008 SOL in fees
if (priorityFeeUi > 0.008) {
updatedFees = uiToMicroLamports(0.008, cu);
}

return makePriorityFeeMicroIx(updatedFees, cu);
});

const { bundleTipIx } = makeTxPriorityIx(feePayer, bundleTipUi, broadcastType);
Expand All @@ -107,22 +124,22 @@ export function formatTransactions(
const priorityFeeIndexes: number[] = [];

for (let i = 0; i < txSizes.length; i++) {
if (flashloanIndex !== i) {
let baseTxSize = txSizes[i];
let baseTxSize = txSizes[i];

if (flashloanIndex !== i) {
if (bundleTipIndex === -1 && txSizes[i] + BUNDLE_TX_SIZE < MAX_TX_SIZE) {
baseTxSize += BUNDLE_TX_SIZE;
bundleTipIndex = i;
}
}

if (baseTxSize + PRIORITY_TX_SIZE < MAX_TX_SIZE) {
priorityFeeIndexes.push(i);
}
if (flashloanIndex === i || baseTxSize + PRIORITY_TX_SIZE < MAX_TX_SIZE) {
priorityFeeIndexes.push(i);
}
}

for (const [index, transaction] of transactions.entries()) {
const hasFlashloan = !!flashloanIndex; // check if there is a flashloan
const hasFlashloan = flashloanIndex !== null; // check if there is a flashloan
const isTxFlashloan = hasFlashloan && flashloanIndex === index; // check if the tx is the flashloan tx

const signers = transaction.signers ?? [];
Expand All @@ -141,8 +158,6 @@ export function formatTransactions(
...(priorityFeeIndexes.includes(index) ? [priorityIxs[index]] : []),
];

console.log("requiredIxs", requiredIxs);

let newTransaction: VersionedTransaction;

if (isV0Tx(transaction)) {
Expand Down Expand Up @@ -195,18 +210,14 @@ export async function sendTransactionAsBundleRpc({
let signatures: TransactionSignature[] = [];
if (isSequentialTxs) {
for (const [index, tx] of versionedTransactions.entries()) {
console.log("length", versionedTransactions.length);
console.log("index", index);
const signature = await connection.sendTransaction(tx, txOpts);
console.log("signature", signature);
const result = await connection.confirmTransaction(
{
...blockStrategy,
signature,
},
confirmCommitment
);
console.log("result", signature);

if (result.value.err) {
onCallback?.(index, false, signature);
Expand Down Expand Up @@ -331,7 +342,7 @@ export async function sendTransactionAsGrpcBundle(

return bundleId;
} catch (error) {
console.error(error);
console.log("GRCP BUNDLE FAILED");
if (throwError) throw new Error("Bundle failed");
}
}
Expand All @@ -350,7 +361,13 @@ export async function sendTransactionAsBundle(base58Txs: string[], throwError =
});

const sendBundleResult = await sendBundleResponse.json();
if (sendBundleResult.error) throw new Error(sendBundleResult.error.message);
if (sendBundleResult.error) {
if (sendBundleResult.error.message.includes("already processed")) {
return "0x0"; // todo add proper bundle id
}

throw new Error(sendBundleResult.error.message);
}

const bundleId = sendBundleResult.result as string;
await sleep(500);
Expand Down Expand Up @@ -389,7 +406,7 @@ export async function sendTransactionAsBundle(base58Txs: string[], throwError =
await sleep(500); // Wait before retrying
}
} catch (error) {
console.error(error);
console.log("API BUNDLE FAILED");
if (throwError) throw new Error("Bundle failed");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ export async function processTransactions({
finalFallbackMethod = strategy.fallbackSequence.filter((method) => method.broadcastType === "BUNDLE");
}

console.log("decided broadcast type:", broadcastType);
console.log("decided fallback methods:", finalFallbackMethod);

let versionedTransactions: VersionedTransaction[] = [];
let minContextSlot: number;
let blockhash: string;
Expand Down Expand Up @@ -250,8 +253,6 @@ export async function processTransactions({
console.log("bundleSignatures:", bundleSignature);
console.log("signatures:", signatures);

if (!signatures || !bundleSignature) throw new Error("Transactions failed to land");

if (signatures.length !== 0) {
// await Promise.all(
// signatures.map(async (signature) => {
Expand All @@ -267,6 +268,7 @@ export async function processTransactions({
// );
return signatures;
} else {
if (!bundleSignature) throw new Error("Transactions failed to land");
return [bundleSignature];
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ export function replaceV0TxInstructions(
instructions: TransactionInstruction[],
replaceOnly?: boolean
): TransactionInstruction[] {
let updatedAdditionalIxs: TransactionInstruction[] = [];
let updatedAdditionalIxs: TransactionInstruction[] = additionalInstructions;

const updatedInstructions = instructions.map((ix) => {
const programId = ix.programId;
const additionalIxs = additionalInstructions.filter((a) => a.programId.equals(programId));
Expand Down
11 changes: 6 additions & 5 deletions packages/mrgn-utils/src/actions/individualFlows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export async function deposit({
} else {
throw new Error("Marginfi account not ready.");
}
multiStepToast.setSuccessAndNext();
multiStepToast.setSuccess();
return txnSig;
} catch (error: any) {
const msg = extractErrorString(error);
Expand Down Expand Up @@ -207,6 +207,7 @@ export async function borrow({
} else {
throw new Error("Marginfi account not ready.");
}
multiStepToast.setSuccess();
return sigs;
} catch (error: any) {
const msg = extractErrorString(error);
Expand Down Expand Up @@ -265,7 +266,7 @@ export async function withdraw({
} else {
throw new Error("Marginfi account not ready.");
}
multiStepToast.setSuccessAndNext();
multiStepToast.setSuccess();
return sigs;
} catch (error: any) {
const msg = extractErrorString(error);
Expand Down Expand Up @@ -326,7 +327,7 @@ export async function repay({
} else {
throw new Error("Marginfi account not ready.");
}
multiStepToast.setSuccessAndNext();
multiStepToast.setSuccess();
return txnSig;
} catch (error: any) {
const msg = extractErrorString(error);
Expand Down Expand Up @@ -387,7 +388,7 @@ export async function looping({ marginfiClient, actionTxns, processOpts, txOpts,
sigs = await marginfiClient.processTransactions([...additionalTxs, flashloanTx], processOpts, txOpts);
}

multiStepToast.setSuccessAndNext();
multiStepToast.setSuccess();
return sigs;
} catch (error: any) {
const msg = extractErrorString(error);
Expand Down Expand Up @@ -451,7 +452,7 @@ export async function repayWithCollat({

sigs = await marginfiClient.processTransactions([...additionalTxs, flashloanTx], processOpts, txOpts);
}
multiStepToast.setSuccessAndNext();
multiStepToast.setSuccess();
return sigs;
} catch (error: any) {
const msg = extractErrorString(error);
Expand Down
12 changes: 12 additions & 0 deletions packages/mrgn-utils/src/toasts/toastUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ export class MultiStepToastHandle {
}
}

setSuccess() {
if (!this._toastId) return;

for (let i = 0; i <= this._stepsWithStatus.length; i++) {
this._stepsWithStatus[i].status = "success";
}
toast.update(this._toastId, {
render: () => <MultiStepToast title={this._title} steps={this._stepsWithStatus} />,
autoClose: false,
});
}

setFailed(message: string) {
if (!this._toastId) return;
this._stepsWithStatus[this._stepIndex].status = "error";
Expand Down

0 comments on commit 2062010

Please sign in to comment.