Skip to content

Commit

Permalink
Opt/dex (#3267)
Browse files Browse the repository at this point in the history
* option dex

* fix lint
  • Loading branch information
wow-sven authored Feb 5, 2025
1 parent 06c2de0 commit c5d9c3e
Show file tree
Hide file tree
Showing 20 changed files with 548 additions and 325 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@











Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import BigNumber from 'bignumber.js';

import { Stack, Button, TextField, FormControl, InputAdornment } from '@mui/material';

import { isNumber } from 'src/utils/reg';
import { formatByIntl } from 'src/utils/number';

interface TokenPairProps {
max: number;
amount: string;
onChange: (amount: string) => void;
}

export default function AmountInput({ max, amount, onChange }: TokenPairProps) {
return (
<FormControl>
<TextField
label="Amount"
placeholder=""
value={amount}
inputMode="decimal"
autoComplete="off"
onChange={(e) => {
const value = e.target.value.replaceAll(',', '');
if (!isNumber(value)) {
return;
}

const nValue = Number(value) > max ? max : Number(value);
onChange(formatByIntl(nValue));
}}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<Stack direction="row" spacing={0.5}>
<Button
size="small"
variant="outlined"
onClick={() => {
onChange(formatByIntl(new BigNumber(max).div(2).toString()));
// onChange();
}}
>
Half
</Button>
<Button
size="small"
variant="outlined"
onClick={() => {
onChange(formatByIntl(max));
}}
>
Max
</Button>
</Stack>
</InputAdornment>
),
}}
/>
</FormControl>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { Box, Button, Select, MenuItem, TextField, InputLabel, FormControl } fro

import { useNetworkVariable } from 'src/hooks/use-networks';

import { toDust, fromDust } from 'src/utils/number';
import { toDust, fromDust, formatByIntl } from 'src/utils/number';

import { toast } from 'src/components/snackbar';

Expand Down Expand Up @@ -139,7 +139,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa

try {
setLoading(true);
const fixdXCount = toDust(xCount, assetsMap?.get(x.type)?.decimals || 0);
const fixdXCount = toDust(xCount.replaceAll(',', ''), assetsMap?.get(x.type)?.decimals || 0);
const result = await client.executeViewFunction({
target: `${dex.address}::router::get_amount_out`,
args: [Args.u64(fixdXCount)],
Expand All @@ -152,7 +152,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa

const yCount = result.return_values![0].decoded_value as string;
const fixdYCount = fromDust(yCount, assetsMap?.get(y.type)?.decimals || 0);
setYCount(fixdYCount.toString());
setYCount(formatByIntl(fixdYCount.toString()));

const xCoin = assetsMap?.get(x.type)!;
const yCoin = assetsMap?.get(y.type)!;
Expand All @@ -162,7 +162,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
type: xCoin.coin_type,
icon: xCoin.icon_url || undefined,
symbol: xCoin.symbol,
amount: xCount,
amount: xCount.replaceAll(',', ''),
decimal: xCoin.decimals,
},
{
Expand Down Expand Up @@ -205,9 +205,9 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa

const xbalance = assetsMap?.get(oldY.type)!.fixedBalance || 0;
if (xRatio !== 0) {
setXCount((xbalance * xRatio).toString());
setXCount(formatByIntl(xbalance * xRatio));
} else if (Number(xCount) > xbalance) {
setXCount(xbalance.toString());
setXCount(formatByIntl(xbalance));
setXRation(0);
}
};
Expand All @@ -217,7 +217,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
return (
<>
<Box sx={{ display: 'flex', alignItems: 'center', mt: 4 }}>
<FormControl sx={{ minWidth: 220 }}>
<FormControl sx={{ minWidth: 300 }}>
<InputLabel id="select-x">X</InputLabel>
<Select
labelId="select-x"
Expand All @@ -226,9 +226,8 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
value={xValue}
label="X"
onChange={(e: SelectChangeEvent) => {
console.log('select x');
const s = e.target.value;
const x = tokenPair!.get(s)![0].x;
const {x} = tokenPair!.get(s)![0];
setX(x);
setXValue(e.target.value);
setY(undefined);
Expand All @@ -243,7 +242,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
[...tokenPair.entries()].map(([key, pairs]) => (
<MenuItem key={key} id={key} value={`${key}`}>
<span>{key} :</span>
<span>{assetsMap?.get(pairs[0].x.type)?.fixedBalance || 0}</span>
<span>{formatByIntl(assetsMap?.get(pairs[0].x.type)?.fixedBalance || 0)}</span>
</MenuItem>
))}
</Select>
Expand Down Expand Up @@ -278,7 +277,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
</FormControl>
</Box>
<Box display="flex" alignItems="center" justifyContent="space-between" sx={{ mt: 2 }}>
<Box sx={{ minWidth: 220, display: 'flex', justifyContent: 'center' }}>
<Box sx={{ minWidth: 300, display: 'flex', justifyContent: 'center' }}>
<Button
startIcon={<ArrowDownwardIcon />}
variant="text"
Expand All @@ -290,17 +289,17 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
</Button>
</Box>
<Box display="flex" alignItems="center">
{[0.25, 0.5, 0.75, 1].map((item, index) => (
{[0.25, 0.5, 0.75, x?.name === 'RGas' ? 0.99 : 1].map((item, index) => (
<Button
key={item.toString()}
variant={xRatio === item ? 'contained' : 'outlined'}
size="small"
sx={{ mx: 0.5 }}
disabled={!x}
// loading={loading && xRatio === item}
onClick={() => {
setXRation(item);
setXCount(((assetsMap?.get(x!.type)!.fixedBalance || 0) * item).toString());
const ration = item === 1 ? 0.99 : item; // TODO: Calculating gas
setXCount(formatByIntl((assetsMap?.get(x!.type)!.fixedBalance || 0) * ration));
}}
>
{item * 100}%
Expand All @@ -309,7 +308,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
</Box>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', mt: 2 }}>
<FormControl sx={{ minWidth: 220 }}>
<FormControl sx={{ minWidth: 300 }}>
<InputLabel id="select-y">Y</InputLabel>
<Select
labelId="select-y"
Expand All @@ -327,7 +326,7 @@ export default function SelectTokenPair({ onLoading, onCallback }: SelectTokenPa
{tokenPair?.get(x?.name || '')?.map((item) => (
<MenuItem key={item.y.name} id={item.y.name} value={`${item.y.name}`}>
<span>{item.y.name} :</span>
<span>{assetsMap?.get(item.y.type)?.fixedBalance || 0}</span>
<span>{formatByIntl(assetsMap?.get(item.y.type)?.fixedBalance || 0)}</span>
</MenuItem>
))}
</Select>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AnnotatedMoveStructView} from '@roochnetwork/rooch-sdk';
import type { IndexerStateIDView, AnnotatedMoveStructView } from '@roochnetwork/rooch-sdk';

import { useMemo } from 'react';
import { useRef, useMemo, useState, useEffect } from 'react';
import {
useRoochClient,
useCurrentAddress,
Expand All @@ -27,19 +27,46 @@ export type AllLiquidityItemType = {
};

export type UseAllLiquidityReturn = {
hasNext: boolean;
index: number;
paginate: (index: number) => void;
lpTokens: AllLiquidityItemType[];
isPending: boolean;
};

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

console.log(limit);
const [paginationModel, setPaginationModel] = useState({ index: 1, limit });
const mapPageToNextCursor = useRef<{ [page: number]: IndexerStateIDView | null }>({});

const queryOptions = useMemo(
() => ({
cursor: mapPageToNextCursor.current[paginationModel.index - 1],
limit: paginationModel.limit.toString(),
}),
[paginationModel]
);

const paginate = (index: number): void => {
if (index < 0) {
return;
}
setPaginationModel({
...paginationModel,
index,
});
};

const { data: tokenPairs, isPending } = useRoochClientQuery('queryObjectStates', {
filter: {
object_type: `${dex.address}::swap::TokenPair`,
},
cursor: queryOptions.cursor,
limit: queryOptions.limit,
queryOption: {
showDisplay: true,
},
Expand Down Expand Up @@ -81,7 +108,19 @@ export function useAllLiquidity(): UseAllLiquidityReturn {
return rowItme;
}, [tokenPairs]);

useEffect(() => {
if (!tokenPairs) {
return;
}
if (tokenPairs.has_next_page) {
mapPageToNextCursor.current[paginationModel.index] = tokenPairs.next_cursor ?? null;
}
}, [paginationModel, tokenPairs]);

return {
hasNext: tokenPairs?.has_next_page || false,
index: paginationModel.index,
paginate,
lpTokens: resolvedTokenPairs,
isPending,
};
Expand Down
Loading

0 comments on commit c5d9c3e

Please sign in to comment.