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