Swap API
生成可直接使用的交易 calldata,通过 Universal Router 执行交换。返回的响应可以直接作为交易发送。POST /api/v1/swap
请求体
{
"tokenIn": "0xB190a6A7fC2873f1Abf145279eD664348d5Ef630",
"tokenOut": "0x3Ac3B30b7f18AEFD4590D7FE4d9C5944aaeB7220",
"amountIn": "1000000000000000000",
"tradeType": 0,
"slippage": 0.5,
"recipient": "0xYourAddress",
"deadline": 1200
}
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
tokenIn | string | 是 | 输入代币地址 |
tokenOut | string | 是 | 输出代币地址 |
amountIn | string | 条件必填 | 输入数量,tradeType=0 时必填 |
amountOut | string | 条件必填 | 输出数量,tradeType=1 时必填 |
tradeType | number | 否 | 0 = 精确输入(默认),1 = 精确输出 |
slippage | number | 否 | 滑点容忍度(百分比,默认:0.5) |
recipient | string | 是 | 接收输出代币的地址 |
deadline | number | 否 | 过期时间(秒,默认:1200 = 20 分钟) |
响应
{
"to": "0x440d7f5FE865eFCcfdCB1ee9a000C114163689ba",
"data": "0x3593564c...",
"value": "0",
"gasEstimate": "100000",
"tradeType": 0,
"quote": {
"tokenIn": "0xb190...",
"tokenOut": "0x3ac3...",
"amountIn": "1000000000000000000",
"amountOut": "1007249042881810956",
"minAmountOut": "1002212797667401901",
"priceImpact": 0.3,
"protocol": "v2",
"path": ["0xb190...", "0x3ac3..."],
"fees": [0],
"hops": 1
},
"deadline": "1764573986",
"slippage": 0.5,
"permit2": "0xc320bc492Bb56169aBE18D3C0a2048c45febC897"
}
| 字段 | 描述 |
|---|---|
to | Universal Router 地址——用作交易的 to 字段 |
data | 编码后的 calldata——用作交易的 data 字段 |
value | 原生 KAS 数量——用作交易的 value 字段(当输入代币为 KAS 时不为零) |
gasEstimate | 预估 Gas 用量 |
quote.minAmountOut | 最低输出数量(精确输入时)——链上滑点保护 |
quote.maxAmountIn | 最高输入数量(精确输出时)——链上滑点保护 |
permit2 | Permit2 合约地址 |
滑点保护
| 交易类型 | 字段 | 计算公式 |
|---|---|---|
| 精确输入 (0) | minAmountOut | amountOut × (1 - slippage / 100) |
| 精确输出 (1) | maxAmountIn | amountIn × (1 + slippage / 100) |
使用方式
// 1. 获取 calldata
const res = await fetch('/swap-api/api/v1/swap', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tokenIn, tokenOut, amountIn,
tradeType: 0,
slippage: 0.5,
recipient: userAddress,
deadline: 1200
})
});
const swapData = await res.json();
// 2. 发送交易
const tx = await signer.sendTransaction({
to: swapData.to,
data: swapData.data,
value: swapData.value
});
示例
{
"tokenIn": "0xB190a6A7fC2873f1Abf145279eD664348d5Ef630",
"tokenOut": "0x3Ac3B30b7f18AEFD4590D7FE4d9C5944aaeB7220",
"amountIn": "1000000000000000000",
"tradeType": 0,
"slippage": 0.5,
"recipient": "0xUserAddress",
"deadline": 1200
}
{
"tokenIn": "0xB190a6A7fC2873f1Abf145279eD664348d5Ef630",
"tokenOut": "0x3Ac3B30b7f18AEFD4590D7FE4d9C5944aaeB7220",
"amountOut": "1000000000000000000",
"tradeType": 1,
"slippage": 0.5,
"recipient": "0xUserAddress",
"deadline": 1200
}