2023-10-23 12:04:17 +00:00
|
|
|
import { LocalStorageKeys } from 'constants/localStorageKeys'
|
2023-07-05 14:43:11 +00:00
|
|
|
import useCurrentAccount from 'hooks/useCurrentAccount'
|
2023-09-05 10:38:20 +00:00
|
|
|
import useLocalStorage from 'hooks/useLocalStorage'
|
|
|
|
import useStore from 'store'
|
2023-07-05 14:43:11 +00:00
|
|
|
|
2023-09-05 10:38:20 +00:00
|
|
|
export default function useAutoLend(): {
|
2023-07-05 14:43:11 +00:00
|
|
|
autoLendEnabledAccountIds: string[]
|
|
|
|
toggleAutoLend: (accountId: string) => void
|
|
|
|
isAutoLendEnabledForCurrentAccount: boolean
|
2023-09-05 10:38:20 +00:00
|
|
|
setAutoLendOnAllAccounts: (lendAssets: boolean) => void
|
|
|
|
enableAutoLendAccountId: (accountId: string) => void
|
2023-07-05 14:43:11 +00:00
|
|
|
} {
|
2023-09-05 10:38:20 +00:00
|
|
|
const accounts = useStore((s) => s.accounts)
|
2023-07-05 14:43:11 +00:00
|
|
|
const currentAccount = useCurrentAccount()
|
|
|
|
const [autoLendEnabledAccountIds, setAutoLendEnabledAccountIds] = useLocalStorage<string[]>(
|
2023-10-23 12:04:17 +00:00
|
|
|
LocalStorageKeys.AUTO_LEND_ENABLED_ACCOUNT_IDS,
|
2023-07-05 14:43:11 +00:00
|
|
|
[],
|
|
|
|
)
|
|
|
|
|
|
|
|
const toggleAutoLend = (accountId: string) => {
|
|
|
|
const setOfAccountIds = new Set(autoLendEnabledAccountIds)
|
|
|
|
|
|
|
|
setOfAccountIds.has(accountId)
|
|
|
|
? setOfAccountIds.delete(accountId)
|
|
|
|
: setOfAccountIds.add(accountId)
|
|
|
|
|
|
|
|
setAutoLendEnabledAccountIds(Array.from(setOfAccountIds))
|
|
|
|
}
|
|
|
|
|
|
|
|
const isAutoLendEnabledForCurrentAccount = currentAccount
|
|
|
|
? autoLendEnabledAccountIds.includes(currentAccount.id)
|
|
|
|
: false
|
|
|
|
|
2023-09-05 10:38:20 +00:00
|
|
|
const setAutoLendOnAllAccounts = (lendAssets: boolean) => {
|
|
|
|
const allAccountIds = accounts ? accounts.map((account) => account.id) : []
|
|
|
|
setAutoLendEnabledAccountIds(lendAssets ? allAccountIds : [])
|
|
|
|
}
|
|
|
|
|
|
|
|
const enableAutoLendAccountId = (accountId: string) => {
|
|
|
|
const setOfAccountIds = new Set(autoLendEnabledAccountIds)
|
|
|
|
|
|
|
|
if (!setOfAccountIds.has(accountId)) setOfAccountIds.add(accountId)
|
2023-09-11 08:35:13 +00:00
|
|
|
setAutoLendEnabledAccountIds(Array.from(setOfAccountIds))
|
2023-09-05 10:38:20 +00:00
|
|
|
}
|
2023-07-05 14:43:11 +00:00
|
|
|
|
2023-09-05 10:38:20 +00:00
|
|
|
return {
|
|
|
|
autoLendEnabledAccountIds,
|
|
|
|
toggleAutoLend,
|
|
|
|
isAutoLendEnabledForCurrentAccount,
|
|
|
|
setAutoLendOnAllAccounts,
|
|
|
|
enableAutoLendAccountId,
|
|
|
|
}
|
|
|
|
}
|