merge main

This commit is contained in:
saml33 2023-03-03 22:29:34 +11:00
commit 49c0d5517c
28 changed files with 1206 additions and 234 deletions

View File

@ -207,11 +207,11 @@ function DepositForm({ onSuccess, token }: DepositFormProps) {
<div>
<SolBalanceWarnings
amount={inputAmount}
className="mt-2"
className="mb-4"
setAmount={setInputAmount}
selectedToken={selectedToken}
/>
<div className="mt-4 grid grid-cols-2">
<div className="grid grid-cols-2">
<div className="col-span-2 flex justify-between">
<Label text={`${t('deposit')} ${t('token')}`} />
<MaxAmountButton

View File

@ -43,6 +43,11 @@ import useMangoGroup from 'hooks/useMangoGroup'
import PnlHistoryModal from '@components/modals/PnlHistoryModal'
import FormatNumericValue from '@components/shared/FormatNumericValue'
import HealthBar from './HealthBar'
const AssetsLiabilities = dynamic(() => import('./AssetsLiabilities'), {
ssr: false,
})
const TABS = ['account-value', 'account:assets-liabilities']
import { PerformanceDataItem } from 'types'
const AccountPage = () => {
@ -73,6 +78,10 @@ const AccountPage = () => {
ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS
)
const [activeTab, setActiveTab] = useLocalStorageState(
'accountHeroKey-0.1',
'account-value'
)
useEffect(() => {
if (mangoAccountAddress || (!mangoAccountAddress && connected)) {
@ -221,99 +230,119 @@ const AccountPage = () => {
return !chartToShow ? (
<>
<div className="flex flex-col border-b-0 border-th-bkg-3 px-6 py-3 lg:flex-row lg:items-center lg:justify-between lg:border-b">
<div className="flex flex-col md:flex-row md:items-center md:space-x-6">
<div id="account-step-three">
<Tooltip
maxWidth="20rem"
placement="bottom-start"
content="The value of your assets (deposits) minus the value of your liabilities (borrows)."
delay={250}
>
<p className="tooltip-underline mb-2 text-base">
{t('account-value')}
</p>
</Tooltip>
<div className="mb-2 flex items-center font-display text-5xl text-th-fgd-1">
{animationSettings['number-scroll'] ? (
group && mangoAccount ? (
<FlipNumbers
height={48}
width={35}
play
delay={0.05}
duration={1}
numbers={formatCurrencyValue(accountValue, 2)}
/>
) : (
<FlipNumbers
height={48}
width={36}
play
delay={0.05}
duration={1}
numbers={'$0.00'}
/>
)
) : (
<FormatNumericValue value={accountValue} isUsd decimals={2} />
)}
</div>
<div className="flex items-center space-x-1.5">
<Change change={accountValueChange} prefix="$" />
<p className="text-xs text-th-fgd-4">{t('rolling-change')}</p>
</div>
</div>
{!performanceLoading ? (
oneDayPerformanceData.length ? (
<div
className="relative mt-4 flex h-40 items-end md:mt-0 md:h-24 md:w-48"
onMouseEnter={() =>
onHoverMenu(showExpandChart, 'onMouseEnter')
}
onMouseLeave={() =>
onHoverMenu(showExpandChart, 'onMouseLeave')
}
<div className="flex flex-col border-b-0 border-th-bkg-3 px-6 py-4 lg:flex-row lg:items-center lg:justify-between lg:border-b">
<div>
<div className="hide-scroll flex justify-center space-x-2 md:justify-start">
{TABS.map((tab) => (
<button
className={`default-transition rounded-md py-1.5 px-2.5 text-sm font-medium md:hover:text-th-fgd-2 ${
activeTab === tab
? 'bg-th-bkg-3 text-th-active'
: 'text-th-fgd-3'
}`}
onClick={() => setActiveTab(tab)}
key={tab}
>
<SimpleAreaChart
color={
accountValueChange >= 0
? COLORS.UP[theme]
: COLORS.DOWN[theme]
}
data={oneDayPerformanceData.concat(latestAccountData)}
name="accountValue"
xKey="time"
yKey="account_equity"
/>
<Transition
appear={true}
className="absolute right-2 bottom-2"
show={showExpandChart || isMobile}
enter="transition ease-in duration-300"
enterFrom="opacity-0 scale-75"
enterTo="opacity-100 scale-100"
leave="transition ease-out duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<IconButton
className="text-th-fgd-3"
hideBg
onClick={() => handleShowAccountValueChart()}
>
<ArrowsPointingOutIcon className="h-5 w-5" />
</IconButton>
</Transition>
{t(tab)}
</button>
))}
</div>
<div className="md:h-24">
{activeTab === 'account-value' ? (
<div className="flex flex-col md:flex-row md:items-end md:space-x-6">
<div className="mx-auto mt-4 md:mx-0">
<div className="mb-2 flex justify-start font-display text-5xl text-th-fgd-1">
{animationSettings['number-scroll'] ? (
group && mangoAccount ? (
<FlipNumbers
height={48}
width={35}
play
delay={0.05}
duration={1}
numbers={formatCurrencyValue(accountValue, 2)}
/>
) : (
<FlipNumbers
height={48}
width={36}
play
delay={0.05}
duration={1}
numbers={'$0.00'}
/>
)
) : (
<FormatNumericValue
value={accountValue}
isUsd
decimals={2}
/>
)}
</div>
<div className="flex items-center justify-center space-x-1.5 md:justify-start">
<Change change={accountValueChange} prefix="$" />
<p className="text-xs text-th-fgd-4">
{t('rolling-change')}
</p>
</div>
</div>
{!performanceLoading ? (
oneDayPerformanceData.length ? (
<div
className="relative mt-4 flex h-40 items-end md:mt-0 md:h-20 md:w-52 lg:w-60"
onMouseEnter={() =>
onHoverMenu(showExpandChart, 'onMouseEnter')
}
onMouseLeave={() =>
onHoverMenu(showExpandChart, 'onMouseLeave')
}
>
<SimpleAreaChart
color={
accountValueChange >= 0
? COLORS.UP[theme]
: COLORS.DOWN[theme]
}
data={oneDayPerformanceData.concat(latestAccountData)}
name="accountValue"
xKey="time"
yKey="account_equity"
/>
<Transition
appear={true}
className="absolute right-2 bottom-2"
show={showExpandChart || isMobile}
enter="transition ease-in duration-300"
enterFrom="opacity-0 scale-75"
enterTo="opacity-100 scale-100"
leave="transition ease-out duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<IconButton
className="text-th-fgd-3"
hideBg
onClick={() => handleShowAccountValueChart()}
>
<ArrowsPointingOutIcon className="h-5 w-5" />
</IconButton>
</Transition>
</div>
) : null
) : mangoAccountAddress ? (
<SheenLoader className="mt-4 flex flex-1 md:mt-0">
<div className="h-40 w-full rounded-md bg-th-bkg-2 md:h-20 md:w-52 lg:w-60" />
</SheenLoader>
) : null}
</div>
) : null
) : mangoAccountAddress ? (
<SheenLoader className="mt-4 flex flex-1 md:mt-0">
<div className="h-40 w-full rounded-md bg-th-bkg-2 md:h-24 md:w-48" />
</SheenLoader>
) : null}
) : null}
{activeTab === 'account:assets-liabilities' ? (
<AssetsLiabilities isMobile={isMobile} />
) : null}
</div>
</div>
<div className="mt-6 mb-1 lg:mt-0 lg:mb-0">
<div className="mt-6 mb-1 lg:mt-0">
<AccountActions />
</div>
</div>

View File

@ -51,7 +51,7 @@ const getFee = (activity: any, mangoAccountAddress: string) => {
}
if (activity_type === 'openbook_trade') {
const { fee_cost, quote_symbol } = activity.activity_details
fee = { value: formatFee(fee_cost), symbol: quote_symbol }
fee = { value: fee_cost, symbol: quote_symbol }
}
return fee
}
@ -258,7 +258,9 @@ const ActivityFeedTable = ({
</span>
</Td>
<Td className="text-right font-mono">
{(Number(fee.value) * value).toFixed(5)}{' '}
{activity_type === 'perp'
? (Number(fee.value) * value).toFixed(5)
: fee.value}{' '}
<span className="font-body text-th-fgd-3">
{fee.symbol}
</span>

View File

@ -0,0 +1,133 @@
import { toUiDecimalsForQuote } from '@blockworks-foundation/mango-v4'
import useMangoAccount from 'hooks/useMangoAccount'
import useMangoGroup from 'hooks/useMangoGroup'
import { useTranslation } from 'next-i18next'
import { useTheme } from 'next-themes'
import { useMemo } from 'react'
import { Cell, Pie, PieChart } from 'recharts'
import { COLORS } from 'styles/colors'
import { formatCurrencyValue } from 'utils/numbers'
import FlipNumbers from 'react-flip-numbers'
import useLocalStorageState from 'hooks/useLocalStorageState'
import { ANIMATION_SETTINGS_KEY } from 'utils/constants'
import { INITIAL_ANIMATION_SETTINGS } from '@components/settings/AnimationSettings'
const AssetsLiabilities = ({ isMobile }: { isMobile: boolean }) => {
const { t } = useTranslation('account')
const { group } = useMangoGroup()
const { mangoAccount } = useMangoAccount()
const { theme } = useTheme()
const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS
)
const [assetsValue, assetsRatio, liabsValue, liabsRatio] = useMemo(() => {
if (!group || !mangoAccount) return [0, 0, 0, 0]
const assets = toUiDecimalsForQuote(mangoAccount.getAssetsValue(group))
const liabs = toUiDecimalsForQuote(mangoAccount.getLiabsValue(group))
const assetsRatio = (assets / (assets + liabs)) * 100
const liabsRatio = 100 - assetsRatio
return [assets, assetsRatio, liabs, liabsRatio]
}, [group, mangoAccount])
const chartData = useMemo(() => {
return [
{ name: 'assets', value: assetsValue },
{ name: 'liabilities', value: liabsValue },
]
}, [assetsValue, liabsValue])
const pieSizes = isMobile
? { size: 160, outerRadius: 80, innerRadius: 64 }
: { size: 80, outerRadius: 40, innerRadius: 30 }
const { size, outerRadius, innerRadius } = pieSizes
return (
<div className="flex flex-col items-center pt-4 md:flex-row md:space-x-4">
{mangoAccount ? (
<PieChart width={size} height={size}>
<Pie
cursor="pointer"
data={chartData}
dataKey="value"
cx="50%"
cy="50%"
outerRadius={outerRadius}
innerRadius={innerRadius}
minAngle={2}
startAngle={90}
endAngle={450}
>
{chartData.map((entry, index) => {
const fillColor =
entry.name === 'assets' ? COLORS.UP[theme] : COLORS.DOWN[theme]
return (
<Cell
key={`cell-${index}`}
fill={fillColor}
stroke={COLORS.BKG1[theme]}
strokeWidth={2}
/>
)
})}
</Pie>
</PieChart>
) : (
<div className="h-20 w-20 rounded-full ring-[8px] ring-inset ring-th-bkg-3" />
)}
<div className="mt-3 flex space-x-6 md:mt-0">
<div className="flex flex-col items-center md:items-start">
<p className="text-base">
{t('assets')}
<span className="ml-2 rounded border border-th-up px-1 py-0.5 text-xxs text-th-up">
{assetsRatio.toFixed()}%
</span>
</p>
{animationSettings['number-scroll'] ? (
<div className="font-display text-2xl text-th-fgd-1 sm:text-4xl">
<FlipNumbers
height={38}
width={30}
play
delay={0.05}
duration={1}
numbers={formatCurrencyValue(assetsValue, 2)}
/>
</div>
) : (
<p className="font-display text-2xl text-th-fgd-1 sm:text-4xl">
{formatCurrencyValue(assetsValue, 2)}
</p>
)}
</div>
<div className="flex flex-col items-center md:items-start">
<p className="text-base">
{t('liabilities')}
<span className="ml-2 rounded border border-th-down px-1 py-0.5 text-xxs text-th-down">
{liabsRatio.toFixed()}%
</span>
</p>
{animationSettings['number-scroll'] ? (
<div className="font-display text-2xl text-th-fgd-1 sm:text-4xl">
<FlipNumbers
height={38}
width={30}
play
delay={0.05}
duration={1}
numbers={formatCurrencyValue(liabsValue, 2)}
/>
</div>
) : (
<p className="font-display text-2xl text-th-fgd-1 sm:text-4xl">
{formatCurrencyValue(liabsValue, 2)}
</p>
)}
</div>
</div>
</div>
)
}
export default AssetsLiabilities

View File

@ -57,7 +57,7 @@ const CreateAccountForm = ({
undefined, // tokenCount
undefined, // serum3Count
8, // perpCount
8 // perpOoCount
10 // perpOoCount
)
if (tx) {
const pk = wallet.adapter.publicKey

View File

@ -93,7 +93,7 @@ const PnlHistoryModal = ({
<Modal isOpen={isOpen} onClose={onClose}>
<div className="h-96">
<div className="flex h-full flex-col">
<h2 className="mb-4">{t('pnl-history')}</h2>
<h2 className="mb-4 w-full text-center">{t('pnl-history')}</h2>
{loading ? (
<div className="space-y-1.5">
{[...Array(4)].map((x, i) => (

File diff suppressed because one or more lines are too long

View File

@ -86,7 +86,7 @@ const UserSetupModal = ({
undefined, // tokenCount
undefined, // serum3Count
8, // perpCount
8 // perpOoCount
10 // perpOoCount
)
actions.fetchMangoAccounts(publicKey)
if (tx) {

View File

@ -8,6 +8,7 @@ type ModalProps = {
isOpen: boolean
onClose: () => void
hideClose?: boolean
backdropBrightness?: number
}
function Modal({
@ -17,6 +18,7 @@ function Modal({
isOpen,
onClose,
hideClose,
backdropBrightness = 0.5,
}: ModalProps) {
const handleClose = () => {
if (disableOutsideClose) return
@ -30,13 +32,13 @@ function Modal({
className="relative z-40 overflow-y-auto"
>
<div
className={`fixed inset-0 backdrop-brightness-[0.3] ${
className={`fixed inset-0 backdrop-brightness-[${backdropBrightness}] ${
disableOutsideClose ? 'pointer-events-none' : ''
}`}
aria-hidden="true"
/>
<div
className={`fixed inset-0 flex items-center text-center sm:justify-center ${
className={`fixed inset-0 flex items-center sm:justify-center ${
fullScreen ? '' : 'sm:px-4'
}`}
>

View File

@ -4,11 +4,18 @@ import SwapForm from './SwapForm'
// import { useWallet } from '@solana/wallet-adapter-react'
import SwapInfoTabs from './SwapInfoTabs'
import dynamic from 'next/dynamic'
import SwapIntroModal from '@components/modals/SwapIntroModal'
import { useLocalStorage } from '@solana/wallet-adapter-react'
import { SHOW_SWAP_INTRO_MODAL } from 'utils/constants'
// import useLocalStorageState from 'hooks/useLocalStorageState'
// import { IS_ONBOARDED_KEY } from 'utils/constants'
const SwapTokenChart = dynamic(() => import('./SwapTokenChart'), { ssr: false })
const SwapPage = () => {
const [showSwapIntro, setShowSwapIntro] = useLocalStorage(
SHOW_SWAP_INTRO_MODAL,
true
)
// const { connected } = useWallet()
// const tourSettings = mangoStore((s) => s.settings.tours)
// const [isOnboarded] = useLocalStorageState(IS_ONBOARDED_KEY)
@ -26,9 +33,12 @@ const SwapPage = () => {
<SwapInfoTabs />
</div>
</div>
{/* {!tourSettings?.swap_tour_seen && isOnboarded && connected ? (
<SwapOnboardingTour />
) : null} */}
{showSwapIntro ? (
<SwapIntroModal
isOpen={showSwapIntro}
onClose={() => setShowSwapIntro(false)}
/>
) : null}
</>
)
}

View File

@ -1,10 +1,17 @@
import SideBadge from '@components/shared/SideBadge'
const PerpSideBadge = ({ basePosition }: { basePosition: number }) => {
return (
<>
{basePosition !== 0 ? (
<SideBadge side={basePosition > 0 ? 'buy' : 'sell'} isPerp />
<div
className={`inline-block rounded uppercase ${
basePosition > 0
? 'text-th-up md:border md:border-th-up'
: 'text-th-down md:border md:border-th-down'
}
uppercase md:-my-0.5 md:px-1.5 md:py-0.5 md:text-xs`}
>
{basePosition > 0 ? 'Long' : 'Short'}
</div>
) : (
'--'
)}

View File

@ -142,7 +142,7 @@ const formatTradeHistory = (
return tradeHistory.flat().map((event) => {
let trade
let market = selectedMarket
let time = 'Recent'
let time = ''
if (isSerumFillEvent(event)) {
trade = parseSerumEvent(event)
} else if (isPerpFillEvent(event)) {

View File

@ -104,7 +104,9 @@ const TradingViewChart = () => {
[theme]
)
const tvWidgetRef = useRef<IChartingLibraryWidget | null>(null)
const tvWidgetRef = useRef<IChartingLibraryWidget>()
const stablePriceButtonRef = useRef<HTMLElement>()
const orderLinesButtonRef = useRef<HTMLElement>()
const selectedMarket = useMemo(() => {
const group = mangoStore.getState().group
@ -151,30 +153,6 @@ const TradingViewChart = () => {
}
}, [selectedMarketName, spotOrPerp])
const createStablePriceButton = useCallback(() => {
const toggleStablePrice = (button: HTMLElement) => {
toggleShowStablePrice((prevState: boolean) => !prevState)
if (button.style.color === hexToRgb(COLORS.ACTIVE[theme])) {
button.style.color = COLORS.FGD4[theme]
} else {
button.style.color = COLORS.ACTIVE[theme]
}
}
const button = tvWidgetRef?.current?.createButton()
if (!button) {
return
}
button.textContent = 'SP'
if (showStablePriceLocalStorage) {
button.style.color = COLORS.ACTIVE[theme]
} else {
button.style.color = COLORS.FGD4[theme]
}
button.setAttribute('title', t('tv-chart:toggle-stable-price'))
button.addEventListener('click', () => toggleStablePrice(button))
}, [showStablePriceLocalStorage, theme, t])
useEffect(() => {
if (showStablePrice !== showStablePriceLocalStorage) {
toggleShowStablePriceLocalStorage(showStablePrice)
@ -183,6 +161,7 @@ const TradingViewChart = () => {
showStablePrice,
showStablePriceLocalStorage,
toggleShowStablePriceLocalStorage,
theme,
])
const drawStablePriceLine = useCallback(
@ -262,6 +241,7 @@ const TradingViewChart = () => {
showOrderLines,
showOrderLinesLocalStorage,
toggleShowOrderLinesLocalStorage,
theme,
])
const deleteLines = useCallback(() => {
@ -633,20 +613,46 @@ const TradingViewChart = () => {
[drawLinesForMarket, deleteLines, theme]
)
const createStablePriceButton = useCallback(() => {
const toggleStablePrice = (button: HTMLElement) => {
toggleShowStablePrice((prevState: boolean) => !prevState)
if (button.style.color === hexToRgb(COLORS.ACTIVE[theme])) {
button.style.color = COLORS.FGD4[theme]
} else {
button.style.color = COLORS.ACTIVE[theme]
}
}
const button = tvWidgetRef?.current?.createButton()
if (!button) {
return
}
button.textContent = 'SP'
button.setAttribute('title', t('tv-chart:toggle-stable-price'))
button.addEventListener('click', () => toggleStablePrice(button))
if (showStablePriceLocalStorage) {
button.style.color = COLORS.ACTIVE[theme]
} else {
button.style.color = COLORS.FGD4[theme]
}
stablePriceButtonRef.current = button
}, [theme, t, showStablePriceLocalStorage])
const createOLButton = useCallback(() => {
const button = tvWidgetRef?.current?.createButton()
if (!button) {
return
}
button.textContent = 'OL'
button.setAttribute('title', t('tv-chart:toggle-order-line'))
button.addEventListener('click', () => toggleOrderLines(button))
if (showOrderLinesLocalStorage) {
button.style.color = COLORS.ACTIVE[theme]
} else {
button.style.color = COLORS.FGD4[theme]
}
button.setAttribute('title', t('tv-chart:toggle-order-line'))
button.addEventListener('click', () => toggleOrderLines(button))
}, [t, theme, toggleOrderLines, showOrderLinesLocalStorage])
orderLinesButtonRef.current = button
}, [t, toggleOrderLines, showOrderLinesLocalStorage, theme])
useEffect(() => {
if (window) {
@ -733,45 +739,25 @@ const TradingViewChart = () => {
}
console.log('creating new chart')
const tvWidget = new widget(widgetOptions)
tvWidgetRef.current = tvWidget
tvWidgetRef.current.onChartReady(function () {
createOLButton()
createStablePriceButton()
// if (showOrderLines) {
// const openOrders = mangoStore.getState().mangoAccount.openOrders
// deleteLines()
// drawLinesForMarket(openOrders)
// }
// if (showStablePrice && stablePrice) {
// const set = mangoStore.getState().set
// const elementId = drawStablePriceLine(stablePrice)
// set((s) => {
// s.tradingView.stablePriceLine = elementId
// })
// }
tvWidgetRef.current.onChartReady(() => {
setChartReady(true)
})
//eslint-disable-next-line
}
}, [
createOLButton,
createStablePriceButton,
selectedMarket,
theme,
spotOrPerp,
defaultProps,
deleteLines,
drawLinesForMarket,
showOrderLines,
showStablePrice,
// stablePrice,
drawStablePriceLine,
setChartReady,
isMobile,
])
}, [selectedMarket, theme, spotOrPerp, defaultProps, isMobile])
// draw custom buttons when chart is ready
useEffect(() => {
if (
chartReady &&
!orderLinesButtonRef.current &&
!stablePriceButtonRef.current
) {
createOLButton()
createStablePriceButton()
}
}, [createOLButton, chartReady, createStablePriceButton])
// update order lines if a user's open orders change
useEffect(() => {
@ -780,51 +766,53 @@ const TradingViewChart = () => {
subscription = mangoStore.subscribe(
(state) => state.mangoAccount.openOrders,
(openOrders) => {
const orderLines = mangoStore.getState().tradingView.orderLines
tvWidgetRef.current?.onChartReady(() => {
let matchingOrderLines = 0
let openOrdersForMarket = 0
if (showOrderLines) {
const orderLines = mangoStore.getState().tradingView.orderLines
tvWidgetRef.current?.onChartReady(() => {
let matchingOrderLines = 0
let openOrdersForMarket = 0
const oOrders = Object.entries(openOrders).map(
([marketPk, orders]) => ({
orders,
marketPk,
})
)
const oOrders = Object.entries(openOrders).map(
([marketPk, orders]) => ({
orders,
marketPk,
})
)
for (const [key] of orderLines) {
oOrders?.forEach(({ orders }) => {
for (const order of orders) {
if (order.orderId == key) {
matchingOrderLines += 1
for (const [key] of orderLines) {
oOrders?.forEach(({ orders }) => {
for (const order of orders) {
if (order.orderId == key) {
matchingOrderLines += 1
}
}
})
}
const selectedMarket =
mangoStore.getState().selectedMarket.current
const selectedMarketPk =
selectedMarket instanceof Serum3Market
? selectedMarket?.serumMarketExternal.toString()
: selectedMarket?.publicKey.toString()
oOrders?.forEach(({ marketPk, orders }) => {
if (marketPk === selectedMarketPk) {
openOrdersForMarket = orders.length
}
})
}
const selectedMarket = mangoStore.getState().selectedMarket.current
const selectedMarketPk =
selectedMarket instanceof Serum3Market
? selectedMarket?.serumMarketExternal.toString()
: selectedMarket?.publicKey.toString()
oOrders?.forEach(({ marketPk, orders }) => {
if (marketPk === selectedMarketPk) {
openOrdersForMarket = orders.length
}
tvWidgetRef.current?.activeChart().dataReady(() => {
if (
matchingOrderLines !== openOrdersForMarket ||
orderLines?.size !== matchingOrderLines
) {
deleteLines()
drawLinesForMarket(openOrders)
}
})
})
tvWidgetRef.current?.activeChart().dataReady(() => {
if (
(showOrderLines &&
matchingOrderLines !== openOrdersForMarket) ||
orderLines?.size !== matchingOrderLines
) {
deleteLines()
drawLinesForMarket(openOrders)
}
})
})
}
}
)
}

View File

@ -53,7 +53,6 @@ const ConnectedMenu = () => {
}
})
disconnect()
wallet?.adapter.disconnect()
notify({
type: 'info',
title: t('wallet-disconnected'),

View File

@ -2,7 +2,6 @@ import { SolanaMobileWalletAdapter } from '@solana-mobile/wallet-adapter-mobile'
import { WalletName, WalletReadyState } from '@solana/wallet-adapter-base'
import { useWallet, Wallet } from '@solana/wallet-adapter-react'
import { StandardWalletAdapter } from '@solana/wallet-standard-wallet-adapter-base'
import { useTranslation } from 'next-i18next'
import React, {
createContext,
ReactNode,
@ -11,7 +10,6 @@ import React, {
useEffect,
useMemo,
} from 'react'
import mangoStore from '@store/mangoStore'
import { notify } from 'utils/notifications'
import useLocalStorageState from 'hooks/useLocalStorageState'
@ -20,7 +18,6 @@ interface EnhancedWalletContextState {
preselectedWalletName: string
handleSelect: (name: WalletName | null) => void
handleConnect: () => Promise<void>
handleDisconnect: () => Promise<void>
}
const EnhancedWalletContext = createContext<EnhancedWalletContextState>(
@ -36,9 +33,7 @@ export default function EnhancedWalletProvider({
}: {
children: ReactNode
}) {
const { wallets, select, wallet, connect, disconnect } = useWallet()
const { t } = useTranslation(['common', 'profile'])
const set = mangoStore((s) => s.set)
const { wallets, select, wallet, connect } = useWallet()
const displayedWallets = useMemo(
() =>
@ -74,6 +69,17 @@ export default function EnhancedWalletProvider({
}
}, [wallet, setPreselectedWalletName])
useEffect(() => {
if (!wallet && preselectedWalletName) {
const wallet = wallets.find(
(w) => w.adapter.name === preselectedWalletName
)
if (wallet) {
select(wallet.adapter.name)
}
}
}, [wallet, preselectedWalletName, wallets, select])
const handleSelect = useCallback(
(name: WalletName | null) => {
setPreselectedWalletName(name)
@ -105,7 +111,7 @@ export default function EnhancedWalletProvider({
adapter.readyState === WalletReadyState.Installed ||
adapter.readyState === WalletReadyState.Loadable
) {
select(adapter.name)
await select(adapter.name)
} else {
notify({
title: `${adapter.name} Error`,
@ -126,18 +132,6 @@ export default function EnhancedWalletProvider({
setPreselectedWalletName,
])
const handleDisconnect = useCallback(async () => {
set((state) => {
state.mangoAccounts = []
state.mangoAccount.current = undefined
})
notify({
type: 'info',
title: t('wallet-disconnected'),
})
await disconnect()
}, [set, t, disconnect])
return (
<EnhancedWalletContext.Provider
value={{
@ -145,7 +139,6 @@ export default function EnhancedWalletProvider({
preselectedWalletName,
handleSelect,
handleConnect,
handleDisconnect,
}}
>
{children}

View File

@ -82,6 +82,7 @@ export default function useLocalStorageState<T = any>(
try {
return JSON.parse(stringState)
} catch (e) {
console.log('Error parsing JSON from localStorage', e)
return stringState
}
}

View File

@ -1,4 +1,7 @@
{
"assets": "Assets",
"assets-liabilities": "Assets & Liabilities",
"liabilities": "Liabilities",
"no-pnl-history": "No PnL History",
"pnl-chart": "PnL Chart",
"pnl-history": "PnL History",

View File

@ -56,11 +56,13 @@
"delegate-account-info": "Account delegated to {{address}}",
"delegate-desc": "Delegate your Mango account to another wallet address",
"delegate-placeholder": "Enter a wallet address to delegate to",
"delete": "Delete",
"deposit": "Deposit",
"deposit-amount": "Deposit Amount",
"deposit-more-sol": "Your SOL wallet balance is too low. Add more to pay for transactions",
"deposit-rate": "Deposit APR",
"disconnect": "Disconnect",
"edit": "Edit",
"edit-account": "Edit Account Name",
"edit-profile-image": "Edit Profile Image",
"explorer": "Explorer",
@ -88,6 +90,7 @@
"max": "Max",
"max-borrow": "Max Borrow",
"more": "More",
"new": "New",
"new-account": "New Account",
"new-account-failed": "Failed to create account",
"new-account-success": "Your new account is ready 😎",

View File

@ -1,4 +1,7 @@
{
"assets": "Assets",
"assets-liabilities": "Assets & Liabilities",
"liabilities": "Liabilities",
"no-pnl-history": "No PnL History",
"pnl-chart": "PnL Chart",
"pnl-history": "PnL History",

View File

@ -56,11 +56,13 @@
"delegate-account-info": "Account delegated to {{address}}",
"delegate-desc": "Delegate your Mango account to another wallet address",
"delegate-placeholder": "Enter a wallet address to delegate to",
"delete": "Delete",
"deposit": "Deposit",
"deposit-amount": "Deposit Amount",
"deposit-more-sol": "Your SOL wallet balance is too low. Add more to pay for transactions",
"deposit-rate": "Deposit APR",
"disconnect": "Disconnect",
"edit": "Edit",
"edit-account": "Edit Account Name",
"edit-profile-image": "Edit Profile Image",
"explorer": "Explorer",
@ -87,6 +89,7 @@
"max": "Max",
"max-borrow": "Max Borrow",
"more": "More",
"new": "New",
"new-account": "New Account",
"new-account-failed": "Failed to create account",
"new-account-success": "Your new account is ready 😎",

View File

@ -1,4 +1,7 @@
{
"assets": "Assets",
"assets-liabilities": "Assets & Liabilities",
"liabilities": "Liabilities",
"no-pnl-history": "No PnL History",
"pnl-chart": "PnL Chart",
"pnl-history": "PnL History",

View File

@ -56,11 +56,13 @@
"delegate-account-info": "Account delegated to {{address}}",
"delegate-desc": "Delegate your Mango account to another wallet address",
"delegate-placeholder": "Enter a wallet address to delegate to",
"delete": "Delete",
"deposit": "Deposit",
"deposit-amount": "Deposit Amount",
"deposit-more-sol": "Your SOL wallet balance is too low. Add more to pay for transactions",
"deposit-rate": "Deposit APR",
"disconnect": "Disconnect",
"edit": "Edit",
"edit-account": "Edit Account Name",
"edit-profile-image": "Edit Profile Image",
"explorer": "Explorer",
@ -87,6 +89,7 @@
"max": "Max",
"max-borrow": "Max Borrow",
"more": "More",
"new": "New",
"new-account": "New Account",
"new-account-failed": "Failed to create account",
"new-account-success": "Your new account is ready 😎",

View File

@ -1,4 +1,7 @@
{
"assets": "Assets",
"assets-liabilities": "Assets & Liabilities",
"liabilities": "Liabilities",
"no-pnl-history": "No PnL History",
"pnl-chart": "PnL Chart",
"pnl-history": "PnL History",

View File

@ -56,11 +56,13 @@
"delegate-account-info": "Account delegated to {{address}}",
"delegate-desc": "Delegate your Mango account to another wallet address",
"delegate-placeholder": "Enter a wallet address to delegate to",
"delete": "Delete",
"deposit": "Deposit",
"deposit-amount": "Deposit Amount",
"deposit-more-sol": "Your SOL wallet balance is too low. Add more to pay for transactions",
"deposit-rate": "Deposit APR",
"disconnect": "Disconnect",
"edit": "Edit",
"edit-account": "Edit Account Name",
"edit-profile-image": "Edit Profile Image",
"explorer": "Explorer",
@ -87,6 +89,7 @@
"max": "Max",
"max-borrow": "Max Borrow",
"more": "More",
"new": "New",
"new-account": "New Account",
"new-account-failed": "Failed to create account",
"new-account-success": "Your new account is ready 😎",

View File

@ -1,4 +1,7 @@
{
"assets": "Assets",
"assets-liabilities": "Assets & Liabilities",
"liabilities": "Liabilities",
"no-pnl-history": "No PnL History",
"pnl-chart": "PnL Chart",
"pnl-history": "PnL History",

View File

@ -56,11 +56,13 @@
"delegate-account-info": "Account delegated to {{address}}",
"delegate-desc": "Delegate your Mango account to another wallet address",
"delegate-placeholder": "Enter a wallet address to delegate to",
"delete": "Delete",
"deposit": "Deposit",
"deposit-amount": "Deposit Amount",
"deposit-more-sol": "Your SOL wallet balance is too low. Add more to pay for transactions",
"deposit-rate": "Deposit APR",
"disconnect": "Disconnect",
"edit": "Edit",
"edit-account": "Edit Account Name",
"edit-profile-image": "Edit Profile Image",
"explorer": "Explorer",
@ -87,6 +89,7 @@
"max": "Max",
"max-borrow": "Max Borrow",
"more": "More",
"new": "New",
"new-account": "New Account",
"new-account-failed": "Failed to create account",
"new-account-success": "Your new account is ready 😎",

View File

@ -622,11 +622,15 @@ const mangoStore = create<MangoStore>()(
if (!selectedMangoAccount || !selectedAccountIsNotInAccountsList) {
const lastAccount = localStorage.getItem(LAST_ACCOUNT_KEY)
newSelectedMangoAccount = mangoAccounts[0]
let lastViewedAccount
if (typeof lastAccount === 'string') {
const lastViewedAccount = mangoAccounts.find(
(m) => m.publicKey.toString() === lastAccount
)
try {
lastViewedAccount = mangoAccounts.find(
(m) => m.publicKey.toString() === JSON.parse(lastAccount)
)
} catch (e) {
console.error('Error parsing last account', e)
}
newSelectedMangoAccount = lastViewedAccount || mangoAccounts[0]
}
}

View File

@ -1,4 +1,4 @@
export const LAST_ACCOUNT_KEY = 'mangoAccount-0.2'
export const LAST_ACCOUNT_KEY = 'mangoAccount-0.3'
export const CLIENT_TX_TIMEOUT = 90000
@ -47,6 +47,8 @@ export const SHOW_STABLE_PRICE_KEY = 'showStablePriceKey-0.1'
export const SHOW_ORDER_LINES_KEY = 'showOrderLines-0.1'
export const SHOW_SWAP_INTRO_MODAL = 'showSwapModal-0.1'
// Unused
export const PROFILE_CATEGORIES = [
'borrower',
@ -68,9 +70,9 @@ export const DEFAULT_MARKET_NAME = 'SOL/USDC'
export const MIN_SOL_BALANCE = 0.001
export const ACCOUNT_ACTION_MODAL_HEIGHT = '506px'
export const ACCOUNT_ACTION_MODAL_HEIGHT = '462px'
export const ACCOUNT_ACTION_MODAL_INNER_HEIGHT = '444px'
export const ACCOUNT_ACTION_MODAL_INNER_HEIGHT = '400px'
export const TRADE_VOLUME_ALERT_KEY = 'tradeVolumeAlert-0.1'