Skip to content

Commit

Permalink
savers lockup logic
Browse files Browse the repository at this point in the history
  • Loading branch information
kaladinlight committed Sep 18, 2024
1 parent ec435a8 commit 42c38c3
Show file tree
Hide file tree
Showing 19 changed files with 231 additions and 154 deletions.
2 changes: 1 addition & 1 deletion src/assets/translations/de/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "Einzahlungen sind vorübergehend deaktiviert.",
"haltedWithdrawTitle": "Auszahlungen sind vorübergehend gestoppt.",
"disabledWithdrawTitle": "Auszahlungen sind vorübergehend deaktiviert.",
"runePoolWithdrawLockedTitle": "Sie müssen %{timeHuman} warten, um abzuheben.",
"withdrawLockedTitle": "Sie müssen %{timeHuman} warten, um abzuheben.",
"haltedDescription": "Bitte twittern Sie an @THORChain, um die Obergrenzen zu erhöhen!",
"protocolFee": "Protokollgebühr",
"fee": "Gebühr",
Expand Down
6 changes: 3 additions & 3 deletions src/assets/translations/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@
"disabledDepositTitle": "Deposits are temporarily disabled.",
"haltedWithdrawTitle": "Withdraws are temporarily halted.",
"disabledWithdrawTitle": "Withdraws are temporarily disabled.",
"runePoolWithdrawLockedTitle": "You have to wait %{timeHuman} to withdraw.",
"withdrawLockedTitle": "You have to wait %{timeHuman} to withdraw.",
"haltedDescription": "Please tweet at @THORChain to raise the caps!",
"protocolFee": "Protocol Fee",
"fee": "Fee",
Expand Down Expand Up @@ -505,8 +505,8 @@
"myRewardsBody": "Your active positions with claimable rewards will appear here.",
"viewAllPositions": "View All Positions",
"liquidityPools": "Liquidity Pools",
"liquidityLockupWarning": "There is a lockup period of %{time} in which you will be unable to withdraw your liquidity.",
"liquidityLocked": "Withdrawing liquidity is locked for %{time}",
"liquidityLockupWarning": "There is a lockup period of %{time}. During lockup you can't access your liquidity.",
"liquidityLocked": "Liquidity Locked (%{time})",
"stakingVaults": "Staking & Vaults",
"farming": "Farming",
"totalEarningBalance": "Total Earning Balance",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/es/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "Depósitos temporalmente deshabilitados.",
"haltedWithdrawTitle": "Retiros suspendidos temporalmente.",
"disabledWithdrawTitle": "Retiros temporalmente deshabilitados.",
"runePoolWithdrawLockedTitle": "Tienes que esperar %{timeHuman} para retirar.",
"withdrawLockedTitle": "Tienes que esperar %{timeHuman} para retirar.",
"haltedDescription": "¡Tuitee a @THORChain para aumentar los límites!",
"protocolFee": "Tarifa de Protocolo",
"fee": "Comisión",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/fr/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "Les dépôts sont temporairement désactivés.",
"haltedWithdrawTitle": "Les retraits sont temporairement interrompus.",
"disabledWithdrawTitle": "Les retraits sont temporairement désactivés.",
"runePoolWithdrawLockedTitle": "Vous devez attendre %{timeHuman} pour retirer.",
"withdrawLockedTitle": "Vous devez attendre %{timeHuman} pour retirer.",
"haltedDescription": "Veuillez tweeter @THORChain pour augmenter les plafonds !",
"protocolFee": "Frais de protocole",
"fee": "Frais",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/ja/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "デポジットは一時的に無効になります。",
"haltedWithdrawTitle": "出金を一時停止しております。",
"disabledWithdrawTitle": "引き出しは一時的に無効になっています。",
"runePoolWithdrawLockedTitle": "引き出すには%{timeHuman}待つ必要があります。",
"withdrawLockedTitle": "引き出すには%{timeHuman}待つ必要があります。",
"haltedDescription": "上限を増やすには、@THORChain でツイートしてください。",
"protocolFee": "プロトコル手数料",
"fee": "手数料",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/pt/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "Os depósitos estão temporariamente desativados.",
"haltedWithdrawTitle": "As retiradas estão temporariamente suspensas.",
"disabledWithdrawTitle": "Os saques estão temporariamente desativados.",
"runePoolWithdrawLockedTitle": "Você tem que esperar %{timeHuman} para sacar.",
"withdrawLockedTitle": "Você tem que esperar %{timeHuman} para sacar.",
"haltedDescription": "Por favor, twitte em @THORChain para aumentar o limite!",
"protocolFee": "Taxas do Protocolo",
"fee": "Taxa",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/ru/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "Депозиты временно отключены.",
"haltedWithdrawTitle": "Вывод средств временно приостановлен.",
"disabledWithdrawTitle": "Вывод средств временно отключен.",
"runePoolWithdrawLockedTitle": "Чтобы снять деньги, вам придется подождать %{timeHuman}.",
"withdrawLockedTitle": "Чтобы снять деньги, вам придется подождать %{timeHuman}.",
"haltedDescription": "Пожалуйста, напишите в твиттере @THORChain, чтобы поднять капитализацию!",
"protocolFee": "Плата за протокол",
"fee": "Комиссия",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/tr/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "Para yatırma işlemleri geçici olarak devre dışı bırakıldı.",
"haltedWithdrawTitle": "Para çekme işlemleri geçici olarak durdurulmuştur.",
"disabledWithdrawTitle": "Para çekme işlemleri geçici olarak devre dışı bırakıldı.",
"runePoolWithdrawLockedTitle": "Para çekmek için %{timeHuman} beklemeniz gerekiyor.",
"withdrawLockedTitle": "Para çekmek için %{timeHuman} beklemeniz gerekiyor.",
"haltedDescription": "Lütfen @THORChain adresine tweet atarak üst sınırınızı yükseltin!",
"protocolFee": "Protokol Ücreti",
"fee": "Ücret",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/uk/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "Депозити тимчасово не працюють.",
"haltedWithdrawTitle": "Виведення коштів тимчасово призупинено.",
"disabledWithdrawTitle": "Виведення коштів тимчасово відключено.",
"runePoolWithdrawLockedTitle": "Ви повинні дочекатися %{timeHuman}, щоб вивести кошти.",
"withdrawLockedTitle": "Ви повинні дочекатися %{timeHuman}, щоб вивести кошти.",
"haltedDescription": "Будь ласка, напишіть у твіттері @THORChain, щоб підняти наш рівень!",
"protocolFee": "Плата за протокол",
"fee": "Комісія",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/zh/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"disabledDepositTitle": "暂时禁止存款。",
"haltedWithdrawTitle": "提款暂时停止。",
"disabledWithdrawTitle": "暂时禁止提款。",
"runePoolWithdrawLockedTitle": "您必须等待 %{timeHuman} 才能提款。",
"withdrawLockedTitle": "您必须等待 %{timeHuman} 才能提款。",
"haltedDescription": "请 @THORChain 发推文以提高上限!",
"protocolFee": "协议费",
"fee": "费用",
Expand Down
4 changes: 3 additions & 1 deletion src/components/Acknowledgement/Acknowledgement.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ type AcknowledgementProps = {
buttonTranslation?: string | [string, InterpolationOptions]
icon?: ComponentWithAs<'svg', IconProps>
disableButton?: boolean
position?: 'relative' | 'static'
}

type StreamingAcknowledgementProps = Omit<AcknowledgementProps, 'message'> & {
Expand All @@ -113,6 +114,7 @@ export const Acknowledgement = ({
buttonTranslation,
disableButton,
icon: CustomIcon,
position = 'relative',
}: AcknowledgementProps) => {
const translate = useTranslate()
const [isShowing, setIsShowing] = useState(false)
Expand Down Expand Up @@ -149,7 +151,7 @@ export const Acknowledgement = ({

return (
<Box
position='relative'
position={position}
borderRadius={boxBorderRadius}
overflow={isShowing ? 'hidden' : 'visible'}
width={'100%'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { AccountId } from '@shapeshiftoss/caip'
import { fromAccountId, fromAssetId, thorchainAssetId, toAssetId } from '@shapeshiftoss/caip'
import { ContractType, getOrCreateContractByType } from '@shapeshiftoss/contracts'
import type { Asset } from '@shapeshiftoss/types'
import { useQueryClient } from '@tanstack/react-query'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { DepositValues } from 'features/defi/components/Deposit/Deposit'
import { Deposit as ReusableDeposit } from 'features/defi/components/Deposit/Deposit'
import type {
Expand All @@ -16,9 +16,11 @@ import pDebounce from 'p-debounce'
import qs from 'qs'
import { useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { useTranslate } from 'react-polyglot'
import { reactQueries } from 'react-queries'
import { useHistory } from 'react-router-dom'
import { encodeFunctionData, getAddress, maxUint256 } from 'viem'
import type { AccountDropdownProps } from 'components/AccountDropdown/AccountDropdown'
import { InfoAcknowledgement } from 'components/Acknowledgement/Acknowledgement'
import { Amount } from 'components/Amount/Amount'
import type { StepComponentProps } from 'components/DeFi/components/Steps'
import { HelperTooltip } from 'components/HelperTooltip/HelperTooltip'
Expand All @@ -33,9 +35,15 @@ import { MixPanelEvent } from 'lib/mixpanel/types'
import { isToken } from 'lib/utils'
import { assertGetEvmChainAdapter, getFeesWithWalletEIP1559Support } from 'lib/utils/evm'
import { fetchHasEnoughBalanceForTxPlusFeesPlusSweep } from 'lib/utils/thorchain/balance'
import { BASE_BPS_POINTS, RUNEPOOL_DEPOSIT_MEMO } from 'lib/utils/thorchain/constants'
import {
BASE_BPS_POINTS,
RUNEPOOL_DEPOSIT_MEMO,
THORCHAIN_BLOCK_TIME_SECONDS,
thorchainBlockTimeMs,
} from 'lib/utils/thorchain/constants'
import { useGetThorchainSaversDepositQuoteQuery } from 'lib/utils/thorchain/hooks/useGetThorchainSaversDepositQuoteQuery'
import { useSendThorTx } from 'lib/utils/thorchain/hooks/useSendThorTx'
import { formatSecondsToDuration } from 'lib/utils/time'
import { isUtxoChainId } from 'lib/utils/utxo'
import type { EstimatedFeesQueryKey } from 'pages/Lending/hooks/useGetEstimatedFeesQuery'
import { queryFn as getEstimatedFeesQueryFn } from 'pages/Lending/hooks/useGetEstimatedFeesQuery'
Expand Down Expand Up @@ -92,6 +100,8 @@ export const Deposit: React.FC<DepositProps> = ({
null,
)
const [daysToBreakEven, setDaysToBreakEven] = useState<string | null>(null)
const [shouldShowInfoAcknowledgement, setShouldShowInfoAcknowledgement] = useState(false)
const [depositValues, setDepositValues] = useState<DepositValues>()
const [inputValues, setInputValues] = useState<{
fiatAmount: string
cryptoAmount: string
Expand Down Expand Up @@ -166,6 +176,29 @@ export const Deposit: React.FC<DepositProps> = ({
selectPortfolioCryptoBalanceBaseUnitByFilter(state, balanceFilter),
)

const liquidityLockupTime = useQuery({
...reactQueries.thornode.mimir(),
staleTime: thorchainBlockTimeMs,
select: mimirData => {
const liquidityLockupBlocks = mimirData.LIQUIDITYLOCKUPBLOCKS as number | undefined
return Number(bnOrZero(liquidityLockupBlocks).times(THORCHAIN_BLOCK_TIME_SECONDS).toFixed(0))
},
})

const runePoolDepositMaturityTime = useQuery({
...reactQueries.thornode.mimir(),
staleTime: thorchainBlockTimeMs,
select: mimirData => {
const runePoolDepositMaturityBlocks = mimirData.RUNEPOOLDEPOSITMATURITYBLOCKS as
| number
| undefined

return Number(
bnOrZero(runePoolDepositMaturityBlocks).times(THORCHAIN_BLOCK_TIME_SECONDS).toFixed(0),
)
},
})

const {
data: thorchainSaversDepositQuote,
isLoading: isThorchainSaversDepositQuoteLoading,
Expand Down Expand Up @@ -816,60 +849,102 @@ export const Deposit: React.FC<DepositProps> = ({
[validateFiatAmountDebounced],
)

const handleContinueMaybeAck = useCallback(
(formValues: DepositValues) => {
setDepositValues(formValues)
if (isRunePool && runePoolDepositMaturityTime.data) {
setShouldShowInfoAcknowledgement(true)
return
}

if (!isRunePool && liquidityLockupTime.data) {
setShouldShowInfoAcknowledgement(true)
return
}

handleContinue(formValues)
},
[liquidityLockupTime, runePoolDepositMaturityTime, isRunePool, handleContinue],
)

const handleAcknowledge = useCallback(() => {
if (!depositValues) return
handleContinue(depositValues)
}, [depositValues, handleContinue])

if (!state || !contextDispatch || !opportunityData) return null

return (
<ReusableDeposit
accountId={accountId}
onAccountIdChange={handleAccountIdChange}
asset={asset}
apy={opportunityData.apy ?? undefined}
cryptoAmountAvailable={balanceCryptoPrecision.toPrecision()}
cryptoInputValidation={cryptoInputValidation}
fiatAmountAvailable={fiatAmountAvailable.toFixed(2)}
fiatInputValidation={fiatInputValidation}
marketData={assetMarketData}
onCancel={handleCancel}
onPercentClick={handlePercentClick}
onContinue={handleContinue}
onBack={handleBack}
onChange={handleInputChange}
percentOptions={percentOptions}
enableSlippage={false}
isLoading={
isEstimatedFeesDataLoading ||
isSweepNeededLoading ||
isThorchainSaversDepositQuoteLoading ||
state.loading
}
<InfoAcknowledgement
message={translate('defi.liquidityLockupWarning', {
time: formatSecondsToDuration(
isRunePool ? runePoolDepositMaturityTime.data ?? 0 : liquidityLockupTime.data ?? 0,
),
})}
onAcknowledge={handleAcknowledge}
shouldShowAcknowledgement={shouldShowInfoAcknowledgement}
setShouldShowAcknowledgement={setShouldShowInfoAcknowledgement}
position='static'
>
{!isRunePool ? (
<>
<Row>
<Row.Label>{translate('common.slippage')}</Row.Label>
<Row.Value>
<Skeleton isLoaded={isThorchainSaversDepositQuoteSuccess}>
<Amount.Crypto value={slippageCryptoAmountPrecision ?? ''} symbol={asset.symbol} />
</Skeleton>
</Row.Value>
</Row>
<Row>
<Row.Label>
<HelperTooltip label={translate('defi.modals.saversVaults.timeToBreakEven.tooltip')}>
{translate('defi.modals.saversVaults.timeToBreakEven.title')}
</HelperTooltip>
</Row.Label>
<Row.Value>
<Skeleton isLoaded={isThorchainSaversDepositQuoteSuccess}>
{translate(
`defi.modals.saversVaults.${bnOrZero(daysToBreakEven).eq(1) ? 'day' : 'days'}`,
{ amount: daysToBreakEven ?? '0' },
)}
</Skeleton>
</Row.Value>
</Row>
</>
) : null}
</ReusableDeposit>
<ReusableDeposit
accountId={accountId}
onAccountIdChange={handleAccountIdChange}
asset={asset}
apy={opportunityData.apy ?? undefined}
cryptoAmountAvailable={balanceCryptoPrecision.toPrecision()}
cryptoInputValidation={cryptoInputValidation}
fiatAmountAvailable={fiatAmountAvailable.toFixed(2)}
fiatInputValidation={fiatInputValidation}
marketData={assetMarketData}
onCancel={handleCancel}
onPercentClick={handlePercentClick}
onContinue={handleContinueMaybeAck}
onBack={handleBack}
onChange={handleInputChange}
percentOptions={percentOptions}
enableSlippage={false}
isLoading={
isEstimatedFeesDataLoading ||
isSweepNeededLoading ||
isThorchainSaversDepositQuoteLoading ||
liquidityLockupTime.isLoading ||
runePoolDepositMaturityTime.isLoading ||
state.loading
}
>
{!isRunePool ? (
<>
<Row>
<Row.Label>{translate('common.slippage')}</Row.Label>
<Row.Value>
<Skeleton isLoaded={isThorchainSaversDepositQuoteSuccess}>
<Amount.Crypto
value={slippageCryptoAmountPrecision ?? ''}
symbol={asset.symbol}
/>
</Skeleton>
</Row.Value>
</Row>
<Row>
<Row.Label>
<HelperTooltip
label={translate('defi.modals.saversVaults.timeToBreakEven.tooltip')}
>
{translate('defi.modals.saversVaults.timeToBreakEven.title')}
</HelperTooltip>
</Row.Label>
<Row.Value>
<Skeleton isLoaded={isThorchainSaversDepositQuoteSuccess}>
{translate(
`defi.modals.saversVaults.${bnOrZero(daysToBreakEven).eq(1) ? 'day' : 'days'}`,
{ amount: daysToBreakEven ?? '0' },
)}
</Skeleton>
</Row.Value>
</Row>
</>
) : null}
</ReusableDeposit>
</InfoAcknowledgement>
)
}
Loading

0 comments on commit 42c38c3

Please sign in to comment.