
Research
/Security News
Mini Shai-Hulud Campaign Hits Red Hat Cloud Services npm Packages
A mini Shai-Hulud campaign compromised Red Hat Cloud Services npm packages to steal developer and CI/CD secrets during installation.
@multiversx/sdk-dapp-swap
Advanced tools
A library to hold the main logic for swapping between tokens on the MultiversX blockchain
A library to hold the main logic for swapping between tokens on the MultiversX blockchain
The library can be installed via npm or yarn.
npm install @multiversx/sdk-dapp-swap
or
yarn add @multiversx/sdk-dapp-swap
sdk-dapp-swap proposes to simplify the process of implementing the swap functionality on MultiversX, providing easy to use utility functions and hooks for a specific application.
There are a couple of requirements that need to be met for the application to work properly.
If you experience bugs, please make sure that you read these, before opening an issue
This library was built for applications that use React, it might not be suitable for usage with other libraries or frameworks.
You need to wrap your application with the SwapAuthorizationProvider component, which is exported by the library, as we need to create a global Context to be able to manipulate the data.
import { SwapAuthorizationProvider } from '@multiversx/sdk-dapp-swap/components/SwapAuthorizationProvider/SwapAuthorizationProvider';
or;
import { SwapAuthorizationProvider } from '@multiversx/sdk-dapp-swap/components';
<SwapAuthorizationProvider
accessToken={accessToken}
graphQLAddress={network.graphQlAddress}
getAuthorizationHeaders={getAuthorizationHeaders} // optional
>
graphQLAddress is a required key that is needed to tell the Apollo Client on what graphQL address it should send the requests. Accepted values are any url string as well as the xExchange GraphQL service environment based endpoint (provided in SwapGraphQLAddressEnum).
accessToken is the accessToken mandatory for authorizing the requests.
SwapAuthorizationProvider also accepts an optional getAuthorizationHeaders async function that returns the headers object that will be provided on each request.
This allows the user to specify extra rules for the authorization of the requests.
getAuthorizationHeaders accepts the requestParams parameter which is of type AuthorizationHeadersRequestParamsType (also exported from the package).
This area covers the hooks required to implement a basic swap functionality.
These hooks are exposed as named exports, which can be imported from sdk-dapp-swap.
import { useTokens } from '@multiversx/sdk-dapp-swap/hooks';
or;
import { useFilteredTokens } from '@multiversx/sdk-dapp-swap/hooks/useFilteredTokens';
const {
tokens,
refetch,
getTokens,
swapConfig,
wrappedEgld,
isTokensError,
isTokensLoading,
totalTokensCount
} = useFilteredTokens(options);
The useFilteredTokens hook returns the state of the tokens based on whether you are authenticated or not. This hook accepts the options object in case the user wants to provide extra variables information for the query (see GetTokensType type).
import { useSwapRoute } from '@multiversx/sdk-dapp-swap/hooks';
or;
import { useSwapRoute } from '@multiversx/sdk-dapp-swap/hooks/useSwapRoute';
// reduces load on the microservice side by not querying transactions if the user does not have enough balance for the swap
const [hasEnoughBalance, setHasEnoughBalance] = useState(false);
const {
swapRoute,
getSwapRoute,
swapActionType,
swapRouteError,
isAmountInLoading,
isSwapRouteLoading,
isAmountOutLoading
} = useSwapRoute({
wrappedEgld,
hasEnoughBalance,
isPollingEnabled: true
});
The useSwapRoute hook returns the swapRoute required to compute the informations regarding both tokens provided in the fields. This hook accepts 2 optional parameters: wrappedEgld EsdtType object and a boolean parameter called isPollingEnabled to decide if the query should have polling or not.
import { useSwapFormHandlers } from '@multiversx/sdk-dapp-swap/hooks';
or;
import { useSwapFormHandlers } from '@multiversx/sdk-dapp-swap/hooks/useSwapFormHandlers';
const {
firstToken,
firstAmount,
secondToken,
secondAmount,
activeRoute,
handleOnChangeFirstAmount,
handleOnChangeSecondAmount,
handleOnChangeFirstSelect,
handleOnChangeSecondSelect,
handleOnChangeSwapRoute,
handleOnFirstMaxBtnChange,
handleSwitchTokens
} = useSwapFormHandlers({
getSwapRoute,
tolerancePercentage
});
useMemo(() => {
setHasEnoughBalance(
getHasEnoughBalance({ token: firstToken?.token, amount: firstAmount })
);
}, [firstToken?.token, firstAmount]);
The useSwapFormHandlers hook returns the state of both the tokens and amounts, as well as the callbacks required for the inputs, selects, the maximum amount button and the button that triggers both tokens to switch. This hook accepts a mandatory parameter called getSwapRoute which is a function that comes from useSwapRoute (see useSwapRoute for reference) and an optional tolerancePercentage, which is the tolerance of the user account.
import { useSwapInfo } from '@multiversx/sdk-dapp-swap/hooks';
or;
import { useSwapInfo } from '@multiversx/sdk-dapp-swap/hooks/useSwapInfo';
const {
tokenInId,
tokenOutId,
exchangeRate,
pricesImpact,
totalTransactionsFee,
minimumAmountReceived,
exchangeRateUsdValue,
switchTokensDirection
} = useSwapInfo({
tolerance,
activeRoute,
firstToken,
firstAmount,
secondToken,
secondAmount,
swapActionType
});
The useSwapInfo hook provides all the informations regarding the swap route, like exchange rate, details about fees, minimum amount received etc. This hook accepts a couple of parameters that implies both tokens and amounts, as well as the active swap route and account tolerance.
import { useSwapValidationSchema } from '@multiversx/sdk-dapp-swap/validation/hooks';
or;
import { useSwapValidationSchema } from '@multiversx/sdk-dapp-swap/validation/hooks/useSwapValidationSchema';
const validationSchema = useSwapValidationSchema({
firstToken,
secondToken,
minAcceptedAmount: minSwapAmount
});
The useSwapInfo hook provides the validation schema in order to facilitate a proper swap. This schema provides rules like insufficient balance, token / minimum token required etc. This hook accepts 2 mandatory firstToken and secondToken parameters, as well as an optional number called minAcceptedAmount which is the minimum amount required for the validation schema.
We recommend to import everything from its own file, in this way you won't be stressed about importing unused code.
You can either go into their specific folder in the module for extra trimming, or import everything together.
for example, these 2 imports are both valid:
import {
useSwapRoute,
useSwapFormHandlers
} from '@multiversx/sdk-dapp-swap/hooks';
and
import { useSwapRoute } from '@multiversx/sdk-dapp-swap/hooks/useSwapRoute';
import { useSwapFormHandlers } from '@multiversx/sdk-dapp-swap/hooks/useSwapFormHandlers';
import {
FIXED_INPUT,
FIXED_OUTPUT,
EGLD_IDENTIFIER,
DIGITS,
MIN_EGLD_DUST,
POLLING_INTERVAL
} from '@multiversx/sdk-dapp-swap/constants/general';
import {
useTokens,
useWrapEgld,
useSwapInfo,
useSwapRoute,
useUnwrapEgld,
useQueryWrapper,
useIsPageVisible,
useRateCalculator,
useLazyQueryWrapper,
useSwapFormHandlers,
useInputAmountUsdValue,
useFetchMaintenanceFlag
} from '@multiversx/sdk-dapp-swap/hooks';
import {
roundAmount,
removeCommas,
canParseAmount,
getTokenDecimals,
getTransactionFee,
translateSwapError,
getSwapActionType,
getBalanceMinusDust,
meaningfulFormatAmount,
createTransactionFromRaw,
calculateMinimumReceived,
getSortedTokensByUsdValue
} from '@multiversx/sdk-dapp-swap/utils';
import {
SwapForm,
SelectOpion,
TokenSelect,
SwapAuthorizationProvider
} from '@multiversx/sdk-dapp-swap/components';
See the open issues for a list of proposed features (and known issues).
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.
One can contribute by creating pull requests, or by opening issues for discovered bugs or desired features.
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)GPL-3.0-or-later
FAQs
A library to hold the main logic for swapping between tokens on the MultiversX blockchain
The npm package @multiversx/sdk-dapp-swap receives a total of 160 weekly downloads. As such, @multiversx/sdk-dapp-swap popularity was classified as not popular.
We found that @multiversx/sdk-dapp-swap demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 12 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Research
/Security News
A mini Shai-Hulud campaign compromised Red Hat Cloud Services npm packages to steal developer and CI/CD secrets during installation.

Research
/Security News
The North Korean malware loader hides in a Packagist-listed package and its GitHub branch to fetch and execute remote code in a likely Contagious Interview-style lure.

Security News
The Rust project is moving toward formal rules on LLM use in contributions after months of internal debate over maintainer burden, code quality, and contributor experience.