Skip to content

Commit

Permalink
trade: improve token select modal
Browse files Browse the repository at this point in the history
  • Loading branch information
sehyunc committed Mar 27, 2024
1 parent db6b873 commit 65a7a44
Show file tree
Hide file tree
Showing 12 changed files with 361 additions and 79 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@
# Typescript
*.tsbuildinfo
next-env.d.ts

.vscode/
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
} from "@/generated"
import { useButton } from "@/hooks/use-button"
import { signPermit2 } from "@/lib/permit2"
import { parseAmount } from "@/lib/utils"
import { stylusDevnetEc2 } from "@/lib/viem"

const MAX_INT = BigInt(
Expand Down Expand Up @@ -49,8 +50,6 @@ export default function DepositButton() {
address: Token.findAddressByTicker(baseTicker) as `0x${string}`,
args: [address ?? "0x"],
})
// TODO: Adjust decimals
// console.log("Balance on L1: ", formatUnits(l1Balance ?? BigInt(0), 18))

// Get L1 ERC20 Allowance
const { data: allowance, queryKey: allowanceQueryKey } =
Expand All @@ -61,7 +60,6 @@ export default function DepositButton() {
env.NEXT_PUBLIC_PERMIT2_CONTRACT as `0x${string}`,
],
})
// console.log(`${baseTicker} allowance on Permit2 contract: `, allowance)

const queryClient = useQueryClient()
const { data: blockNumber } = useBlockNumber({ watch: true })
Expand All @@ -78,8 +76,9 @@ export default function DepositButton() {

const hasRpcConnectionError = typeof allowance === "undefined"
const hasInsufficientBalance = l1Balance
? l1Balance < parseUnits(baseTokenAmount, 18)
: false
? l1Balance <
parseAmount(baseTokenAmount, new Token({ ticker: baseTicker }))
: true
const needsApproval = allowance === BigInt(0) && approveStatus !== "success"

const isDisabled =
Expand Down
3 changes: 1 addition & 2 deletions trade.renegade.fi/app/(desktop)/[base]/[quote]/trading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Flex, HStack, Input, Text, useDisclosure } from "@chakra-ui/react"
import React, { createRef, useEffect, useRef, useState } from "react"

import { BlurredOverlay } from "@/components/modals/blurred-overlay"
import { TokenSelectModal } from "@/components/modals/token-select-modal"
import { TokenSelectModal } from "@/components/modals/trading-token-select-modal"
import { PlaceOrderButton } from "@/components/place-order-button"
import { OrderProvider, useOrder } from "@/contexts/Order/order-context"
import { Direction } from "@/contexts/Order/types"
Expand Down Expand Up @@ -172,7 +172,6 @@ function TradingInner() {
</Flex>
<TokenSelectModal
isOpen={tokenMenuIsOpen}
isTrading
onClose={onCloseTokenMenu}
setToken={setBaseToken}
/>
Expand Down
20 changes: 10 additions & 10 deletions trade.renegade.fi/app/api/fund/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
formatEther,
http,
parseAbi,
parseEther
parseEther,
} from "viem"
import { privateKeyToAccount } from "viem/accounts"

Expand All @@ -15,20 +15,20 @@ import { stylusDevnetEc2 } from "@/lib/viem"
const TOKENS_TO_FUND: { ticker: string; amount: string }[] = [
{
ticker: "WETH",
amount: "10"
amount: "10",
},
{
ticker: "USDC",
amount: "100000"
amount: "100000",
},
{
ticker: "WBTC",
amount: "3"
amount: "3",
},
{
ticker: "DYDX",
amount: "3"
}
amount: "3",
},
]

// TODO: Make sure mint works
Expand Down Expand Up @@ -101,18 +101,18 @@ export async function GET(request: Request) {
functionName: "mint",
args: [recipient, tokenAmount],
nonce: ++transactionCount,
});
})

const tokenHash = await walletClient.writeContract(tokenRequest);
const tokenHash = await walletClient.writeContract(tokenRequest)
const tokenTransaction = await publicClient.waitForTransactionReceipt({
hash: tokenHash,
});
})
console.log(
`Funded ${recipient} with ${formatAmount(
tokenAmount,
token
)} ${ticker}. Transaction hash: ${tokenTransaction.transactionHash}`
);
)
}

return new Response("Success!", {
Expand Down
2 changes: 1 addition & 1 deletion trade.renegade.fi/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ const theme = extendTheme({ config, styles, colors, components })
* │ Wallet Config |
* └─────────────────────┘
*/
const wagmiConfig = createConfig(
export const wagmiConfig = createConfig(
getDefaultConfig({
appDescription:
"On-chain dark pool. MPC-based cryptocurrency DEX for anonymous crosses at midpoint prices.",
Expand Down
108 changes: 66 additions & 42 deletions trade.renegade.fi/components/modals/token-select-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,22 @@ import {
ModalContent,
ModalHeader,
ModalOverlay,
Spinner,
Text,
VStack,
} from "@chakra-ui/react"
import { Token } from "@renegade-fi/renegade-js"
import { useQueryClient } from "@tanstack/react-query"
import Image from "next/image"
import { useMemo, useState } from "react"
import { useEffect, useMemo, useState } from "react"
import SimpleBar from "simplebar-react"
import "simplebar-react/dist/simplebar.min.css"
import { formatUnits } from "viem/utils"
import { useAccount } from "wagmi"
import { useAccount, useBlockNumber } from "wagmi"

import { ViewEnum, useApp } from "@/contexts/App/app-context"
import { useReadErc20BalanceOf } from "@/generated"
import { useBalance } from "@/hooks/use-balance"
import { wagmiConfig } from "@/app/providers"
import { useApp } from "@/contexts/App/app-context"
import { readErc20BalanceOf, useReadErc20BalanceOf } from "@/generated"
import { useDebounce } from "@/hooks/use-debounce"
import { DISPLAYED_TICKERS, TICKER_TO_NAME } from "@/lib/tokens"

Expand All @@ -32,21 +34,47 @@ interface TokenSelectModalProps {
isOpen: boolean
onClose: () => void
setToken: (ticker: string) => void
isTrading?: boolean
}
export function TokenSelectModal({
isOpen,
onClose,
setToken,
isTrading,
}: TokenSelectModalProps) {
const [searchTerm, setSearchTerm] = useState("")
const debouncedSearchTerm = useDebounce(searchTerm, 300)

const { address } = useAccount()

const [tickerBalances, setTickerBalances] = useState<
{ base: string; balance: bigint }[]
>([])

useEffect(() => {
const fetchBalances = async () => {
const result: { base: string; balance: bigint }[] = []
for (const [ticker] of DISPLAYED_TICKERS) {
const balance = await readErc20BalanceOf(wagmiConfig, {
address: Token.findAddressByTicker(ticker) as `0x${string}`,
args: [address ?? "0x"],
})
result.push({ base: ticker, balance: balance })
}
const sortedResult = result.sort((a, b) => {
if (a.balance > b.balance) return -1
if (a.balance < b.balance) return 1
return 0
})
setTickerBalances(sortedResult)
}
fetchBalances()
}, [address])

const filteredTickers = useMemo(() => {
return DISPLAYED_TICKERS.filter(([ticker]) =>
ticker.toLowerCase().includes(debouncedSearchTerm.toLowerCase())
return tickerBalances.filter(({ base }) =>
base.toLowerCase().includes(debouncedSearchTerm.toLowerCase())
)
}, [debouncedSearchTerm])
}, [debouncedSearchTerm, tickerBalances])

return (
<Modal isCentered isOpen={isOpen} onClose={onClose} scrollBehavior="inside">
<ModalOverlay
Expand Down Expand Up @@ -79,7 +107,7 @@ export function TokenSelectModal({
</ModalHeader>
<ModalBody padding="0">
<ModalCloseButton />
{filteredTickers.length === 0 && (
{filteredTickers.length === 0 && searchTerm ? (
<Box display="grid" minHeight="80%" placeContent="center">
<Text
color="white.50"
Expand All @@ -89,28 +117,30 @@ export function TokenSelectModal({
No results found
</Text>
</Box>
)}
<SimpleBar
style={{
height: "100%",
}}
>
{filteredTickers
.filter(([base]) => (isTrading ? base !== "USDC" : true))
.map(([ticker]) => {
) : filteredTickers.length === 0 ? (
<Box display="grid" minHeight="80%" placeContent="center">
<Spinner />
</Box>
) : (
<SimpleBar
style={{
height: "100%",
}}
>
{filteredTickers.map(({ base }) => {
return (
<Row
key={ticker}
ticker={ticker}
tokenName={TICKER_TO_NAME[ticker]}
key={base}
ticker={base}
onRowClick={() => {
onClose()
setToken(ticker)
setToken(base)
}}
/>
)
})}
</SimpleBar>
</SimpleBar>
)}
</ModalBody>
</ModalContent>
</Modal>
Expand All @@ -119,32 +149,26 @@ export function TokenSelectModal({

interface RowProps {
ticker: string
tokenName: string
onRowClick: () => void
}

const Row = ({ ticker, tokenName, onRowClick }: RowProps) => {
const Row = ({ ticker, onRowClick }: RowProps) => {
const { address } = useAccount()
const { tokenIcons, view } = useApp()
const balances = useBalance()
// TODO: Live update
const { data: erc20Balance } = useReadErc20BalanceOf({
const { tokenIcons } = useApp()
const { data: erc20Balance, queryKey } = useReadErc20BalanceOf({
address: Token.findAddressByTicker(ticker) as `0x${string}`,
args: [address ?? "0x"],
})
const queryClient = useQueryClient()
const { data: blockNumber } = useBlockNumber({ watch: true })
useEffect(() => {
queryClient.invalidateQueries({ queryKey })
}, [queryClient, queryKey, blockNumber])

const balanceAmount = useMemo(() => {
let result = "0"

const addr = Token.findAddressByTicker(ticker)
if (view === ViewEnum.TRADING) {
const matchingBalance = Object.values(balances).find(
({ mint: { address } }) => `0x${address}` === addr
)
result = matchingBalance ? matchingBalance.amount.toString() : "0"
} else if (view === ViewEnum.DEPOSIT) {
result = erc20Balance ? formatUnits(erc20Balance, 18) : "0" // Adjust the decimals as needed
}
result = erc20Balance ? formatUnits(erc20Balance, 18) : "0" // Adjust the decimals as needed

// Check if result has decimals and truncate to 2 decimals without rounding
if (result.includes(".")) {
Expand All @@ -153,7 +177,7 @@ const Row = ({ ticker, tokenName, onRowClick }: RowProps) => {
}

return result
}, [balances, erc20Balance, ticker, view])
}, [erc20Balance])
return (
<Grid
className="wrapper"
Expand Down Expand Up @@ -181,7 +205,7 @@ const Row = ({ ticker, tokenName, onRowClick }: RowProps) => {
priority
/>
<VStack alignItems="start" gap="0">
<Text>{tokenName}</Text>
<Text>{TICKER_TO_NAME[ticker]}</Text>
<Text color="white.60" fontSize="0.7em">
{ticker}
</Text>
Expand Down
Loading

0 comments on commit 65a7a44

Please sign in to comment.