Merge FundAccount and AccountFund (#431)

*  Merge FundAccount and AccountFund

* fix build

* 🐛 fundAccount not showing, small typos/text corrections
This commit is contained in:
Bob van der Helm 2023-09-07 10:20:19 +02:00 committed by GitHub
parent d3c73303c5
commit 93e725fc59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 143 additions and 263 deletions

View File

@ -41,4 +41,4 @@ describe('<AccountDetails />', () => {
const container = screen.queryByTestId('account-details')
expect(container).not.toBeInTheDocument()
})
})
})

View File

@ -12,7 +12,7 @@ import { useLocation, useNavigate } from 'react-router-dom'
import { getAmountChangeColor } from 'components/Account/AccountBalancesTable/functions'
import useAccountBalanceData from 'components/Account/AccountBalancesTable/useAccountBalanceData'
import AccountFund from 'components/Account/AccountFund'
import AccountFundFullPage from 'components/Account/AccountFund/AccountFundFullPage'
import ActionButton from 'components/Button/ActionButton'
import DisplayCurrency from 'components/DisplayCurrency'
import { FormattedNumber } from 'components/FormattedNumber'
@ -147,7 +147,7 @@ export default function Index(props: Props) {
}
useStore.setState({
focusComponent: {
component: <AccountFund />,
component: <AccountFundFullPage />,
onClose: () => {
useStore.setState({ getStartedModal: true })
},

View File

@ -1,7 +1,7 @@
import { useCallback, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import AccountFund from 'components/Account/AccountFund'
import AccountFundFullPage from 'components/Account/AccountFund/AccountFundFullPage'
import FullOverlayContent from 'components/FullOverlayContent'
import WalletSelect from 'components/Wallet/WalletSelect'
import useToggle from 'hooks/useToggle'
@ -27,7 +27,7 @@ export default function AccountCreateFirst() {
navigate(getRoute(getPage(pathname), address, accountId))
useStore.setState({
focusComponent: {
component: <AccountFund />,
component: <AccountFundFullPage />,
onClose: () => {
useStore.setState({ getStartedModal: true })
},
@ -51,4 +51,4 @@ export default function AccountCreateFirst() {
docs='account'
/>
)
}
}

View File

@ -154,4 +154,4 @@ function AccountDetails(props: Props) {
</div>
</div>
)
}
}

View File

@ -1,20 +1,18 @@
import classNames from 'classnames'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import Button from 'components/Button'
import Card from 'components/Card'
import DepositCapMessage from 'components/DepositCapMessage'
import FullOverlayContent from 'components/FullOverlayContent'
import { Plus } from 'components/Icons'
import { ArrowRight, Plus } from 'components/Icons'
import SwitchAutoLend from 'components/Switch/SwitchAutoLend'
import Text from 'components/Text'
import TokenInputWithSlider from 'components/TokenInput/TokenInputWithSlider'
import WalletBridges from 'components/Wallet/WalletBridges'
import { BN_ZERO } from 'constants/math'
import useAccounts from 'hooks/useAccounts'
import useCurrentAccount from 'hooks/useCurrentAccount'
import useAutoLend from 'hooks/useAutoLend'
import useMarketAssets from 'hooks/useMarketAssets'
import useToggle from 'hooks/useToggle'
import { useUpdatedAccount } from 'hooks/useUpdatedAccount'
import useWalletBalances from 'hooks/useWalletBalances'
import useStore from 'store'
import { BNCoin } from 'types/classes/BNCoin'
@ -24,56 +22,78 @@ import { defaultFee } from 'utils/constants'
import { getCapLeftWithBuffer } from 'utils/generic'
import { BN } from 'utils/helpers'
export default function AccountFund() {
const address = useStore((s) => s.address)
interface Props {
account?: Account
address: string
accountId: string
isFullPage?: boolean
}
export default function AccountFundContent(props: Props) {
const deposit = useStore((s) => s.deposit)
const walletAssetModal = useStore((s) => s.walletAssetsModal)
const { accountId } = useParams()
const { data: accounts } = useAccounts(address)
const currentAccount = useCurrentAccount()
const [isFunding, setIsFunding] = useToggle(false)
const [selectedAccountId, setSelectedAccountId] = useState<null | string>(null)
const [fundingAssets, setFundingAssets] = useState<BNCoin[]>([])
const { data: walletBalances } = useWalletBalances(address)
const { data: marketAssets } = useMarketAssets()
const { data: walletBalances } = useWalletBalances(props.address)
const { autoLendEnabledAccountIds } = useAutoLend()
const [isLending, toggleIsLending] = useToggle(false)
const { simulateDeposits } = useUpdatedAccount(props.account)
const baseAsset = getBaseAsset()
const hasAssetSelected = fundingAssets.length > 0
const hasFundingAssets =
fundingAssets.length > 0 && fundingAssets.every((a) => a.toCoin().amount !== '0')
const { data: marketAssets } = useMarketAssets()
const [isLending, toggleIsLending] = useToggle(false)
const baseBalance = useMemo(
() => walletBalances.find(byDenom(baseAsset.denom))?.amount ?? '0',
[walletBalances, baseAsset],
)
const balances = walletBalances.map((coin) => new BNCoin(coin))
const selectedDenoms = useMemo(() => {
return walletAssetModal?.selectedDenoms ?? []
}, [walletAssetModal?.selectedDenoms])
const handleClick = useCallback(async () => {
setIsFunding(true)
if (!accountId) return
const result = await deposit({
accountId,
coins: fundingAssets,
lend: isLending,
})
setIsFunding(false)
if (result) useStore.setState({ focusComponent: null, walletAssetsModal: null })
}, [setIsFunding, accountId, deposit, fundingAssets, isLending])
const baseBalance = useMemo(
() => walletBalances.find(byDenom(baseAsset.denom))?.amount ?? '0',
[walletBalances, baseAsset],
)
const handleSelectAssetsClick = useCallback(() => {
useStore.setState({
walletAssetsModal: {
isOpen: true,
selectedDenoms,
isBorrow: false,
},
})
}, [selectedDenoms])
const handleClick = useCallback(async () => {
setIsFunding(true)
if (!props.accountId) return
const result = await deposit({
accountId: props.accountId,
coins: fundingAssets,
lend: isLending,
})
setIsFunding(false)
if (result)
useStore.setState({
fundAndWithdrawModal: null,
walletAssetsModal: null,
focusComponent: null,
})
}, [setIsFunding, props.accountId, deposit, fundingAssets, isLending])
useEffect(() => {
if (BN(baseBalance).isLessThan(defaultFee.amount[0].amount)) {
useStore.setState({ focusComponent: { component: <WalletBridges /> } })
}
}, [baseBalance])
useEffect(() => {
simulateDeposits(isLending ? 'lend' : 'deposit', fundingAssets)
}, [isLending, fundingAssets, simulateDeposits])
useEffect(() => {
const currentSelectedDenom = fundingAssets.map((asset) => asset.denom)
@ -101,15 +121,8 @@ export default function AccountFund() {
}, [])
useEffect(() => {
if (BN(baseBalance).isLessThan(defaultFee.amount[0].amount)) {
useStore.setState({ focusComponent: { component: <WalletBridges /> } })
}
}, [baseBalance])
useEffect(() => {
if (accounts && !selectedAccountId && accountId)
setSelectedAccountId(currentAccount?.id ?? accountId)
}, [accounts, selectedAccountId, accountId, currentAccount])
toggleIsLending(autoLendEnabledAccountIds.includes(props.accountId))
}, [props.accountId, autoLendEnabledAccountIds, toggleIsLending])
const depositCapReachedCoins = useMemo(() => {
const depositCapReachedCoins: BNCoin[] = []
@ -126,15 +139,9 @@ export default function AccountFund() {
return depositCapReachedCoins
}, [fundingAssets, marketAssets])
if (!selectedAccountId) return null
return (
<FullOverlayContent
title={`Fund Credit Account #${selectedAccountId}`}
copy='In order to start trading with this account, you need to deposit funds.'
docs='fund'
>
<Card className='w-full p-6 bg-white/5'>
<>
<div>
{!hasAssetSelected && <Text>Please select an asset.</Text>}
{fundingAssets.map((coin) => {
const asset = getAssetByDenom(coin.denom) as Asset
@ -143,7 +150,10 @@ export default function AccountFund() {
return (
<div
key={asset.symbol}
className='w-full p-4 border rounded-base border-white/20 bg-white/5'
className={classNames(
'w-full mb-4',
props.isFullPage && 'w-full p-4 border rounded-base border-white/20 bg-white/5',
)}
>
<TokenInputWithSlider
asset={asset}
@ -175,20 +185,21 @@ export default function AccountFund() {
/>
<SwitchAutoLend
className='pt-4 mt-4 border border-transparent border-t-white/10'
accountId={selectedAccountId}
accountId={props.accountId}
value={isLending}
onChange={toggleIsLending}
/>
<Button
className='w-full mt-4'
text='Fund account'
color='tertiary'
disabled={!hasFundingAssets || depositCapReachedCoins.length > 0}
showProgressIndicator={isFunding}
onClick={handleClick}
size='lg'
/>
</Card>
</FullOverlayContent>
</div>
<Button
className='w-full mt-4'
text='Fund account'
disabled={!hasFundingAssets || depositCapReachedCoins.length > 0}
showProgressIndicator={isFunding}
onClick={handleClick}
color={props.isFullPage ? 'tertiary' : undefined}
size={props.isFullPage ? 'lg' : undefined}
rightIcon={props.isFullPage ? undefined : <ArrowRight />}
/>
</>
)
}
}

View File

@ -0,0 +1,42 @@
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import AccountFundContent from 'components/Account/AccountFund/AccountFundContent'
import Card from 'components/Card'
import FullOverlayContent from 'components/FullOverlayContent'
import useAccounts from 'hooks/useAccounts'
import useCurrentAccount from 'hooks/useCurrentAccount'
import useStore from 'store'
export default function AccountFundFullPage() {
const address = useStore((s) => s.address)
const { accountId } = useParams()
const { data: accounts } = useAccounts(address)
const currentAccount = useCurrentAccount()
const [selectedAccountId, setSelectedAccountId] = useState<null | string>(null)
useEffect(() => {
if (accounts && !selectedAccountId && accountId)
setSelectedAccountId(currentAccount?.id ?? accountId)
}, [accounts, selectedAccountId, accountId, currentAccount])
if (!selectedAccountId || !address) return null
return (
<FullOverlayContent
title={`Fund Credit Account #${selectedAccountId}`}
copy='In order to start trading with this account, you need to deposit funds.'
docs='fund'
>
<Card className='w-full p-6 bg-white/5'>
<AccountFundContent
account={currentAccount}
address={address}
accountId={selectedAccountId}
isFullPage
/>
</Card>
</FullOverlayContent>
)
}

View File

@ -2,7 +2,7 @@ import classNames from 'classnames'
import { useCallback, useEffect } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import AccountFund from 'components/Account/AccountFund'
import AccountFundFullPage from 'components/Account/AccountFund/AccountFundFullPage'
import AccountStats from 'components/Account/AccountStats'
import Button from 'components/Button'
import Card from 'components/Card'
@ -94,7 +94,7 @@ export default function AccountList(props: Props) {
if (positionBalance.isLessThanOrEqualTo(0)) {
useStore.setState({
focusComponent: {
component: <AccountFund />,
component: <AccountFundFullPage />,
onClose: () => {
useStore.setState({ getStartedModal: true })
},
@ -143,4 +143,4 @@ export default function AccountList(props: Props) {
})}
</div>
)
}
}

View File

@ -3,7 +3,7 @@ import { useCallback, useEffect } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import AccountCreateFirst from 'components/Account/AccountCreateFirst'
import AccountFund from 'components/Account/AccountFund'
import AccountFund from 'components/Account/AccountFund/AccountFundFullPage'
import AccountList from 'components/Account/AccountList'
import Button from 'components/Button'
import { CircularProgress } from 'components/CircularProgress'
@ -164,4 +164,4 @@ export default function AccountMenuContent(props: Props) {
)
}
export { ACCOUNT_MENU_BUTTON_ID }
export { ACCOUNT_MENU_BUTTON_ID }

View File

@ -126,4 +126,4 @@ function Item(props: ItemProps) {
<div className='flex h-4.5 w-full'>{props.children}</div>
</div>
)
}
}

View File

@ -24,7 +24,7 @@ export default function AccoundDeleteAlertDialog(props: Props) {
title,
description,
negativeButton: {
text: 'Close',
text: 'Cancel',
icon: <Enter />,
onClick: closeHandler,
},
@ -33,4 +33,4 @@ export default function AccoundDeleteAlertDialog(props: Props) {
}, [showAlertDialog, title, description, closeHandler, positiveButton])
return null
}
}

View File

@ -95,7 +95,7 @@ function AccountDeleteModal(props: Props) {
description='Deleting your credit account is irreversible.'
closeHandler={closeDeleteAccountModal}
positiveButton={{
text: 'Close Positions',
text: 'Delete Account',
icon: <ArrowRight />,
isAsync: true,
onClick: deleteAccountHandler,
@ -140,4 +140,4 @@ function AccountDeleteModal(props: Props) {
</div>
</Modal>
)
}
}

View File

@ -1,25 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import Button from 'components/Button'
import DepositCapMessage from 'components/DepositCapMessage'
import { ArrowRight, Plus } from 'components/Icons'
import SwitchAutoLend from 'components/Switch/SwitchAutoLend'
import Text from 'components/Text'
import TokenInputWithSlider from 'components/TokenInput/TokenInputWithSlider'
import WalletBridges from 'components/Wallet/WalletBridges'
import { BN_ZERO } from 'constants/math'
import useAutoLend from 'hooks/useAutoLend'
import useMarketAssets from 'hooks/useMarketAssets'
import useToggle from 'hooks/useToggle'
import { useUpdatedAccount } from 'hooks/useUpdatedAccount'
import useWalletBalances from 'hooks/useWalletBalances'
import AccountFundContent from 'components/Account/AccountFund/AccountFundContent'
import useStore from 'store'
import { BNCoin } from 'types/classes/BNCoin'
import { byDenom } from 'utils/array'
import { getAssetByDenom, getBaseAsset } from 'utils/assets'
import { defaultFee } from 'utils/constants'
import { getCapLeftWithBuffer } from 'utils/generic'
import { BN } from 'utils/helpers'
interface Props {
account: Account
@ -27,161 +7,10 @@ interface Props {
export default function FundAccount(props: Props) {
const { account } = props
const accountId = account.id
const address = useStore((s) => s.address)
const deposit = useStore((s) => s.deposit)
const walletAssetModal = useStore((s) => s.walletAssetsModal)
const [isFunding, setIsFunding] = useToggle(false)
const [fundingAssets, setFundingAssets] = useState<BNCoin[]>([])
const { data: walletBalances } = useWalletBalances(address)
const baseAsset = getBaseAsset()
const hasAssetSelected = fundingAssets.length > 0
const hasFundingAssets =
fundingAssets.length > 0 && fundingAssets.every((a) => a.toCoin().amount !== '0')
const { autoLendEnabledAccountIds } = useAutoLend()
const [isLending, toggleIsLending] = useToggle(false)
const { simulateDeposits } = useUpdatedAccount(account)
const { data: marketAssets } = useMarketAssets()
const baseBalance = useMemo(
() => walletBalances.find(byDenom(baseAsset.denom))?.amount ?? '0',
[walletBalances, baseAsset],
)
const accountId = account.id
if (!address) return null
const balances = walletBalances.map((coin) => new BNCoin(coin))
const selectedDenoms = useMemo(() => {
return walletAssetModal?.selectedDenoms ?? []
}, [walletAssetModal?.selectedDenoms])
const handleClick = useCallback(async () => {
setIsFunding(true)
if (!accountId) return
const result = await deposit({
accountId,
coins: fundingAssets,
lend: isLending,
})
setIsFunding(false)
if (result) useStore.setState({ fundAndWithdrawModal: null, walletAssetsModal: null })
}, [setIsFunding, accountId, deposit, fundingAssets, isLending])
const handleSelectAssetsClick = useCallback(() => {
useStore.setState({
walletAssetsModal: {
isOpen: true,
selectedDenoms,
isBorrow: false,
},
})
}, [selectedDenoms])
useEffect(() => {
toggleIsLending(autoLendEnabledAccountIds.includes(accountId))
}, [accountId, autoLendEnabledAccountIds, toggleIsLending])
useEffect(() => {
const currentSelectedDenom = fundingAssets.map((asset) => asset.denom)
if (
selectedDenoms.every((denom) => currentSelectedDenom.includes(denom)) &&
selectedDenoms.length === currentSelectedDenom.length
)
return
const newFundingAssets = selectedDenoms.map((denom) =>
BNCoin.fromDenomAndBigNumber(denom, BN(fundingAssets.find(byDenom(denom))?.amount ?? '0')),
)
setFundingAssets(newFundingAssets)
}, [selectedDenoms, fundingAssets])
const updateFundingAssets = useCallback((amount: BigNumber, denom: string) => {
setFundingAssets((fundingAssets) => {
const updateIdx = fundingAssets.findIndex(byDenom(denom))
if (updateIdx === -1) return fundingAssets
fundingAssets[updateIdx].amount = amount
return [...fundingAssets]
})
}, [])
useEffect(() => {
simulateDeposits(isLending ? 'lend' : 'deposit', fundingAssets)
}, [isLending, fundingAssets, simulateDeposits])
useEffect(() => {
if (BN(baseBalance).isLessThan(defaultFee.amount[0].amount)) {
useStore.setState({ focusComponent: { component: <WalletBridges /> } })
}
}, [baseBalance])
const depositCapReachedCoins = useMemo(() => {
const depositCapReachedCoins: BNCoin[] = []
fundingAssets.forEach((asset) => {
const marketAsset = marketAssets.find(byDenom(asset.denom))
if (!marketAsset) return
const capLeft = getCapLeftWithBuffer(marketAsset.cap)
if (asset.amount.isLessThanOrEqualTo(capLeft)) return
depositCapReachedCoins.push(BNCoin.fromDenomAndBigNumber(asset.denom, capLeft))
})
return depositCapReachedCoins
}, [fundingAssets, marketAssets])
return (
<>
<div className='flex flex-wrap items-start'>
{!hasAssetSelected && <Text>Please select an asset.</Text>}
{fundingAssets.map((coin) => {
const asset = getAssetByDenom(coin.denom) as Asset
const balance = balances.find(byDenom(coin.denom))?.amount ?? BN_ZERO
return (
<TokenInputWithSlider
key={coin.denom}
asset={asset}
onChange={(amount) => updateFundingAssets(amount, asset.denom)}
amount={coin.amount ?? BN_ZERO}
max={balance}
balances={balances}
maxText='Max'
disabled={isFunding}
className='w-full mb-4'
/>
)
})}
<Button
className='w-full mt-4'
text='Select assets'
color='tertiary'
rightIcon={<Plus />}
iconClassName='w-3'
onClick={handleSelectAssetsClick}
disabled={isFunding}
/>
<DepositCapMessage
action='fund'
coins={depositCapReachedCoins}
className='pr-4 py-2 mt-4'
showIcon
/>
<SwitchAutoLend
className='pt-4 mt-4 border border-transparent border-t-white/10'
accountId={accountId}
onChange={toggleIsLending}
value={isLending}
/>
</div>
<Button
className='w-full mt-4'
text='Fund account'
rightIcon={<ArrowRight />}
disabled={!hasFundingAssets || depositCapReachedCoins.length > 0}
showProgressIndicator={isFunding}
onClick={handleClick}
/>
</>
)
return <AccountFundContent account={account} address={address} accountId={accountId} />
}

View File

@ -1,10 +1,7 @@
import { useState } from 'react'
import AccountSummary from 'components/Account/AccountSummary'
import Card from 'components/Card'
import FundAccount from 'components/Modals/FundWithdraw/FundAccount'
import WithdrawFromAccount from 'components/Modals/FundWithdraw/WithdrawFromAccount'
import useStore from 'store'
interface Props {
account: Account

View File

@ -43,4 +43,4 @@ export default function AccountDetailsCard() {
const className = {
tabWrapper: 'flex w-full items-center bg-white/10 pt-4 pl-4 font-semibold',
tab: 'mr-4 pb-3 cursor-pointer select-none flex flex-row border-b-2 border-pink border-solid',
}
}

View File

@ -255,4 +255,4 @@ export class OsmosisTheGraphDataFeed implements IDatafeedChartApi {
unsubscribeBars(listenerGuid: string): void {
// TheGraph doesn't support websockets yet
}
}
}

View File

@ -20,6 +20,7 @@ import { formatAmountWithSymbol } from 'utils/formatters'
import getTokenOutFromSwapResponse from 'utils/getTokenOutFromSwapResponse'
import { BN } from 'utils/helpers'
function generateExecutionMessage(
sender: string | undefined = '',
contract: string,
@ -243,7 +244,7 @@ export default function createBroadcastSlice(
.join(' and ')
handleResponseMessages(
response,
`Deposited ${options.lend ? 'and lent ' : ''}${depositString} to Credit Credit Account ${
`Deposited ${options.lend ? 'and lent ' : ''}${depositString} to Credit Account ${
options.accountId
}`,
)
@ -533,4 +534,4 @@ export default function createBroadcastSlice(
}
},
}
}
}