Skip to content

Commit

Permalink
fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
wow-sven committed Jan 29, 2025
1 parent b843cb0 commit 02e1310
Show file tree
Hide file tree
Showing 6 changed files with 272 additions and 66 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { AnnotatedMoveStructView, BalanceInfoView } from '@roochnetwork/rooch-sdk';
import {
useCurrentAddress,
useRoochClient,
useRoochClientQuery,
} from '@roochnetwork/rooch-sdk-kit';
import { useMemo, useState, useCallback } from 'react';
import { useNetworkVariable } from 'src/hooks/use-networks';
import { formatCoin } from 'src/utils/format-number';

export type AllLiquidityItemType = {
id: string;
createAt: number;
x: {
id: string;
symbol: string;
type: string;
};
y: {
id: string;
symbol: string;
type: string;
};
lpTokenId: string;
creator: string;
};

export type UseAllLiquidityReturn = {
lpTokens: AllLiquidityItemType[];
isPending: boolean;
};

export function useAllLiquidity(): UseAllLiquidityReturn {
const currentAddress = useCurrentAddress();
const dex = useNetworkVariable('dex');
const client = useRoochClient();

const { data: tokenPairs, isPending } = useRoochClientQuery('queryObjectStates', {
filter: {
object_type: `${dex.address}::swap::TokenPair`,
},
queryOption: {
showDisplay: true,
},
});

const resolvedTokenPairs = useMemo(() => {
if (!tokenPairs) {
return [];
}

const rowItme: AllLiquidityItemType[] = tokenPairs!.data.map((item) => {
const xView = item.decoded_value!.value.balance_x as AnnotatedMoveStructView;
let xType = xView.type.replace('0x2::object::Object<0x3::coin_store::CoinStore<', '');
xType = xType.replace('>>', '');
const xName = xType.split('::');
const yView = item.decoded_value!.value.balance_y as AnnotatedMoveStructView;
let yType = yView.type.replace('0x2::object::Object<0x3::coin_store::CoinStore<', '');
yType = yType.replace('>>', '');
const yName = yType.split('::');
const lpView = item.decoded_value!.value.coin_info as AnnotatedMoveStructView;
return {
id: item.id,
creator: item.decoded_value!.value.creator as string,
createAt: Number(item.created_at),
lpTokenId: lpView.value.id as string,
x: {
id: xView.value.id as string,
symbol: xName[xName.length - 1].replace('>>', ''),
type: xType,
},
y: {
id: yView.value.id as string,
symbol: yName[xName.length - 1].replace('>>', ''),
type: yType,
},
};
});

return rowItme;
}, [tokenPairs]);

return {
lpTokens: resolvedTokenPairs,
isPending,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function useOwnerLiquidity(): UseOwnerLiquidityReturn {
if (!assetsList) {
return [];
}
console.log('owner', assetsList);
const tokens: OwnerLiquidityItemType[] = assetsList!.data
.filter((item) => item.symbol.startsWith('RDexLP'))
.map((item) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { BalanceInfoView, AnnotatedMoveStructView } from '@roochnetwork/rooch-sdk';

import { toast } from 'sonner';
import { toast } from 'src/components/snackbar';
import BigNumber from 'bignumber.js';
import { useDebounce } from 'react-use';
import { Args, Transaction } from '@roochnetwork/rooch-sdk';
Expand Down Expand Up @@ -221,7 +221,9 @@ export default function AddLiquidityModal({
const y = BigNumber(yBalance).multipliedBy(xRate);

if (y.toNumber() > Number(assetsMap.get(row.y.type)?.balance || 0)) {
setYLabelError(`Insufficient`);
setYLabelError('Insufficient');
} else {
setYLabelError(undefined);
}
setYAmount(y.toFixed(0, 1));
}, [xAmount, reserveX, reserveY, row.x.type, row.y.type, assetsMap]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,18 +158,6 @@ export default function AllLiquidityList() {
}
}, [paginationModel, tokenPairs]);

// const {
// data: assetsList,
// isPending,
// refetch: refetchAssetsList,
// } = useRoochClientQuery(
// 'getBalances',
// {
// owner: currentAddress?.toStr() || '',
// },
// { refetchInterval: 5000 }
// );

const [openAddLiquidityModal, setOpenAddLiquidityModal] = useState(false);
const [selectedRow, setSelectedRow] = useState<AllLiquidityItemType>();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Args, type BalanceInfoView } from '@roochnetwork/rooch-sdk';
import { Args, Transaction, type BalanceInfoView } from '@roochnetwork/rooch-sdk';

import {
SessionKeyGuard,
useCurrentAddress,
useRoochClient,
useRoochClientQuery,
useSignAndExecuteTransaction,
WalletGuard,
} from '@roochnetwork/rooch-sdk-kit';

Expand All @@ -22,12 +24,13 @@ import {
Icon,
} from '@mui/material';
import dayjs from 'dayjs';
import { Fragment, useEffect, useMemo, useState } from 'react';
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
import { LoadingButton } from '@mui/lab';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import type { OwnerLiquidityItemType } from '../../hooks/use-owner-liquidity';
import { useNetworkVariable } from 'src/hooks/use-networks';
import { toast } from 'src/components/snackbar';

export type FarmRowItemType = {
id: string;
Expand All @@ -47,32 +50,121 @@ export type FarmRowItemType = {

type RowItemProps = {
row: FarmRowItemType;
selectRow?: FarmRowItemType;
onOpenStakeModal: (row: FarmRowItemType) => void;
onOpenAddLiquidityModal: (row: FarmRowItemType) => void;
};

export default function FarmRowItem({ row, onOpenStakeModal }: RowItemProps) {
export default function FarmRowItem({
row,
onOpenStakeModal,
onOpenAddLiquidityModal,
selectRow,
}: RowItemProps) {
const [openCollapse, setOpenCollapse] = useState(false);
const client = useRoochClient();
const dex = useNetworkVariable('dex');
const currentAddress = useCurrentAddress();
const [staked, setStaked] = useState(false);
const [harvest, setHarvest] = useState(0);
const [rewardCoin, setRewardCoin] = useState<BalanceInfoView>();
const { mutateAsync, isPending } = useSignAndExecuteTransaction();

useEffect(() => {
if (!openCollapse || harvest) {
const fetchHarvest = useCallback(() => {
if (!openCollapse) {
return;
}
client
.executeViewFunction({
target: `${dex.address}::liquidity_incentive::query_harvest_token_amount`,
args: [Args.address(currentAddress?.toStr() || ''), Args.objectId(row.id)],
target: `${dex.address}::liquidity_incentive::query_stake`,
args: [Args.objectId(row.id), Args.address(currentAddress?.toStr() || '')],
typeArgs: [row.x.type, row.y.type, row.reward],
})
.then((result) => {
const s = result.return_values![0].decoded_value as number;
setHarvest(s);
console.log(result);
console.log('staked', s);
setStaked(s > 0);
if (s > 0) {
client
.executeViewFunction({
target: `${dex.address}::liquidity_incentive::query_harvest_token_amount`,
args: [Args.address(currentAddress?.toStr() || ''), Args.objectId(row.id)],
typeArgs: [row.x.type, row.y.type, row.reward],
})
.then((result) => {
const s = result.return_values![0].decoded_value as number;
setHarvest(s);
});
}
});
}, [client, dex, openCollapse, row]);

useEffect(() => {
fetchHarvest();
console.log('sel');
}, [selectRow]);

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

useEffect(() => {
client
.getBalance({
owner: currentAddress?.toStr() || '',
coinType: row.reward,
})
.then((result) => {
setRewardCoin(result);
});
}, [openCollapse, client, currentAddress, row]);

const handleHarvest = () => {
const tx = new Transaction();
tx.callFunction({
target: `${dex.address}::liquidity_incentive::harvest`,
args: [Args.objectId(row.id)],
typeArgs: [row.x.type, row.y.type, row.reward],
});
mutateAsync({
transaction: tx,
})
.then((result) => {
if (result.execution_info.status.type === 'executed') {
fetchHarvest();
toast.success('harvest success');
} else {
toast.error('harvest failed');
}
})
.catch((e: any) => {
console.log(e);
toast.error('harvest failed');
});
};

const handleAction = (target: 'harvest' | 'unstake') => {
const tx = new Transaction();
tx.callFunction({
target: `${dex.address}::liquidity_incentive::${target}`,
args: [Args.objectId(row.id)],
typeArgs: [row.x.type, row.y.type, row.reward],
});
mutateAsync({
transaction: tx,
})
.then((result) => {
if (result.execution_info.status.type === 'executed') {
fetchHarvest();
toast.success(`${target} success`);
} else {
toast.error(`${target} failed`);
}
})
.catch((e: any) => {
toast.error(`${target} failed`);
});
}, [openCollapse]);
};

return (
<Fragment key={row.id}>
Expand Down Expand Up @@ -104,15 +196,6 @@ export default function FarmRowItem({ row, onOpenStakeModal }: RowItemProps) {

<TableCell align="right" sx={{ pr: 1 }}>
{openCollapse ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
{/* <WalletGuard
onClick={() => {
onOpenViewModal(row);
}}
>
<Button variant="outlined" size="small">
Remove
</Button>
</WalletGuard> */}
</TableCell>
</TableRow>
<TableRow>
Expand All @@ -133,19 +216,46 @@ export default function FarmRowItem({ row, onOpenStakeModal }: RowItemProps) {
height: '100%',
}}
>
<LoadingButton variant="outlined" size="small">
<Button
variant="outlined"
size="small"
onClick={() => onOpenAddLiquidityModal(row)}
>
Get {row.x.name}-{row.y.name} LP
</LoadingButton>
</Button>
</CardContent>
</Card>
<Card sx={{ width: '100%' }}>
<CardContent>
<Typography className="text-gray-600 !text-sm !font-semibold">
Balance:
</Typography>
<LoadingButton variant="outlined" size="small">
Harvest
</LoadingButton>
<CardContent
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
}}
>
<Stack direction="column">
<Typography className="text-gray-600 !text-sm !font-semibold">
Eligible ${rewardCoin?.symbol}: {harvest}
</Typography>
{staked && (
<SessionKeyGuard
onClick={() => {
handleAction(harvest > 0 ? 'harvest' : 'unstake');
}}
>
<LoadingButton
loading={isPending}
sx={{ mt: 1 }}
variant="outlined"
size="small"
>
{harvest > 0 && 'Harvest'}
{harvest < 1 && 'Unstake'}
</LoadingButton>
</SessionKeyGuard>
)}
</Stack>
</CardContent>
</Card>
<Card sx={{ width: '100%' }}>
Expand Down
Loading

0 comments on commit 02e1310

Please sign in to comment.