Skip to content

Commit

Permalink
supply and withdraw
Browse files Browse the repository at this point in the history
  • Loading branch information
vidvidvid committed Dec 16, 2024
1 parent 79a3c16 commit 0dd65d8
Show file tree
Hide file tree
Showing 5 changed files with 212 additions and 99 deletions.
76 changes: 61 additions & 15 deletions packages/ui/app/_components/earn/MorphoDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// components/MorphoDialog.tsx
import { useState } from 'react';
import { useCallback, useEffect, useState } from 'react';

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

import { Button } from '@ui/components/ui/button';
import {
Expand All @@ -20,6 +22,7 @@ import {
import { useMorphoProtocol } from '@ui/hooks/earn/useMorphoProtocol';

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

interface MorphoDialogProps {
asset: string[];
Expand All @@ -28,15 +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 assetSymbol = asset[0] as 'USDC' | 'WETH';

// Token addresses for Base network
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 @@ -46,13 +63,25 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
if (!isConnected) return;

try {
if (chainId !== base.id) {
try {
await switchChain({ chainId: base.id });
return;
} catch (switchError) {
console.error('Failed to switch network:', switchError);
return;
}
}

setIsProcessing(true);
const parsedAmount = utils.parseUnits(
amount,
assetSymbol === 'WETH' ? 18 : 6
);
await supply(assetSymbol, parsedAmount);
setAmount('');

await fetchMaxWithdraw();
} catch (error) {
console.error('Supply error:', error);
} finally {
Expand All @@ -64,13 +93,25 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
if (!isConnected) return;

try {
if (chainId !== base.id) {
try {
await switchChain({ chainId: base.id });
return;
} catch (switchError) {
console.error('Failed to switch network:', switchError);
return;
}
}

setIsProcessing(true);
const parsedAmount = utils.parseUnits(
amount,
assetSymbol === 'WETH' ? 18 : 6
);
await withdraw(assetSymbol, parsedAmount);
setAmount('');

await fetchMaxWithdraw();
} catch (error) {
console.error('Withdraw error:', error);
} finally {
Expand Down Expand Up @@ -101,9 +142,9 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
<MaxDeposit
amount={amount}
tokenName={assetSymbol}
token={tokenAddresses[assetSymbol]}
token={morphoBaseAddresses.tokens[assetSymbol]}
handleInput={handleInputChange}
chain={8453} // Base chain ID
chain={base.id}
headerText="Supply Amount"
decimals={assetSymbol === 'WETH' ? 18 : 6}
/>
Expand All @@ -116,7 +157,9 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
? 'Connect Wallet'
: isProcessing
? 'Processing...'
: 'Supply'}
: chainId !== base.id
? 'Switch to Base'
: 'Supply'}
</Button>
</>
)}
Expand All @@ -130,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={8453}
chain={base.id}
headerText="Withdraw Amount"
useUnderlyingBalance={true}
useUnderlyingBalance
decimals={assetSymbol === 'WETH' ? 18 : 6}
/>
<Button
Expand All @@ -147,7 +191,9 @@ export function MorphoDialog({ asset }: MorphoDialogProps) {
? 'Connect Wallet'
: isProcessing
? 'Processing...'
: 'Withdraw'}
: chainId !== base.id
? 'Switch to Base'
: 'Withdraw'}
</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 0dd65d8

Please sign in to comment.