use latest prettier

This commit is contained in:
tjs 2023-07-21 14:47:53 -04:00
parent e63c0f4252
commit 3d8588d434
187 changed files with 1258 additions and 1149 deletions

View File

@ -110,7 +110,7 @@ export const calcPricePrecision = (num: number | string) => {
export const formatPrice = ( export const formatPrice = (
num: number, num: number,
precision?: number, precision?: number,
gr0 = true gr0 = true,
): string => { ): string => {
if (!num) { if (!num) {
return num.toString() return num.toString()
@ -132,7 +132,7 @@ export const formatPrice = (
const matchString: string = match[0].slice(1) const matchString: string = match[0].slice(1)
formated = formated.replace( formated = formated.replace(
/\.0{4,15}/g, /\.0{4,15}/g,
`.0${SUBSCRIPT_NUMBER_MAP[matchString.length]}` `.0${SUBSCRIPT_NUMBER_MAP[matchString.length]}`,
) )
} }

View File

@ -51,7 +51,7 @@ export function subscribeOnStream(
onRealtimeCallback: any, onRealtimeCallback: any,
subscriberUID: any, subscriberUID: any,
onResetCacheNeededCallback: any, onResetCacheNeededCallback: any,
lastBar: any lastBar: any,
) { ) {
subscriptionItem = { subscriptionItem = {
resolution, resolution,

View File

@ -3,7 +3,7 @@ type CoingeckoOhlcv = [
open: number, open: number,
high: number, high: number,
low: number, low: number,
close: number close: number,
][] ][]
export type ChartDataItem = { export type ChartDataItem = {
@ -16,16 +16,16 @@ export type ChartDataItem = {
export const fetchChartData = async ( export const fetchChartData = async (
baseTokenId: string | undefined, baseTokenId: string | undefined,
quoteTokenId: string | undefined, quoteTokenId: string | undefined,
daysToShow: string daysToShow: string,
): Promise<ChartDataItem[]> => { ): Promise<ChartDataItem[]> => {
if (!baseTokenId || !quoteTokenId) return [] if (!baseTokenId || !quoteTokenId) return []
try { try {
const [inputResponse, outputResponse] = await Promise.all([ const [inputResponse, outputResponse] = await Promise.all([
fetch( fetch(
`https://api.coingecko.com/api/v3/coins/${baseTokenId}/ohlc?vs_currency=usd&days=${daysToShow}` `https://api.coingecko.com/api/v3/coins/${baseTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`,
), ),
fetch( fetch(
`https://api.coingecko.com/api/v3/coins/${quoteTokenId}/ohlc?vs_currency=usd&days=${daysToShow}` `https://api.coingecko.com/api/v3/coins/${quoteTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`,
), ),
]) ])
@ -36,7 +36,7 @@ export const fetchChartData = async (
const parsedData: ChartDataItem[] = [] const parsedData: ChartDataItem[] = []
for (const inputTokenCandle of inputTokenData) { for (const inputTokenCandle of inputTokenData) {
const outputTokenCandle = outputTokenData.find( const outputTokenCandle = outputTokenData.find(
(outputTokenCandle) => outputTokenCandle[0] === inputTokenCandle[0] (outputTokenCandle) => outputTokenCandle[0] === inputTokenCandle[0],
) )
if (outputTokenCandle) { if (outputTokenCandle) {
if (['usd-coin', 'tether'].includes(quoteTokenId)) { if (['usd-coin', 'tether'].includes(quoteTokenId)) {

View File

@ -72,11 +72,11 @@ const configurationData = {
const getTickerFromMktAddress = ( const getTickerFromMktAddress = (
group: Group, group: Group,
symbolAddress: string symbolAddress: string,
): string | null => { ): string | null => {
try { try {
const serumMkt = group.getSerum3MarketByExternalMarket( const serumMkt = group.getSerum3MarketByExternalMarket(
new PublicKey(symbolAddress) new PublicKey(symbolAddress),
) )
if (serumMkt) { if (serumMkt) {
@ -88,7 +88,7 @@ const getTickerFromMktAddress = (
const perpMarkets = Array.from(group.perpMarketsMapByMarketIndex.values()) const perpMarkets = Array.from(group.perpMarketsMapByMarketIndex.values())
const perpMkt = perpMarkets.find( const perpMkt = perpMarkets.find(
(perpMarket) => perpMarket.publicKey.toString() === symbolAddress (perpMarket) => perpMarket.publicKey.toString() === symbolAddress,
) )
if (perpMkt) { if (perpMkt) {
@ -102,12 +102,12 @@ let marketType: 'spot' | 'perp'
export const queryPerpBars = async ( export const queryPerpBars = async (
tokenAddress: string, tokenAddress: string,
resolution: typeof SUPPORTED_RESOLUTIONS[number], resolution: (typeof SUPPORTED_RESOLUTIONS)[number],
periodParams: { periodParams: {
firstDataRequest: boolean firstDataRequest: boolean
from: number from: number
to: number to: number
} },
): Promise<Bar[]> => { ): Promise<Bar[]> => {
const { from, to } = periodParams const { from, to } = periodParams
@ -150,12 +150,12 @@ export const queryPerpBars = async (
export const queryBirdeyeBars = async ( export const queryBirdeyeBars = async (
tokenAddress: string, tokenAddress: string,
resolution: typeof SUPPORTED_RESOLUTIONS[number], resolution: (typeof SUPPORTED_RESOLUTIONS)[number],
periodParams: { periodParams: {
firstDataRequest: boolean firstDataRequest: boolean
from: number from: number
to: number to: number
} },
): Promise<Bar[]> => { ): Promise<Bar[]> => {
const { from, to } = periodParams const { from, to } = periodParams
const urlParameters = { const urlParameters = {
@ -167,7 +167,7 @@ export const queryBirdeyeBars = async (
const query = Object.keys(urlParameters) const query = Object.keys(urlParameters)
.map( .map(
(name: string) => (name: string) =>
`${name}=${encodeURIComponent((urlParameters as any)[name])}` `${name}=${encodeURIComponent((urlParameters as any)[name])}`,
) )
.join('&') .join('&')
@ -207,14 +207,14 @@ export default {
_userInput: string, _userInput: string,
_exchange: string, _exchange: string,
_symbolType: string, _symbolType: string,
_onResultReadyCallback: (items: SearchSymbolResultItem[]) => void _onResultReadyCallback: (items: SearchSymbolResultItem[]) => void,
) => { ) => {
return return
}, },
resolveSymbol: async ( resolveSymbol: async (
symbolAddress: string, symbolAddress: string,
onSymbolResolvedCallback: (symbolInfo: SymbolInfo) => void onSymbolResolvedCallback: (symbolInfo: SymbolInfo) => void,
// _onResolveErrorCallback: any, // _onResolveErrorCallback: any,
// _extension: any // _extension: any
) => { ) => {
@ -283,9 +283,9 @@ export default {
bars: Bar[], bars: Bar[],
t: { t: {
noData: boolean noData: boolean
} },
) => void, ) => void,
onErrorCallback: (e: any) => void onErrorCallback: (e: any) => void,
) => { ) => {
try { try {
const { firstDataRequest } = periodParams const { firstDataRequest } = periodParams
@ -298,14 +298,14 @@ export default {
bars = await queryPerpBars( bars = await queryPerpBars(
symbolInfo.address, symbolInfo.address,
resolution as any, resolution as any,
periodParams periodParams,
) )
} else { } else {
marketType = 'spot' marketType = 'spot'
bars = await queryBirdeyeBars( bars = await queryBirdeyeBars(
symbolInfo.address, symbolInfo.address,
resolution as any, resolution as any,
periodParams periodParams,
) )
} }
if (!bars || bars.length === 0) { if (!bars || bars.length === 0) {
@ -335,7 +335,7 @@ export default {
resolution: string, resolution: string,
onRealtimeCallback: (data: any) => void, onRealtimeCallback: (data: any) => void,
subscriberUID: string, subscriberUID: string,
onResetCacheNeededCallback: () => void onResetCacheNeededCallback: () => void,
) => { ) => {
subscriptionIds.set(subscriberUID, symbolInfo.address) subscriptionIds.set(subscriberUID, symbolInfo.address)
if (symbolInfo.description?.includes('PERP')) { if (symbolInfo.description?.includes('PERP')) {
@ -345,7 +345,7 @@ export default {
onRealtimeCallback, onRealtimeCallback,
subscriberUID, subscriberUID,
onResetCacheNeededCallback, onResetCacheNeededCallback,
lastBarsCache.get(symbolInfo.address) lastBarsCache.get(symbolInfo.address),
) )
} else { } else {
subscribeOnSpotStream( subscribeOnSpotStream(
@ -354,7 +354,7 @@ export default {
onRealtimeCallback, onRealtimeCallback,
subscriberUID, subscriberUID,
onResetCacheNeededCallback, onResetCacheNeededCallback,
lastBarsCache.get(symbolInfo.address) lastBarsCache.get(symbolInfo.address),
) )
} }
}, },

View File

@ -66,12 +66,12 @@ const configurationData = {
export const queryBars = async ( export const queryBars = async (
tokenAddress: string, tokenAddress: string,
resolution: typeof SUPPORTED_RESOLUTIONS[number], resolution: (typeof SUPPORTED_RESOLUTIONS)[number],
periodParams: { periodParams: {
firstDataRequest: boolean firstDataRequest: boolean
from: number from: number
to: number to: number
} },
): Promise<Bar[]> => { ): Promise<Bar[]> => {
const { from, to } = periodParams const { from, to } = periodParams
const urlParameters = { const urlParameters = {
@ -121,14 +121,14 @@ export default {
_userInput: string, _userInput: string,
_exchange: string, _exchange: string,
_symbolType: string, _symbolType: string,
_onResultReadyCallback: (items: SearchSymbolResultItem[]) => void _onResultReadyCallback: (items: SearchSymbolResultItem[]) => void,
) => { ) => {
return return
}, },
resolveSymbol: async ( resolveSymbol: async (
symbolAddress: string, symbolAddress: string,
onSymbolResolvedCallback: (symbolInfo: SymbolInfo) => void onSymbolResolvedCallback: (symbolInfo: SymbolInfo) => void,
// _onResolveErrorCallback: any, // _onResolveErrorCallback: any,
// _extension: any // _extension: any
) => { ) => {
@ -187,16 +187,16 @@ export default {
bars: Bar[], bars: Bar[],
t: { t: {
noData: boolean noData: boolean
} },
) => void, ) => void,
onErrorCallback: (e: any) => void onErrorCallback: (e: any) => void,
) => { ) => {
try { try {
const { firstDataRequest } = periodParams const { firstDataRequest } = periodParams
const bars = await queryBars( const bars = await queryBars(
symbolInfo.address, symbolInfo.address,
resolution as any, resolution as any,
periodParams periodParams,
) )
if (!bars || bars.length === 0) { if (!bars || bars.length === 0) {
// "noData" should be set if there is no data in the requested period. // "noData" should be set if there is no data in the requested period.
@ -226,7 +226,7 @@ export default {
resolution: string, resolution: string,
onRealtimeCallback: (data: any) => void, onRealtimeCallback: (data: any) => void,
subscriberUID: string, subscriberUID: string,
onResetCacheNeededCallback: () => void onResetCacheNeededCallback: () => void,
) => { ) => {
subscribeOnStream( subscribeOnStream(
symbolInfo, symbolInfo,
@ -234,7 +234,7 @@ export default {
onRealtimeCallback, onRealtimeCallback,
subscriberUID, subscriberUID,
onResetCacheNeededCallback, onResetCacheNeededCallback,
lastBarsCache.get(symbolInfo.address) lastBarsCache.get(symbolInfo.address),
) )
}, },

View File

@ -59,7 +59,7 @@ export function subscribeOnStream(
onRealtimeCallback: any, onRealtimeCallback: any,
subscriberUID: any, subscriberUID: any,
onResetCacheNeededCallback: any, onResetCacheNeededCallback: any,
lastBar: any lastBar: any,
) { ) {
subscriptionItem = { subscriptionItem = {
resolution, resolution,

View File

@ -6,7 +6,7 @@ export type NotificationSettings = {
export const fetchNotificationSettings = async ( export const fetchNotificationSettings = async (
wallet: string, wallet: string,
token: string token: string,
) => { ) => {
const data = await fetch( const data = await fetch(
`${NOTIFICATION_API}notifications/user/getSettings`, `${NOTIFICATION_API}notifications/user/getSettings`,
@ -15,7 +15,7 @@ export const fetchNotificationSettings = async (
authorization: token, authorization: token,
publickey: wallet, publickey: wallet,
}, },
} },
) )
const body = await data.json() const body = await data.json()

View File

@ -57,7 +57,7 @@ function BorrowForm({ onSuccess, token }: BorrowFormProps) {
const [inputAmount, setInputAmount] = useState('') const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const [selectedToken, setSelectedToken] = useState( const [selectedToken, setSelectedToken] = useState(
token || INPUT_TOKEN_DEFAULT token || INPUT_TOKEN_DEFAULT,
) )
const [showTokenList, setShowTokenList] = useState(false) const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('') const [sizePercentage, setSizePercentage] = useState('')
@ -91,11 +91,11 @@ function BorrowForm({ onSuccess, token }: BorrowFormProps) {
setSizePercentage(percentage) setSizePercentage(percentage)
const amount = floorToDecimal( const amount = floorToDecimal(
new Decimal(percentage).div(100).mul(tokenMax), new Decimal(percentage).div(100).mul(tokenMax),
bank.mintDecimals bank.mintDecimals,
) )
setInputAmount(amount.toFixed()) setInputAmount(amount.toFixed())
}, },
[tokenMax, bank] [tokenMax, bank],
) )
const setMax = useCallback(() => { const setMax = useCallback(() => {
@ -123,7 +123,7 @@ function BorrowForm({ onSuccess, token }: BorrowFormProps) {
mangoAccount, mangoAccount,
bank!.mint, bank!.mint,
Number(inputAmount), Number(inputAmount),
true true,
) )
notify({ notify({
title: 'Transaction confirmed', title: 'Transaction confirmed',

View File

@ -43,7 +43,7 @@ interface DepositFormProps {
export const walletBalanceForToken = ( export const walletBalanceForToken = (
walletTokens: TokenAccount[], walletTokens: TokenAccount[],
token: string token: string,
): { maxAmount: number; maxDecimals: number } => { ): { maxAmount: number; maxDecimals: number } => {
const group = mangoStore.getState().group const group = mangoStore.getState().group
const bank = group?.banksMapByName.get(token)?.[0] const bank = group?.banksMapByName.get(token)?.[0]
@ -67,7 +67,7 @@ function DepositForm({ onSuccess, token }: DepositFormProps) {
const [inputAmount, setInputAmount] = useState('') const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const [selectedToken, setSelectedToken] = useState( const [selectedToken, setSelectedToken] = useState(
token || INPUT_TOKEN_DEFAULT token || INPUT_TOKEN_DEFAULT,
) )
const [showTokenList, setShowTokenList] = useState(false) const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('') const [sizePercentage, setSizePercentage] = useState('')
@ -98,11 +98,11 @@ function DepositForm({ onSuccess, token }: DepositFormProps) {
setSizePercentage(percentage) setSizePercentage(percentage)
const amount = floorToDecimal( const amount = floorToDecimal(
new Decimal(tokenMax.maxAmount).mul(percentage).div(100), new Decimal(tokenMax.maxAmount).mul(percentage).div(100),
tokenMax.maxDecimals tokenMax.maxDecimals,
) )
setInputAmount(amount.toFixed()) setInputAmount(amount.toFixed())
}, },
[tokenMax] [tokenMax],
) )
const handleSelectToken = (token: string) => { const handleSelectToken = (token: string) => {
@ -124,7 +124,7 @@ function DepositForm({ onSuccess, token }: DepositFormProps) {
group, group,
mangoAccount, mangoAccount,
bank.mint, bank.mint,
parseFloat(inputAmount) parseFloat(inputAmount),
) )
notify({ notify({
title: 'Transaction confirmed', title: 'Transaction confirmed',
@ -225,7 +225,7 @@ function DepositForm({ onSuccess, token }: DepositFormProps) {
value={inputAmount} value={inputAmount}
onValueChange={(e: NumberFormatValues) => { onValueChange={(e: NumberFormatValues) => {
setInputAmount( setInputAmount(
!Number.isNaN(Number(e.value)) ? e.value : '' !Number.isNaN(Number(e.value)) ? e.value : '',
) )
}} }}
isAllowed={withValueLimit} isAllowed={withValueLimit}

View File

@ -22,7 +22,7 @@ const HealthImpactTokenChange = ({
mangoAccount.simHealthRatioWithTokenPositionUiChanges( mangoAccount.simHealthRatioWithTokenPositionUiChanges(
group, group,
[{ mintPk, uiTokenAmount }], [{ mintPk, uiTokenAmount }],
HealthType.maint HealthType.maint,
) )
return projectedHealth! > 100 return projectedHealth! > 100

View File

@ -36,7 +36,7 @@ const termsLastUpdated = 1679441610978
const Layout = ({ children }: { children: ReactNode }) => { const Layout = ({ children }: { children: ReactNode }) => {
const [isCollapsed, setIsCollapsed] = useLocalStorageState( const [isCollapsed, setIsCollapsed] = useLocalStorageState(
SIDEBAR_COLLAPSE_KEY, SIDEBAR_COLLAPSE_KEY,
false false,
) )
const { width } = useViewport() const { width } = useViewport()
@ -52,9 +52,12 @@ const Layout = ({ children }: { children: ReactNode }) => {
const animationFrames = 15 const animationFrames = 15
for (let x = 1; x <= animationFrames; x++) { for (let x = 1; x <= animationFrames; x++) {
setTimeout(() => { setTimeout(
window.dispatchEvent(new Event('resize')) () => {
}, (sideBarAnimationDuration / animationFrames) * x) window.dispatchEvent(new Event('resize'))
},
(sideBarAnimationDuration / animationFrames) * x,
)
} }
}, [isCollapsed]) }, [isCollapsed])
@ -124,7 +127,7 @@ const TermsOfUse = () => {
const { connected } = useWallet() const { connected } = useWallet()
const [acceptTerms, setAcceptTerms] = useLocalStorageState( const [acceptTerms, setAcceptTerms] = useLocalStorageState(
ACCEPT_TERMS_KEY, ACCEPT_TERMS_KEY,
'' '',
) )
const showTermsOfUse = useMemo(() => { const showTermsOfUse = useMemo(() => {

View File

@ -38,17 +38,23 @@ const HydrateStore = () => {
actions.fetchGroup() actions.fetchGroup()
}, [marketName]) }, [marketName])
useInterval(() => { useInterval(
actions.fetchGroup() () => {
}, (slowNetwork ? 40 : 20) * SECONDS) actions.fetchGroup()
},
(slowNetwork ? 40 : 20) * SECONDS,
)
// refetches open orders every 30 seconds // refetches open orders every 30 seconds
// only the selected market's open orders are updated via websocket // only the selected market's open orders are updated via websocket
useInterval(() => { useInterval(
if (mangoAccountAddress) { () => {
actions.fetchOpenOrders() if (mangoAccountAddress) {
} actions.fetchOpenOrders()
}, (slowNetwork ? 60 : 30) * SECONDS) }
},
(slowNetwork ? 60 : 30) * SECONDS,
)
// refetch trade history and activity feed when switching accounts // refetch trade history and activity feed when switching accounts
useEffect(() => { useEffect(() => {
@ -59,10 +65,13 @@ const HydrateStore = () => {
}, [mangoAccountAddress]) }, [mangoAccountAddress])
// reload and parse market fills from the event queue // reload and parse market fills from the event queue
useInterval(async () => { useInterval(
const actions = mangoStore.getState().actions async () => {
actions.loadMarketFills() const actions = mangoStore.getState().actions
}, (slowNetwork ? 60 : 20) * SECONDS) actions.loadMarketFills()
},
(slowNetwork ? 60 : 20) * SECONDS,
)
// The websocket library solana/web3.js uses closes its websocket connection when the subscription list // The websocket library solana/web3.js uses closes its websocket connection when the subscription list
// is empty after opening its first time, preventing subsequent subscriptions from receiving responses. // is empty after opening its first time, preventing subsequent subscriptions from receiving responses.
@ -92,11 +101,11 @@ const HydrateStore = () => {
if (context.slot > lastSeenSlot) { if (context.slot > lastSeenSlot) {
const decodedMangoAccount = client.program.coder.accounts.decode( const decodedMangoAccount = client.program.coder.accounts.decode(
'mangoAccount', 'mangoAccount',
info?.data info?.data,
) )
const newMangoAccount = MangoAccount.from( const newMangoAccount = MangoAccount.from(
mangoAccount.publicKey, mangoAccount.publicKey,
decodedMangoAccount decodedMangoAccount,
) )
if (newMangoAccount.serum3Active().length > 0) { if (newMangoAccount.serum3Active().length > 0) {
await newMangoAccount.reloadSerum3OpenOrders(client) await newMangoAccount.reloadSerum3OpenOrders(client)
@ -107,7 +116,7 @@ const HydrateStore = () => {
}) })
actions.fetchOpenOrders() actions.fetchOpenOrders()
} }
} },
) )
return () => { return () => {

View File

@ -45,7 +45,7 @@ function RepayForm({ onSuccess, token }: RepayFormProps) {
const [inputAmount, setInputAmount] = useState('') const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const [selectedToken, setSelectedToken] = useState( const [selectedToken, setSelectedToken] = useState(
token || INPUT_TOKEN_DEFAULT token || INPUT_TOKEN_DEFAULT,
) )
const [showTokenList, setShowTokenList] = useState(false) const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('') const [sizePercentage, setSizePercentage] = useState('')
@ -69,7 +69,7 @@ function RepayForm({ onSuccess, token }: RepayFormProps) {
const borrowAmount = useMemo(() => { const borrowAmount = useMemo(() => {
if (!mangoAccount || !bank) return new Decimal(0) if (!mangoAccount || !bank) return new Decimal(0)
const amount = new Decimal( const amount = new Decimal(
mangoAccount.getTokenBorrowsUi(bank) mangoAccount.getTokenBorrowsUi(bank),
).toDecimalPlaces(bank.mintDecimals, Decimal.ROUND_UP) ).toDecimalPlaces(bank.mintDecimals, Decimal.ROUND_UP)
return amount return amount
}, [bank, mangoAccount]) }, [bank, mangoAccount])
@ -78,7 +78,7 @@ function RepayForm({ onSuccess, token }: RepayFormProps) {
if (!bank) return if (!bank) return
const amount = new Decimal(borrowAmount).toDecimalPlaces( const amount = new Decimal(borrowAmount).toDecimalPlaces(
bank.mintDecimals, bank.mintDecimals,
Decimal.ROUND_UP Decimal.ROUND_UP,
) )
setInputAmount(amount.toFixed()) setInputAmount(amount.toFixed())
setSizePercentage('100') setSizePercentage('100')
@ -95,7 +95,7 @@ function RepayForm({ onSuccess, token }: RepayFormProps) {
setInputAmount(amount.toFixed()) setInputAmount(amount.toFixed())
}, },
[bank, borrowAmount] [bank, borrowAmount],
) )
const handleSelectToken = (token: string) => { const handleSelectToken = (token: string) => {
@ -130,7 +130,7 @@ function RepayForm({ onSuccess, token }: RepayFormProps) {
mangoAccount, mangoAccount,
bank.mint, bank.mint,
actualAmount, actualAmount,
true true,
) )
notify({ notify({
title: 'Transaction confirmed', title: 'Transaction confirmed',
@ -154,7 +154,7 @@ function RepayForm({ onSuccess, token }: RepayFormProps) {
}) })
} }
}, },
[bank, publicKey?.toBase58(), sizePercentage] [bank, publicKey?.toBase58(), sizePercentage],
) )
useEffect(() => { useEffect(() => {
@ -236,7 +236,7 @@ function RepayForm({ onSuccess, token }: RepayFormProps) {
value={inputAmount} value={inputAmount}
onValueChange={(e: NumberFormatValues) => { onValueChange={(e: NumberFormatValues) => {
setInputAmount( setInputAmount(
!Number.isNaN(Number(e.value)) ? e.value : '' !Number.isNaN(Number(e.value)) ? e.value : '',
) )
}} }}
isAllowed={withValueLimit} isAllowed={withValueLimit}

View File

@ -10,7 +10,7 @@ const tpsWarningThreshold = 1300
const getRecentPerformance = async ( const getRecentPerformance = async (
connection: Connection, connection: Connection,
setTps: (x: number) => void setTps: (x: number) => void,
) => { ) => {
try { try {
const samples = 2 const samples = 2

View File

@ -38,13 +38,13 @@ const TokenList = () => {
const { t } = useTranslation(['common', 'token', 'trade']) const { t } = useTranslation(['common', 'token', 'trade'])
const [showZeroBalances, setShowZeroBalances] = useLocalStorageState( const [showZeroBalances, setShowZeroBalances] = useLocalStorageState(
SHOW_ZERO_BALANCES_KEY, SHOW_ZERO_BALANCES_KEY,
true true,
) )
const { mangoAccount, mangoAccountAddress } = useMangoAccount() const { mangoAccount, mangoAccountAddress } = useMangoAccount()
const { initContributions } = useHealthContributions() const { initContributions } = useHealthContributions()
const spotBalances = mangoStore((s) => s.mangoAccount.spotBalances) const spotBalances = mangoStore((s) => s.mangoAccount.spotBalances)
const totalInterestData = mangoStore( const totalInterestData = mangoStore(
(s) => s.mangoAccount.interestTotals.data (s) => s.mangoAccount.interestTotals.data,
) )
const { width } = useViewport() const { width } = useViewport()
const showTableView = width ? width > breakpoints.md : false const showTableView = width ? width > breakpoints.md : false
@ -136,7 +136,7 @@ const TokenList = () => {
const hasInterestEarned = totalInterestData.find( const hasInterestEarned = totalInterestData.find(
(d) => (d) =>
d.symbol.toLowerCase() === symbol.toLowerCase() || d.symbol.toLowerCase() === symbol.toLowerCase() ||
(symbol === 'ETH (Portal)' && d.symbol === 'ETH') (symbol === 'ETH (Portal)' && d.symbol === 'ETH'),
) )
const interestAmount = hasInterestEarned const interestAmount = hasInterestEarned
@ -273,7 +273,7 @@ const MobileTokenListItem = ({ bank }: { bank: BankWithBalance }) => {
const { mangoAccount } = useMangoAccount() const { mangoAccount } = useMangoAccount()
const { initContributions } = useHealthContributions() const { initContributions } = useHealthContributions()
const totalInterestData = mangoStore( const totalInterestData = mangoStore(
(s) => s.mangoAccount.interestTotals.data (s) => s.mangoAccount.interestTotals.data,
) )
const tokenBank = bank.bank const tokenBank = bank.bank
const mint = tokenBank.mint const mint = tokenBank.mint
@ -282,7 +282,7 @@ const MobileTokenListItem = ({ bank }: { bank: BankWithBalance }) => {
const hasInterestEarned = totalInterestData.find( const hasInterestEarned = totalInterestData.find(
(d) => (d) =>
d.symbol.toLowerCase() === symbol.toLowerCase() || d.symbol.toLowerCase() === symbol.toLowerCase() ||
(symbol === 'ETH (Portal)' && d.symbol === 'ETH') (symbol === 'ETH (Portal)' && d.symbol === 'ETH'),
) )
const interestAmount = hasInterestEarned const interestAmount = hasInterestEarned
@ -464,7 +464,7 @@ const ActionsMenu = ({
? setShowWithdrawModal(true) ? setShowWithdrawModal(true)
: setShowRepayModal(true) : setShowRepayModal(true)
}, },
[] [],
) )
const balance = useMemo(() => { const balance = useMemo(() => {
@ -474,7 +474,7 @@ const ActionsMenu = ({
const handleSwap = useCallback(() => { const handleSwap = useCallback(() => {
const tokenInfo = mangoTokens.find( const tokenInfo = mangoTokens.find(
(t) => t.address === bank.mint.toString() (t) => t.address === bank.mint.toString(),
) )
const group = mangoStore.getState().group const group = mangoStore.getState().group
if (balance && balance > 0) { if (balance && balance > 0) {
@ -493,7 +493,7 @@ const ActionsMenu = ({
} else { } else {
if (tokenInfo?.symbol === 'USDC') { if (tokenInfo?.symbol === 'USDC') {
const solTokenInfo = mangoTokens.find( const solTokenInfo = mangoTokens.find(
(t) => t.address === WRAPPED_SOL_MINT.toString() (t) => t.address === WRAPPED_SOL_MINT.toString(),
) )
const solBank = group?.getFirstBankByMint(WRAPPED_SOL_MINT) const solBank = group?.getFirstBankByMint(WRAPPED_SOL_MINT)
set((s) => { set((s) => {

View File

@ -49,7 +49,7 @@ function WithdrawForm({ onSuccess, token }: WithdrawFormProps) {
const [inputAmount, setInputAmount] = useState('') const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const [selectedToken, setSelectedToken] = useState( const [selectedToken, setSelectedToken] = useState(
token || INPUT_TOKEN_DEFAULT token || INPUT_TOKEN_DEFAULT,
) )
const [showTokenList, setShowTokenList] = useState(false) const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('') const [sizePercentage, setSizePercentage] = useState('')
@ -82,17 +82,17 @@ function WithdrawForm({ onSuccess, token }: WithdrawFormProps) {
if (percentage !== '100') { if (percentage !== '100') {
amount = floorToDecimal( amount = floorToDecimal(
new Decimal(adjustedTokenMax).mul(percentage).div(100), new Decimal(adjustedTokenMax).mul(percentage).div(100),
bank.mintDecimals bank.mintDecimals,
) )
} else { } else {
amount = floorToDecimal( amount = floorToDecimal(
new Decimal(adjustedTokenMax), new Decimal(adjustedTokenMax),
bank.mintDecimals bank.mintDecimals,
) )
} }
setInputAmount(amount.toString()) setInputAmount(amount.toString())
}, },
[bank, adjustedTokenMax] [bank, adjustedTokenMax],
) )
const setMax = useCallback(() => { const setMax = useCallback(() => {
@ -116,7 +116,7 @@ function WithdrawForm({ onSuccess, token }: WithdrawFormProps) {
mangoAccount, mangoAccount,
bank.mint, bank.mint,
withdrawAmount, withdrawAmount,
false false,
) )
notify({ notify({
title: 'Transaction confirmed', title: 'Transaction confirmed',
@ -227,7 +227,7 @@ function WithdrawForm({ onSuccess, token }: WithdrawFormProps) {
value={inputAmount} value={inputAmount}
onValueChange={(e: NumberFormatValues) => onValueChange={(e: NumberFormatValues) =>
setInputAmount( setInputAmount(
!Number.isNaN(Number(e.value)) ? e.value : '' !Number.isNaN(Number(e.value)) ? e.value : '',
) )
} }
isAllowed={withValueLimit} isAllowed={withValueLimit}

View File

@ -29,7 +29,7 @@ import { breakpoints } from 'utils/theme'
export const handleCopyAddress = ( export const handleCopyAddress = (
mangoAccount: MangoAccount, mangoAccount: MangoAccount,
successMessage: string successMessage: string,
) => { ) => {
copyToClipboard(mangoAccount.publicKey.toString()) copyToClipboard(mangoAccount.publicKey.toString())
notify({ notify({
@ -121,7 +121,7 @@ const AccountActions = () => {
mangoAccount!, mangoAccount!,
t('copy-address-success', { t('copy-address-success', {
pk: abbreviateAddress(mangoAccount!.publicKey), pk: abbreviateAddress(mangoAccount!.publicKey),
}) }),
) )
} }
> >

View File

@ -40,7 +40,7 @@ const AccountHeroStats = ({
useAccountHourlyVolumeStats() useAccountHourlyVolumeStats()
const totalInterestData = mangoStore( const totalInterestData = mangoStore(
(s) => s.mangoAccount.interestTotals.data (s) => s.mangoAccount.interestTotals.data,
) )
useEffect(() => { useEffect(() => {
@ -63,7 +63,7 @@ const AccountHeroStats = ({
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
enabled: !!mangoAccountAddress, enabled: !!mangoAccountAddress,
} },
) )
const { const {
@ -79,7 +79,7 @@ const AccountHeroStats = ({
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
enabled: !!mangoAccountAddress, enabled: !!mangoAccountAddress,
} },
) )
const maintHealth = useMemo(() => { const maintHealth = useMemo(() => {
@ -91,7 +91,7 @@ const AccountHeroStats = ({
const leverage = useMemo(() => { const leverage = useMemo(() => {
if (!group || !mangoAccount) return 0 if (!group || !mangoAccount) return 0
const assetsValue = toUiDecimalsForQuote( const assetsValue = toUiDecimalsForQuote(
mangoAccount.getAssetsValue(group).toNumber() mangoAccount.getAssetsValue(group).toNumber(),
) )
if (isNaN(assetsValue / accountValue)) { if (isNaN(assetsValue / accountValue)) {
@ -110,7 +110,7 @@ const AccountHeroStats = ({
if (totalInterestData.length) { if (totalInterestData.length) {
return totalInterestData.reduce( return totalInterestData.reduce(
(a, c) => a + (c.borrow_interest_usd * -1 + c.deposit_interest_usd), (a, c) => a + (c.borrow_interest_usd * -1 + c.deposit_interest_usd),
0 0,
) )
} }
return 0.0 return 0.0
@ -120,7 +120,7 @@ const AccountHeroStats = ({
if (fundingData?.length && mangoAccountAddress) { if (fundingData?.length && mangoAccountAddress) {
return fundingData.reduce( return fundingData.reduce(
(a, c) => a + c.long_funding + c.short_funding, (a, c) => a + c.long_funding + c.short_funding,
0 0,
) )
} }
return 0.0 return 0.0
@ -268,7 +268,7 @@ const AccountHeroStats = ({
value={ value={
group && mangoAccount group && mangoAccount
? toUiDecimalsForQuote( ? toUiDecimalsForQuote(
mangoAccount.getCollateralValue(group) mangoAccount.getCollateralValue(group),
) )
: 0 : 0
} }
@ -289,7 +289,7 @@ const AccountHeroStats = ({
value={ value={
group && mangoAccount group && mangoAccount
? toUiDecimalsForQuote( ? toUiDecimalsForQuote(
mangoAccount.getAssetsValue(group, HealthType.init) mangoAccount.getAssetsValue(group, HealthType.init),
) )
: 0 : 0
} }

View File

@ -42,7 +42,7 @@ const AccountPage = () => {
const isMobile = width ? width < breakpoints.md : false const isMobile = width ? width < breakpoints.md : false
const [activeTab, setActiveTab] = useLocalStorageState( const [activeTab, setActiveTab] = useLocalStorageState(
'accountHeroKey-0.1', 'accountHeroKey-0.1',
'account-value' 'account-value',
) )
const { performanceData, rollingDailyData } = useAccountPerformanceData() const { performanceData, rollingDailyData } = useAccountPerformanceData()
const router = useRouter() const router = useRouter()
@ -53,7 +53,7 @@ const AccountPage = () => {
const query = { ...router.query, ['view']: view } const query = { ...router.query, ['view']: view }
router.push({ pathname: router.pathname, query }) router.push({ pathname: router.pathname, query })
}, },
[router] [router],
) )
const handleCloseDailyPnlModal = () => { const handleCloseDailyPnlModal = () => {

View File

@ -40,7 +40,7 @@ const AccountValue = ({
const [showExpandChart, setShowExpandChart] = useState<boolean>(false) const [showExpandChart, setShowExpandChart] = useState<boolean>(false)
const [animationSettings] = useLocalStorageState( const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const { width } = useViewport() const { width } = useViewport()
const { performanceLoading: loading } = useAccountPerformanceData() const { performanceLoading: loading } = useAccountPerformanceData()

View File

@ -48,7 +48,7 @@ export const getFee = (activity: any, mangoAccountAddress: string) => {
const value = price * quantity const value = price * quantity
fee = { fee = {
value: formatFee( value: formatFee(
mangoAccountAddress === maker ? maker_fee * value : taker_fee * value mangoAccountAddress === maker ? maker_fee * value : taker_fee * value,
), ),
symbol: 'USDC', symbol: 'USDC',
} }
@ -63,14 +63,14 @@ export const getFee = (activity: any, mangoAccountAddress: string) => {
if (side === 'liqee') { if (side === 'liqee') {
fee = { fee = {
value: formatNumericValue( value: formatNumericValue(
Math.abs(liab_amount) - Math.abs(asset_amount * asset_price) Math.abs(liab_amount) - Math.abs(asset_amount * asset_price),
), ),
symbol: liab_symbol, symbol: liab_symbol,
} }
} else { } else {
fee = { fee = {
value: formatNumericValue( value: formatNumericValue(
Math.abs(asset_amount * asset_price) - Math.abs(liab_amount) Math.abs(asset_amount * asset_price) - Math.abs(liab_amount),
), ),
symbol: liab_symbol, symbol: liab_symbol,
} }
@ -81,14 +81,14 @@ export const getFee = (activity: any, mangoAccountAddress: string) => {
if (base_transfer > 0) { if (base_transfer > 0) {
fee = { fee = {
value: formatNumericValue( value: formatNumericValue(
Math.abs(base_transfer * price) - Math.abs(quote_transfer) Math.abs(base_transfer * price) - Math.abs(quote_transfer),
), ),
symbol: 'USDC', symbol: 'USDC',
} }
} else { } else {
fee = { fee = {
value: formatNumericValue( value: formatNumericValue(
Math.abs(quote_transfer) - Math.abs(base_transfer * price) Math.abs(quote_transfer) - Math.abs(base_transfer * price),
), ),
symbol: 'USDC', symbol: 'USDC',
} }
@ -99,7 +99,7 @@ export const getFee = (activity: any, mangoAccountAddress: string) => {
export const getCreditAndDebit = ( export const getCreditAndDebit = (
activity: any, activity: any,
mangoAccountAddress: string mangoAccountAddress: string,
) => { ) => {
const { activity_type } = activity const { activity_type } = activity
let credit = { value: '0', symbol: '' } let credit = { value: '0', symbol: '' }
@ -270,7 +270,7 @@ const ActivityFeedTable = () => {
const { connected } = useWallet() const { connected } = useWallet()
const [preferredExplorer] = useLocalStorageState( const [preferredExplorer] = useLocalStorageState(
PREFERRED_EXPLORER_KEY, PREFERRED_EXPLORER_KEY,
EXPLORERS[0] EXPLORERS[0],
) )
const { width } = useViewport() const { width } = useViewport()
const showTableView = width ? width > breakpoints.md : false const showTableView = width ? width > breakpoints.md : false
@ -285,7 +285,7 @@ const ActivityFeedTable = () => {
actions.fetchActivityFeed( actions.fetchActivityFeed(
mangoAccountAddress, mangoAccountAddress,
offset + PAGINATION_PAGE_LENGTH, offset + PAGINATION_PAGE_LENGTH,
queryParams queryParams,
) )
}, [actions, offset, queryParams, mangoAccountAddress]) }, [actions, offset, queryParams, mangoAccountAddress])
@ -376,7 +376,7 @@ const ActivityFeedTable = () => {
<div className="flex items-center justify-end"> <div className="flex items-center justify-end">
<Tooltip <Tooltip
content={`View on ${t( content={`View on ${t(
`settings:${preferredExplorer.name}` `settings:${preferredExplorer.name}`,
)}`} )}`}
placement="top-end" placement="top-end"
> >
@ -515,7 +515,7 @@ const MobileActivityFeedItem = ({
const { t } = useTranslation(['common', 'activity']) const { t } = useTranslation(['common', 'activity'])
const [preferredExplorer] = useLocalStorageState( const [preferredExplorer] = useLocalStorageState(
PREFERRED_EXPLORER_KEY, PREFERRED_EXPLORER_KEY,
EXPLORERS[0] EXPLORERS[0],
) )
const { mangoAccountAddress } = useMangoAccount() const { mangoAccountAddress } = useMangoAccount()
const { activity_type, block_datetime } = activity const { activity_type, block_datetime } = activity

View File

@ -50,7 +50,7 @@ const ActivityFilters = () => {
const actions = mangoStore((s) => s.actions) const actions = mangoStore((s) => s.actions)
const { mangoAccountAddress } = useMangoAccount() const { mangoAccountAddress } = useMangoAccount()
const [advancedFilters, setAdvancedFilters] = useState<AdvancedFilters>( const [advancedFilters, setAdvancedFilters] = useState<AdvancedFilters>(
DEFAULT_ADVANCED_FILTERS DEFAULT_ADVANCED_FILTERS,
) )
const [params, setParams] = useState<string[]>([]) const [params, setParams] = useState<string[]>([])
const { t } = useTranslation(['common', 'activity']) const { t } = useTranslation(['common', 'activity'])
@ -64,7 +64,7 @@ const ActivityFilters = () => {
if (entry[1].length) { if (entry[1].length) {
// ETH should be renamed to ETH (Portal) in the database // ETH should be renamed to ETH (Portal) in the database
const alignSymbolsToBackend = entry[1].map((e: string) => const alignSymbolsToBackend = entry[1].map((e: string) =>
e === 'ETH (Portal)' ? 'ETH' : e e === 'ETH (Portal)' ? 'ETH' : e,
) )
advancedParams = advancedParams =
advancedParams + `&${entry[0]}=${alignSymbolsToBackend}` advancedParams + `&${entry[0]}=${alignSymbolsToBackend}`

View File

@ -19,7 +19,7 @@ const AssetsLiabilities = ({ isMobile }: { isMobile: boolean }) => {
const { theme } = useTheme() const { theme } = useTheme()
const [animationSettings] = useLocalStorageState( const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const [assetsValue, assetsRatio, liabsValue, liabsRatio] = useMemo(() => { const [assetsValue, assetsRatio, liabsValue, liabsRatio] = useMemo(() => {

View File

@ -54,16 +54,16 @@ const CreateAccountForm = ({
group, group,
newAccountNum, newAccountNum,
name || `Account ${newAccountNum + 1}`, name || `Account ${newAccountNum + 1}`,
16 // tokenCount 16, // tokenCount
) )
if (tx) { if (tx) {
const pk = wallet.adapter.publicKey const pk = wallet.adapter.publicKey
const mangoAccounts = await client.getMangoAccountsForOwner(group, pk!) const mangoAccounts = await client.getMangoAccountsForOwner(group, pk!)
const reloadedMangoAccounts = await Promise.all( const reloadedMangoAccounts = await Promise.all(
mangoAccounts.map((ma) => ma.reloadSerum3OpenOrders(client)) mangoAccounts.map((ma) => ma.reloadSerum3OpenOrders(client)),
) )
const newAccount = mangoAccounts.find( const newAccount = mangoAccounts.find(
(acc) => acc.accountNum === newAccountNum (acc) => acc.accountNum === newAccountNum,
) )
if (newAccount) { if (newAccount) {
await newAccount.reloadSerum3OpenOrders(client) await newAccount.reloadSerum3OpenOrders(client)

View File

@ -36,7 +36,7 @@ import SheenLoader from '@components/shared/SheenLoader'
const fetchHourlyFunding = async (mangoAccountPk: string) => { const fetchHourlyFunding = async (mangoAccountPk: string) => {
try { try {
const data = await fetch( const data = await fetch(
`${MANGO_DATA_API_URL}/stats/funding-account-hourly?mango-account=${mangoAccountPk}` `${MANGO_DATA_API_URL}/stats/funding-account-hourly?mango-account=${mangoAccountPk}`,
) )
const res = await data.json() const res = await data.json()
if (res) { if (res) {
@ -80,7 +80,7 @@ const FundingChart = ({ hideChart }: { hideChart: () => void }) => {
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
enabled: !!mangoAccountAddress, enabled: !!mangoAccountAddress,
} },
) )
useEffect(() => { useEffect(() => {
@ -100,7 +100,7 @@ const FundingChart = ({ hideChart }: { hideChart: () => void }) => {
} }
const data = rawData.reduce((a: HourlyFundingChartData[], c) => { const data = rawData.reduce((a: HourlyFundingChartData[], c) => {
const found: HourlyFundingChartData | undefined = a.find( const found: HourlyFundingChartData | undefined = a.find(
(item) => item['time'] === c.time (item) => item['time'] === c.time,
) )
const marketKey = Object.keys(c)[0] const marketKey = Object.keys(c)[0]
const marketFunding = Object.values(c)[0] const marketFunding = Object.values(c)[0]
@ -123,7 +123,7 @@ const FundingChart = ({ hideChart }: { hideChart: () => void }) => {
if (active && payload && payload.length) { if (active && payload && payload.length) {
const load = payload[0].payload const load = payload[0].payload
const data: [string, any][] = Object.entries(load).filter( const data: [string, any][] = Object.entries(load).filter(
(p) => p[0] !== 'time' && p[0] !== 'total' (p) => p[0] !== 'time' && p[0] !== 'total',
) )
return ( return (
<div className="rounded-md bg-th-bkg-2 p-4"> <div className="rounded-md bg-th-bkg-2 p-4">

View File

@ -22,10 +22,10 @@ const HealthContributions = ({ hideView }: { hideView: () => void }) => {
const { group } = useMangoGroup() const { group } = useMangoGroup()
const { mangoAccount, mangoAccountAddress } = useMangoAccount() const { mangoAccount, mangoAccountAddress } = useMangoAccount()
const [initActiveIndex, setInitActiveIndex] = useState<number | undefined>( const [initActiveIndex, setInitActiveIndex] = useState<number | undefined>(
undefined undefined,
) )
const [maintActiveIndex, setMaintActiveIndex] = useState<number | undefined>( const [maintActiveIndex, setMaintActiveIndex] = useState<number | undefined>(
undefined undefined,
) )
const { initContributions, maintContributions } = useHealthContributions() const { initContributions, maintContributions } = useHealthContributions()
@ -37,7 +37,7 @@ const HealthContributions = ({ hideView }: { hideView: () => void }) => {
if (item.asset === 'USDC') { if (item.asset === 'USDC') {
const hasPerp = const hasPerp =
!!item.contributionDetails?.perpMarketContributions.find( !!item.contributionDetails?.perpMarketContributions.find(
(perp: PerpMarketContribution) => Math.abs(perp.contributionUi) > 0 (perp: PerpMarketContribution) => Math.abs(perp.contributionUi) > 0,
) )
initHealthContributions.push({ initHealthContributions.push({
...item, ...item,
@ -73,7 +73,7 @@ const HealthContributions = ({ hideView }: { hideView: () => void }) => {
if (item.asset === 'USDC') { if (item.asset === 'USDC') {
const hasPerp = const hasPerp =
!!item.contributionDetails?.perpMarketContributions.find( !!item.contributionDetails?.perpMarketContributions.find(
(perp: PerpMarketContribution) => Math.abs(perp.contributionUi) > 0 (perp: PerpMarketContribution) => Math.abs(perp.contributionUi) > 0,
) )
maintHealthContributions.push({ maintHealthContributions.push({
...item, ...item,
@ -111,7 +111,7 @@ const HealthContributions = ({ hideView }: { hideView: () => void }) => {
const splitData = initHealthContributions.reduce( const splitData = initHealthContributions.reduce(
( (
acc: { market: HealthContribution[]; token: HealthContribution[] }, acc: { market: HealthContribution[]; token: HealthContribution[] },
obj: HealthContribution obj: HealthContribution,
) => { ) => {
const isPerp = obj.asset.includes('PERP') const isPerp = obj.asset.includes('PERP')
const isSpotMarket = obj.asset.includes('/') const isSpotMarket = obj.asset.includes('/')
@ -123,7 +123,7 @@ const HealthContributions = ({ hideView }: { hideView: () => void }) => {
} }
return acc return acc
}, },
{ market: [], token: [] } { market: [], token: [] },
) )
return [splitData.market, splitData.token] return [splitData.market, splitData.token]
}, [initHealthContributions]) }, [initHealthContributions])
@ -133,7 +133,7 @@ const HealthContributions = ({ hideView }: { hideView: () => void }) => {
const splitData = maintHealthContributions.reduce( const splitData = maintHealthContributions.reduce(
( (
acc: { market: HealthContribution[]; token: HealthContribution[] }, acc: { market: HealthContribution[]; token: HealthContribution[] },
obj: HealthContribution obj: HealthContribution,
) => { ) => {
const isPerp = obj.asset.includes('PERP') const isPerp = obj.asset.includes('PERP')
const isSpotMarket = obj.asset.includes('/') const isSpotMarket = obj.asset.includes('/')
@ -145,7 +145,7 @@ const HealthContributions = ({ hideView }: { hideView: () => void }) => {
} }
return acc return acc
}, },
{ market: [], token: [] } { market: [], token: [] },
) )
const markets = splitData.market.filter((d) => d.contribution > 0) const markets = splitData.market.filter((d) => d.contribution > 0)
const tokens = splitData.token const tokens = splitData.token

View File

@ -109,7 +109,7 @@ const HistoryTabs = () => {
paid: `${formatNumericValue(swap_in_amount, inDecimals)} ${inSymbol}`, paid: `${formatNumericValue(swap_in_amount, inDecimals)} ${inSymbol}`,
received: `${formatNumericValue( received: `${formatNumericValue(
swap_out_amount, swap_out_amount,
outDecimals outDecimals,
)} ${outSymbol}`, )} ${outSymbol}`,
value: formatCurrencyValue(swap_out_price_usd * swap_out_amount), value: formatCurrencyValue(swap_out_price_usd * swap_out_amount),
borrow: `${borrowAmount} ${inSymbol}`, borrow: `${borrowAmount} ${inSymbol}`,
@ -135,7 +135,7 @@ const HistoryTabs = () => {
let market let market
if ('market' in trade) { if ('market' in trade) {
market = group.getSerum3MarketByExternalMarket( market = group.getSerum3MarketByExternalMarket(
new PublicKey(trade.market) new PublicKey(trade.market),
) )
} else if ('perp_market' in trade) { } else if ('perp_market' in trade) {
market = group.getPerpMarketByMarketIndex(trade.market_index) market = group.getPerpMarketByMarketIndex(trade.market_index)

View File

@ -22,7 +22,7 @@ const LiquidationDetails = ({
const { t } = useTranslation(['common', 'activity', 'settings']) const { t } = useTranslation(['common', 'activity', 'settings'])
const [preferredExplorer] = useLocalStorageState( const [preferredExplorer] = useLocalStorageState(
PREFERRED_EXPLORER_KEY, PREFERRED_EXPLORER_KEY,
EXPLORERS[0] EXPLORERS[0],
) )
const getAssetLiquidatedReturned = (details: SpotOrPerpLiquidationItem) => { const getAssetLiquidatedReturned = (details: SpotOrPerpLiquidationItem) => {
@ -209,7 +209,7 @@ const LiquidationDetails = ({
> >
<span className="mr-1.5"> <span className="mr-1.5">
{abbreviateAddress( {abbreviateAddress(
new PublicKey(activity.activity_details.counterparty) new PublicKey(activity.activity_details.counterparty),
)} )}
</span> </span>
<ArrowTopRightOnSquareIcon className="h-3 w-3" /> <ArrowTopRightOnSquareIcon className="h-3 w-3" />

View File

@ -38,13 +38,13 @@ const MangoAccountSummary = () => {
const [accountPnl, accountValue, freeCollateral, health] = useMemo(() => { const [accountPnl, accountValue, freeCollateral, health] = useMemo(() => {
if (!group || !mangoAccount) return [0, 0, 0, 0] if (!group || !mangoAccount) return [0, 0, 0, 0]
const accountPnl = toUiDecimalsForQuote( const accountPnl = toUiDecimalsForQuote(
mangoAccount.getPnl(group).toNumber() mangoAccount.getPnl(group).toNumber(),
) )
const accountValue = toUiDecimalsForQuote( const accountValue = toUiDecimalsForQuote(
mangoAccount.getEquity(group).toNumber() mangoAccount.getEquity(group).toNumber(),
) )
const freeCollateral = toUiDecimalsForQuote( const freeCollateral = toUiDecimalsForQuote(
mangoAccount.getCollateralValue(group).toNumber() mangoAccount.getCollateralValue(group).toNumber(),
) )
const health = mangoAccount.getHealthRatioUi(group, HealthType.maint) const health = mangoAccount.getHealthRatioUi(group, HealthType.maint)
return [accountPnl, accountValue, freeCollateral, health] return [accountPnl, accountValue, freeCollateral, health]
@ -53,7 +53,7 @@ const MangoAccountSummary = () => {
const leverage = useMemo(() => { const leverage = useMemo(() => {
if (!group || !mangoAccount) return 0 if (!group || !mangoAccount) return 0
const assetsValue = toUiDecimalsForQuote( const assetsValue = toUiDecimalsForQuote(
mangoAccount.getAssetsValue(group).toNumber() mangoAccount.getAssetsValue(group).toNumber(),
) )
if (isNaN(assetsValue / accountValue)) { if (isNaN(assetsValue / accountValue)) {

View File

@ -63,7 +63,7 @@ const MarketsHealthTable = ({
const { asset, contribution, isAsset } = cont const { asset, contribution, isAsset } = cont
const market = group.getSerum3MarketByName(asset) const market = group.getSerum3MarketByName(asset)
const bank = group.banksMapByTokenIndex.get( const bank = group.banksMapByTokenIndex.get(
market.baseTokenIndex market.baseTokenIndex,
)?.[0] )?.[0]
let initAssetWeight = 0 let initAssetWeight = 0
@ -155,7 +155,7 @@ const MarketsHealthTable = ({
const { asset, contribution, isAsset } = cont const { asset, contribution, isAsset } = cont
const market = group.getSerum3MarketByName(asset) const market = group.getSerum3MarketByName(asset)
const bank = group.banksMapByTokenIndex.get( const bank = group.banksMapByTokenIndex.get(
market.baseTokenIndex market.baseTokenIndex,
)?.[0] )?.[0]
let initAssetWeight = 0 let initAssetWeight = 0

View File

@ -19,7 +19,7 @@ const PerpTradeDetails = ({ activity }: { activity: PerpTradeActivity }) => {
const { mangoAccountAddress } = useMangoAccount() const { mangoAccountAddress } = useMangoAccount()
const [preferredExplorer] = useLocalStorageState( const [preferredExplorer] = useLocalStorageState(
PREFERRED_EXPLORER_KEY, PREFERRED_EXPLORER_KEY,
EXPLORERS[0] EXPLORERS[0],
) )
const { const {
maker, maker,

View File

@ -44,7 +44,7 @@ const BorrowPage = () => {
} }
const [animationSettings] = useLocalStorageState( const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const filteredBanks = useMemo(() => { const filteredBanks = useMemo(() => {
@ -58,7 +58,7 @@ const BorrowPage = () => {
if (!filteredBanks.length) return 0 if (!filteredBanks.length) return 0
return filteredBanks.reduce( return filteredBanks.reduce(
(a, c) => a + Math.abs(c.borrowedAmount) * c.bank.uiPrice, (a, c) => a + Math.abs(c.borrowedAmount) * c.bank.uiPrice,
0 0,
) )
}, [filteredBanks]) }, [filteredBanks])
@ -75,7 +75,7 @@ const BorrowPage = () => {
group, group,
usdcBank, usdcBank,
mangoAccount, mangoAccount,
true true,
).toNumber() ).toNumber()
if (borrowValue) { if (borrowValue) {

View File

@ -26,7 +26,7 @@ import TokenLogo from '@components/shared/TokenLogo'
export const getAvailableToBorrow = ( export const getAvailableToBorrow = (
bankWithBal: BankWithBalance, bankWithBal: BankWithBalance,
group: Group group: Group,
) => { ) => {
const { balance, bank, maxBorrow } = bankWithBal const { balance, bank, maxBorrow } = bankWithBal
const { mint, mintDecimals, minVaultToDepositsRatio } = bankWithBal.bank const { mint, mintDecimals, minVaultToDepositsRatio } = bankWithBal.bank
@ -40,7 +40,7 @@ export const getAvailableToBorrow = (
const available = Decimal.min( const available = Decimal.min(
availableAccountBorrow.toFixed(bank.mintDecimals), availableAccountBorrow.toFixed(bank.mintDecimals),
Decimal.max(0, availableVaultBalance.toFixed(mintDecimals)) Decimal.max(0, availableVaultBalance.toFixed(mintDecimals)),
) )
return available return available
} }
@ -61,7 +61,7 @@ const YourBorrowsTable = ({ banks }: { banks: BankWithBalance[] }) => {
setSelectedToken(token) setSelectedToken(token)
action === 'borrow' ? setShowBorrowModal(true) : setShowRepayModal(true) action === 'borrow' ? setShowBorrowModal(true) : setShowRepayModal(true)
}, },
[] [],
) )
return ( return (

View File

@ -17,7 +17,7 @@ const ChatForm = ({
const validateMessageText = useCallback(async (text: string) => { const validateMessageText = useCallback(async (text: string) => {
try { try {
const response = await fetch( const response = await fetch(
`https://www.purgomalum.com/service/json?text=${text}&fill_char=*` `https://www.purgomalum.com/service/json?text=${text}&fill_char=*`,
) )
const profanityCheck = await response.json() const profanityCheck = await response.json()
@ -45,7 +45,7 @@ const ChatForm = ({
setLatestMessages(newMessages) setLatestMessages(newMessages)
setMessageText('') setMessageText('')
}, },
[messageText, messages, publicKey, validateMessageText, setLatestMessages] [messageText, messages, publicKey, validateMessageText, setLatestMessages],
) )
const callbackRef = useCallback((inputElement: HTMLInputElement) => { const callbackRef = useCallback((inputElement: HTMLInputElement) => {

View File

@ -17,7 +17,7 @@ const GovernanceDelegate = () => {
const getCurrentVotingPower = GovernanceStore((s) => s.getCurrentVotingPower) const getCurrentVotingPower = GovernanceStore((s) => s.getCurrentVotingPower)
const [selectedDelegatePk, setSelectedDelegatePk] = useLocalStorageState( const [selectedDelegatePk, setSelectedDelegatePk] = useLocalStorageState(
`${publicKey?.toBase58()}${GOVERNANCE_DELEGATE_KEY}` `${publicKey?.toBase58()}${GOVERNANCE_DELEGATE_KEY}`,
) )
const currentDelegate = delegates const currentDelegate = delegates
.find((x) => x.pubkey.toBase58() === selectedDelegatePk) .find((x) => x.pubkey.toBase58() === selectedDelegatePk)

View File

@ -90,7 +90,7 @@ const ListMarket = ({ goBack }: { goBack: () => void }) => {
const [baseTokens, quoteTokens] = useMemo(() => { const [baseTokens, quoteTokens] = useMemo(() => {
if (!group) return [[], []] if (!group) return [[], []]
const allTokens = [...group.banksMapByName.keys()].sort((a, b) => const allTokens = [...group.banksMapByName.keys()].sort((a, b) =>
a.localeCompare(b) a.localeCompare(b),
) )
return [ return [
allTokens.filter((t) => t !== quoteToken), allTokens.filter((t) => t !== quoteToken),
@ -152,7 +152,7 @@ const ListMarket = ({ goBack }: { goBack: () => void }) => {
} }
return invalidFields return invalidFields
}, },
[t] [t],
) )
const handlePropose = useCallback(async () => { const handlePropose = useCallback(async () => {
const invalidFields = isFormValid(advForm) const invalidFields = isFormValid(advForm)
@ -189,7 +189,7 @@ const ListMarket = ({ goBack }: { goBack: () => void }) => {
advForm.proposalDescription, advForm.proposalDescription,
index, index,
proposalTx, proposalTx,
vsrClient! vsrClient!,
) )
setProposalPk(proposalAddress.toBase58()) setProposalPk(proposalAddress.toBase58())
setCurrentView(VIEWS.SUCCESS) setCurrentView(VIEWS.SUCCESS)
@ -255,7 +255,7 @@ const ListMarket = ({ goBack }: { goBack: () => void }) => {
baseBank.uiPrice, baseBank.uiPrice,
quoteBank.uiPrice, quoteBank.uiPrice,
baseBank.mintDecimals, baseBank.mintDecimals,
quoteBank.mintDecimals quoteBank.mintDecimals,
) )
} }
return { return {
@ -289,7 +289,7 @@ const ListMarket = ({ goBack }: { goBack: () => void }) => {
{t('market-pair')}{' '} {t('market-pair')}{' '}
{baseToken && quoteToken {baseToken && quoteToken
? `- ${formatTokenSymbol(baseToken)}/${formatTokenSymbol( ? `- ${formatTokenSymbol(baseToken)}/${formatTokenSymbol(
quoteToken quoteToken,
)}` )}`
: null} : null}
</h2> </h2>
@ -506,7 +506,7 @@ const ListMarket = ({ goBack }: { goBack: () => void }) => {
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange={(e: ChangeEvent<HTMLInputElement>) =>
handleSetAdvForm( handleSetAdvForm(
'openBookMarketExternalPk', 'openBookMarketExternalPk',
e.target.value e.target.value,
) )
} }
/> />
@ -549,7 +549,7 @@ const ListMarket = ({ goBack }: { goBack: () => void }) => {
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange={(e: ChangeEvent<HTMLInputElement>) =>
handleSetAdvForm( handleSetAdvForm(
'proposalDescription', 'proposalDescription',
e.target.value e.target.value,
) )
} }
/> />

View File

@ -128,7 +128,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
? governances[MANGO_DAO_WALLET_GOVERNANCE.toBase58()].account.config ? governances[MANGO_DAO_WALLET_GOVERNANCE.toBase58()].account.config
.minCommunityTokensToCreateProposal .minCommunityTokensToCreateProposal
: new BN(0), : new BN(0),
[governances] [governances],
) as BN ) as BN
const mintVoterWeightNumber = governances const mintVoterWeightNumber = governances
? fmtTokenAmount(minVoterWeight, MANGO_MINT_DECIMALS) ? fmtTokenAmount(minVoterWeight, MANGO_MINT_DECIMALS)
@ -139,7 +139,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
baseTokenPrice, baseTokenPrice,
quoteBank.uiPrice, quoteBank.uiPrice,
currentTokenInfo.decimals, currentTokenInfo.decimals,
quoteBank.mintDecimals quoteBank.mintDecimals,
) )
} }
return { return {
@ -190,7 +190,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
new BN(index).toArrayLike(Buffer, 'le', 2), new BN(index).toArrayLike(Buffer, 'le', 2),
new BN(bankNum).toArrayLike(Buffer, 'le', 4), new BN(bankNum).toArrayLike(Buffer, 'le', 4),
], ],
client.programId client.programId,
) )
setAdvForm({ setAdvForm({
...advForm, ...advForm,
@ -210,7 +210,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
}) })
setLoadingListingParams(false) setLoadingListingParams(false)
}, },
[advForm, client.programId, connection, group, mint, proposals] [advForm, client.programId, connection, group, mint, proposals],
) )
const handleGetRoutesWithFixedArgs = useCallback( const handleGetRoutesWithFixedArgs = useCallback(
@ -229,10 +229,10 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
mode, mode,
FEE, FEE,
walletForCheck, walletForCheck,
'JUPITER' 'JUPITER',
) )
}, },
[wallet.publicKey] [wallet.publicKey],
) )
const handleLiqudityCheck = useCallback( const handleLiqudityCheck = useCallback(
@ -256,7 +256,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
(acc: { amount: string; priceImpactPct: number }[], val) => { (acc: { amount: string; priceImpactPct: number }[], val) => {
if (val.swapMode === 'ExactIn') { if (val.swapMode === 'ExactIn') {
const exactOutRoute = bestRoutesSwaps.find( const exactOutRoute = bestRoutesSwaps.find(
(x) => x.amount === val.amount && x.swapMode === 'ExactOut' (x) => x.amount === val.amount && x.swapMode === 'ExactOut',
) )
acc.push({ acc.push({
amount: val.amount.toString(), amount: val.amount.toString(),
@ -267,14 +267,14 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
} }
return acc return acc
}, },
[] [],
) )
const midTierCheck = averageSwaps.find( const midTierCheck = averageSwaps.find(
(x) => x.amount === TWENTY_K_USDC_BASE (x) => x.amount === TWENTY_K_USDC_BASE,
) )
const indexForTierFromSwaps = averageSwaps.findIndex( const indexForTierFromSwaps = averageSwaps.findIndex(
(x) => x?.priceImpactPct && x?.priceImpactPct * 100 < 1 (x) => x?.priceImpactPct && x?.priceImpactPct * 100 < 1,
) )
const tier = const tier =
indexForTierFromSwaps > -1 indexForTierFromSwaps > -1
@ -285,8 +285,8 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
handleGetPoolParams( handleGetPoolParams(
swaps.find( swaps.find(
(x) => x.bestRoute!.amount.toString() === TWENTY_K_USDC_BASE (x) => x.bestRoute!.amount.toString() === TWENTY_K_USDC_BASE,
)!.routes )!.routes,
) )
return tier return tier
} catch (e) { } catch (e) {
@ -297,7 +297,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
}) })
} }
}, },
[t, handleGetRoutesWithFixedArgs] [t, handleGetRoutesWithFixedArgs],
) )
const handleGetPoolParams = (routes: never[] | RouteInfo[]) => { const handleGetPoolParams = (routes: never[] | RouteInfo[]) => {
@ -378,7 +378,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
} }
return invalidFields return invalidFields
}, },
[t] [t],
) )
const propose = useCallback(async () => { const propose = useCallback(async () => {
@ -405,7 +405,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
group!.publicKey.toBuffer(), group!.publicKey.toBuffer(),
new PublicKey(advForm.mintPk).toBuffer(), new PublicKey(advForm.mintPk).toBuffer(),
], ],
client.programId client.programId,
) )
const proposalTx = [] const proposalTx = []
@ -436,7 +436,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
Number(tierPreset.liquidationFee), Number(tierPreset.liquidationFee),
Number(tierPreset.minVaultToDepositsRatio), Number(tierPreset.minVaultToDepositsRatio),
new BN(tierPreset.netBorrowLimitWindowSizeTs), new BN(tierPreset.netBorrowLimitWindowSizeTs),
new BN(tierPreset.netBorrowLimitPerWindowQuote) new BN(tierPreset.netBorrowLimitPerWindowQuote),
) )
.accounts({ .accounts({
admin: MANGO_DAO_WALLET, admin: MANGO_DAO_WALLET,
@ -474,7 +474,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
false, false,
null, null,
null, null,
null null,
) )
.accounts({ .accounts({
oracle: new PublicKey(advForm.oraclePk), oracle: new PublicKey(advForm.oraclePk),
@ -531,7 +531,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
advForm.proposalDescription, advForm.proposalDescription,
advForm.tokenIndex, advForm.tokenIndex,
proposalTx, proposalTx,
vsrClient vsrClient,
) )
setProposalPk(proposalAddress.toBase58()) setProposalPk(proposalAddress.toBase58())
} catch (e) { } catch (e) {
@ -648,7 +648,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
<p>{t('mint')}</p> <p>{t('mint')}</p>
<p className="flex items-center"> <p className="flex items-center">
{abbreviateAddress( {abbreviateAddress(
new PublicKey(currentTokenInfo?.address) new PublicKey(currentTokenInfo?.address),
)} )}
</p> </p>
</div> </div>
@ -739,7 +739,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange={(e: ChangeEvent<HTMLInputElement>) =>
handleSetAdvForm( handleSetAdvForm(
'openBookMarketExternalPk', 'openBookMarketExternalPk',
e.target.value e.target.value,
) )
} }
/> />
@ -801,7 +801,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange={(e: ChangeEvent<HTMLInputElement>) =>
handleSetAdvForm( handleSetAdvForm(
'openBookProgram', 'openBookProgram',
e.target.value e.target.value,
) )
} }
/> />
@ -842,7 +842,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange={(e: ChangeEvent<HTMLInputElement>) =>
handleSetAdvForm( handleSetAdvForm(
'proposalTitle', 'proposalTitle',
e.target.value e.target.value,
) )
} }
/> />
@ -866,7 +866,7 @@ const ListToken = ({ goBack }: { goBack: () => void }) => {
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange={(e: ChangeEvent<HTMLInputElement>) =>
handleSetAdvForm( handleSetAdvForm(
'proposalDescription', 'proposalDescription',
e.target.value e.target.value,
) )
} }
/> />

View File

@ -23,7 +23,7 @@ const OnBoarding = ({ minVotes }: { minVotes?: BN }) => {
? new BN( ? new BN(
governances[ governances[
MANGO_DAO_WALLET_GOVERNANCE.toBase58() MANGO_DAO_WALLET_GOVERNANCE.toBase58()
].account.config.minCommunityTokensToCreateProposal.toString() ].account.config.minCommunityTokensToCreateProposal.toString(),
) )
: new BN(0) : new BN(0)
const mintVoterWeightNumber = governances const mintVoterWeightNumber = governances
@ -50,7 +50,7 @@ const OnBoarding = ({ minVotes }: { minVotes?: BN }) => {
</> </>
} }
desc={`${t('on-boarding-deposit-info')} ${t( desc={`${t('on-boarding-deposit-info')} ${t(
'on-boarding-description-1' 'on-boarding-description-1',
)}`} )}`}
/> />
</div> </div>

View File

@ -58,7 +58,7 @@ const ProposalCard = ({
const [voteType, setVoteType] = useState<VoteKind | undefined>(undefined) const [voteType, setVoteType] = useState<VoteKind | undefined>(undefined)
const [voteRecordAddress, setVoteRecordAddress] = useState<PublicKey | null>( const [voteRecordAddress, setVoteRecordAddress] = useState<PublicKey | null>(
null null,
) )
const [isVoteCast, setIsVoteCast] = useState(false) const [isVoteCast, setIsVoteCast] = useState(false)
const [description, setDescription] = useState('') const [description, setDescription] = useState('')
@ -73,7 +73,7 @@ const ProposalCard = ({
setProcessedVoteType( setProcessedVoteType(
voteType === VoteKind.Approve voteType === VoteKind.Approve
? PROCESSED_VOTE_TYPE.APPROVE ? PROCESSED_VOTE_TYPE.APPROVE
: PROCESSED_VOTE_TYPE.DENY : PROCESSED_VOTE_TYPE.DENY,
) )
try { try {
await castVote( await castVote(
@ -83,7 +83,7 @@ const ProposalCard = ({
voter.tokenOwnerRecord!, voter.tokenOwnerRecord!,
voteType, voteType,
vsrClient!, vsrClient!,
client client,
) )
await updateProposals(proposal.pubkey) await updateProposals(proposal.pubkey)
} catch (e) { } catch (e) {
@ -106,7 +106,7 @@ const ProposalCard = ({
proposal, proposal,
voter.tokenOwnerRecord!, voter.tokenOwnerRecord!,
client, client,
voteRecordAddress! voteRecordAddress!,
) )
await updateProposals(proposal.pubkey) await updateProposals(proposal.pubkey)
} catch (e) { } catch (e) {
@ -140,14 +140,14 @@ const ProposalCard = ({
const voteRecordAddress = await getVoteRecordAddress( const voteRecordAddress = await getVoteRecordAddress(
MANGO_GOVERNANCE_PROGRAM, MANGO_GOVERNANCE_PROGRAM,
proposal.pubkey, proposal.pubkey,
voter.tokenOwnerRecord!.pubkey! voter.tokenOwnerRecord!.pubkey!,
) )
setVoteRecordAddress(voteRecordAddress) setVoteRecordAddress(voteRecordAddress)
try { try {
const governanceAccount = await getGovernanceAccount( const governanceAccount = await getGovernanceAccount(
connection, connection,
voteRecordAddress, voteRecordAddress,
VoteRecord VoteRecord,
) )
setIsVoteCast(true) setIsVoteCast(true)
setVoteType(governanceAccount.account.vote?.voteType) setVoteType(governanceAccount.account.vote?.voteType)

View File

@ -89,7 +89,7 @@ const Vote = () => {
proposal={x} proposal={x}
mangoMint={mangoMint} mangoMint={mangoMint}
></ProposalCard> ></ProposalCard>
) ),
) )
) : ( ) : (
<div className="flex h-56 items-center justify-center rounded-lg border border-th-bkg-3 p-6"> <div className="flex h-56 items-center justify-center rounded-lg border border-th-bkg-3 p-6">

View File

@ -26,7 +26,7 @@ const QuorumProgress = ({ governance, proposal, communityMint }: Props) => {
realm && realm &&
getMintMaxVoteWeight( getMintMaxVoteWeight(
communityMint, communityMint,
realm.account.config.communityMintMaxVoteWeightSource realm.account.config.communityMintMaxVoteWeightSource,
) )
const minimumYesVotes = const minimumYesVotes =
@ -35,7 +35,7 @@ const QuorumProgress = ({ governance, proposal, communityMint }: Props) => {
const yesVoteCount = fmtTokenAmount( const yesVoteCount = fmtTokenAmount(
new BN(proposal.account.getYesVoteCount().toString()), new BN(proposal.account.getYesVoteCount().toString()),
communityMint.decimals communityMint.decimals,
) )
const rawYesVotesRequired = minimumYesVotes - yesVoteCount const rawYesVotesRequired = minimumYesVotes - yesVoteCount

View File

@ -15,11 +15,11 @@ const VoteResults = ({ proposal, communityMint }: VoteResultsProps) => {
const yesVoteCount = fmtTokenAmount( const yesVoteCount = fmtTokenAmount(
proposal.getYesVoteCount() as BN, proposal.getYesVoteCount() as BN,
communityMint.decimals communityMint.decimals,
) )
const noVoteCount = fmtTokenAmount( const noVoteCount = fmtTokenAmount(
proposal.getNoVoteCount() as BN, proposal.getNoVoteCount() as BN,
communityMint.decimals communityMint.decimals,
) )
const totalVoteCount = yesVoteCount + noVoteCount const totalVoteCount = yesVoteCount + noVoteCount
const getRelativeVoteCount = (voteCount: number) => const getRelativeVoteCount = (voteCount: number) =>

View File

@ -23,7 +23,7 @@ export interface LeaderboardRes {
type DaysToShow = '1DAY' | '1WEEK' | 'ALLTIME' type DaysToShow = '1DAY' | '1WEEK' | 'ALLTIME'
const isLeaderboard = ( const isLeaderboard = (
response: null | EmptyObject | LeaderboardRes[] response: null | EmptyObject | LeaderboardRes[],
): response is LeaderboardRes[] => { ): response is LeaderboardRes[] => {
if (response && Array.isArray(response)) { if (response && Array.isArray(response)) {
return true return true
@ -33,10 +33,10 @@ const isLeaderboard = (
const fetchLeaderboard = async ( const fetchLeaderboard = async (
daysToShow: DaysToShow, daysToShow: DaysToShow,
offset = 0 offset = 0,
): Promise<Array<LeaderboardRes>> => { ): Promise<Array<LeaderboardRes>> => {
const data = await fetch( const data = await fetch(
`${MANGO_DATA_API_URL}/leaderboard-pnl?over_period=${daysToShow}&offset=${offset}` `${MANGO_DATA_API_URL}/leaderboard-pnl?over_period=${daysToShow}&offset=${offset}`,
) )
const parsedData: null | EmptyObject | LeaderboardRes[] = await data.json() const parsedData: null | EmptyObject | LeaderboardRes[] = await data.json()
@ -63,7 +63,7 @@ const LeaderboardPage = () => {
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
keepPreviousData: true, keepPreviousData: true,
getNextPageParam: (_lastPage, pages) => pages.length * 20, getNextPageParam: (_lastPage, pages) => pages.length * 20,
} },
) )
const leaderboardData = useMemo(() => { const leaderboardData = useMemo(() => {

View File

@ -27,11 +27,11 @@ const CloseAccountModal = ({ isOpen, onClose }: ModalProps) => {
const mangoAccount = mangoStore((s) => s.mangoAccount) const mangoAccount = mangoStore((s) => s.mangoAccount)
const perpPositions = mangoStore((s) => s.mangoAccount.perpPositions) const perpPositions = mangoStore((s) => s.mangoAccount.perpPositions)
const openPerpPositions = Object.values(perpPositions).filter((p) => const openPerpPositions = Object.values(perpPositions).filter((p) =>
p.basePositionLots.toNumber() p.basePositionLots.toNumber(),
) )
const group = mangoStore.getState().group const group = mangoStore.getState().group
const unsettledBalances = Object.values(mangoAccount.spotBalances).filter( const unsettledBalances = Object.values(mangoAccount.spotBalances).filter(
(x) => x.unsettled && x.unsettled > 0 (x) => x.unsettled && x.unsettled > 0,
) )
const unsettledPerpPositions = useUnsettledPerpPositions() const unsettledPerpPositions = useUnsettledPerpPositions()
const [hasBorrows, setHasBorrows] = useState(false) const [hasBorrows, setHasBorrows] = useState(false)
@ -49,7 +49,7 @@ const CloseAccountModal = ({ isOpen, onClose }: ModalProps) => {
const tx = await client.emptyAndCloseMangoAccount(group, mangoAccount) const tx = await client.emptyAndCloseMangoAccount(group, mangoAccount)
if (tx) { if (tx) {
const newMangoAccounts = mangoAccounts.filter( const newMangoAccounts = mangoAccounts.filter(
(ma) => !ma.publicKey.equals(mangoAccount.publicKey) (ma) => !ma.publicKey.equals(mangoAccount.publicKey),
) )
let newCurrentAccount: MangoAccount let newCurrentAccount: MangoAccount
if (newMangoAccounts[0]) { if (newMangoAccounts[0]) {
@ -99,7 +99,7 @@ const CloseAccountModal = ({ isOpen, onClose }: ModalProps) => {
.filter((token: TokenPosition) => .filter((token: TokenPosition) =>
token token
.balance(group.getFirstBankByTokenIndex(token.tokenIndex)) .balance(group.getFirstBankByTokenIndex(token.tokenIndex))
.isNeg() .isNeg(),
).length ).length
) { ) {
setHasBorrows(true) setHasBorrows(true)
@ -137,8 +137,8 @@ const CloseAccountModal = ({ isOpen, onClose }: ModalProps) => {
mangoAccount && group mangoAccount && group
? formatCurrencyValue( ? formatCurrencyValue(
toUiDecimalsForQuote( toUiDecimalsForQuote(
mangoAccount!.current!.getEquity(group) mangoAccount!.current!.getEquity(group),
) ),
) )
: 0, : 0,
})} })}

View File

@ -157,11 +157,11 @@ const CreateOpenbookMarketModal = ({
const getMinLamportsToCreateMarket = async () => { const getMinLamportsToCreateMarket = async () => {
const accountsSpace = 84522 + MARKET_STATE_LAYOUT_V2.span const accountsSpace = 84522 + MARKET_STATE_LAYOUT_V2.span
const minLamports = await connection.getMinimumBalanceForRentExemption( const minLamports = await connection.getMinimumBalanceForRentExemption(
accountsSpace accountsSpace,
) )
setSolNeededToCreateMarket( setSolNeededToCreateMarket(
Math.round((minLamports / LAMPORTS_PER_SOL + Number.EPSILON) * 100) / Math.round((minLamports / LAMPORTS_PER_SOL + Number.EPSILON) * 100) /
100 100,
) )
} }
getMinLamportsToCreateMarket() getMinLamportsToCreateMarket()

View File

@ -135,7 +135,7 @@ const CreateSwitchboardOracleModal = ({
}, },
}, },
], ],
}) }),
).finish(), ).finish(),
}, },
{ {
@ -201,7 +201,7 @@ const CreateSwitchboardOracleModal = ({
}, },
}, },
], ],
}) }),
).finish(), ).finish(),
}, },
], ],

View File

@ -22,7 +22,7 @@ const DelegateModal = ({ isOpen, onClose }: ModalProps) => {
const [delegateAddress, setDelegateAddress] = useState( const [delegateAddress, setDelegateAddress] = useState(
mangoAccount?.delegate?.toString() !== DEFAULT_DELEGATE mangoAccount?.delegate?.toString() !== DEFAULT_DELEGATE
? mangoAccount!.delegate.toString() ? mangoAccount!.delegate.toString()
: '' : '',
) )
const handleDelegateAccount = async (address: string) => { const handleDelegateAccount = async (address: string) => {
@ -44,7 +44,7 @@ const DelegateModal = ({ isOpen, onClose }: ModalProps) => {
group, group,
mangoAccount, mangoAccount,
undefined, undefined,
delegateAddress ? new PublicKey(address) : undefined delegateAddress ? new PublicKey(address) : undefined,
) )
onClose() onClose()
notify({ notify({
@ -82,7 +82,7 @@ const DelegateModal = ({ isOpen, onClose }: ModalProps) => {
<InlineNotification <InlineNotification
type="info" type="info"
desc={`Account is delegated to ${abbreviateAddress( desc={`Account is delegated to ${abbreviateAddress(
mangoAccount.delegate mangoAccount.delegate,
)}`} )}`}
/> />
</div> </div>

View File

@ -117,11 +117,11 @@ const MangoAccountsListModal = ({
acc = mangoAccount acc = mangoAccount
} }
const accountValue = toUiDecimalsForQuote( const accountValue = toUiDecimalsForQuote(
Number(acc.getEquity(group!)) Number(acc.getEquity(group!)),
).toFixed(2) ).toFixed(2)
const maintHealth = acc.getHealthRatioUi( const maintHealth = acc.getHealthRatioUi(
group!, group!,
HealthType.maint HealthType.maint,
) )
return ( return (
<div <div
@ -207,7 +207,7 @@ const MangoAccountsListModal = ({
acc, acc,
t('copy-address-success', { t('copy-address-success', {
pk: abbreviateAddress(acc.publicKey), pk: abbreviateAddress(acc.publicKey),
}) }),
) )
} }
hideBg hideBg

View File

@ -51,12 +51,12 @@ const ModifyTvOrderModal = ({
const { t } = useTranslation(['common', 'trade']) const { t } = useTranslation(['common', 'trade'])
const [modifiedOrderPrice, setModifiedOrderPrice] = useState(price) const [modifiedOrderPrice, setModifiedOrderPrice] = useState(price)
const [modifiedOrderSize, setModifiedOrderSize] = useState( const [modifiedOrderSize, setModifiedOrderSize] = useState(
order.size.toString() order.size.toString(),
) )
const { baseSymbol, selectedMarket, serumOrPerpMarket } = useSelectedMarket() const { baseSymbol, selectedMarket, serumOrPerpMarket } = useSelectedMarket()
const [savedCheckboxSettings] = useLocalStorageState( const [savedCheckboxSettings] = useLocalStorageState(
TRADE_CHECKBOXES_KEY, TRADE_CHECKBOXES_KEY,
DEFAULT_CHECKBOX_SETTINGS DEFAULT_CHECKBOX_SETTINGS,
) )
const tickDecimals = useMemo(() => { const tickDecimals = useMemo(() => {
@ -99,13 +99,13 @@ const ModifyTvOrderModal = ({
Date.now(), Date.now(),
PerpOrderType.limit, PerpOrderType.limit,
undefined, undefined,
undefined undefined,
) )
} else { } else {
const marketPk = findSerum3MarketPkInOpenOrders(o) const marketPk = findSerum3MarketPkInOpenOrders(o)
if (!marketPk) return if (!marketPk) return
const market = group.getSerum3MarketByExternalMarket( const market = group.getSerum3MarketByExternalMarket(
new PublicKey(marketPk) new PublicKey(marketPk),
) )
tx = await client.modifySerum3Order( tx = await client.modifySerum3Order(
group, group,
@ -118,7 +118,7 @@ const ModifyTvOrderModal = ({
Serum3SelfTradeBehavior.decrementTake, Serum3SelfTradeBehavior.decrementTake,
Serum3OrderType.limit, Serum3OrderType.limit,
Date.now(), Date.now(),
10 10,
) )
} }
actions.fetchOpenOrders() actions.fetchOpenOrders()
@ -139,7 +139,7 @@ const ModifyTvOrderModal = ({
}) })
} }
}, },
[findSerum3MarketPkInOpenOrders, modifiedOrderPrice, modifiedOrderSize] [findSerum3MarketPkInOpenOrders, modifiedOrderPrice, modifiedOrderSize],
) )
return selectedMarket ? ( return selectedMarket ? (

View File

@ -129,7 +129,7 @@ const SharePositionModal = ({
<p className="ml-2 font-mono text-base text-white"> <p className="ml-2 font-mono text-base text-white">
{formatNumericValue( {formatNumericValue(
entryPrice, entryPrice,
getDecimalCount(market.tickSize) getDecimalCount(market.tickSize),
)} )}
</p> </p>
</div> </div>
@ -140,7 +140,7 @@ const SharePositionModal = ({
<p className="ml-2 font-mono text-base text-white"> <p className="ml-2 font-mono text-base text-white">
{formatNumericValue( {formatNumericValue(
market.uiPrice, market.uiPrice,
getDecimalCount(market.tickSize) getDecimalCount(market.tickSize),
)} )}
</p> </p>
</div> </div>

View File

@ -26,11 +26,11 @@ const TradeVolumeAlertModal = ({ isOpen, onClose }: ModalProps) => {
const { t } = useTranslation(['common', 'trade']) const { t } = useTranslation(['common', 'trade'])
const [soundSettings, setSoundSettings] = useLocalStorageState( const [soundSettings, setSoundSettings] = useLocalStorageState(
SOUND_SETTINGS_KEY, SOUND_SETTINGS_KEY,
INITIAL_SOUND_SETTINGS INITIAL_SOUND_SETTINGS,
) )
const [alertSettings, setAlertSettings] = useLocalStorageState( const [alertSettings, setAlertSettings] = useLocalStorageState(
TRADE_VOLUME_ALERT_KEY, TRADE_VOLUME_ALERT_KEY,
DEFAULT_VOLUME_ALERT_SETTINGS DEFAULT_VOLUME_ALERT_SETTINGS,
) )
const [formValues, setFormValues] = useState(alertSettings) const [formValues, setFormValues] = useState(alertSettings)

View File

@ -70,7 +70,7 @@ const UserSetupModal = ({
const banks = useBanksWithBalances('walletBalance') const banks = useBanksWithBalances('walletBalance')
const [, setAcceptTerms] = useLocalStorageState(ACCEPT_TERMS_KEY, '') const [, setAcceptTerms] = useLocalStorageState(ACCEPT_TERMS_KEY, '')
const [walletsToDisplay, setWalletstoDisplay] = useState<'default' | 'all'>( const [walletsToDisplay, setWalletstoDisplay] = useState<'default' | 'all'>(
'default' 'default',
) )
const walletsDisplayed = useMemo(() => { const walletsDisplayed = useMemo(() => {
@ -78,7 +78,7 @@ const UserSetupModal = ({
const detectedWallets = wallets.filter( const detectedWallets = wallets.filter(
(w) => (w) =>
w.readyState === WalletReadyState.Installed || w.readyState === WalletReadyState.Installed ||
w.readyState === WalletReadyState.Loadable w.readyState === WalletReadyState.Loadable,
) )
if (walletsToDisplay === 'default') { if (walletsToDisplay === 'default') {
@ -107,7 +107,7 @@ const UserSetupModal = ({
group, group,
0, 0,
accountName || 'Account 1', accountName || 'Account 1',
16 // tokenCount 16, // tokenCount
) )
actions.fetchMangoAccounts(publicKey) actions.fetchMangoAccounts(publicKey)
if (tx) { if (tx) {
@ -147,7 +147,7 @@ const UserSetupModal = ({
group, group,
mangoAccount, mangoAccount,
bank.mint, bank.mint,
parseFloat(depositAmount) parseFloat(depositAmount),
) )
notify({ notify({
title: 'Transaction confirmed', title: 'Transaction confirmed',
@ -197,7 +197,7 @@ const UserSetupModal = ({
const setMax = useCallback(() => { const setMax = useCallback(() => {
const max = new Decimal(tokenMax.amount).toDecimalPlaces( const max = new Decimal(tokenMax.amount).toDecimalPlaces(
tokenMax.decimals, tokenMax.decimals,
Decimal.ROUND_FLOOR Decimal.ROUND_FLOOR,
) )
setDepositAmount(max.toString()) setDepositAmount(max.toString())
setSizePercentage('100') setSizePercentage('100')
@ -212,7 +212,7 @@ const UserSetupModal = ({
.toDecimalPlaces(tokenMax.decimals, Decimal.ROUND_FLOOR) .toDecimalPlaces(tokenMax.decimals, Decimal.ROUND_FLOOR)
setDepositAmount(amount.toString()) setDepositAmount(amount.toString())
}, },
[tokenMax] [tokenMax],
) )
const handleNextStep = () => { const handleNextStep = () => {
@ -456,7 +456,7 @@ const UserSetupModal = ({
value={depositAmount} value={depositAmount}
onValueChange={(e: NumberFormatValues) => { onValueChange={(e: NumberFormatValues) => {
setDepositAmount( setDepositAmount(
!Number.isNaN(Number(e.value)) ? e.value : '' !Number.isNaN(Number(e.value)) ? e.value : '',
) )
}} }}
isAllowed={withValueLimit} isAllowed={withValueLimit}

View File

@ -22,7 +22,7 @@ import { notify } from 'utils/notifications'
export const createSolanaMessage = ( export const createSolanaMessage = (
wallet: WalletContextState, wallet: WalletContextState,
setCookie: (wallet: string, token: string) => void setCookie: (wallet: string, token: string) => void,
) => { ) => {
const payload = new Payload() const payload = new Payload()
payload.domain = window.location.host payload.domain = window.location.host
@ -121,7 +121,7 @@ const NotificationsDrawer = ({
}) })
} }
}, },
[NOTIFICATION_API, headers] [NOTIFICATION_API, headers],
) )
const remove = useCallback( const remove = useCallback(
@ -136,7 +136,7 @@ const NotificationsDrawer = ({
body: JSON.stringify({ body: JSON.stringify({
ids: ids, ids: ids,
}), }),
} },
) )
const body = await resp.json() const body = await resp.json()
const error = body.error const error = body.error
@ -158,7 +158,7 @@ const NotificationsDrawer = ({
} }
setIsRemoving(false) setIsRemoving(false)
}, },
[NOTIFICATION_API, headers] [NOTIFICATION_API, headers],
) )
// Mark all notifications as seen when the inbox is opened // Mark all notifications as seen when the inbox is opened
@ -241,7 +241,7 @@ const NotificationsDrawer = ({
<CalendarIcon className="mr-1 h-3.5 w-3.5" /> <CalendarIcon className="mr-1 h-3.5 w-3.5" />
<p className="text-xs"> <p className="text-xs">
{dayjs(notification.createdAt).format( {dayjs(notification.createdAt).format(
'DD MMM YYYY, h:mma' 'DD MMM YYYY, h:mma',
)} )}
</p> </p>
</div> </div>

View File

@ -39,7 +39,7 @@ const TransactionNotificationList = () => {
const notEnoughSoLMessage = t('deposit-more-sol') const notEnoughSoLMessage = t('deposit-more-sol')
const [notificationPosition] = useLocalStorageState( const [notificationPosition] = useLocalStorageState(
NOTIFICATION_POSITION_KEY, NOTIFICATION_POSITION_KEY,
'bottom-left' 'bottom-left',
) )
const [mounted, setMounted] = useState(false) const [mounted, setMounted] = useState(false)
const { maxSolDeposit } = useSolBalance() const { maxSolDeposit } = useSolBalance()
@ -49,10 +49,10 @@ const TransactionNotificationList = () => {
useEffect(() => { useEffect(() => {
if (transactionNotifications.length) { if (transactionNotifications.length) {
const customErrorNotification = transactionNotifications.find( const customErrorNotification = transactionNotifications.find(
(n) => n.description && n.description.includes('"Custom":1') (n) => n.description && n.description.includes('"Custom":1'),
) )
const notEnoughSolNotification = transactionNotifications.find( const notEnoughSolNotification = transactionNotifications.find(
(n) => n.title && n.title.includes(notEnoughSoLMessage) (n) => n.title && n.title.includes(notEnoughSoLMessage),
) )
if ( if (
@ -125,11 +125,11 @@ const TransactionNotification = ({
}) => { }) => {
const [notificationPosition] = useLocalStorageState( const [notificationPosition] = useLocalStorageState(
NOTIFICATION_POSITION_KEY, NOTIFICATION_POSITION_KEY,
'Bottom-Left' 'Bottom-Left',
) )
const [preferredExplorer] = useLocalStorageState( const [preferredExplorer] = useLocalStorageState(
PREFERRED_EXPLORER_KEY, PREFERRED_EXPLORER_KEY,
EXPLORERS[0] EXPLORERS[0],
) )
const { type, title, description, txid, show, id } = notification const { type, title, description, txid, show, id } = notification
@ -151,7 +151,7 @@ const TransactionNotification = ({
if ((type === 'error' || type === 'success') && txid) { if ((type === 'error' || type === 'success') && txid) {
setMangoStore((s) => { setMangoStore((s) => {
const newNotifications = s.transactionNotifications.map((n) => const newNotifications = s.transactionNotifications.map((n) =>
n.txid === txid && n.type === 'confirm' ? { ...n, show: false } : n n.txid === txid && n.type === 'confirm' ? { ...n, show: false } : n,
) )
s.transactionNotifications = newNotifications s.transactionNotifications = newNotifications
}) })
@ -161,7 +161,7 @@ const TransactionNotification = ({
const hideNotification = useCallback(() => { const hideNotification = useCallback(() => {
setMangoStore((s) => { setMangoStore((s) => {
const newNotifications = s.transactionNotifications.map((n) => const newNotifications = s.transactionNotifications.map((n) =>
n.id === id ? { ...n, show: false } : n n.id === id ? { ...n, show: false } : n,
) )
s.transactionNotifications = newNotifications s.transactionNotifications = newNotifications
}) })

View File

@ -73,7 +73,7 @@ const EditNftProfilePic = ({ onClose }: { onClose: () => void }) => {
} }
const response = await fetch( const response = await fetch(
`${MANGO_DATA_API_URL}/user-data/profile-details`, `${MANGO_DATA_API_URL}/user-data/profile-details`,
requestOptions requestOptions,
) )
if (response.status === 200) { if (response.status === 200) {
await actions.fetchProfileDetails(publicKey.toString()) await actions.fetchProfileDetails(publicKey.toString())
@ -119,7 +119,7 @@ const EditNftProfilePic = ({ onClose }: { onClose: () => void }) => {
} }
const response = await fetch( const response = await fetch(
`${MANGO_DATA_API_URL}/user-data/profile-details`, `${MANGO_DATA_API_URL}/user-data/profile-details`,
requestOptions requestOptions,
) )
if (response.status === 200) { if (response.status === 200) {
await actions.fetchProfileDetails(publicKey.toString()) await actions.fetchProfileDetails(publicKey.toString())

View File

@ -31,7 +31,7 @@ const EditProfileForm = ({
const profile = mangoStore((s) => s.profile.details) const profile = mangoStore((s) => s.profile.details)
const { publicKey, signMessage } = useWallet() const { publicKey, signMessage } = useWallet()
const [profileName, setProfileName] = useState( const [profileName, setProfileName] = useState(
startCase(profile?.profile_name) || '' startCase(profile?.profile_name) || '',
) )
const [inputError, setInputError] = useState('') const [inputError, setInputError] = useState('')
const [loadUniquenessCheck, setLoadUniquenessCheck] = useState(false) const [loadUniquenessCheck, setLoadUniquenessCheck] = useState(false)
@ -43,7 +43,7 @@ const EditProfileForm = ({
try { try {
setLoadUniquenessCheck(true) setLoadUniquenessCheck(true)
const response = await fetch( const response = await fetch(
`${MANGO_DATA_API_URL}/user-data/check-profile-name-unique?profile-name=${name}` `${MANGO_DATA_API_URL}/user-data/check-profile-name-unique?profile-name=${name}`,
) )
const uniquenessCheck = await response.json() const uniquenessCheck = await response.json()
@ -105,7 +105,7 @@ const EditProfileForm = ({
} }
const response = await fetch( const response = await fetch(
`${MANGO_DATA_API_URL}/user-data/profile-details`, `${MANGO_DATA_API_URL}/user-data/profile-details`,
requestOptions requestOptions,
) )
if (response.status === 200) { if (response.status === 200) {
setLoadUpdateProfile(false) setLoadUpdateProfile(false)

View File

@ -54,7 +54,7 @@ const Leaderboards = ({
staleTime: 1000 * 60, staleTime: 1000 * 60,
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
} },
) )
const isLoading = const isLoading =
@ -96,7 +96,7 @@ const Leaderboards = ({
rewardsLeaderboardData.map( rewardsLeaderboardData.map(
(wallet: RewardsLeaderboardItem, i: number) => ( (wallet: RewardsLeaderboardItem, i: number) => (
<LeaderboardCard rank={i + 1} key={i} wallet={wallet} /> <LeaderboardCard rank={i + 1} key={i} wallet={wallet} />
) ),
) )
) : ( ) : (
<div className="flex justify-center rounded-lg border border-th-bkg-3 p-8"> <div className="flex justify-center rounded-lg border border-th-bkg-3 p-8">

View File

@ -66,7 +66,7 @@ export const tiers = ['seed', 'mango', 'whale', 'bot']
const fetchRewardsPoints = async (walletPk: string | undefined) => { const fetchRewardsPoints = async (walletPk: string | undefined) => {
try { try {
const data = await fetch( const data = await fetch(
`${MANGO_DATA_API_URL}/user-data/campaign-total-points-wallet?wallet-pk=${walletPk}` `${MANGO_DATA_API_URL}/user-data/campaign-total-points-wallet?wallet-pk=${walletPk}`,
) )
const res = await data.json() const res = await data.json()
return res return res
@ -78,7 +78,7 @@ const fetchRewardsPoints = async (walletPk: string | undefined) => {
export const fetchLeaderboard = async (tier: string | undefined) => { export const fetchLeaderboard = async (tier: string | undefined) => {
try { try {
const data = await fetch( const data = await fetch(
`${MANGO_DATA_API_URL}/user-data/campaign-leaderboard?tier=${tier}` `${MANGO_DATA_API_URL}/user-data/campaign-leaderboard?tier=${tier}`,
) )
const res = await data.json() const res = await data.json()
return res return res
@ -195,7 +195,7 @@ const Season = ({
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
enabled: !!wallet?.adapter, enabled: !!wallet?.adapter,
} },
) )
const { const {
@ -210,7 +210,7 @@ const Season = ({
staleTime: 1000 * 60, staleTime: 1000 * 60,
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
} },
) )
useEffect(() => { useEffect(() => {

View File

@ -41,7 +41,7 @@ const SearchPage = () => {
try { try {
setLoading(true) setLoading(true)
const response = await fetch( const response = await fetch(
`${MANGO_DATA_API_URL}/user-data/profile-search?search-string=${searchString}&search-method=${searchType}` `${MANGO_DATA_API_URL}/user-data/profile-search?search-string=${searchString}&search-method=${searchType}`,
) )
const data = await response.json() const data = await response.json()
setSearchResults(data) setSearchResults(data)
@ -115,7 +115,7 @@ const SearchPage = () => {
<MangoAccountItem item={r} type={searchType} /> <MangoAccountItem item={r} type={searchType} />
) : ( ) : (
<WalletItem item={r} /> <WalletItem item={r} />
) ),
) )
) : showNoResults ? ( ) : showNoResults ? (
<div className="flex flex-col items-center rounded-md border border-th-bkg-3 p-4"> <div className="flex flex-col items-center rounded-md border border-th-bkg-3 p-4">

View File

@ -13,7 +13,7 @@ const AnimationSettings = () => {
const { t } = useTranslation(['common', 'settings']) const { t } = useTranslation(['common', 'settings'])
const [animationSettings, setAnimationSettings] = useLocalStorageState( const [animationSettings, setAnimationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const handleToggleAnimationSetting = (settingName: string) => { const handleToggleAnimationSetting = (settingName: string) => {

View File

@ -63,21 +63,21 @@ const DisplaySettings = () => {
const { theme, setTheme } = useTheme() const { theme, setTheme } = useTheme()
const [savedLanguage, setSavedLanguage] = useLocalStorageState( const [savedLanguage, setSavedLanguage] = useLocalStorageState(
'language', 'language',
'en' 'en',
) )
const router = useRouter() const router = useRouter()
const { pathname, asPath, query } = router const { pathname, asPath, query } = router
const [notificationPosition, setNotificationPosition] = useLocalStorageState( const [notificationPosition, setNotificationPosition] = useLocalStorageState(
NOTIFICATION_POSITION_KEY, NOTIFICATION_POSITION_KEY,
'bottom-left' 'bottom-left',
) )
const [tradeFormUi, setTradeFormUi] = useLocalStorageState( const [tradeFormUi, setTradeFormUi] = useLocalStorageState(
SIZE_INPUT_UI_KEY, SIZE_INPUT_UI_KEY,
'slider' 'slider',
) )
const [tradeChartUi, setTradeChartUi] = useLocalStorageState( const [tradeChartUi, setTradeChartUi] = useLocalStorageState(
TRADE_CHART_UI_KEY, TRADE_CHART_UI_KEY,
'trading-view' 'trading-view',
) )
const [, setTradeLayout] = useLocalStorageState(TRADE_LAYOUT_KEY, 'chartLeft') const [, setTradeLayout] = useLocalStorageState(TRADE_LAYOUT_KEY, 'chartLeft')
@ -87,7 +87,7 @@ const DisplaySettings = () => {
router.push({ pathname, query }, asPath, { locale: l }) router.push({ pathname, query }, asPath, { locale: l })
dayjs.locale(l == 'zh_tw' ? 'zh-tw' : l) dayjs.locale(l == 'zh_tw' ? 'zh-tw' : l)
}, },
[router, pathname, query, asPath, setSavedLanguage] [router, pathname, query, asPath, setSavedLanguage],
) )
return ( return (

View File

@ -120,7 +120,7 @@ const HotKeysSettings = () => {
{Object.entries(options).map((e) => { {Object.entries(options).map((e) => {
return e[1] return e[1]
? `${e[0] !== 'margin' ? ', ' : ''}${t( ? `${e[0] !== 'margin' ? ', ' : ''}${t(
`trade:${e[0]}` `trade:${e[0]}`,
)}` )}`
: '' : ''
})} })}

View File

@ -49,7 +49,7 @@ const NotificationSettings = () => {
onChange={() => onChange={() =>
handleSettingChange( handleSettingChange(
'fillsNotifications', 'fillsNotifications',
!data?.fillsNotifications !data?.fillsNotifications,
) )
} }
/> />

View File

@ -15,7 +15,7 @@ const PreferredExplorerSettings = () => {
const { t } = useTranslation('settings') const { t } = useTranslation('settings')
const [preferredExplorer, setPreferredExplorer] = useLocalStorageState( const [preferredExplorer, setPreferredExplorer] = useLocalStorageState(
PREFERRED_EXPLORER_KEY, PREFERRED_EXPLORER_KEY,
EXPLORERS[0] EXPLORERS[0],
) )
return ( return (
<> <>

View File

@ -50,11 +50,11 @@ const RpcSettings = () => {
const [showCustomForm, setShowCustomForm] = useState(false) const [showCustomForm, setShowCustomForm] = useState(false)
const [rpcEndpointProvider, setRpcEndpointProvider] = useLocalStorageState( const [rpcEndpointProvider, setRpcEndpointProvider] = useLocalStorageState(
RPC_PROVIDER_KEY, RPC_PROVIDER_KEY,
RPC_URLS[0].value RPC_URLS[0].value,
) )
const [storedPriorityFee, setStoredPriorityFee] = useLocalStorageState( const [storedPriorityFee, setStoredPriorityFee] = useLocalStorageState(
PRIORITY_FEE_KEY, PRIORITY_FEE_KEY,
DEFAULT_PRIORITY_FEE.value DEFAULT_PRIORITY_FEE.value,
) )
const [storedUseOrderbookFeed, setStoredUseOrderbookFeed] = const [storedUseOrderbookFeed, setStoredUseOrderbookFeed] =
useLocalStorageState(USE_ORDERBOOK_FEED_KEY, true) useLocalStorageState(USE_ORDERBOOK_FEED_KEY, true)
@ -77,7 +77,7 @@ const RpcSettings = () => {
const handleSetEndpointProvider = (provider: string) => { const handleSetEndpointProvider = (provider: string) => {
const endpointProvider = RPC_URLS.find( const endpointProvider = RPC_URLS.find(
(node) => node.label === provider (node) => node.label === provider,
) || { label: 'Custom', value: rpcEndpointProvider } ) || { label: 'Custom', value: rpcEndpointProvider }
setRpcEndpointProvider(endpointProvider.value) setRpcEndpointProvider(endpointProvider.value)
if (provider !== 'Custom') { if (provider !== 'Custom') {
@ -96,7 +96,7 @@ const RpcSettings = () => {
} }
} }
}, },
[setStoredPriorityFee, actions, wallet] [setStoredPriorityFee, actions, wallet],
) )
useEffect(() => { useEffect(() => {

View File

@ -14,7 +14,7 @@ const SoundSettings = () => {
const { t } = useTranslation(['common', 'settings']) const { t } = useTranslation(['common', 'settings'])
const [soundSettings, setSoundSettings] = useLocalStorageState( const [soundSettings, setSoundSettings] = useLocalStorageState(
SOUND_SETTINGS_KEY, SOUND_SETTINGS_KEY,
INITIAL_SOUND_SETTINGS INITIAL_SOUND_SETTINGS,
) )
const handleToggleSoundSetting = (settingName: string) => { const handleToggleSoundSetting = (settingName: string) => {

View File

@ -293,7 +293,7 @@ const Balance = ({ bank }: { bank: BankWithBalance }) => {
let tickDecimals: number let tickDecimals: number
if (selectedMarket instanceof Serum3Market) { if (selectedMarket instanceof Serum3Market) {
const market = group.getSerum3ExternalMarket( const market = group.getSerum3ExternalMarket(
selectedMarket.serumMarketExternal selectedMarket.serumMarketExternal,
) )
minOrderDecimals = getDecimalCount(market.minOrderSize) minOrderDecimals = getDecimalCount(market.minOrderSize)
tickDecimals = getDecimalCount(market.tickSize) tickDecimals = getDecimalCount(market.tickSize)
@ -306,7 +306,7 @@ const Balance = ({ bank }: { bank: BankWithBalance }) => {
const floorBalance = floorToDecimal(balance, tickDecimals).toNumber() const floorBalance = floorToDecimal(balance, tickDecimals).toNumber()
const baseSize = floorToDecimal( const baseSize = floorToDecimal(
floorBalance / price, floorBalance / price,
minOrderDecimals minOrderDecimals,
).toNumber() ).toNumber()
const quoteSize = floorToDecimal(baseSize * price, tickDecimals) const quoteSize = floorToDecimal(baseSize * price, tickDecimals)
set((s) => { set((s) => {
@ -322,7 +322,7 @@ const Balance = ({ bank }: { bank: BankWithBalance }) => {
}) })
} }
}, },
[selectedMarket] [selectedMarket],
) )
const handleSwapFormBalanceClick = useCallback( const handleSwapFormBalanceClick = useCallback(
@ -356,7 +356,7 @@ const Balance = ({ bank }: { bank: BankWithBalance }) => {
}) })
} }
}, },
[bank] [bank],
) )
const balance = bank.balance const balance = bank.balance
@ -393,7 +393,7 @@ const Balance = ({ bank }: { bank: BankWithBalance }) => {
className="font-normal underline underline-offset-2 md:underline-offset-4 md:hover:no-underline" className="font-normal underline underline-offset-2 md:underline-offset-4 md:hover:no-underline"
onClick={() => onClick={() =>
handleSwapFormBalanceClick( handleSwapFormBalanceClick(
Number(floorToDecimal(balance, tokenBank.mintDecimals)) Number(floorToDecimal(balance, tokenBank.mintDecimals)),
) )
} }
> >

View File

@ -100,7 +100,7 @@ const DetailedAreaOrBarChart: FunctionComponent<
const { theme } = useTheme() const { theme } = useTheme()
const [animationSettings] = useLocalStorageState( const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const handleMouseMove = (coords: any) => { const handleMouseMove = (coords: any) => {
@ -134,7 +134,7 @@ const DetailedAreaOrBarChart: FunctionComponent<
if (filteredData.length) { if (filteredData.length) {
if (mouseData) { if (mouseData) {
const index = filteredData.findIndex( const index = filteredData.findIndex(
(d: any) => d[xKey] === mouseData[xKey] (d: any) => d[xKey] === mouseData[xKey],
) )
const change = const change =
index >= 0 ? filteredData[index][yKey] - filteredData[0][yKey] : 0 index >= 0 ? filteredData[index][yKey] - filteredData[0][yKey] : 0
@ -216,7 +216,7 @@ const DetailedAreaOrBarChart: FunctionComponent<
mouseData[yKey] < 0 ? '-' : '' mouseData[yKey] < 0 ? '-' : ''
}${prefix}${formatNumericValue( }${prefix}${formatNumericValue(
Math.abs(mouseData[yKey]), Math.abs(mouseData[yKey]),
yDecimals yDecimals,
)}${suffix}`} )}${suffix}`}
/> />
) : ( ) : (
@ -249,7 +249,7 @@ const DetailedAreaOrBarChart: FunctionComponent<
{dayjs(mouseData[xKey]).format( {dayjs(mouseData[xKey]).format(
tooltipDateFormat tooltipDateFormat
? tooltipDateFormat ? tooltipDateFormat
: 'DD MMM YY, h:mma' : 'DD MMM YY, h:mma',
)} )}
</p> </p>
</div> </div>
@ -273,9 +273,9 @@ const DetailedAreaOrBarChart: FunctionComponent<
: '' : ''
}${prefix}${formatNumericValue( }${prefix}${formatNumericValue(
Math.abs( Math.abs(
filteredData[filteredData.length - 1][yKey] filteredData[filteredData.length - 1][yKey],
), ),
yDecimals yDecimals,
)}${suffix}`} )}${suffix}`}
/> />
) : ( ) : (
@ -308,11 +308,11 @@ const DetailedAreaOrBarChart: FunctionComponent<
} text-th-fgd-4`} } text-th-fgd-4`}
> >
{dayjs( {dayjs(
filteredData[filteredData.length - 1][xKey] filteredData[filteredData.length - 1][xKey],
).format( ).format(
tooltipDateFormat tooltipDateFormat
? tooltipDateFormat ? tooltipDateFormat
: 'DD MMM YY, h:mma' : 'DD MMM YY, h:mma',
)} )}
</p> </p>
</div> </div>
@ -341,7 +341,7 @@ const DetailedAreaOrBarChart: FunctionComponent<
<linearGradient <linearGradient
id={`gradientArea-${title?.replace( id={`gradientArea-${title?.replace(
/[^a-zA-Z]/g, /[^a-zA-Z]/g,
'' '',
)}`} )}`}
x1="0" x1="0"
y1={flipGradientCoords ? '1' : '0'} y1={flipGradientCoords ? '1' : '0'}
@ -380,7 +380,7 @@ const DetailedAreaOrBarChart: FunctionComponent<
strokeWidth={1.5} strokeWidth={1.5}
fill={`url(#gradientArea-${title?.replace( fill={`url(#gradientArea-${title?.replace(
/[^a-zA-Z]/g, /[^a-zA-Z]/g,
'' '',
)})`} )})`}
/> />
<XAxis <XAxis

View File

@ -11,7 +11,7 @@ const FavoriteMarketButton = ({
}) => { }) => {
const [favoriteMarkets, setFavoriteMarkets] = useLocalStorageState<string[]>( const [favoriteMarkets, setFavoriteMarkets] = useLocalStorageState<string[]>(
FAVORITE_MARKETS_KEY, FAVORITE_MARKETS_KEY,
[] [],
) )
const addToFavorites = (marketName: string) => { const addToFavorites = (marketName: string) => {
@ -24,7 +24,7 @@ const FavoriteMarketButton = ({
} }
return favoriteMarkets.find( return favoriteMarkets.find(
(marketName: string) => marketName === market.name (marketName: string) => marketName === market.name,
) ? ( ) ? (
<button <button
className="flex items-center justify-center text-th-active focus-visible:text-th-fgd-4 md:hover:text-th-fgd-3" className="flex items-center justify-center text-th-active focus-visible:text-th-fgd-4 md:hover:text-th-fgd-3"

View File

@ -15,7 +15,7 @@ const SuccessParticles = () => {
const set = mangoStore((s) => s.set) const set = mangoStore((s) => s.set)
const [animationSettings] = useLocalStorageState( const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const tokenLogo = useMemo(() => { const tokenLogo = useMemo(() => {
@ -70,7 +70,7 @@ const SuccessParticles = () => {
set((s) => { set((s) => {
s.successAnimation.swap = false s.successAnimation.swap = false
}), }),
8000 8000,
) )
} }
if (showForTrade) { if (showForTrade) {
@ -79,7 +79,7 @@ const SuccessParticles = () => {
set((s) => { set((s) => {
s.successAnimation.trade = false s.successAnimation.trade = false
}), }),
8000 8000,
) )
} }
}, [showForSwap, showForTrade]) }, [showForSwap, showForTrade])

View File

@ -62,7 +62,7 @@ export const TrBody = forwardRef<HTMLTableRowElement, TrBodyProps>(
{children} {children}
</tr> </tr>
) )
} },
) )
TrBody.displayName = 'TrBody' TrBody.displayName = 'TrBody'

View File

@ -22,7 +22,7 @@ const TokenLogo = ({
let jupiterLogoURI let jupiterLogoURI
if (mangoTokens?.length) { if (mangoTokens?.length) {
jupiterLogoURI = mangoTokens.find( jupiterLogoURI = mangoTokens.find(
(t) => t.address === bank?.mint.toString() (t) => t.address === bank?.mint.toString(),
)?.logoURI )?.logoURI
} }
return jupiterLogoURI return jupiterLogoURI

View File

@ -26,7 +26,7 @@ const TokenVaultWarnings = ({
const maxWithdraw = getMaxWithdrawForBank(group, bank, mangoAccount) const maxWithdraw = getMaxWithdrawForBank(group, bank, mangoAccount)
const maxBorrow = mangoAccount.getMaxWithdrawWithBorrowForTokenUi( const maxBorrow = mangoAccount.getMaxWithdrawWithBorrowForTokenUi(
group, group,
bank.mint bank.mint,
) )
return [maxWithdraw, maxBorrow] return [maxWithdraw, maxBorrow]

View File

@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
export default function useDebounce<T>( export default function useDebounce<T>(
value: T, value: T,
delay: number delay: number,
): [T, (value: T) => void] { ): [T, (value: T) => void] {
// State and setters for debounced value // State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState(value) const [debouncedValue, setDebouncedValue] = useState(value)
@ -19,7 +19,7 @@ export default function useDebounce<T>(
clearTimeout(handler) clearTimeout(handler)
} }
}, },
[value, delay] // Only re-call effect if value or delay changes [value, delay], // Only re-call effect if value or delay changes
) )
return [debouncedValue, setDebouncedValue] return [debouncedValue, setDebouncedValue]
} }

View File

@ -3,7 +3,7 @@ import { useRef, useEffect } from 'react'
export default function useInterval( export default function useInterval(
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: (...args: any[]) => any, callback: (...args: any[]) => any,
delay: number delay: number,
) { ) {
const savedCallback = useRef<() => void>() const savedCallback = useRef<() => void>()

View File

@ -20,7 +20,7 @@ const AverageFundingChart = ({
const groupByHourlyInterval = ( const groupByHourlyInterval = (
data: PerpStatsItem[], data: PerpStatsItem[],
intervalDurationHours: number intervalDurationHours: number,
) => { ) => {
const intervalMillis = intervalDurationHours * 60 * 60 * 1000 const intervalMillis = intervalDurationHours * 60 * 60 * 1000
const groupedData = [] const groupedData = []

View File

@ -39,15 +39,15 @@ const MangoPerpStatsCharts = () => {
const data = perpStats.reduce( const data = perpStats.reduce(
(a: PerpStatsData, c: PerpStatsItem) => { (a: PerpStatsData, c: PerpStatsItem) => {
const hasDateFee = a.feeValues.find( const hasDateFee = a.feeValues.find(
(d: FeeValueItem) => d.date === c.date_hour (d: FeeValueItem) => d.date === c.date_hour,
) )
const hasDateOpenInterest = a.openInterestValues.find( const hasDateOpenInterest = a.openInterestValues.find(
(d: OiValueItem) => d.date === c.date_hour (d: OiValueItem) => d.date === c.date_hour,
) )
const hasDateVolume = a.volumeValues.find( const hasDateVolume = a.volumeValues.find(
(d: VolumeValueItem) => d.date === c.date_hour (d: VolumeValueItem) => d.date === c.date_hour,
) )
if (!hasDateFee) { if (!hasDateFee) {
@ -66,7 +66,7 @@ const MangoPerpStatsCharts = () => {
}) })
} else { } else {
hasDateOpenInterest.openInterest += Math.floor( hasDateOpenInterest.openInterest += Math.floor(
c.open_interest * c.price c.open_interest * c.price,
) )
} }
@ -81,19 +81,19 @@ const MangoPerpStatsCharts = () => {
return a return a
}, },
{ feeValues: [], openInterestValues: [], volumeValues: [] } { feeValues: [], openInterestValues: [], volumeValues: [] },
) )
const { feeValues, openInterestValues, volumeValues } = data const { feeValues, openInterestValues, volumeValues } = data
const sortedFeeValues = feeValues.sort( const sortedFeeValues = feeValues.sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime() (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
) )
const sortedOpenInterestValues = openInterestValues.sort( const sortedOpenInterestValues = openInterestValues.sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime() (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
) )
const sortedVolumeValues = volumeValues.sort( const sortedVolumeValues = volumeValues.sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime() (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
) )
return [sortedFeeValues, sortedOpenInterestValues, sortedVolumeValues] return [sortedFeeValues, sortedOpenInterestValues, sortedVolumeValues]

View File

@ -28,7 +28,7 @@ import { DAILY_SECONDS } from 'utils/constants'
export const getOneDayPerpStats = ( export const getOneDayPerpStats = (
stats: PerpStatsItem[] | null, stats: PerpStatsItem[] | null,
marketName: string marketName: string,
) => { ) => {
return stats return stats
? stats ? stats
@ -46,7 +46,7 @@ export const getOneDayPerpStats = (
export const goToPerpMarketDetails = ( export const goToPerpMarketDetails = (
market: PerpMarket, market: PerpMarket,
router: NextRouter router: NextRouter,
) => { ) => {
const query = { ...router.query, ['market']: market.name } const query = { ...router.query, ['market']: market.name }
router.push({ pathname: router.pathname, query }) router.push({ pathname: router.pathname, query })
@ -107,14 +107,14 @@ const PerpMarketsOverviewTable = () => {
let fundingRateApr let fundingRateApr
if (rate.isSuccess) { if (rate.isSuccess) {
const marketRate = rate?.data?.find( const marketRate = rate?.data?.find(
(r) => r.market_index === market.perpMarketIndex (r) => r.market_index === market.perpMarketIndex,
) )
if (marketRate) { if (marketRate) {
fundingRate = formatFunding.format( fundingRate = formatFunding.format(
marketRate.funding_rate_hourly marketRate.funding_rate_hourly,
) )
fundingRateApr = formatFunding.format( fundingRateApr = formatFunding.format(
marketRate.funding_rate_hourly * 8760 marketRate.funding_rate_hourly * 8760,
) )
} else { } else {
fundingRate = '' fundingRate = ''
@ -190,9 +190,9 @@ const PerpMarketsOverviewTable = () => {
<FormatNumericValue <FormatNumericValue
value={group.toUiPrice( value={group.toUiPrice(
I80F48.fromNumber( I80F48.fromNumber(
market.stablePriceModel.stablePrice market.stablePriceModel.stablePrice,
), ),
market.baseDecimals market.baseDecimals,
)} )}
isUsd isUsd
/> />
@ -260,7 +260,7 @@ const PerpMarketsOverviewTable = () => {
<p className="text-th-fgd-4"> <p className="text-th-fgd-4">
$ $
{numberCompacter.format( {numberCompacter.format(
openInterest * market.uiPrice openInterest * market.uiPrice,
)} )}
</p> </p>
</> </>
@ -328,12 +328,12 @@ const MobilePerpMarketItem = ({ market }: { market: PerpMarket }) => {
let fundingRateApr: string let fundingRateApr: string
if (rate.isSuccess) { if (rate.isSuccess) {
const marketRate = rate?.data?.find( const marketRate = rate?.data?.find(
(r) => r.market_index === market.perpMarketIndex (r) => r.market_index === market.perpMarketIndex,
) )
if (marketRate) { if (marketRate) {
fundingRate = formatFunding.format(marketRate.funding_rate_hourly) fundingRate = formatFunding.format(marketRate.funding_rate_hourly)
fundingRateApr = formatFunding.format( fundingRateApr = formatFunding.format(
marketRate.funding_rate_hourly * 8760 marketRate.funding_rate_hourly * 8760,
) )
} else { } else {
fundingRate = '' fundingRate = ''

View File

@ -41,7 +41,7 @@ const PerpPositionsStatsTable = ({
<tbody> <tbody>
{positions.map(({ account, perpPosition, mangoAccount }, i) => { {positions.map(({ account, perpPosition, mangoAccount }, i) => {
const market = group.getPerpMarketByMarketIndex( const market = group.getPerpMarketByMarketIndex(
perpPosition.marketIndex perpPosition.marketIndex,
) )
const basePosition = perpPosition.getBasePositionUi(market) const basePosition = perpPosition.getBasePositionUi(market)
@ -49,7 +49,7 @@ const PerpPositionsStatsTable = ({
const floorBasePosition = floorToDecimal( const floorBasePosition = floorToDecimal(
basePosition, basePosition,
getDecimalCount(market.minOrderSize) getDecimalCount(market.minOrderSize),
).toNumber() ).toNumber()
const isLong = basePosition > 0 const isLong = basePosition > 0
@ -179,7 +179,7 @@ const PerpPositionsStatsTable = ({
<div className="border-b border-th-bkg-3"> <div className="border-b border-th-bkg-3">
{positions.map(({ account, perpPosition, mangoAccount }) => { {positions.map(({ account, perpPosition, mangoAccount }) => {
const market = group.getPerpMarketByMarketIndex( const market = group.getPerpMarketByMarketIndex(
perpPosition.marketIndex perpPosition.marketIndex,
) )
const basePosition = perpPosition.getBasePositionUi(market) const basePosition = perpPosition.getBasePositionUi(market)
@ -187,7 +187,7 @@ const PerpPositionsStatsTable = ({
const floorBasePosition = floorToDecimal( const floorBasePosition = floorToDecimal(
basePosition, basePosition,
getDecimalCount(market.minOrderSize) getDecimalCount(market.minOrderSize),
).toNumber() ).toNumber()
const isLong = basePosition > 0 const isLong = basePosition > 0

View File

@ -40,7 +40,7 @@ const SpotMarketsTable = () => {
staleTime: 1000 * 60, staleTime: 1000 * 60,
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
} },
) )
return ( return (
@ -62,30 +62,30 @@ const SpotMarketsTable = () => {
.sort((a, b) => a.name.localeCompare(b.name)) .sort((a, b) => a.name.localeCompare(b.name))
.map((mkt) => { .map((mkt) => {
const baseBank = group?.getFirstBankByTokenIndex( const baseBank = group?.getFirstBankByTokenIndex(
mkt.baseTokenIndex mkt.baseTokenIndex,
) )
const quoteBank = group?.getFirstBankByTokenIndex( const quoteBank = group?.getFirstBankByTokenIndex(
mkt.quoteTokenIndex mkt.quoteTokenIndex,
) )
const market = group?.getSerum3ExternalMarket( const market = group?.getSerum3ExternalMarket(
mkt.serumMarketExternal mkt.serumMarketExternal,
) )
let price let price
if (baseBank && market && quoteBank) { if (baseBank && market && quoteBank) {
price = floorToDecimal( price = floorToDecimal(
baseBank.uiPrice / quoteBank.uiPrice, baseBank.uiPrice / quoteBank.uiPrice,
getDecimalCount(market.tickSize) getDecimalCount(market.tickSize),
).toNumber() ).toNumber()
} }
let tickerData: TickerData | undefined let tickerData: TickerData | undefined
if (spotVolumeData && spotVolumeData.length) { if (spotVolumeData && spotVolumeData.length) {
tickerData = spotVolumeData.find( tickerData = spotVolumeData.find(
(m: TickerData) => m.ticker_id === mkt.name (m: TickerData) => m.ticker_id === mkt.name,
) )
} }
const birdeyeData = birdeyePrices.find( const birdeyeData = birdeyePrices.find(
(m) => m.mint === mkt.serumMarketExternal.toString() (m) => m.mint === mkt.serumMarketExternal.toString(),
) )
const birdeyeChange = const birdeyeChange =
@ -163,7 +163,7 @@ const SpotMarketsTable = () => {
{tickerData ? ( {tickerData ? (
<span> <span>
{numberCompacter.format( {numberCompacter.format(
parseFloat(tickerData.target_volume) parseFloat(tickerData.target_volume),
)}{' '} )}{' '}
<span className="font-body text-th-fgd-4"> <span className="font-body text-th-fgd-4">
{quoteBank?.name} {quoteBank?.name}
@ -222,14 +222,14 @@ const MobileSpotMarketItem = ({
if (!baseBank || !quoteBank || !serumMarket) return 0 if (!baseBank || !quoteBank || !serumMarket) return 0
return floorToDecimal( return floorToDecimal(
baseBank.uiPrice / quoteBank.uiPrice, baseBank.uiPrice / quoteBank.uiPrice,
getDecimalCount(serumMarket.tickSize) getDecimalCount(serumMarket.tickSize),
).toNumber() ).toNumber()
}, [baseBank, quoteBank, serumMarket]) }, [baseBank, quoteBank, serumMarket])
const birdeyeData = useMemo(() => { const birdeyeData = useMemo(() => {
if (!loadingPrices) { if (!loadingPrices) {
return birdeyePrices.find( return birdeyePrices.find(
(m) => m.mint === market.serumMarketExternal.toString() (m) => m.mint === market.serumMarketExternal.toString(),
) )
} }
return null return null
@ -254,7 +254,7 @@ const MobileSpotMarketItem = ({
let tickerData: TickerData | undefined let tickerData: TickerData | undefined
if (spotVolumeData && spotVolumeData.length) { if (spotVolumeData && spotVolumeData.length) {
tickerData = spotVolumeData.find( tickerData = spotVolumeData.find(
(m: TickerData) => m.ticker_id === market.name (m: TickerData) => m.ticker_id === market.name,
) )
} }
@ -336,7 +336,7 @@ const MobileSpotMarketItem = ({
{tickerData ? ( {tickerData ? (
<span> <span>
{numberCompacter.format( {numberCompacter.format(
parseFloat(tickerData.target_volume) parseFloat(tickerData.target_volume),
)}{' '} )}{' '}
<span className="font-body text-th-fgd-4"> <span className="font-body text-th-fgd-4">
{quoteBank?.name} {quoteBank?.name}

View File

@ -19,7 +19,7 @@ const StatsPage = () => {
const actions = mangoStore.getState().actions const actions = mangoStore.getState().actions
const perpStats = mangoStore((s) => s.perpStats.data) const perpStats = mangoStore((s) => s.perpStats.data)
const perpPositionsStatsNotLoaded = mangoStore( const perpPositionsStatsNotLoaded = mangoStore(
(s) => s.perpStats.positions.initialLoad (s) => s.perpStats.positions.initialLoad,
) )
const { group } = useMangoGroup() const { group } = useMangoGroup()
const { width } = useViewport() const { width } = useViewport()

View File

@ -98,7 +98,7 @@ const TokenDetailsTable = () => {
const [oracleProvider, oracleLinkPath] = getOracleProvider(bank) const [oracleProvider, oracleLinkPath] = getOracleProvider(bank)
const mintInfo = group.mintInfosMapByMint.get( const mintInfo = group.mintInfosMapByMint.get(
bank.mint.toString() bank.mint.toString(),
) )
return ( return (
@ -131,7 +131,7 @@ const TokenDetailsTable = () => {
<Td> <Td>
<p className="text-right"> <p className="text-right">
{(100 * bank.loanOriginationFeeRate.toNumber()).toFixed( {(100 * bank.loanOriginationFeeRate.toNumber()).toFixed(
2 2,
)} )}
% %
</p> </p>
@ -262,7 +262,7 @@ const TokenDetailsTable = () => {
</Tooltip> </Tooltip>
<p className="font-mono text-th-fgd-1"> <p className="font-mono text-th-fgd-1">
{(bank.liquidationFee.toNumber() * 100).toFixed( {(bank.liquidationFee.toNumber() * 100).toFixed(
2 2,
)} )}
% %
</p> </p>

View File

@ -84,11 +84,11 @@ const TokenOverviewTable = () => {
deposits * bank.minVaultToDepositsRatio deposits * bank.minVaultToDepositsRatio
const available = Decimal.max( const available = Decimal.max(
0, 0,
availableVaultBalance.toFixed(bank.mintDecimals) availableVaultBalance.toFixed(bank.mintDecimals),
) )
const feesEarned = toUiDecimals( const feesEarned = toUiDecimals(
bank.collectedFeesNative, bank.collectedFeesNative,
bank.mintDecimals bank.mintDecimals,
) )
return ( return (
@ -201,11 +201,11 @@ const TokenOverviewTable = () => {
deposits * bank.minVaultToDepositsRatio deposits * bank.minVaultToDepositsRatio
const available = Decimal.max( const available = Decimal.max(
0, 0,
availableVaultBalance.toFixed(bank.mintDecimals) availableVaultBalance.toFixed(bank.mintDecimals),
) )
const feesEarned = toUiDecimals( const feesEarned = toUiDecimals(
bank.collectedFeesNative, bank.collectedFeesNative,
bank.mintDecimals bank.mintDecimals,
) )
return ( return (
<Disclosure key={bank.name}> <Disclosure key={bank.name}>

View File

@ -39,7 +39,7 @@ const TokenStatsCharts = () => {
a + a +
c.bank.uiPrice * c.bank.uiPrice *
toUiDecimals(c.bank.collectedFeesNative, c.bank.mintDecimals), toUiDecimals(c.bank.collectedFeesNative, c.bank.mintDecimals),
0 0,
), ),
] ]
} }

View File

@ -81,7 +81,7 @@ const RoutesModal = ({
{ {
jupiterTokens.find( jupiterTokens.find(
(item) => (item) =>
item?.address === r?.outputMint?.toString() item?.address === r?.outputMint?.toString(),
)?.symbol )?.symbol
} }
</span> </span>

View File

@ -121,14 +121,14 @@ const SwapForm = () => {
} }
}) })
}, },
[] [],
) )
const setAmountFromSlider = useCallback( const setAmountFromSlider = useCallback(
(amount: string) => { (amount: string) => {
setAmountInFormValue(amount, true) setAmountInFormValue(amount, true)
}, },
[setAmountInFormValue] [setAmountInFormValue],
) )
const setAmountOutFormValue = useCallback((amountOut: string) => { const setAmountOutFormValue = useCallback((amountOut: string) => {
@ -149,7 +149,7 @@ const SwapForm = () => {
} }
setAmountOutFormValue(borrowAmount.toString()) setAmountOutFormValue(borrowAmount.toString())
}, },
[setAmountOutFormValue] [setAmountOutFormValue],
) )
/* /*
@ -192,7 +192,7 @@ const SwapForm = () => {
} }
setAmountInFormValue(e.value) setAmountInFormValue(e.value)
}, },
[swapMode, setAmountInFormValue] [swapMode, setAmountInFormValue],
) )
const handleAmountOutChange = useCallback( const handleAmountOutChange = useCallback(
@ -205,7 +205,7 @@ const SwapForm = () => {
} }
setAmountOutFormValue(e.value) setAmountOutFormValue(e.value)
}, },
[swapMode, setAmountOutFormValue] [swapMode, setAmountOutFormValue],
) )
const handleTokenInSelect = useCallback((mintAddress: string) => { const handleTokenInSelect = useCallback((mintAddress: string) => {
@ -242,10 +242,10 @@ const SwapForm = () => {
s.swap.outputBank = inputBank s.swap.outputBank = inputBank
}) })
setAnimateSwitchArrow( setAnimateSwitchArrow(
(prevanimateSwitchArrow) => prevanimateSwitchArrow + 1 (prevanimateSwitchArrow) => prevanimateSwitchArrow + 1,
) )
}, },
[setAmountInFormValue] [setAmountInFormValue],
) )
const maintProjectedHealth = useMemo(() => { const maintProjectedHealth = useMemo(() => {
@ -272,7 +272,7 @@ const SwapForm = () => {
uiTokenAmount: amountOutAsDecimal.toNumber(), uiTokenAmount: amountOutAsDecimal.toNumber(),
}, },
], ],
HealthType.maint HealthType.maint,
) )
return simulatedHealthRatio > 100 return simulatedHealthRatio > 100
? 100 ? 100
@ -401,7 +401,7 @@ const SwapForm = () => {
<span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4"> <span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4">
{inputBank {inputBank
? formatCurrencyValue( ? formatCurrencyValue(
inputBank.uiPrice * Number(amountInFormValue) inputBank.uiPrice * Number(amountInFormValue),
) )
: ''} : ''}
</span> </span>
@ -434,8 +434,8 @@ const SwapForm = () => {
onClick={() => onClick={() =>
setBorrowAmountOut( setBorrowAmountOut(
outputTokenBalanceBorrow.toFixed( outputTokenBalanceBorrow.toFixed(
outputBank?.mintDecimals || 9 outputBank?.mintDecimals || 9,
) ),
) )
} }
value={outputTokenBalanceBorrow} value={outputTokenBalanceBorrow}
@ -476,7 +476,7 @@ const SwapForm = () => {
<span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4"> <span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4">
{outputBank {outputBank
? formatCurrencyValue( ? formatCurrencyValue(
outputBank.uiPrice * Number(amountOutFormValue) outputBank.uiPrice * Number(amountOutFormValue),
) )
: ''} : ''}
</span> </span>

View File

@ -166,7 +166,7 @@ const SwapFormTokenList = ({
new PublicKey(token.address), new PublicKey(token.address),
outputBank.mint, outputBank.mint,
group, group,
useMargin useMargin,
) )
return { ...token, ...max } return { ...token, ...max }
}) })
@ -174,7 +174,7 @@ const SwapFormTokenList = ({
.sort((a, b) => .sort((a, b) =>
useMargin useMargin
? Number(b.amountWithBorrow) - Number(a.amountWithBorrow) ? Number(b.amountWithBorrow) - Number(a.amountWithBorrow)
: Number(b.amount) - Number(a.amount) : Number(b.amount) - Number(a.amount),
) )
return filteredSortedTokens return filteredSortedTokens

View File

@ -36,7 +36,7 @@ const SwapHistoryTable = () => {
const showTableView = width ? width > breakpoints.md : false const showTableView = width ? width > breakpoints.md : false
const [preferredExplorer] = useLocalStorageState( const [preferredExplorer] = useLocalStorageState(
PREFERRED_EXPLORER_KEY, PREFERRED_EXPLORER_KEY,
EXPLORERS[0] EXPLORERS[0],
) )
useEffect(() => { useEffect(() => {
@ -56,7 +56,7 @@ const SwapHistoryTable = () => {
actions.fetchSwapHistory( actions.fetchSwapHistory(
mangoAccountAddress, mangoAccountAddress,
0, 0,
offset + PAGINATION_PAGE_LENGTH offset + PAGINATION_PAGE_LENGTH,
) )
}, [actions, offset, mangoAccountAddress]) }, [actions, offset, mangoAccountAddress])
@ -196,7 +196,7 @@ const SwapHistoryTable = () => {
<div className="flex items-center justify-end"> <div className="flex items-center justify-end">
<Tooltip <Tooltip
content={`View on ${t( content={`View on ${t(
`settings:${preferredExplorer.name}` `settings:${preferredExplorer.name}`,
)}`} )}`}
placement="top-end" placement="top-end"
> >

View File

@ -19,7 +19,7 @@ const SwapPage = () => {
const actions = mangoStore((s) => s.actions) const actions = mangoStore((s) => s.actions)
const [showSwapIntro, setShowSwapIntro] = useLocalStorage( const [showSwapIntro, setShowSwapIntro] = useLocalStorage(
SHOW_SWAP_INTRO_MODAL, SHOW_SWAP_INTRO_MODAL,
true true,
) )
useEffect(() => { useEffect(() => {

View File

@ -59,17 +59,17 @@ type JupiterRouteInfoProps = {
const deserializeJupiterIxAndAlt = async ( const deserializeJupiterIxAndAlt = async (
connection: Connection, connection: Connection,
swapTransaction: string swapTransaction: string,
): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => { ): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => {
const parsedSwapTransaction = VersionedTransaction.deserialize( const parsedSwapTransaction = VersionedTransaction.deserialize(
Buffer.from(swapTransaction, 'base64') Buffer.from(swapTransaction, 'base64'),
) )
const message = parsedSwapTransaction.message const message = parsedSwapTransaction.message
// const lookups = message.addressTableLookups // const lookups = message.addressTableLookups
const addressLookupTablesResponses = await Promise.all( const addressLookupTablesResponses = await Promise.all(
message.addressTableLookups.map((alt) => message.addressTableLookups.map((alt) =>
connection.getAddressLookupTable(alt.accountKey) connection.getAddressLookupTable(alt.accountKey),
) ),
) )
const addressLookupTables: AddressLookupTableAccount[] = const addressLookupTables: AddressLookupTableAccount[] =
addressLookupTablesResponses addressLookupTablesResponses
@ -87,7 +87,7 @@ const prepareMangoRouterInstructions = async (
selectedRoute: RouteInfo, selectedRoute: RouteInfo,
inputMint: PublicKey, inputMint: PublicKey,
outputMint: PublicKey, outputMint: PublicKey,
userPublicKey: PublicKey userPublicKey: PublicKey,
): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => { ): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => {
if (!selectedRoute || !selectedRoute.mints || !selectedRoute.instructions) { if (!selectedRoute || !selectedRoute.mints || !selectedRoute.instructions) {
return [[], []] return [[], []]
@ -97,8 +97,8 @@ const prepareMangoRouterInstructions = async (
...selectedRoute.mints.filter( ...selectedRoute.mints.filter(
(routeMint) => (routeMint) =>
!mintsToFilterOut.find((filterOutMint) => !mintsToFilterOut.find((filterOutMint) =>
filterOutMint.equals(routeMint) filterOutMint.equals(routeMint),
) ),
), ),
] ]
const additionalInstructions = [] const additionalInstructions = []
@ -106,7 +106,7 @@ const prepareMangoRouterInstructions = async (
const ix = await createAssociatedTokenAccountIdempotentInstruction( const ix = await createAssociatedTokenAccountIdempotentInstruction(
userPublicKey, userPublicKey,
userPublicKey, userPublicKey,
mint mint,
) )
additionalInstructions.push(ix) additionalInstructions.push(ix)
} }
@ -123,7 +123,7 @@ export const fetchJupiterTransaction = async (
userPublicKey: PublicKey, userPublicKey: PublicKey,
slippage: number, slippage: number,
inputMint: PublicKey, inputMint: PublicKey,
outputMint: PublicKey outputMint: PublicKey,
): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => { ): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => {
const transactions = await ( const transactions = await (
await fetch('https://quote-api.jup.ag/v4/swap', { await fetch('https://quote-api.jup.ag/v4/swap', {
@ -148,7 +148,7 @@ export const fetchJupiterTransaction = async (
const [ixs, alts] = await deserializeJupiterIxAndAlt( const [ixs, alts] = await deserializeJupiterIxAndAlt(
connection, connection,
swapTransaction swapTransaction,
) )
const isSetupIx = (pk: PublicKey): boolean => const isSetupIx = (pk: PublicKey): boolean =>
@ -202,14 +202,14 @@ const SwapReviewRouteInfo = ({
const outputBank = mangoStore((s) => s.swap.outputBank) const outputBank = mangoStore((s) => s.swap.outputBank)
const [soundSettings] = useLocalStorageState( const [soundSettings] = useLocalStorageState(
SOUND_SETTINGS_KEY, SOUND_SETTINGS_KEY,
INITIAL_SOUND_SETTINGS INITIAL_SOUND_SETTINGS,
) )
const focusRef = useRef<HTMLButtonElement>(null) const focusRef = useRef<HTMLButtonElement>(null)
const amountOut = useMemo(() => { const amountOut = useMemo(() => {
if (!selectedRoute || !outputTokenInfo) return if (!selectedRoute || !outputTokenInfo) return
return new Decimal(selectedRoute.outAmount.toString()).div( return new Decimal(selectedRoute.outAmount.toString()).div(
10 ** outputTokenInfo.decimals 10 ** outputTokenInfo.decimals,
) )
}, [selectedRoute, outputTokenInfo]) }, [selectedRoute, outputTokenInfo])
@ -228,7 +228,7 @@ const SwapReviewRouteInfo = ({
if (inputId && outputId) { if (inputId && outputId) {
try { try {
const results = await fetch( const results = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=${inputId},${outputId}&vs_currencies=usd` `https://api.coingecko.com/api/v3/simple/price?ids=${inputId},${outputId}&vs_currencies=usd`,
) )
const json = await results.json() const json = await results.json()
if (json[inputId]?.usd && json[outputId]?.usd) { if (json[inputId]?.usd && json[outputId]?.usd) {
@ -275,7 +275,7 @@ const SwapReviewRouteInfo = ({
selectedRoute, selectedRoute,
inputBank.mint, inputBank.mint,
outputBank.mint, outputBank.mint,
mangoAccount.owner mangoAccount.owner,
) )
: await fetchJupiterTransaction( : await fetchJupiterTransaction(
connection, connection,
@ -283,7 +283,7 @@ const SwapReviewRouteInfo = ({
wallet.publicKey, wallet.publicKey,
slippage, slippage,
inputBank.mint, inputBank.mint,
outputBank.mint outputBank.mint,
) )
try { try {
@ -358,8 +358,8 @@ const SwapReviewRouteInfo = ({
.div(amountOut) .div(amountOut)
.minus( .minus(
new Decimal(coingeckoPrices?.outputCoingeckoPrice).div( new Decimal(coingeckoPrices?.outputCoingeckoPrice).div(
coingeckoPrices?.inputCoingeckoPrice coingeckoPrices?.inputCoingeckoPrice,
) ),
) )
.div(amountIn.div(amountOut)) .div(amountIn.div(amountOut))
.mul(100) .mul(100)
@ -540,7 +540,7 @@ const SwapReviewRouteInfo = ({
token: inputTokenInfo?.symbol, token: inputTokenInfo?.symbol,
rate: formatNumericValue( rate: formatNumericValue(
inputBank!.getBorrowRateUi(), inputBank!.getBorrowRateUi(),
2 2,
), ),
}) })
: t('swap:tooltip-borrow-no-balance', { : t('swap:tooltip-borrow-no-balance', {
@ -548,7 +548,7 @@ const SwapReviewRouteInfo = ({
token: inputTokenInfo?.symbol, token: inputTokenInfo?.symbol,
rate: formatNumericValue( rate: formatNumericValue(
inputBank!.getBorrowRateUi(), inputBank!.getBorrowRateUi(),
2 2,
), ),
}) })
} }
@ -667,7 +667,7 @@ const SwapReviewRouteInfo = ({
) : ( ) : (
selectedRoute?.marketInfos.map((info, index) => { selectedRoute?.marketInfos.map((info, index) => {
const feeToken = jupiterTokens.find( const feeToken = jupiterTokens.find(
(item) => item?.address === info.lpFee?.mint (item) => item?.address === info.lpFee?.mint,
) )
return ( return (
<div className="flex justify-between" key={index}> <div className="flex justify-between" key={index}>
@ -690,7 +690,7 @@ const SwapReviewRouteInfo = ({
undefined, undefined,
{ {
maximumSignificantDigits: 2, maximumSignificantDigits: 2,
} },
)} )}
%) %)
</p> </p>

View File

@ -102,7 +102,7 @@ interface ExtendedReferenceDotProps extends ReferenceDotProps {
flipPrices: boolean flipPrices: boolean
mouseEnter: ( mouseEnter: (
swap: SwapHistoryItem | undefined, swap: SwapHistoryItem | undefined,
coingeckoPrice: string | number | undefined coingeckoPrice: string | number | undefined,
) => void ) => void
mouseLeave: MouseEventHandler mouseLeave: MouseEventHandler
} }
@ -120,7 +120,7 @@ const SwapHistoryArrows = (props: ExtendedReferenceDotProps) => {
mouseLeave, mouseLeave,
} = props } = props
const swapDetails = swapHistory.find( const swapDetails = swapHistory.find(
(swap) => dayjs(swap.block_datetime).unix() * 1000 === x (swap) => dayjs(swap.block_datetime).unix() * 1000 === x,
) )
const side = const side =
swapDetails?.swap_in_symbol === swapMarketName.split('/')[0] swapDetails?.swap_in_symbol === swapMarketName.split('/')[0]
@ -186,7 +186,7 @@ const SwapTokenChart = () => {
const { theme } = useTheme() const { theme } = useTheme()
const [animationSettings] = useLocalStorageState( const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const swapHistory = mangoStore((s) => s.mangoAccount.swapHistory.data) const swapHistory = mangoStore((s) => s.mangoAccount.swapHistory.data)
const loadSwapHistory = mangoStore((s) => s.mangoAccount.swapHistory.loading) const loadSwapHistory = mangoStore((s) => s.mangoAccount.swapHistory.loading)
@ -200,7 +200,7 @@ const SwapTokenChart = () => {
const handleSwapMouseEnter = useCallback( const handleSwapMouseEnter = useCallback(
( (
swap: SwapHistoryItem | undefined, swap: SwapHistoryItem | undefined,
coingeckoPrice: string | number | undefined coingeckoPrice: string | number | undefined,
) => { ) => {
if (swap) { if (swap) {
setSwapTooltipData(swap) setSwapTooltipData(swap)
@ -209,7 +209,7 @@ const SwapTokenChart = () => {
setSwapTooltipCoingeckoPrice(coingeckoPrice) setSwapTooltipCoingeckoPrice(coingeckoPrice)
} }
}, },
[setSwapTooltipData, setSwapTooltipCoingeckoPrice] [setSwapTooltipData, setSwapTooltipCoingeckoPrice],
) )
const handleSwapMouseLeave = useCallback(() => { const handleSwapMouseLeave = useCallback(() => {
@ -302,9 +302,9 @@ const SwapTokenChart = () => {
return ( return (
<> <>
<p className="text-center text-th-fgd-2">{`${t( <p className="text-center text-th-fgd-2">{`${t(
side side,
)} ${amount} ${symbol} at ${formatNumericValue( )} ${amount} ${symbol} at ${formatNumericValue(
price price,
)} ${priceSymbol} for ${formatCurrencyValue(value)}`}</p> )} ${priceSymbol} for ${formatCurrencyValue(value)}`}</p>
{coingeckoPercentageDifference ? ( {coingeckoPercentageDifference ? (
<p <p
@ -321,7 +321,7 @@ const SwapTokenChart = () => {
</> </>
) )
}, },
[flipPrices, swapMarketName, swapTooltipCoingeckoPrice] [flipPrices, swapMarketName, swapTooltipCoingeckoPrice],
) )
const { const {
@ -336,7 +336,7 @@ const SwapTokenChart = () => {
staleTime: 1000 * 60 * 1, staleTime: 1000 * 60 * 1,
enabled: !!baseTokenId && !!quoteTokenId, enabled: !!baseTokenId && !!quoteTokenId,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
} },
) )
const coingeckoData = useMemo(() => { const coingeckoData = useMemo(() => {
@ -371,7 +371,7 @@ const SwapTokenChart = () => {
.filter( .filter(
(swap) => (swap) =>
chartSymbols.includes(swap.swap_in_symbol) && chartSymbols.includes(swap.swap_in_symbol) &&
chartSymbols.includes(swap.swap_out_symbol) chartSymbols.includes(swap.swap_out_symbol),
) )
.map((val) => dayjs(val.block_datetime).unix() * 1000) .map((val) => dayjs(val.block_datetime).unix() * 1000)
}, [swapHistory, loadSwapHistory, inputBank, outputBank]) }, [swapHistory, loadSwapHistory, inputBank, outputBank])
@ -408,7 +408,7 @@ const SwapTokenChart = () => {
const maxTime = coingeckoData[coingeckoData.length - 1].time const maxTime = coingeckoData[coingeckoData.length - 1].time
if (swapHistoryPoints.length && showSwaps) { if (swapHistoryPoints.length && showSwaps) {
const swapPoints = swapHistoryPoints.filter( const swapPoints = swapHistoryPoints.filter(
(point) => point.time >= minTime && point.time <= maxTime (point) => point.time >= minTime && point.time <= maxTime,
) )
return coingeckoData.concat(swapPoints).sort((a, b) => a.time - b.time) return coingeckoData.concat(swapPoints).sort((a, b) => a.time - b.time)
} else return coingeckoData } else return coingeckoData
@ -420,7 +420,7 @@ const SwapTokenChart = () => {
setMouseData(coords.activePayload[0].payload) setMouseData(coords.activePayload[0].payload)
} }
}, },
[setMouseData] [setMouseData],
) )
const handleMouseLeave = useCallback(() => { const handleMouseLeave = useCallback(() => {
@ -524,7 +524,7 @@ const SwapTokenChart = () => {
width={35} width={35}
play play
numbers={formatNumericValue( numbers={formatNumericValue(
chartData[chartData.length - 1].price chartData[chartData.length - 1].price,
)} )}
/> />
) : ( ) : (
@ -540,7 +540,7 @@ const SwapTokenChart = () => {
</div> </div>
<p className="text-sm text-th-fgd-4"> <p className="text-sm text-th-fgd-4">
{dayjs(chartData[chartData.length - 1].time).format( {dayjs(chartData[chartData.length - 1].time).format(
'DD MMM YY, h:mma' 'DD MMM YY, h:mma',
)} )}
</p> </p>
</> </>

View File

@ -11,10 +11,10 @@ const useJupiterSwapData = () => {
if (inputBank && outputBank) { if (inputBank && outputBank) {
return [ return [
mangoTokens?.find( mangoTokens?.find(
(item) => item?.address === inputBank.mint.toString() || '' (item) => item?.address === inputBank.mint.toString() || '',
), ),
mangoTokens?.find( mangoTokens?.find(
(item) => item?.address === outputBank.mint.toString() || '' (item) => item?.address === outputBank.mint.toString() || '',
), ),
] ]
} else { } else {

View File

@ -27,7 +27,7 @@ const fetchJupiterRoutes = async (
amount = 0, amount = 0,
slippage = 50, slippage = 50,
swapMode = 'ExactIn', swapMode = 'ExactIn',
feeBps = 0 feeBps = 0,
) => { ) => {
{ {
const paramsString = new URLSearchParams({ const paramsString = new URLSearchParams({
@ -40,7 +40,7 @@ const fetchJupiterRoutes = async (
}).toString() }).toString()
const response = await fetch( const response = await fetch(
`https://quote-api.jup.ag/v4/quote?${paramsString}` `https://quote-api.jup.ag/v4/quote?${paramsString}`,
) )
const res = await response.json() const res = await response.json()
@ -60,7 +60,7 @@ const fetchMangoRoutes = async (
slippage = 50, slippage = 50,
swapMode = 'ExactIn', swapMode = 'ExactIn',
feeBps = 0, feeBps = 0,
wallet = PublicKey.default.toBase58() wallet = PublicKey.default.toBase58(),
) => { ) => {
{ {
const defaultOtherAmount = const defaultOtherAmount =
@ -118,7 +118,7 @@ export const handleGetRoutes = async (
swapMode = 'ExactIn', swapMode = 'ExactIn',
feeBps = 0, feeBps = 0,
wallet: string | undefined | null, wallet: string | undefined | null,
mode: SwapModes = 'ALL' mode: SwapModes = 'ALL',
) => { ) => {
try { try {
wallet ||= PublicKey.default.toBase58() wallet ||= PublicKey.default.toBase58()
@ -129,7 +129,7 @@ export const handleGetRoutes = async (
slippage, slippage,
swapMode, swapMode,
feeBps, feeBps,
wallet wallet,
) )
const jupiterRoute = fetchJupiterRoutes( const jupiterRoute = fetchJupiterRoutes(
inputMint, inputMint,
@ -137,7 +137,7 @@ export const handleGetRoutes = async (
amount, amount,
slippage, slippage,
swapMode, swapMode,
feeBps feeBps,
) )
const routes = [] const routes = []
@ -166,7 +166,7 @@ export const handleGetRoutes = async (
).sort((a, b) => ).sort((a, b) =>
swapMode === 'ExactIn' swapMode === 'ExactIn'
? Number(b.bestRoute.outAmount) - Number(a.bestRoute.outAmount) ? Number(b.bestRoute.outAmount) - Number(a.bestRoute.outAmount)
: Number(a.bestRoute.inAmount) - Number(b.bestRoute.inAmount) : Number(a.bestRoute.inAmount) - Number(b.bestRoute.inAmount),
) )
return { return {
routes: sortedByBiggestOutAmount[0].routes, routes: sortedByBiggestOutAmount[0].routes,
@ -227,7 +227,7 @@ const useQuoteRoutes = ({
swapMode, swapMode,
0, 0,
wallet, wallet,
mode mode,
), ),
{ {
cacheTime: 1000 * 60, cacheTime: 1000 * 60,
@ -235,7 +235,7 @@ const useQuoteRoutes = ({
enabled: enabled ? enabled() : amount ? true : false, enabled: enabled ? enabled() : amount ? true : false,
refetchInterval: 20000, refetchInterval: 20000,
retry: 3, retry: 3,
} },
) )
return amount return amount

View File

@ -11,13 +11,13 @@ export const getMaxWithdrawForBank = (
group: Group, group: Group,
bank: Bank, bank: Bank,
mangoAccount: MangoAccount, mangoAccount: MangoAccount,
allowBorrow = false allowBorrow = false,
): Decimal => { ): Decimal => {
const accountBalance = mangoAccount.getTokenBalanceUi(bank) const accountBalance = mangoAccount.getTokenBalanceUi(bank)
const vaultBalance = group.getTokenVaultBalanceByMintUi(bank.mint) const vaultBalance = group.getTokenVaultBalanceByMintUi(bank.mint)
const maxBorrow = mangoAccount.getMaxWithdrawWithBorrowForTokenUi( const maxBorrow = mangoAccount.getMaxWithdrawWithBorrowForTokenUi(
group, group,
bank.mint bank.mint,
) )
const maxWithdraw = allowBorrow const maxWithdraw = allowBorrow
? Decimal.min(vaultBalance, maxBorrow) ? Decimal.min(vaultBalance, maxBorrow)
@ -32,7 +32,7 @@ export const getTokenInMax = (
inputMint: PublicKey, inputMint: PublicKey,
outputMint: PublicKey, outputMint: PublicKey,
group: Group, group: Group,
useMargin: boolean useMargin: boolean,
) => { ) => {
const inputBank = group.getFirstBankByMint(inputMint) const inputBank = group.getFirstBankByMint(inputMint)
const outputBank = group.getFirstBankByMint(outputMint) const outputBank = group.getFirstBankByMint(outputMint)
@ -49,11 +49,11 @@ export const getTokenInMax = (
const outputReduceOnly = outputBank.areDepositsReduceOnly() const outputReduceOnly = outputBank.areDepositsReduceOnly()
const inputTokenBalance = new Decimal( const inputTokenBalance = new Decimal(
mangoAccount.getTokenBalanceUi(inputBank) mangoAccount.getTokenBalanceUi(inputBank),
) )
const outputTokenBalance = new Decimal( const outputTokenBalance = new Decimal(
mangoAccount.getTokenBalanceUi(outputBank) mangoAccount.getTokenBalanceUi(outputBank),
) )
const maxAmountWithoutMargin = const maxAmountWithoutMargin =
@ -65,7 +65,7 @@ export const getTokenInMax = (
const rawMaxUiAmountWithBorrow = mangoAccount.getMaxSourceUiForTokenSwap( const rawMaxUiAmountWithBorrow = mangoAccount.getMaxSourceUiForTokenSwap(
group, group,
inputBank.mint, inputBank.mint,
outputBank.mint outputBank.mint,
) )
const maxUiAmountWithBorrow = const maxUiAmountWithBorrow =
@ -79,19 +79,19 @@ export const getTokenInMax = (
group group
.getTokenVaultBalanceByMintUi(inputBank.mint) .getTokenVaultBalanceByMintUi(inputBank.mint)
.toFixed(inputBank.mintDecimals), .toFixed(inputBank.mintDecimals),
inputBank.mintDecimals inputBank.mintDecimals,
) )
const maxAmount = useMargin const maxAmount = useMargin
? Decimal.min( ? Decimal.min(
maxAmountWithoutMargin, maxAmountWithoutMargin,
inputBankVaultBalance, inputBankVaultBalance,
maxUiAmountWithBorrow maxUiAmountWithBorrow,
) )
: Decimal.min( : Decimal.min(
maxAmountWithoutMargin, maxAmountWithoutMargin,
inputBankVaultBalance, inputBankVaultBalance,
maxUiAmountWithBorrow maxUiAmountWithBorrow,
) )
const maxAmountWithBorrow = inputReduceOnly const maxAmountWithBorrow = inputReduceOnly
@ -125,7 +125,7 @@ export const useTokenMax = (useMargin = true): TokenMaxResults => {
inputBank.mint, inputBank.mint,
outputBank.mint, outputBank.mint,
group, group,
useMargin useMargin,
) )
} }
} catch (e) { } catch (e) {

View File

@ -28,7 +28,7 @@ const ActionPanel = ({ bank }: { bank: Bank }) => {
const handleTrade = () => { const handleTrade = () => {
const set = mangoStore.getState().set const set = mangoStore.getState().set
const market = serumMarkets.find( const market = serumMarkets.find(
(m) => m.baseTokenIndex === bank?.tokenIndex (m) => m.baseTokenIndex === bank?.tokenIndex,
) )
if (market) { if (market) {
set((state) => { set((state) => {

View File

@ -39,7 +39,7 @@ const ChartTabs = ({ bank }: { bank: Bank }) => {
} }
return a.sort( return a.sort(
(a, b) => (a, b) =>
new Date(a.date_hour).getTime() - new Date(b.date_hour).getTime() new Date(a.date_hour).getTime() - new Date(b.date_hour).getTime(),
) )
}, []) }, [])
}, [tokenStats, bank]) }, [tokenStats, bank])

View File

@ -41,7 +41,7 @@ interface BirdeyeResponse {
const fetchBirdeyePrices = async ( const fetchBirdeyePrices = async (
daysToShow: string, daysToShow: string,
mint: string mint: string,
): Promise<BirdeyePriceResponse[] | []> => { ): Promise<BirdeyePriceResponse[] | []> => {
const interval = daysToShow === '1' ? '30m' : daysToShow === '7' ? '1H' : '4H' const interval = daysToShow === '1' ? '30m' : daysToShow === '7' ? '1H' : '4H'
const queryEnd = Math.floor(Date.now() / 1000) const queryEnd = Math.floor(Date.now() / 1000)
@ -81,7 +81,7 @@ const CoingeckoStats = ({
retry: 3, retry: 3,
enabled: !!bank, enabled: !!bank,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
} },
) )
const { const {

View File

@ -56,7 +56,7 @@ const fetchTokenInfo = async (tokenId: string | undefined) => {
if (!tokenId) return if (!tokenId) return
const response = await fetch( const response = await fetch(
`https://api.coingecko.com/api/v3/coins/${tokenId}?localization=false&tickers=false&developer_data=false&sparkline=false&community_data=false `https://api.coingecko.com/api/v3/coins/${tokenId}?localization=false&tickers=false&developer_data=false&sparkline=false&community_data=false
` `,
) )
const data = await response.json() const data = await response.json()
return data return data
@ -71,7 +71,7 @@ const TokenPage = () => {
const { mangoTokens } = useJupiterMints() const { mangoTokens } = useJupiterMints()
const [animationSettings] = useLocalStorageState( const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY, ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS INITIAL_ANIMATION_SETTINGS,
) )
const bankName = useMemo(() => { const bankName = useMemo(() => {
@ -118,7 +118,7 @@ const TokenPage = () => {
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
enabled: !!coingeckoId, enabled: !!coingeckoId,
} },
) )
const { high_24h, low_24h, price_change_percentage_24h } = const { high_24h, low_24h, price_change_percentage_24h } =

View File

@ -115,20 +115,20 @@ const TokenParams = ({ bank }: { bank: Bank }) => {
<p className="font-mono text-th-fgd-2"> <p className="font-mono text-th-fgd-2">
{bank.name === 'USDC' {bank.name === 'USDC'
? `$${toUiDecimalsForQuote( ? `$${toUiDecimalsForQuote(
bank.depositWeightScaleStartQuote bank.depositWeightScaleStartQuote,
).toExponential(1)}` ).toExponential(1)}`
: formatCurrencyValue( : formatCurrencyValue(
toUiDecimalsForQuote(bank.depositWeightScaleStartQuote) toUiDecimalsForQuote(bank.depositWeightScaleStartQuote),
)} )}
</p> </p>
<span className="text-th-fgd-4">|</span> <span className="text-th-fgd-4">|</span>
<p className="font-mono text-th-fgd-2"> <p className="font-mono text-th-fgd-2">
{bank.name === 'USDC' {bank.name === 'USDC'
? `$${toUiDecimalsForQuote( ? `$${toUiDecimalsForQuote(
bank.depositWeightScaleStartQuote bank.depositWeightScaleStartQuote,
).toExponential(1)}` ).toExponential(1)}`
: formatCurrencyValue( : formatCurrencyValue(
toUiDecimalsForQuote(bank.borrowWeightScaleStartQuote) toUiDecimalsForQuote(bank.borrowWeightScaleStartQuote),
)} )}
</p> </p>
</div> </div>
@ -152,8 +152,8 @@ const TokenParams = ({ bank }: { bank: Bank }) => {
<p className="font-mono text-th-fgd-2"> <p className="font-mono text-th-fgd-2">
{formatCurrencyValue( {formatCurrencyValue(
toUiDecimalsForQuote( toUiDecimalsForQuote(
I80F48.fromI64(bank.netBorrowsInWindow).mul(bank.price) I80F48.fromI64(bank.netBorrowsInWindow).mul(bank.price),
) ),
)} )}
</p> </p>
</div> </div>
@ -165,7 +165,7 @@ const TokenParams = ({ bank }: { bank: Bank }) => {
</Tooltip> </Tooltip>
<p className="font-mono text-th-fgd-2"> <p className="font-mono text-th-fgd-2">
{formatCurrencyValue( {formatCurrencyValue(
toUiDecimals(bank.netBorrowLimitPerWindowQuote, 6) toUiDecimals(bank.netBorrowLimitPerWindowQuote, 6),
)} )}
</p> </p>
</div> </div>

View File

@ -31,17 +31,17 @@ const fetchTopTokenAccounts = async (tokenIndex: number) => {
try { try {
const promises = [ const promises = [
fetch( fetch(
`${MANGO_DATA_API_URL}/leaderboard-token-deposits?token-index=${tokenIndex}` `${MANGO_DATA_API_URL}/leaderboard-token-deposits?token-index=${tokenIndex}`,
), ),
fetch( fetch(
`${MANGO_DATA_API_URL}/leaderboard-token-borrows?token-index=${tokenIndex}` `${MANGO_DATA_API_URL}/leaderboard-token-borrows?token-index=${tokenIndex}`,
), ),
] ]
const [depositsResponse, borrowsResponse] = await Promise.all(promises) const [depositsResponse, borrowsResponse] = await Promise.all(promises)
const [depositsData, borrowsData]: [ const [depositsData, borrowsData]: [
TopDepositorBorrower[], TopDepositorBorrower[],
TopDepositorBorrower[] TopDepositorBorrower[],
] = await Promise.all([depositsResponse.json(), borrowsResponse.json()]) ] = await Promise.all([depositsResponse.json(), borrowsResponse.json()])
// const depositorProfilesResponse = await Promise.all( // const depositorProfilesResponse = await Promise.all(
@ -93,7 +93,7 @@ const TopTokenAccounts = ({ bank }: { bank: Bank }) => {
staleTime: 1000 * 60, staleTime: 1000 * 60,
retry: 3, retry: 3,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
} },
) )
const topAccountsData = data ? data : [[], []] const topAccountsData = data ? data : [[], []]

Some files were not shown because too many files have changed in this diff Show More