@dhedge/trading-widget v3.10.6
dHEDGE Trading Widget API Docs
Get started
Requirements:
Widget library has some vital peerDependencies as a core tool stack. Make sure having all those dependencies installed in app before starting the integration:
"@tanstack/react-query": "^5.28.4",
"react": ">=18.2.0",
"viem": "^2.8.14",
"wagmi": "^2.5.11"- Installation:
npm i @dhedge/trading-widget- Providers hierarchy
import { WagmiProvider } from 'wagmi'
import { TradingPanelProvider, TradingWidget } from '@dhedge/trading-widget'- Setup Wagmi Provider on top level or use existing one in your app
- Setup TradingPanelProvider
Providing a
getSwapDatacallback is mandatory for depositing with off-chain swaps. - Setup TradingWidget
- Minimum required config
See bare minimum setup example: packages/trading-widget/src/examples/simple-example.tsx
- Styling
import '@dhedge/trading-widget/style.css'Initially widget takes full parent width
See TradingWidget -> theme config to manage customization
API
TradingPanelProvider
Top level provider component. Headless part of trading logic. API handles params to setup initialState and actions. See below for more details
name type default value description onUpdateSendTokenInput(payload: Partial\<{ address: Address; symbol:string; value:string; decimals:number; isLoading?:boolean}>) => voidundefined triggers on send token change onUpdateTradingSettings(payload: Partial\<{ slippage: number \| 'auto'; minSlippage?:numberisInfiniteAllowance:boolean; isMultiAssetWithdrawalEnabled:boolean; isMaxSlippageLoading:boolean}>) => voidundefined triggers on trading settings change onSetTradingType(payload: 'deposit' \| 'withdraw') => voidundefined triggers on trading type change onUpdateTradingMeta(payload: Partial\<{ approvingStatus: 'pending' \| 'success'}>) => voidundefined triggers on trading meta change onUpdateTradingModal(payload: Partial\<{ isOpen: boolean; status:'Success' \| 'None' \| 'Mining' \| 'Wallet'}>) => voidundefined triggers on trading modal change onUpdateTransactions(payload: AddTransaction | UpdateTransaction | RemoveTransaction) => void undefined triggers on transaction action change onTradingSettleError(error: Error) => voidundefined triggers on trading settle error onTransactionError(error: Error, action:TransactionAction|undefined, chainId?:ChainId, txHash?:Address) => voidundefined triggers on transaction error onTransactionSuccess(data: WaitForTransactionReceiptReturnType, action:TransactionAction|undefined, link?:string) => voidundefined triggers on transaction success onTransactionEstimationError(error: EstimationError, address:Address, chainId?:ChainId, account?:Address) => voidundefined triggers on transaction estimation error onTokenSelector(payload: { isOpen: boolean; entity:'token' \| 'pool'}) => voidundefined triggers on token selector change onLog(eventName: string, payload?:Record<string, unknown>) => voidundefined triggers on log event onSimulateTransaction(payload: { chainId: ChainId; from:Address: to:Address; input:string; gas:number; value?:string}) => Promise<{ link?:string; simulation: { status:boolean; error_message:string} } | null>undefined triggers to simulate transaction and get error details after failed tx estimation getSwapData({ signal: AbortSignal, variables: { chainId:number; sourceAddress:Address; destinationAddress:Address; walletAddress:Address; fromAddress:Address; amount:string; slippage:string} }) => Promise<{ destinationAmount:string; txData:string; routerKey:'ONE_INCH' / 'ONE_INCH_V5' / 'ZERO_X' / 'PARASWAP'} } | null>undefined provides off chain swap data based on send token value
Source: packages/trading-widget/src/core-kit/providers/index.tsx
Default values: undefined
name type default value description poolAddressAddress AddressZeroCurrent active pool address poolConfigMapRecord<Address, PoolConfig> {}Map of pool configs available for trading settings{ slippage: number \| 'auto'; minSlippage?:number; isInfiniteAllowance:boolean; isMultiAssetWithdrawalEnabled:boolean; isMaxSlippageLoading:boolean}{ slippage: 'auto'; isInfiniteAllowance:false; isMultiAssetWithdrawalEnabled:true; isMaxSlippageLoading:false}Panel settings type'deposit' | 'withdraw' 'deposit'Trading type input{ sendToken: { address: Address; symbol:string; value:string; decimals:number; isLoading?:boolean}; receiveToken: { address:Address; symbol:string; value:string; decimals:number; isLoading?:boolean} }poolConfigMap[poolAddress]Send/receive tokens pair entryFee{ deposit: number; depositWithCustomCooldown:number; }{ deposit: 0; depositWithCustomCooldown:0.1}Entry fee config map meta{ approvingStatus?: 'pending' \| 'success'}{}Trading meta info modal{ isOpen: boolean; status:'Success' \| 'None' \| 'Mining' \| 'Wallet'; action:'deposit' \| 'withdraw' \| 'approve \| 'oraclesUpdate'; link?:string; sendToken: TradingToken | null; receiveToken: TradingToken | null }{ isOpen:false,status:'None', receiveToken:null, sendToken:null}Trading modal state transactions{ action: 'deposit' \| 'withdraw' \| 'approve'; symbol:string; chainId:ChainId; txHash?:Address}[][]Pending transactions poolFallbackData{ address: Address; managerLogicAddress?:Address; poolCompositions:PoolComposition[]; tokenPrice?:string; apy?: { value:number; currency:'USD' \| 'ETH'} }{ address: AddressZero}Current active pool fallback data to override or extend contract's response defaultChainIdnumber (optional) undefined Chain id that will be returned from useNetwork wagmi hook when connected to unsupported network
Source: packages/trading-widget/src/core-kit/providers/index.tsx
Default values: packages/trading-widget/src/core-kit/providers/index.tsx
TradingWidget
UI configuration provider. Manages params to configure custom styling, components, translations and basic trading params. Decomposed into config, components, theme and translation params. See below for more details
params
name type default value description isGeoBlockedbooleanfalseRestricts depositing action button and conditionally renders GeoBlockAlert component isSanctionedbooleanfalseRestricts depositing action button and conditionally renders SanctionedAlert component depositQuoteDiffWarningThresholdnumber1Deposit slippage absolute percent value warning threshold, Affects styling to warn user depositQuoteDiffErrorThresholdnumber3Deposit slippage absolute percent value error threshold, Affects styling to warn user defaultWithdrawSlippageScalenumber[][0.1, 0.3, 0.5, 1, 1.5, 3]Initial withdraw slippage absolute percent. Further adjustments are available in panel settings defaultSwapTransactionSlippagenumber0.3Default slippage (%) applied to swap transaction. defaultNoSwapMinDepositAmountGapnumber0.1Default gap (%) for min received vault tokens during no swap deposits. defaultLockTimestring'24 hours'Formatted default deposit lock time to be displayed in panel (Long lockup period is used to bypass entry fee and can be managed in panel settings) customLockTimestring'15 minutes'Formatted custom deposit lock time alternative to be displayed in panel stablePrecisionnumber3Number of decimals to be displayed in stables (e.g USDC balance) defaultPrecisionnumber6Number of decimals to be displayed in token values stakingChainIdnumber10(Optimism)ChainId to be used in staking logic termsOfUseAcceptedbooleantrueRequires user to confirm terms of use by rendering DepositTermsOfUse component before deposit action standalonebooleantrueHandles token selection in SPA mode chainConfigPartial<Record<ChainId, { name: string; iconPath: string }>>{}Sets map of chain nameandiconPath
actions
name type default value description onConnect() => void() => {}Widget has built-in Connect Walletaction button that triggersonConnectcallback assuming starting of abstract wallet connection process. After all the only requirement is to get connected wallet inside wagmi'suseAccounthook to make trading operations possibleonAcceptTermsOfUse() => Promise<boolean>() => Promise.resolve(true)Callback is triggered after user's approval of Terms of Use statements assuming switching of external config.termsOfUseAcceptedparam totruestate
Source: packages/trading-widget/src/trading-widget/providers/config-provider
Default values: packages/trading-widget/src/trading-widget/providers/config-provider/config-provider.defaults.ts
name type default value description GeoBlockAlertComponentType <GeoBlockAlert>Component replaces deposit button while isGeoBlockedconfig param is set totrueSanctionedAlertComponentType <SanctionedAlert>Component replaces deposit button while isSanctionedconfig param is set totrueDepositMetaInfoComponentType undefinedComponent is injected into deposit meta part of widget layout nearby TransactionOverviewDisclosure WithdrawMetaInfoComponentType undefinedComponent is injected into withdraw meta part of widget layout nearby WithdrawTransactionOverviewDisclosure ExtraActionButtonComponentType undefinedComponent is injected below deposit action button and rendered if isGeoBlockedconfig param is set tofalseImageComponentType <img>Component optionally can be used to pass nextjsImage component to be used for assets renderingLogoSpinnerComponentType<SVGProps> <Spinner>Component is injected into widget pending transaction overlay. Assume using of spinning animation DepositTermsOfUseComponentType undefinedComponent is injected into TermsOfUseOverlayto extend default terms of use statement pointsActionButtonComponentType <ActionButton>Component overrides default ActionButtonand hasButtonPropsAPI
Source: packages/trading-widget/src/trading-widget/providers/component-provider/component-provider.tsx
Default values: undefined
global
color
path: global.color[name]
name type default value description colorTextPrimarystring #ffffffPrimary text color colorTextPrimaryHoverstring #ffffffCCPrimary hover text color colorBorderPrimarystring global?.color?.colorTextPrimary ?? #ffffffPrimary border color colorTextSecondarystring #9DA2ADSecondary text color colorBgPrimarystring #1B2432Primary bg color colorBgSecondarystring #2B313ESecondary bg color colorTextAccentstring #ffffffAccent text color colorTextAccentHoverstring #ffffffCCAccent hover text color colorBgAccentFromstring #73D393Accent bg gradient fromcolorcolorBgAccentTostring #34855EAccent bg gradient tocolorcolorBgAccentFromHoverstring #73D393CCAccent hover bg gradient fromcolorcolorBgAccentToHoverstring #162435Accent hover bg gradient tocolorcolorTextNeutralstring #9DA2AD80Neutral text color colorBgNeutralstring #9DA2AD33Neutral bg color colorTextLoadingstring #ffffff99Loading text color colorTextErrorstring #EF4444Error text color colorTextWarningstring #AFA58DWarning text color colorIconstring global?.color?.colorTextPrimary ?? #ffffffWarning text color
size
path: global.size[name]
name type default value description gapstring 0.25remGeneral flex gap spacerstring 4pxGeneral spacer fontSizeBasestring 16pxFont size base lineHeightBasestring 24pxLine height base fontSizeXsstring 12pxFont size xs lineHeightXsstring 16pxLine height xs fontSizeSmstring 14pxFont size sm lineHeightSmstring 20pxLine height sm fontSizeLgstring 18pxFont size lg lineHeightLgstring 28pxLine height lg iconSizestring 20pxIcon size base iconSizeSmstring 24pxIcon size sm iconSecondarySizestring 16pxIcon secondary size iconSecondarySizeSmstring 16pxIcon secondary size sm labelFontSizestring config?.global?.size?.fontSizeXs ?? 12pxLabel font size labelLineHeightstring config?.global?.size?.lineHeightXs ?? 16pxLabel font size labelLineHeightstring config?.global?.size?.lineHeightXs ?? 16pxLabel font size
style
path: global.style[name]
name type default value description radiusPrimarystring 1remGeneral border radius radiusSecondarystring 1remSecondary border radius fontWeightLightstring 300Font weight light fontWeightMediumstring 500Font weight medium fontWeightBoldstring 700Font weight bold actionOpacitystring 1Action element opacity actionOpacityHoverstring 0.8Action hover element opacity
component
popup
path: component.popup[name]
name type default value description color.colorTextstring config?.global?.color?.colorTextSecondary ?? #9DA2ADPopup text color color.colorBgstring config?.global?.color?.colorBgSecondary ?? #2B313EPopup bg color color.colorBorderstring config?.global?.color?.colorTextSecondary ?? #9DA2ADPopup bg color size.fontSizestring config?.global?.size?.fontSizeXs ?? 12pxPopup font size
popupList
path: component.popupList[name]
name type default value description color.itemBgEvenstring transparentPopup list even item bg color color.itemBgOddstring #2A3648Popup list odd item bg color color.headerBgstring #1B2432Popup list header bg color
tabGroup
path: component.tabGroup[name]
name type default value description size.pxstring global.size.spacer * 3Tab group padding inline
tabContent
path: component.tabContent[name]
name type default value description size.ptstring global.size.spacer * 3Tab content padding top size.pxstring 0pxTab content padding inline size.pbstring global.size.spacer * 9Tab content padding bottom size.gapstring global.size.spacer * 2Tab content flex gap
tab
path: component.tab[name]
name type default value description size.pxstring global.size.spacer * 9Tab padding inline size.pystring global.size.spacer * 3Tab padding block size.fontSizestring global.size.fontSizeSmTab font size color.colorBgstring global.color.colorBgNeutralTab bg color color.colorTextstring global.color.colorTextNeutralTab text color color.selectColorTextstring global.color.colorTextPrimaryTab select text color color.colorTextHoverstring global.color.colorTextPrimaryHoverTab hover text color style.fontWeightstring global.style.fontWeightBoldTab font weight style.lineHeightstring global.size.lineHeightSmTab line height
balance
path: component.balance[name]
name type default value description size.pxstring global.size.spacer * 3Balance padding inline size.gapstring global.size.gapBalance flex gap size.fontSizestring global.size.fontSizeLgBalance font size size.lineHeightstring global.size.lineHeightLgBalance line height size.priceFontSizestring global.size.fontSizeBaseBalance price font size size.priceLineHeightstring global.size.lineHeightBaseBalance price line height color.colorTextstring global.color.colorTextPrimaryBalance text color color.priceColorTextstring global.color.colorTextSecondaryBalance price text color
inputGroup
path: component.inputGroup[name]
name type default value description size.pxstring global.size.spacer * 3Input group padding inline size.gapstring global.size.gapInput group flex gap
input
path: component.input[name]
name type default value description size.pxstring global.size.spacer * 3Input padding inline size.pystring global.size.spacer * 2Input padding block size.gapstring global.size.gap * 2Input flex gap size.priceGapstring global.size.gap * 2Input flex gap size.iconSizestring global.size.iconSizeInput icon size size.iconSizeSmstring global.size.iconSizeSmInput icon size sm size.labelFontSizestring global.size.fontSizeSmInput label line height size.labelLineHeightstring global.size.lineHeightSmInput label font size size.fontSizestring global.size.fontSizeSmInput font size size.lineHeightstring global.size.lineHeightSmInput line height size.fontSizeLgstring global.size.fontSizeLgInput font size lg size.lineHeightLgstring global.size.lineHeightLgInput line height lg size.tokenFontSizestring global.size.fontSizeXsInput token font size size.tokenLineHeightstring global.size.lineHeightXsInput token line height size.tokenFontSizeSmstring global.size.fontSizeBaseInput token font size sm size.tokenLineHeightSmstring global.size.lineHeightBaseInput token line height sm size.buttonPxstring global.size.spacer * 2Input button padding inline size.buttonPystring global.size.spacerInput button padding block size.buttonFontSizestring global?.size?.fontSizeXsInput button font size size.buttonLineHeightstring global?.size?.lineHeightXsInput button line height color.textColorstring global.color.colorTextPrimaryInput text color color.loadingTextColorstring global.color.colorTextLoadingInput loading text color color.bgColorstring global.color.colorBgNeutralInput bg color color.bgColorFocusstring transparentInput bg color color.borderColorstring #4C505BInput border color color.borderColorFocusstring global.color.colorTextPrimaryInput border focus color color.placeholderColorstring global.color.colorTextSecondaryInput placeholder color color.buttonBgColorstring global.color.colorBgSecondaryInput button bg color color.buttonBorderColorstring global.color.colorBgAccentToInput button border color color.buttonTextColorstring global.color.colorTextPrimaryInput button text color style.radiusstring global.style.radiusPrimaryInput border radius style.labelFontWeightstring global.style.fontWeightLightInput label font weight style.fontWeightstring global.style.fontWeightLightInput font weight style.tokenFontWeightstring global.style.fontWeightLightInput token font weight style.buttonRadiusstring 30pxInput button border radius
tooltip
path: component.tooltip[name]
name type default value description color.colorBgstring #12171FTooltip bg color color.colorTextstring #ffffffTooltip bg color
switch
path: component.switch[name]
name type default value description color.colorBgCheckedstring #152E4DSwitch checked bg color color.colorBgstring #4C505BSwitch unchecked bg color
actionButton
path: component.actionButton[name]
name type default value description size.borderWidthstring 1pxAction button border width color.colorBgFromstring global.color.colorBgAccentFromAction button bg gradient color from color.colorBgTostring global.color.colorBgAccentToAction button bg gradient color to color.colorBgFromHoverstring global.color.colorBgAccentFromHoverAction button hover bg gradient color from color.colorBgToHoverstring global.color.colorBgAccentToAction button hover bg gradient color to color.colorBorderstring global.color.colorBgAccentFromAction button border color color.colorTextstring global.color.colorTextAccentAction button text color color.colorTextstring global.color.colorTextAccentAction button text color color.outlineColorBorderstring #ffffff33Action outline button border color color.outlineColorBorderHoverstring #ffffffCCAction outline button hover border color color.outlineColorTextstring global.color.colorTextPrimaryAction outline button text color
meta
path: component.meta[name]
name type default value description size.gapstring global.size.gapMeta flex gap size.pxstring global.size.spacer * 3Meta padding inline color.linkTextColorstring global.color.colorBgAccentFromMeta link text color color.panelBgHoverstring config.global.color.colorBgNeutralMeta panel hover bg
Source: packages/trading-widget/src/trading-widget/providers/theme-provider/theme-provider.tsx
Default values: undefined
name type default value description depositSlippageWarningstring Excludes entry fee. Slippage may be amplified by the leverage. See the docs for more info. withdrawSlippageWarningstring Slippage only applies to single asset withdrawals and withdrawals from vaults with debt positions in Aave. minSlippageWarningstring Flexible min slippage value that is likely enough to process the transaction. highSlippageWarningstring We recommend using another asset to trade with lower slippage. recommendedMinSlippagestring Recommended Min Slippage projectedDailyEarningsTooltipstring Projected daily earnings are based on the current APY and may differ from actual earnings. dailyEarningsstring Daily Earnings projectedYearlyEarningsTooltipstring Projected yearly earnings are based on the current APY and may differ from actual earnings. yearlyEarningsstring Yearly Earnings fullReceiveDetailsstring See full details influencing what you will receive. tradeDetailsstring Trade details maxSlippagestring Max slippage minReceiveAmountstring You will receive no less than this amount. minReceivedstring Minimum Received estimatedMultiAssetFractionsstring Estimated multi asset fractions infinitestring Infinite tokenAllowancestring Token Allowance entryFeestring Entry Fee entryFeeExplanationstring When you deposit, the token takes a small entry fee. This fee helps cover the costs when we rebalance the underlying funds, and it's shared among all token holders. amountToBeApprovedstring Amount of {symbol} tokens to be approved. Can be customized in settings. minDepositUsdstring Minimum deposit in USD. minDepositstring Minimum Deposit tokensLockTimestring Purchased tokens will have a {lockTime} lock. slippageTolerancestring Slippage tolerance bypassEntryFeestring Bypass Entry Fee tokenAmountToApprovestring Amount of tokens to be approved. autostring Auto autoSlippageDescriptionstring App is testing different slippage ranges, starting low and increasing until it's likely to pass lengthenLockupstring Lengthen lockup to remove entry fee depositstring Buy withdrawstring Sell yourBalancestring Your Balance maxstring Max allAssetsstring All Assets allstring All payWithstring Pay with buyEstimatedstring Buy (estimated) sellstring Sell receiveEstimatedstring Receive (estimated) confirmInWalletstring Please confirm in wallet pendingstring Pending... approvestring Approve connectWalletstring Connect Wallet minimumPurchasestring Minimum purchase is ${value} poolIsInactivestring {poolSymbol} token is no longer active. Please withdraw from them. poolIsPrivatestring This vault is currently private updateOraclesstring Update Oracles checkingOraclesstring Checking Oracles confirmMaxSlippagestring Confirm {slippagePercentage}% max slippage withdrawalWindowDisabledstring You can sell your {tokenSymbol} tokens during withdrawal window period starting from {startTime} withdrawalLiquidityDisabledstring Intended withdraw value is greater than available liquidity ({symbol} {value}) withdrawCooldownstring You can sell your {tokenSymbol} tokens in {cooldownEndTime} termsOfUsestring Terms Of Use termOfUseDepositListTitlestring Please know the following before depositing termOfUseDepositAssetSlippagestring When exiting, investors receive single asset or the underlying vault assets. Withdraw slippage can be customized in withdraw settings termOfUseDepositBugsstring There may be interface bugs on the platform termOfUseDepositDowntimestring There may be interface downtime (planned and unplanned) termOfUseDepositAuditRiskstring Smart contracts are audited but a risk is still present termOfUseDepositAcceptstring Accept & Deposit backstring Back highSlippagestring High Slippage Alert responsibleHighSlippagestring By proceeding with this trade, you acknowledge and accept the possibility of experiencing high slippage, resulting in a potential difference between the expected and executed price. highSlippageListTitlestring Please consider the following before confirming highSlippageQuoteDiffstring Be aware that the final amount of assets you receive may be different from the initially quoted value. highSlippageRiskstring Ensure that you understand the risks associated with high slippage and are comfortable proceeding with the trade. confirmstring Confirm selectTokenstring Select Token sendingOrderToWalletstring Sending order to your wallet settingUpTxstring Setting up transaction updateSynthetixOraclesstring Updating Synthetix Oracles approveSpendingstring Approve {symbol} spending paystring Pay multiAssetFractionsstring multi asset fractions explorerstring Explorer asstring As
Source: packages/trading-widget/src/trading-widget/providers/translation-provider/translation-provider.tsx
Default values: packages/trading-widget/src/trading-widget/providers/translation-provider/translation-provider.defaults.ts
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
12 months ago
1 year ago
1 year ago
12 months ago
1 year ago
1 year ago
1 year ago
12 months ago
12 months ago
12 months ago
12 months ago
12 months ago
12 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
12 months ago
11 months ago
12 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
11 months ago
11 months ago
11 months ago
11 months ago
10 months ago
1 year ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
10 months ago
1 year ago
1 year ago
1 year ago
1 year ago
11 months ago
1 year ago
11 months ago
1 year ago
11 months ago
11 months ago
1 year ago
11 months ago
11 months ago
1 year ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
11 months ago
12 months ago
11 months ago
11 months ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
11 months ago
1 year ago
1 year ago
11 months ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
12 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago