|
| 1 | +import { getAssetDecimals, getAssetMultiLocation } from "@paraspell/assets" |
| 2 | +import type { TCurrency, TMultiLocation, TNodeDotKsmWithRelayChains } from "@paraspell/sdk" |
| 3 | +import type { |
| 4 | + RouterBuilderCore, |
| 5 | + TBuildTransactionsOptions, |
| 6 | + TExchangeInput, |
| 7 | + TRouterAsset, |
| 8 | + TRouterPlan |
| 9 | +} from "@paraspell/xcm-router" |
| 10 | +import { RouterBuilder } from "@paraspell/xcm-router" |
| 11 | +import { parseUnits } from "@polkadot-agent-kit/common" |
| 12 | +import type { PolkadotSigner } from "polkadot-api/signer" |
| 13 | + |
| 14 | +import { getPairSupported } from "../utils/defi" |
| 15 | + |
| 16 | +// Constants |
| 17 | +const DEFAULT_SLIPPAGE_PCT = "1" |
| 18 | +const HYDRATION_DEX = "HydrationDex" |
| 19 | + |
| 20 | +export interface SwapTokenArgs { |
| 21 | + from?: string |
| 22 | + to?: string |
| 23 | + currencyFrom: string |
| 24 | + currencyTo: string |
| 25 | + amount: string |
| 26 | + sender?: string |
| 27 | + receiver?: string |
| 28 | + dex?: string |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Builds a token swap transaction supporting both cross-chain and DEX-specific swaps. |
| 33 | + * |
| 34 | + * This function uses the \@paraspell/xcm-router RouterBuilder to construct token swaps |
| 35 | + * that exchange one token for another within the Polkadot ecosystem. |
| 36 | + * |
| 37 | + * **Two supported modes:** |
| 38 | + * 1. **Cross-chain swap**: Uses XCM routing between different chains via Hydration DEX |
| 39 | + * 2. **DEX-specific swap**: Direct swap within a specific DEX (e.g., HydrationDex) |
| 40 | + * |
| 41 | + * @param args - The swap configuration object |
| 42 | + * @param signer - The Polkadot signer for transaction signing |
| 43 | + * @param isCrossChainSwap - Boolean flag to determine swap type |
| 44 | + * @returns A Promise resolving to a TRouterPlan object containing the swap transaction plan |
| 45 | + */ |
| 46 | +export const swapTokens = async ( |
| 47 | + args: SwapTokenArgs, |
| 48 | + signer: PolkadotSigner, |
| 49 | + isCrossChainSwap: boolean |
| 50 | +): Promise<TRouterPlan> => { |
| 51 | + validateSwapArgs(args, isCrossChainSwap) |
| 52 | + |
| 53 | + return isCrossChainSwap |
| 54 | + ? await executeCrossChainSwap(args, signer) |
| 55 | + : await executeDexSwap(args, signer) |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Validates swap arguments based on swap type |
| 60 | + */ |
| 61 | +function validateSwapArgs(args: SwapTokenArgs, isCrossChainSwap: boolean): void { |
| 62 | + if (isCrossChainSwap) { |
| 63 | + if (!args.from || !args.to) { |
| 64 | + throw new Error("Cross-chain swaps require both 'from' and 'to' chain parameters") |
| 65 | + } |
| 66 | + } else { |
| 67 | + if (!args.dex) { |
| 68 | + throw new Error("DEX-specific swaps require 'dex' parameter") |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + if (!args.currencyFrom || !args.currencyTo) { |
| 73 | + throw new Error("Both 'currencyFrom' and 'currencyTo' are required") |
| 74 | + } |
| 75 | + |
| 76 | + if (!args.amount || parseFloat(args.amount) <= 0) { |
| 77 | + throw new Error("Amount must be a positive number") |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Executes cross-chain swap using XCM routing |
| 83 | + */ |
| 84 | +async function executeCrossChainSwap( |
| 85 | + args: SwapTokenArgs, |
| 86 | + signer: PolkadotSigner |
| 87 | +): Promise<TRouterPlan> { |
| 88 | + const { multilocationFrom, multilocationTo } = getCrossChainMultilocations(args) |
| 89 | + if (!multilocationFrom || !multilocationTo) { |
| 90 | + throw new Error("Failed to get multilocations for cross-chain swap") |
| 91 | + } |
| 92 | + const formattedAmount = formatCrossChainAmount(args) |
| 93 | + |
| 94 | + // Validate fees before proceeding |
| 95 | + await validateSwapFees({ |
| 96 | + builder: createCrossChainRouterBuilder( |
| 97 | + args, |
| 98 | + multilocationFrom, |
| 99 | + multilocationTo, |
| 100 | + formattedAmount |
| 101 | + ), |
| 102 | + swapType: "cross-chain" |
| 103 | + }) |
| 104 | + |
| 105 | + return await createCrossChainRouterBuilder( |
| 106 | + args, |
| 107 | + multilocationFrom, |
| 108 | + multilocationTo, |
| 109 | + formattedAmount |
| 110 | + ) |
| 111 | + .signer(signer) |
| 112 | + .buildTransactions() |
| 113 | +} |
| 114 | + |
| 115 | +/** |
| 116 | + * Executes DEX-specific swap |
| 117 | + */ |
| 118 | +async function executeDexSwap(args: SwapTokenArgs, signer: PolkadotSigner): Promise<TRouterPlan> { |
| 119 | + const { currencyFrom, currencyTo } = validateAndGetDexPair(args) |
| 120 | + const decimals = getAssetDecimals("Hydration", args.currencyFrom) |
| 121 | + if (!decimals) { |
| 122 | + throw new Error(`Failed to get decimals for ${args.currencyFrom} on Hydration`) |
| 123 | + } |
| 124 | + |
| 125 | + const formattedAmount = parseUnits(args.amount, decimals) |
| 126 | + |
| 127 | + // Validate fees before proceeding |
| 128 | + await validateSwapFees({ |
| 129 | + builder: createDexRouterBuilder( |
| 130 | + args, |
| 131 | + currencyFrom, |
| 132 | + currencyTo, |
| 133 | + BigInt(formattedAmount).toString() |
| 134 | + ), |
| 135 | + swapType: "DEX-specific" |
| 136 | + }) |
| 137 | + |
| 138 | + return await createDexRouterBuilder( |
| 139 | + args, |
| 140 | + currencyFrom, |
| 141 | + currencyTo, |
| 142 | + BigInt(formattedAmount).toString() |
| 143 | + ) |
| 144 | + .signer(signer) |
| 145 | + .buildTransactions() |
| 146 | +} |
| 147 | + |
| 148 | +/** |
| 149 | + * Gets multilocations for cross-chain currencies |
| 150 | + */ |
| 151 | +function getCrossChainMultilocations(args: SwapTokenArgs) { |
| 152 | + const multilocationFrom = getAssetMultiLocation(args.from as TNodeDotKsmWithRelayChains, { |
| 153 | + symbol: args.currencyFrom |
| 154 | + }) |
| 155 | + |
| 156 | + const multilocationTo = getAssetMultiLocation(args.to as TNodeDotKsmWithRelayChains, { |
| 157 | + symbol: args.currencyTo |
| 158 | + }) |
| 159 | + |
| 160 | + return { multilocationFrom, multilocationTo } |
| 161 | +} |
| 162 | + |
| 163 | +/** |
| 164 | + * Formats amount for cross-chain swaps using proper decimals |
| 165 | + */ |
| 166 | +function formatCrossChainAmount(args: SwapTokenArgs): string { |
| 167 | + const decimals = getAssetDecimals(args.from as TNodeDotKsmWithRelayChains, args.currencyFrom) |
| 168 | + |
| 169 | + if (!decimals) { |
| 170 | + throw new Error(`Failed to get decimals for ${args.currencyFrom} on ${args.from}`) |
| 171 | + } |
| 172 | + |
| 173 | + return parseUnits(args.amount, decimals).toString() |
| 174 | +} |
| 175 | + |
| 176 | +/** |
| 177 | + * Validates DEX pair support and returns currency objects |
| 178 | + */ |
| 179 | +function validateAndGetDexPair(args: SwapTokenArgs) { |
| 180 | + const pair = getPairSupported(args.currencyFrom, args.currencyTo, args.dex) |
| 181 | + |
| 182 | + if (!pair) { |
| 183 | + throw new Error( |
| 184 | + `Trading pair ${args.currencyFrom}/${args.currencyTo} is not supported on ${args.dex}` |
| 185 | + ) |
| 186 | + } |
| 187 | + |
| 188 | + return { |
| 189 | + currencyFrom: pair[0], |
| 190 | + currencyTo: pair[1] |
| 191 | + } |
| 192 | +} |
| 193 | + |
| 194 | +/** |
| 195 | + * Creates router builder for cross-chain swaps |
| 196 | + */ |
| 197 | +function createCrossChainRouterBuilder( |
| 198 | + args: SwapTokenArgs, |
| 199 | + multilocationFrom: TMultiLocation, |
| 200 | + multilocationTo: TMultiLocation, |
| 201 | + formattedAmount: string |
| 202 | +) { |
| 203 | + return RouterBuilder() |
| 204 | + .from(args.from as TNodeDotKsmWithRelayChains) |
| 205 | + .to(args.to as TNodeDotKsmWithRelayChains) |
| 206 | + .exchange(HYDRATION_DEX) |
| 207 | + .currencyFrom({ multilocation: multilocationFrom }) |
| 208 | + .currencyTo({ multilocation: multilocationTo }) |
| 209 | + .amount(BigInt(formattedAmount).toString()) |
| 210 | + .slippagePct(DEFAULT_SLIPPAGE_PCT) |
| 211 | + .senderAddress(args.sender || "") |
| 212 | + .recipientAddress(args.receiver || "") |
| 213 | +} |
| 214 | + |
| 215 | +/** |
| 216 | + * Creates router builder for DEX-specific swaps |
| 217 | + */ |
| 218 | +function createDexRouterBuilder( |
| 219 | + args: SwapTokenArgs, |
| 220 | + currencyFrom: TRouterAsset, |
| 221 | + currencyTo: TRouterAsset, |
| 222 | + formattedAmount: string |
| 223 | +) { |
| 224 | + return RouterBuilder() |
| 225 | + .exchange(args.dex as TExchangeInput) |
| 226 | + .currencyFrom({ id: currencyFrom.assetId as TCurrency }) |
| 227 | + .currencyTo({ id: currencyTo.assetId as TCurrency }) |
| 228 | + .amount(formattedAmount) |
| 229 | + .slippagePct(DEFAULT_SLIPPAGE_PCT) |
| 230 | + .senderAddress(args.sender || "") |
| 231 | + .recipientAddress(args.receiver || "") |
| 232 | +} |
| 233 | + |
| 234 | +/** |
| 235 | + * Validates swap fees before execution |
| 236 | + */ |
| 237 | +async function validateSwapFees({ |
| 238 | + builder, |
| 239 | + swapType |
| 240 | +}: { |
| 241 | + builder: RouterBuilderCore<TBuildTransactionsOptions> |
| 242 | + swapType: "cross-chain" | "DEX-specific" |
| 243 | +}): Promise<void> { |
| 244 | + const fees = await builder.getXcmFees() |
| 245 | + |
| 246 | + if (fees.failureChain || fees.failureReason) { |
| 247 | + throw new Error( |
| 248 | + `Failed to calculate ${swapType} swap fees: ${fees.failureChain || fees.failureReason}` |
| 249 | + ) |
| 250 | + } |
| 251 | +} |
0 commit comments