Skip to content

Commit

Permalink
order: include worst case price
Browse files Browse the repository at this point in the history
  • Loading branch information
sehyunc committed Sep 19, 2024
1 parent 9e50050 commit 96fe0fd
Show file tree
Hide file tree
Showing 8 changed files with 198 additions and 191 deletions.
4 changes: 2 additions & 2 deletions app/trade/[base]/components/charts/fill-chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { useOHLC } from "@/hooks/use-ohlc"
import { oneMinute } from "@/lib/constants/time"
import { formatCurrency, formatNumber, formatPercentage } from "@/lib/format"
import { remapToken } from "@/lib/token"
import { adjustPriceDecimals } from "@/lib/utils"
import { decimalNormalizePrice } from "@/lib/utils"

const chartConfig = {
price: {
Expand Down Expand Up @@ -60,7 +60,7 @@ export function FillChart({ order }: { order: OrderMetadata }) {
timestamp: Number(fill.price.timestamp),
amount: Number(formatNumber(fill.amount, token.decimals)),
price: Number(
adjustPriceDecimals(
decimalNormalizePrice(
fill.price.price,
token.decimals,
quoteToken.decimals,
Expand Down
4 changes: 2 additions & 2 deletions app/trade/[base]/components/order-details/details-content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
formatPercentage,
} from "@/lib/format"
import { getVWAP } from "@/lib/order"
import { adjustPriceDecimals } from "@/lib/utils"
import { decimalNormalizePrice } from "@/lib/utils"

export function DetailsContent({ order }: { order: OrderMetadata }) {
const token = Token.findByAddress(order.data.base_mint)
Expand Down Expand Up @@ -80,7 +80,7 @@ export function DetailsContent({ order }: { order: OrderMetadata }) {
const amountLong = formatNumber(fill.amount, token.decimals, true)
const value = amountTimesPrice(
fill.amount,
adjustPriceDecimals(
decimalNormalizePrice(
fill.price.price,
token.decimals,
quoteToken.decimals,
Expand Down
12 changes: 12 additions & 0 deletions components/dialogs/new-order-stepper/steps/default.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import React from "react"

import { VisuallyHidden } from "@radix-ui/react-visually-hidden"
import { Token, UpdateType, useCreateOrder } from "@renegade-fi/react"
import { toast } from "sonner"
Expand Down Expand Up @@ -29,23 +31,33 @@ import {

import { useMediaQuery } from "@/hooks/use-media-query"
import { usePrepareCreateOrder } from "@/hooks/use-prepare-create-order"
import { usePriceQuery } from "@/hooks/use-price-query"
import { Side } from "@/lib/constants/protocol"
import { constructStartToastMessage } from "@/lib/constants/task"
import { GAS_FEE_TOOLTIP } from "@/lib/constants/tooltips"
import { formatNumber, safeParseUnits } from "@/lib/format"
import { decimalCorrectPrice } from "@/lib/utils"

export function DefaultStep(props: NewOrderConfirmationProps) {
const { onNext, setTaskId } = useStepper()
const isDesktop = useMediaQuery("(min-width: 768px)")

const baseToken = Token.findByTicker(props.base)
const quoteToken = Token.findByTicker("USDC")
const { data: price } = usePriceQuery(baseToken.address)

const worstCasePrice = React.useMemo(() => {
if (!price) return 0
const wcp = price * (props.isSell ? 0.5 : 1.5)
return decimalCorrectPrice(wcp, baseToken.decimals, quoteToken.decimals)
}, [baseToken.decimals, price, props.isSell, quoteToken.decimals])

const { request } = usePrepareCreateOrder({
base: baseToken.address,
quote: quoteToken.address,
side: props.isSell ? "sell" : "buy",
amount: props.amount,
worstCasePrice: worstCasePrice.toString(),
})

const { createOrder } = useCreateOrder({
Expand Down
18 changes: 16 additions & 2 deletions hooks/use-prepare-create-order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export type UsePrepareCreateOrderParameters = {
quote: `0x${string}`
side: "buy" | "sell"
amount: string
worstCasePrice: string
}

export type UsePrepareCreateOrderReturnType = {
Expand All @@ -28,7 +29,7 @@ export type UsePrepareCreateOrderReturnType = {
export function usePrepareCreateOrder(
parameters: UsePrepareCreateOrderParameters,
) {
const { id = "", base, quote, side, amount } = parameters
const { id = "", base, quote, side, amount, worstCasePrice } = parameters
const config = useConfig()
const { data: wallet, isSuccess } = useBackOfQueueWallet()
const request = React.useMemo(() => {
Expand All @@ -37,6 +38,7 @@ export function usePrepareCreateOrder(
if (!isSuccess) return Error("Failed to fetch wallet.")
if (wallet.orders.filter((order) => order.amount).length >= MAX_ORDERS)
return Error("Max orders reached.")
if (!worstCasePrice) return Error("Worst case price is required")
const parsedAmount = safeParseUnits(
amount,
Token.findByAddress(base).decimals,
Expand All @@ -50,7 +52,19 @@ export function usePrepareCreateOrder(
quote,
side,
toHex(parsedAmount),
worstCasePrice,
) as string
}, [config, wallet, id, base, quote, side, amount, isSuccess])
}, [
config.state.seed,
config.utils,
isSuccess,
wallet,
amount,
base,
id,
quote,
side,
worstCasePrice,
])
return { request }
}
4 changes: 2 additions & 2 deletions lib/order.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { OrderMetadata, Token } from "@renegade-fi/react"

import { amountTimesPrice } from "@/hooks/use-usd-price"
import { adjustPriceDecimals } from "@/lib/utils"
import { decimalNormalizePrice } from "@/lib/utils"

export function getVWAP(order: OrderMetadata): number {
if (order.fills.length === 0) {
Expand All @@ -18,7 +18,7 @@ export function getVWAP(order: OrderMetadata): number {
const fillVolume = fill.amount
const fillValue = amountTimesPrice(
fill.amount,
adjustPriceDecimals(
decimalNormalizePrice(
fill.price.price,
token.decimals,
quoteToken.decimals,
Expand Down
34 changes: 27 additions & 7 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Metadata } from "next/types"
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

import { safeParseUnits } from "@/lib/format"
import { isTestnet } from "@/lib/viem"

export function cn(...inputs: ClassValue[]) {
Expand All @@ -13,14 +14,14 @@ export const getURL = (path = "") => {
// Check if NEXT_PUBLIC_SITE_URL is set and non-empty. Set this to your site URL in production env.
let url =
process?.env?.NEXT_PUBLIC_SITE_URL &&
process.env.NEXT_PUBLIC_SITE_URL.trim() !== ""
process.env.NEXT_PUBLIC_SITE_URL.trim() !== ""
? process.env.NEXT_PUBLIC_SITE_URL
: // If not set, check for NEXT_PUBLIC_VERCEL_URL, which is automatically set by Vercel.
process?.env?.NEXT_PUBLIC_VERCEL_URL &&
process.env.NEXT_PUBLIC_VERCEL_URL.trim() !== ""
process?.env?.NEXT_PUBLIC_VERCEL_URL &&
process.env.NEXT_PUBLIC_VERCEL_URL.trim() !== ""
? process.env.NEXT_PUBLIC_VERCEL_URL
: // If neither is set, default to localhost for local development.
"http://localhost:3000"
"http://localhost:3000"

// Trim the URL and remove trailing slash if exists.
url = url.replace(/\/+$/, "")
Expand Down Expand Up @@ -164,11 +165,30 @@ export function constructMetadata({
}
}

export function adjustPriceDecimals(
// Inverse of decimalCorrectPrice
export function decimalNormalizePrice(
price: number,
baseDecimals: number,
quoteDecimals: number,
): number {
const adjustedPrice = price * Math.pow(10, baseDecimals - quoteDecimals)
return adjustedPrice
const decimalDiff = baseDecimals - quoteDecimals
const normalizedPrice = safeParseUnits(
price.toFixed(baseDecimals + quoteDecimals),
decimalDiff,
)
if (normalizedPrice instanceof Error) return 0

return Number(normalizedPrice)
}

// Decimal correct a price for a given token pair
export function decimalCorrectPrice(
price: number,
baseDecimals: number,
quoteDecimals: number,
) {
const decimalDiff = quoteDecimals - baseDecimals
const correctedPrice = price * Math.pow(10, decimalDiff)

return correctedPrice
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"@radix-ui/react-tooltip": "^1.1.0",
"@radix-ui/react-visually-hidden": "^1.1.0",
"@renegade-fi/internal-sdk": "0.0.0-canary-20240829175257",
"@renegade-fi/react": "0.2.2",
"@renegade-fi/react": "0.3.0",
"@renegade-fi/tradingview-charts": "0.27.6",
"@tanstack/react-query": "^5.45.1",
"@tanstack/react-table": "^8.17.3",
Expand Down
Loading

0 comments on commit 96fe0fd

Please sign in to comment.