Skip to content

Commit

Permalink
supply and withdraw
Browse files Browse the repository at this point in the history
cleanup
  • Loading branch information
vidvidvid committed Dec 16, 2024
1 parent 59b1f41 commit 63708a1
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 195 deletions.
81 changes: 30 additions & 51 deletions packages/ui/app/_components/earn/MorphoDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useState } from 'react';
import { useCallback, useEffect, useState } from 'react';

import { utils } from 'ethers';
import { chain } from 'mathjs';
import { base } from 'viem/chains';
import { useChainId, useConfig, useSwitchChain } from 'wagmi';
import { useChainId, useSwitchChain } from 'wagmi';
import { chainIdToConfig } from '@ionicprotocol/chains';

import { Button } from '@ui/components/ui/button';
import {
Expand All @@ -20,9 +20,9 @@ import {
TabsTrigger
} from '@ui/components/ui/tabs';
import { useMorphoProtocol } from '@ui/hooks/earn/useMorphoProtocol';
import { useToast } from '@ui/hooks/use-toast';

import MaxDeposit from '../MaxDeposit';
import { morphoBaseAddresses } from '@ui/utils/morphoUtils';

interface MorphoDialogProps {
asset: string[];
Expand All @@ -31,17 +31,29 @@ interface MorphoDialogProps {
export function MorphoDialog({ asset }: MorphoDialogProps) {
const [amount, setAmount] = useState('');
const [isProcessing, setIsProcessing] = useState(false);
const { supply, withdraw, isLoading, isConnected } = useMorphoProtocol();
const { supply, withdraw, getMaxWithdraw, isLoading, isConnected } =
useMorphoProtocol();
const [maxWithdraw, setMaxWithdraw] = useState<bigint>(BigInt(0));
const chainId = useChainId();
const { switchChain } = useSwitchChain();
const { toast } = useToast();

const assetSymbol = asset[0] as 'USDC' | 'WETH';

const tokenAddresses: { [key: string]: `0x${string}` } = {
WETH: '0x4200000000000000000000000000000000000006',
USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
};
const fetchMaxWithdraw = useCallback(async () => {
if (isConnected && !isLoading) {
const max = await getMaxWithdraw(assetSymbol);
setMaxWithdraw(max);
}
}, [isConnected, isLoading, assetSymbol, getMaxWithdraw]);

useEffect(() => {
fetchMaxWithdraw();
}, [fetchMaxWithdraw]);

const formattedMaxWithdraw = utils.formatUnits(
maxWithdraw,
assetSymbol === 'WETH' ? 18 : 6
);

const handleInputChange = (value?: string) => {
setAmount(value || '');
Expand All @@ -51,18 +63,10 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
if (!isConnected) return;

try {
// Check if user is on Base network
if (chainId !== base.id) {
toast({
title: 'Wrong Network',
description: 'Please switch to Base network to continue',
variant: 'destructive'
});

// If switchChain is available, prompt to switch
try {
await switchChain({ chainId: base.id });
return; // Return here as the switch will trigger a re-render
return;
} catch (switchError) {
console.error('Failed to switch network:', switchError);
return;
Expand All @@ -77,18 +81,9 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
await supply(assetSymbol, parsedAmount);
setAmount('');

toast({
title: 'Success',
description: `Successfully supplied ${amount} ${assetSymbol}`
});
await fetchMaxWithdraw();
} catch (error) {
console.error('Supply error:', error);
toast({
title: 'Transaction Failed',
description:
error instanceof Error ? error.message : 'Failed to supply assets',
variant: 'destructive'
});
} finally {
setIsProcessing(false);
}
Expand All @@ -98,18 +93,10 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
if (!isConnected) return;

try {
// Check if user is on Base network
if (chainId !== base.id) {
toast({
title: 'Wrong Network',
description: 'Please switch to Base network to continue',
variant: 'destructive'
});

// If switchChain is available, prompt to switch
try {
await switchChain({ chainId: base.id });
return; // Return here as the switch will trigger a re-render
return;
} catch (switchError) {
console.error('Failed to switch network:', switchError);
return;
Expand All @@ -124,18 +111,9 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
await withdraw(assetSymbol, parsedAmount);
setAmount('');

toast({
title: 'Success',
description: `Successfully withdrawn ${amount} ${assetSymbol}`
});
await fetchMaxWithdraw();
} catch (error) {
console.error('Withdraw error:', error);
toast({
title: 'Transaction Failed',
description:
error instanceof Error ? error.message : 'Failed to withdraw assets',
variant: 'destructive'
});
} finally {
setIsProcessing(false);
}
Expand Down Expand Up @@ -164,7 +142,7 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
<MaxDeposit
amount={amount}
tokenName={assetSymbol}
token={tokenAddresses[assetSymbol]}
token={morphoBaseAddresses.tokens[assetSymbol]}
handleInput={handleInputChange}
chain={base.id}
headerText="Supply Amount"
Expand Down Expand Up @@ -195,12 +173,13 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
<>
<MaxDeposit
amount={amount}
max={formattedMaxWithdraw}
tokenName={assetSymbol}
token={tokenAddresses[assetSymbol]}
token={morphoBaseAddresses.tokens[assetSymbol]}
handleInput={handleInputChange}
chain={base.id}
headerText="Withdraw Amount"
useUnderlyingBalance={true}
useUnderlyingBalance
decimals={assetSymbol === 'WETH' ? 18 : 6}
/>
<Button
Expand Down
3 changes: 1 addition & 2 deletions packages/ui/app/_components/earn/MorphoTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ import Image from 'next/image';

import { useMorphoData } from '@ui/hooks/earn/useMorphoData';
import type { MorphoRow } from '@ui/types/Earn';
import { morphoVaults } from '@ui/utils/morphoUtils';

import { MorphoDialog } from './MorphoDialog';
import CommonTable from '../CommonTable';

import type { EnhancedColumnDef } from '../CommonTable';

export default function MorphoTable() {
const { rows, isLoading } = useMorphoData(morphoVaults);
const { rows, isLoading } = useMorphoData();

const columns: EnhancedColumnDef<MorphoRow>[] = [
{
Expand Down
6 changes: 3 additions & 3 deletions packages/ui/hooks/earn/useMorphoData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { useQuery } from '@tanstack/react-query';
import { request, gql } from 'graphql-request';

import type { MorphoRow } from '@ui/types/Earn';
import { morphoVaults } from '@ui/utils/morphoUtils';

const MORPHO_API_URL = 'https://blue-api.morpho.org/graphql';

Expand Down Expand Up @@ -54,15 +54,15 @@ const fetchMorphoData = async (): Promise<MorphoResponse> => {
return request(MORPHO_API_URL, VAULT_QUERY);
};

export const useMorphoData = (initialRows: MorphoRow[]) => {
export const useMorphoData = () => {
const { data, isLoading, error } = useQuery({
queryKey: ['morphoVaults'],
queryFn: fetchMorphoData,
staleTime: 30000,
refetchInterval: 60000
});

const rows = initialRows.map((row) => {
const rows = morphoVaults.map((row) => {
const vaultSymbol = `ionic${row.asset[0]}`;
const vaultData = data?.vaults.items.find(
(vault) => vault.symbol === vaultSymbol
Expand Down
Loading

0 comments on commit 63708a1

Please sign in to comment.