BrainDex exposes three functions for swapping tokens, after common router patterns of allowing the network currency as either the input or the output of the swap, as well as allowing swaps of tokens for tokens.
Calling the swap function with route request response parameters
In cases where the end-user is attempting to swap to or from the network currency, the route request JSON must be populated with the corresponding input/output wrapped version of the network currency. For example, if the end-user wants to swap from native ETH, token_in will be the WETH address.
A sample call to prepare a swap transaction using wagmi.sh:
const { config,error } =usePrepareContractWrite({ address: BrainDexRouterContract, abi: BrainDexRouterAbi, functionName:"multiSwapTokensForTokens", args: [ token_in,// Supplied by frontend token_out,// Supplied by frontend to,// Supplied by frontend amount_in,// Supplied by frontend amount_out_min,// computed using amount_out net slippage timestamp,// Supplied by frontend swap_paths,// Supplied by pathfinderResponse ], overrides: {},
swap_viz_data and price_impact are not used in the on-chain call, and are for frontend visualization / route visualization purposes only.
Security Considerations
While we return token_in, token_out, and amount_in from the route response, when calling the relevant swap function, for safety the following parameters should be supplied directly from the frontend interface, and not from the route request response:
tokenIn: The token to swap from
tokenOut: The token to swap to
amountIn: The desired amount of tokens to swap from
to: The account which should receive the output swap
deadline: The deadline in UNIX time after which processing the swap will result in a revert
The following two parameters should be processed from the route response object:
amountOutMin: This is a computed parameter equal to the amount_out quote, net the slippage margin as processed by a frontend. This should be at least marginally lower than the actual quote value, as transactions trading with exactly 0% slippage are likely to fail.
swapData: This parameter should be passed directly from the route response object to the smart contract call as is.
A Note on Gas Estimation
We do not currently provide gas estimation via the BrainDex API -- gas estimation should be done locally. In addition, we have found that for most compatible chains, the gas estimate can sometimes be insufficient to complete the swap, so we recommend that implementers buffer their gas estimates by 1.2x the returned value to ensure swap success.