import { useState, useEffect, useRef } from 'react' import styled from '@emotion/styled' import useMarket from '../hooks/useMarket' import useIpAddress from '../hooks/useIpAddress' import useConnection from '../hooks/useConnection' import { PublicKey } from '@solana/web3.js' import { getTokenBySymbol, IDS, PerpMarket } from '@blockworks-foundation/mango-client' import { notify } from '../utils/notifications' // import { placeAndSettle } from '../utils/mango' import { calculateMarketPrice, getDecimalCount } from '../utils' import FloatingElement from './FloatingElement' import { floorToDecimal } from '../utils/index' import useMangoStore from '../stores/useMangoStore' import Button from './Button' import TradeType from './TradeType' import Input from './Input' import Switch from './Switch' import { Market } from '@project-serum/serum' import { I80F48, NEG_ONE_I80F48 } from '@blockworks-foundation/mango-client/lib/src/fixednum' const StyledRightInput = styled(Input)` border-left: 1px solid transparent; ` export default function TradeForm() { const set = useMangoStore((s) => s.set) const connected = useMangoStore((s) => s.wallet.connected) const actions = useMangoStore((s) => s.actions) const { connection, cluster } = useConnection() const groupConfig = useMangoStore((s) => s.selectedMangoGroup.config); const marketConfig = useMangoStore((s) => s.selectedMarket.config); const market = useMangoStore((s) => s.selectedMarket.current); const { side, baseSize, quoteSize, price, tradeType } = useMangoStore( (s) => s.tradeForm ) const { ipAllowed } = useIpAddress() const [postOnly, setPostOnly] = useState(false) const [ioc, setIoc] = useState(false) const [submitting, setSubmitting] = useState(false) const orderBookRef = useRef(useMangoStore.getState().selectedMarket.orderBook) const orderbook = orderBookRef.current useEffect( () => useMangoStore.subscribe( (orderBook) => (orderBookRef.current = orderBook), (state) => state.selectedMarket.orderBook ), [] ) console.log({orderbook, orderBookRef}); const setSide = (side) => set((s) => { s.tradeForm.side = side }) const setBaseSize = (baseSize) => set((s) => { if (!Number.isNaN(parseFloat(baseSize))) { s.tradeForm.baseSize = parseFloat(baseSize) } else { s.tradeForm.baseSize = baseSize } }) const setQuoteSize = (quoteSize) => set((s) => { if (!Number.isNaN(parseFloat(quoteSize))) { s.tradeForm.quoteSize = parseFloat(quoteSize) } else { s.tradeForm.quoteSize = quoteSize } }) const setPrice = (price) => set((s) => { if (!Number.isNaN(parseFloat(price))) { s.tradeForm.price = parseFloat(price) } else { s.tradeForm.price = price } }) const setTradeType = (type) => set((s) => { s.tradeForm.tradeType = type }) const markPriceRef = useRef(useMangoStore.getState().selectedMarket.markPrice) const markPrice = markPriceRef.current useEffect( () => useMangoStore.subscribe( (markPrice) => (markPriceRef.current = markPrice as number), (state) => state.selectedMarket.markPrice ), [] ) let minOrderSize = "0"; if (market instanceof Market && market.minOrderSize) { minOrderSize = market.minOrderSize.toString(); } else if (market instanceof PerpMarket) { const baseDecimals = getTokenBySymbol(groupConfig, marketConfig.base_symbol).decimals; const baseUnit = I80F48.fromNumber(Math.pow(10, baseDecimals)); const baseLotSize = I80F48.fromI64(market.contractSize); minOrderSize = baseLotSize.div(baseUnit).toString(); } const sizeDecimalCount = getDecimalCount(minOrderSize); let tickSize = 1; if (market instanceof Market) { tickSize = market.tickSize; } else if (market instanceof PerpMarket) { const baseDecimals = getTokenBySymbol(groupConfig, marketConfig.base_symbol).decimals; const baseUnit = I80F48.fromNumber(Math.pow(10, baseDecimals)); const baseLotSize = I80F48.fromI64(market.contractSize); const quoteDecimals = getTokenBySymbol(groupConfig, groupConfig.quote_symbol).decimals; const quoteUnit = I80F48.fromNumber(Math.pow(10, quoteDecimals)); const quoteLotSize = I80F48.fromI64(market.quoteLotSize); tickSize = quoteLotSize.mul(baseUnit).div(baseLotSize).div(quoteUnit).toNumber(); } const onSetPrice = (price: number | '') => { setPrice(price) if (!price) return if (baseSize) { onSetBaseSize(baseSize) } } const onSetBaseSize = (baseSize: number | '') => { const { price } = useMangoStore.getState().tradeForm setBaseSize(baseSize) if (!baseSize) { setQuoteSize('') return } const usePrice = Number(price) || markPrice if (!usePrice) { setQuoteSize('') return } const rawQuoteSize = baseSize * usePrice const quoteSize = baseSize && floorToDecimal(rawQuoteSize, sizeDecimalCount) setQuoteSize(quoteSize) } const onSetQuoteSize = (quoteSize: number | '') => { setQuoteSize(quoteSize) if (!quoteSize) { setBaseSize('') return } if (!Number(price) && tradeType === 'Limit') { setBaseSize('') return } const usePrice = Number(price) || markPrice const rawBaseSize = quoteSize / usePrice const baseSize = quoteSize && floorToDecimal(rawBaseSize, sizeDecimalCount) setBaseSize(baseSize) } const postOnChange = (checked) => { if (checked) { setIoc(false) } setPostOnly(checked) } const iocOnChange = (checked) => { if (checked) { setPostOnly(false) } setIoc(checked) } async function onSubmit() { /* if (!price && tradeType === 'Limit') { console.warn('Missing price') notify({ message: 'Missing price', type: 'error', }) return } else if (!baseSize) { console.warn('Missing size') notify({ message: 'Missing size', type: 'error', }) return } const marginAccount = useMangoStore.getState().selectedMarginAccount.current const mangoGroup = useMangoStore.getState().selectedMangoGroup.current const wallet = useMangoStore.getState().wallet.current if (!mangoGroup || !marketAddress || !marginAccount || !market) return setSubmitting(true) try { let calculatedPrice if (tradeType === 'Market') { calculatedPrice = side === 'buy' ? calculateMarketPrice(orderbook.asks, baseSize, side) : calculateMarketPrice(orderbook.bids, baseSize, side) } await placeAndSettle( connection, new PublicKey(IDS[cluster].mango_program_id), mangoGroup, marginAccount, market, wallet, side, calculatedPrice ?? price, baseSize, ioc ? 'ioc' : postOnly ? 'postOnly' : 'limit' ) console.log('Successfully placed trade!') setPrice('') onSetBaseSize('') actions.fetchMarginAccounts() } catch (e) { notify({ message: 'Error placing order', description: e.message, txid: e.txid, type: 'error', }) } finally { setSubmitting(false) } */ } const handleTradeTypeChange = (tradeType) => { setTradeType(tradeType) if (tradeType === 'Market') { setIoc(true) setPrice('') } else { const priceOnBook = side === 'buy' ? orderbook?.asks : orderbook?.bids; if (priceOnBook && priceOnBook.length > 0 && priceOnBook[0].length > 0) { setPrice(priceOnBook[0][0]); } setIoc(false) } } const disabledTradeButton = (!price && tradeType === 'Limit') || !baseSize || !connected || submitting return (
onSetPrice(e.target.value)} value={price} disabled={tradeType === 'Market'} prefix={'Price'} suffix={groupConfig.quote_symbol} className="rounded-r-none" wrapperClassName="w-3/5" /> onSetBaseSize(e.target.value)} value={baseSize} className="rounded-r-none" wrapperClassName="w-3/5" prefix={'Size'} suffix={marketConfig.base_symbol} /> onSetQuoteSize(e.target.value)} value={quoteSize} className="rounded-l-none" wrapperClassName="w-2/5" suffix={groupConfig.quote_symbol} /> {tradeType !== 'Market' ? (
POST
IOC
) : null}
{ipAllowed ? ( connected ? ( side === 'buy' ? ( ) : ( ) ) : ( <> {/*
*/} ) ) : ( )}
) }