Skip to content

Commit

Permalink
Merge pull request #44 from dhedge/feat/add-all-assets-withdrawal-sli…
Browse files Browse the repository at this point in the history
…ppage-settings

feat(Trading Widget): add multi assets withdrawal slippage settings
  • Loading branch information
dimlbc authored May 16, 2024
2 parents a7dcfc2 + b20a3fc commit 24181d0
Show file tree
Hide file tree
Showing 19 changed files with 126 additions and 55 deletions.
2 changes: 1 addition & 1 deletion packages/trading-widget/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dhedge/trading-widget",
"version": "0.0.9",
"version": "0.1.0",
"type": "module",
"main": "dist/index.js",
"module": "dist/index.mjs",
Expand Down
31 changes: 18 additions & 13 deletions packages/trading-widget/src/core-kit/abi/pool-logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1010,19 +1010,6 @@ export const PoolLogicAbi = [
stateMutability: 'nonpayable',
type: 'function',
},
{
inputs: [
{
internalType: 'uint256',
name: '_fundTokenAmount',
type: 'uint256',
},
],
name: 'withdraw',
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
},
{
inputs: [
{
Expand Down Expand Up @@ -1060,4 +1047,22 @@ export const PoolLogicAbi = [
stateMutability: 'view',
type: 'function',
},
{
inputs: [
{
internalType: 'uint256',
name: '_fundTokenAmount',
type: 'uint256',
},
{
internalType: 'uint256',
name: '_slippageTolerance',
type: 'uint256',
},
],
name: 'withdrawSafe',
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
},
] as const
3 changes: 2 additions & 1 deletion packages/trading-widget/src/core-kit/const/default-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ export const DEFAULT_WITHDRAW_SLIPPAGE_SCALE = [
]
export const DEFAULT_DEPOSIT_SLIPPAGE_SCALE = [DEFAULT_DEPOSIT_SLIPPAGE]

export const DEFAULT_WITHDRAW_METHOD = 'withdraw'
export const DEFAULT_EASY_SWAPPER_WITHDRAW_METHOD = 'withdraw'
export const DEFAULT_MULTI_ASSET_WITHDRAW_METHOD = 'withdrawSafe'

export const NATIVE_TOKEN_DEPOSIT_GAS_LIMIT = 4200000

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import { DefaultSellingParams } from 'core-kit/models'

import type { TradingToken } from 'core-kit/types'

import { getOrderedTxArgs } from 'core-kit/utils'
import {
getOrderedTxArgs,
getSlippageToleranceForWithdrawSafe,
} from 'core-kit/utils'
import { TEST_ADDRESS } from 'tests/mocks'
import { act, renderHook } from 'tests/test-utils'

Expand Down Expand Up @@ -121,6 +124,7 @@ describe('useWithdraw', () => {
expect(sendMock).toHaveBeenCalledTimes(1)
expect(sendMock).toHaveBeenCalledWith(
fromTokenAmount.shiftedBy(DEFAULT_PRECISION).toFixed(0),
getSlippageToleranceForWithdrawSafe(settings.slippage),
)
})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useCallback, useMemo } from 'react'

import {
DEFAULT_EASY_SWAPPER_WITHDRAW_METHOD,
DEFAULT_MULTI_ASSET_WITHDRAW_METHOD,
DEFAULT_PRECISION,
DEFAULT_WITHDRAW_METHOD,
DEFAULT_WITHDRAW_SLIPPAGE,
DEFAULT_WITHDRAW_SLIPPAGE_SCALE,
} from 'core-kit/const'
Expand All @@ -23,7 +24,11 @@ import type {
ContractActionFunc,
SendEstimationResult,
} from 'core-kit/types/web3.types'
import { getOrderedTxArgs, logTransactionArguments } from 'core-kit/utils'
import {
getOrderedTxArgs,
getSlippageToleranceForWithdrawSafe,
logTransactionArguments,
} from 'core-kit/utils'

import { useIsMultiAssetWithdraw } from './use-is-multi-asset-withdraw'
import { useWithdrawSlippage } from './use-withdraw-slippage'
Expand All @@ -45,10 +50,11 @@ export const useWithdraw = (): ContractActionFunc => {

const onSettled = useTradingSettleHandler(action)

const { method: functionName = DEFAULT_WITHDRAW_METHOD } =
poolConfig.withdrawParams.customTokens.find(
({ address }) => address === receiveToken.address,
) ?? { method: DEFAULT_WITHDRAW_METHOD }
const functionName = isMultiAssetsWithdraw
? DEFAULT_MULTI_ASSET_WITHDRAW_METHOD
: poolConfig.withdrawParams.customTokens.find(
({ address }) => address === receiveToken.address,
)?.method ?? DEFAULT_EASY_SWAPPER_WITHDRAW_METHOD
const { send, estimate } = useContractFunction({
contractId: isMultiAssetsWithdraw ? 'poolLogic' : 'easySwapper',
dynamicContractAddress: isMultiAssetsWithdraw
Expand Down Expand Up @@ -135,7 +141,14 @@ export const useWithdraw = (): ContractActionFunc => {
logTransactionArguments(txArgs)

if (isMultiAssetsWithdraw) {
return send(txArgs.fromTokenAmount)
return send(
txArgs.fromTokenAmount,
getSlippageToleranceForWithdrawSafe(
tradingSlippage === 'auto'
? DEFAULT_WITHDRAW_SLIPPAGE
: tradingSlippage,
),
)
}
const isAuto = tradingSlippage === 'auto'
const slippageValue = isAuto
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,7 @@ export const useFlatmoneyPointsUserBalances =
address: vaultAddress,
chainId,
})
const userVaultPortionInPercents = totalSupply
? new BigNumber(balance)
.shiftedBy(DEFAULT_PRECISION)
.dividedBy(totalSupply)
: new BigNumber(0)

const isFmedVault = isFlatMoneyEarlyDepositorAddress(vaultAddress)
const fetchUserPointsBalances =
isFmedVault && !isEqualAddress(account, AddressZero)
Expand All @@ -55,6 +51,11 @@ export const useFlatmoneyPointsUserBalances =
} = useFmedVestedPoints({ enabled: fetchUserPointsBalances })

return useMemo(() => {
const userVaultPortionInPercents = totalSupply
? new BigNumber(balance)
.shiftedBy(DEFAULT_PRECISION)
.dividedBy(totalSupply)
: new BigNumber(0)
const userPortionOfLockedPointsBalance = lockedVaultPointsBalance
? new BigNumber(lockedVaultPointsBalance.toString())
.multipliedBy(userVaultPortionInPercents)
Expand All @@ -80,10 +81,11 @@ export const useFlatmoneyPointsUserBalances =
isLoading,
}
}, [
totalSupply,
balance,
lockedVaultPointsBalance,
unlockTaxInPercents,
unlockTime,
userVaultPortionInPercents,
isLoading,
])
}
2 changes: 1 addition & 1 deletion packages/trading-widget/src/core-kit/providers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const getDefaultTradingPanelState = (
settings: {
slippage: 'auto',
isInfiniteAllowance: false,
isMultiAssetWithdrawalEnabled: false,
isMultiAssetWithdrawalEnabled: true,
isMaxSlippageLoading: false,
...config?.settings,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export type TransactionAction =

export type DepositMethodName = 'deposit' | 'depositWithCustomCooldown'

export type WithdrawMethodName = 'withdraw' | 'withdrawSUSD'
export type WithdrawMethodName = 'withdraw' | 'withdrawSUSD' | 'withdrawSafe'

export type SwapEntity = 'token' | 'pool'

Expand Down
21 changes: 21 additions & 0 deletions packages/trading-widget/src/core-kit/utils/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,24 @@ export const logTransactionArguments = (txArgs: TxArgs) =>
{},
),
)

/**
* Calculates the slippage tolerance for withdrawSafe.
* Returns an integer number from 0 to 10000,
* where 10_000 = 100%, 100 = 1%, 10 = 0.1%, 1 = 0.01% etc.
* @param {string} slippage - The slippage value in % from 0 to 100.
* @returns {string} - The slippage tolerance.
*/
export const getSlippageToleranceForWithdrawSafe = (
slippage: number,
): string => {
const minSlippageStep = new BigNumber(0.01)
const slippageBN = new BigNumber(slippage)

const slippageToUse =
!slippageBN.isZero() && slippageBN.lt(minSlippageStep)
? minSlippageStep
: slippageBN

return slippageToUse.multipliedBy(100).toFixed(0)
}
3 changes: 2 additions & 1 deletion packages/trading-widget/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ export {
DEFAULT_DEPOSIT_SLIPPAGE,
DEFAULT_WITHDRAW_SLIPPAGE,
DEFAULT_WITHDRAW_SLIPPAGE_SCALE,
DEFAULT_WITHDRAW_METHOD,
DEFAULT_EASY_SWAPPER_WITHDRAW_METHOD,
DEFAULT_MULTI_ASSET_WITHDRAW_METHOD,
DEFAULT_DEPOSIT_SLIPPAGE_SCALE,
DEFAULT_DEPOSIT_METHOD,
DEFAULT_PROMISE_TIMEOUT_MS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,15 @@ export const useDepositTransactionDisclosure = () => {
const themeType = useGetThemeTypeBySlippage(
isAutoSlippage ? minSlippage ?? 0 : slippage,
)

const slippagePlaceholder = useGetSlippagePlaceholder(
'deposit',
const slippagePlaceholder = useGetSlippagePlaceholder({
tradingType: 'deposit',
slippage,
minSlippage,
)
})
const slippageTooltipText =
themeType === THEME_TYPE.DEFAULT ? t.slippageWarning : t.highSlippageWarning
themeType === THEME_TYPE.DEFAULT
? t.depositSlippageWarning
: t.highSlippageWarning

const getMinReceiveText = () => {
if (isAutoSlippage) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const DepositSettings: FC = () => {
<>
<SettingsOption
label={t.slippageTolerance}
tooltipText={t.slippageWarning}
tooltipText={t.depositSlippageWarning}
>
<SlippageSelector />
</SettingsOption>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ export const SlippageSelector: FC = () => {
onCustomSlippageSelect,
} = useSlippageSelector()

const placeholder = useGetSlippagePlaceholder(
const placeholder = useGetSlippagePlaceholder({
tradingType,
settings.slippage,
settings.minSlippage,
)
slippage: settings.slippage,
minSlippage: settings.minSlippage,
})

return (
<div className="dtw-flex dtw-items-center dtw-space-x-3">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
useTradingPanelSettings,
} from 'core-kit/hooks/state'

import { useIsMultiAssetWithdraw } from 'core-kit/hooks/trading/withdraw'
import {
useGetSlippagePlaceholder,
useGetThemeTypeBySlippage,
Expand All @@ -28,6 +29,7 @@ export const useWithdrawTransactionDisclosure = () => {
] = useTradingPanelSettings()
const [receiveToken] = useReceiveTokenInput()
const [sendToken] = useSendTokenInput()
const isMultiAssetsWithdraw = useIsMultiAssetWithdraw()

const isAutoSlippage = slippage === 'auto'
const isMinSlippageNumber = isNumber(minSlippage)
Expand All @@ -36,13 +38,16 @@ export const useWithdrawTransactionDisclosure = () => {
isAutoSlippage ? minSlippage ?? 0 : slippage,
)

const slippagePlaceholder = useGetSlippagePlaceholder(
'withdraw',
const slippagePlaceholder = useGetSlippagePlaceholder({
tradingType: 'withdraw',
slippage,
minSlippage,
)
showDefaultSlippage: isMultiAssetsWithdraw,
})
const slippageTooltipText =
themeType === THEME_TYPE.DEFAULT ? t.slippageWarning : t.highSlippageWarning
themeType === THEME_TYPE.DEFAULT
? t.withdrawSlippageWarning
: t.highSlippageWarning

const getMinReceiveText = () => {
if (receiveToken.symbol === 'all') {
Expand Down Expand Up @@ -90,5 +95,6 @@ export const useWithdrawTransactionDisclosure = () => {
minSlippage,
showApplyMinSlippageButton,
handleMinTradingSlippage,
isMultiAssetsWithdraw,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const WithdrawTransactionOverviewDisclosure = () => {
allowanceRequired,
sendTokenSymbol,
tokenAllowance,
isMultiAssetsWithdraw,
} = useWithdrawTransactionDisclosure()

const collapseItems = useMemo<TransactionDisclosureItemProps[]>(() => {
Expand Down Expand Up @@ -64,7 +65,7 @@ export const WithdrawTransactionOverviewDisclosure = () => {
},
]

if (!isAutoSlippage) {
if (!isAutoSlippage && !isMultiAssetsWithdraw) {
items.push({
tooltipText: t.minSlippageWarning,
label: t.recommendedMinSlippage,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const WithdrawSettings: FC = () => {
<>
<SettingsOption
label={t.slippageTolerance}
tooltipText={t.slippageWarning}
tooltipText={t.withdrawSlippageWarning}
>
<SlippageSelector />
</SettingsOption>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import isNumber from 'lodash.isnumber'

import { DEFAULT_WITHDRAW_SLIPPAGE } from 'core-kit/const'
import type { TradingPanelType } from 'core-kit/types'

import { useConfigContextParams } from 'trading-widget/providers/config-provider'

export const useGetSlippagePlaceholder = (
tradingType: TradingPanelType,
slippage: number | 'auto',
minSlippage?: number,
) => {
export const useGetSlippagePlaceholder = ({
tradingType,
slippage,
minSlippage,
showDefaultSlippage,
}: {
tradingType: TradingPanelType
slippage: number | 'auto'
minSlippage?: number
showDefaultSlippage?: boolean
}) => {
const { defaultDepositSlippage, defaultWithdrawSlippageScale } =
useConfigContextParams()

if (showDefaultSlippage) {
return tradingType === 'deposit'
? defaultDepositSlippage.toString()
: DEFAULT_WITHDRAW_SLIPPAGE.toString()
}

if (slippage !== 'auto') {
return slippage.toString()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { TranslationMap } from './translation-provider.types'

export const DEFAULT_TRANSLATION_DATA: TranslationMap = {
slippageWarning:
depositSlippageWarning:
'Includes entry fee. We recommend 2-3%, but usually it will be < 1%. Slippage may be amplified by the leverage. See the docs for more info.',
withdrawSlippageWarning:
'Slippage only applies to single asset withdrawals and withdrawals from vaults with debt positions in Aave.',
minSlippageWarning:
'Flexible min slippage value that is likely enough to process the transaction.',
highSlippageWarning:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export type TranslationMap = {
slippageWarning: string
depositSlippageWarning: string
withdrawSlippageWarning: string
minSlippageWarning: string
highSlippageWarning: string
recommendedMinSlippage: string
Expand Down

0 comments on commit 24181d0

Please sign in to comment.