@michaleffffff/mcp-trading-server 3.0.3 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +9 -3
- package/TOOL_EXAMPLES.md +4 -0
- package/dist/prompts/tradingGuide.js +4 -0
- package/dist/server.js +2 -2
- package/dist/tools/accountTransfer.js +89 -3
- package/dist/tools/closeAllPositions.js +3 -5
- package/dist/tools/closePosition.js +59 -11
- package/dist/tools/manageLiquidity.js +6 -1
- package/dist/tools/marketInfo.js +18 -2
- package/dist/utils/slippage.js +23 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.0.4 - 2026-03-17
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- `get_my_lp_holdings` tool for listing all wallet LP balances with standardized naming.
|
|
7
|
+
- Enriched `manage_liquidity` response with `lpAssetNames` (e.g., `mBTC.USDC`).
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- Improved `close_all_positions` with more robust automated price fetching.
|
|
11
|
+
- `get_liquidity_info` now accepts human-readable prices and `raw:` prefixes.
|
|
12
|
+
- Updated `TOOL_EXAMPLES.md` to include LP holding and management samples.
|
|
13
|
+
|
|
3
14
|
## 3.0.3 - 2026-03-17
|
|
4
15
|
|
|
5
16
|
### Changed
|
package/README.md
CHANGED
|
@@ -124,7 +124,8 @@ The server will run using `stdio` transport and can be connected by any MCP-comp
|
|
|
124
124
|
2. **Configure env**: Copy `.env.example` to `.env` and fill in `PRIVATE_KEY`, `RPC_URL`, etc.
|
|
125
125
|
3. **Start the server**: Run `npm run build` then `npm run start` (use `npm run dev` for development).
|
|
126
126
|
4. **Configure your MCP client**: Set `command/args/env` in your MCP client (see Claude Desktop example below).
|
|
127
|
-
5. **Common flow**: Use `search_market` (or `get_pool_list`) to get `poolId`, then optionally `get_market_price` / `get_oracle_price` to view prices, and finally use `open_position_simple` (recommended) to open a position.
|
|
127
|
+
5. **Common flow**: Use `search_market` (or `get_pool_list`) to get `poolId`, then optionally `get_market_price` / `get_oracle_price` to view prices, and finally use `open_position_simple` (recommended) to open a position.
|
|
128
|
+
Note: `open_position_simple` does not accept `tpPrice` / `tpSize` / `slPrice` / `slSize`. Use `set_tp_sl` (for positions) or `update_order_tp_sl` (for orders).
|
|
128
129
|
6. **Tool examples**: See `TOOL_EXAMPLES.md` for practical examples for every tool, common workflows, and parameter-unit guidance.
|
|
129
130
|
|
|
130
131
|
**Minimal open position example:**
|
|
@@ -160,7 +161,12 @@ The server will run using `stdio` transport and can be connected by any MCP-comp
|
|
|
160
161
|
- **Raw units (explicit)**: Prefix with `raw:` to pass raw units exactly (e.g. `raw:100000000` for 100 USDC with 6 decimals).
|
|
161
162
|
- **Price**: `"price"` is human by default and will be converted to **30-decimal** format internally. Use `raw:` to pass a 30-decimal integer directly.
|
|
162
163
|
- **Slippage**: `slippagePct` uses 4-decimal raw units: `100` = `1%`, `50` = `0.5%`, `1000` = `10%`.
|
|
163
|
-
- **
|
|
164
|
+
- **close_all_positions slippage**: Supports raw 4dp (`100`) and human percent strings (`"1.0"` or `"1%"`).
|
|
165
|
+
- **get_liquidity_info marketPrice**: Supports raw 30-dec integer, `raw:...`, and human price inputs (`"2172.5"` / `human:2172.5`).
|
|
166
|
+
- **close_position full-close helper**: `size` and `collateralAmount` accept `ALL` / `FULL` / `MAX` to auto-use exact live raw values.
|
|
167
|
+
- **manage_liquidity action**: Case-insensitive (`ADD`, `add`, `Increase` all supported).
|
|
168
|
+
- **account_deposit approval**: `account_deposit` now supports `autoApprove` and `approveMax` to auto-handle allowance when required.
|
|
169
|
+
- **Note**: `check_approval.amount` still expects **raw integer strings**.
|
|
164
170
|
- **`adjust_margin` units**: human amount is supported (e.g. `"1"` means 1 quote token). For exact atomic amount, use `raw:` (e.g. `"raw:1"`).
|
|
165
171
|
|
|
166
172
|
## P0 Reliability Contract (AI-friendly)
|
|
@@ -290,7 +296,7 @@ The server exposes tools categorized for AI:
|
|
|
290
296
|
For practical tool-by-tool examples, see: `TOOL_EXAMPLES.md`
|
|
291
297
|
|
|
292
298
|
### Trading Operations
|
|
293
|
-
* **open_position_simple**: High-level open position helper (recommended). Computes price/size/tradingFee internally.
|
|
299
|
+
* **open_position_simple**: High-level open position helper (recommended). Computes price/size/tradingFee internally. It only handles open/increase parameters and does **not** accept TP/SL fields (`tpPrice`, `tpSize`, `slPrice`, `slSize`); unknown keys are rejected by strict schema validation.
|
|
294
300
|
* **execute_trade**: Execute a new trade or add to an existing position (includes parameter preflight, supports `human:`/`raw:` amount prefixes, auto-computes `tradingFee` when omitted).
|
|
295
301
|
* **close_position**: Close an open position.
|
|
296
302
|
* **close_all_positions**: Emergency: close ALL open positions in a pool at once.
|
package/TOOL_EXAMPLES.md
CHANGED
|
@@ -62,6 +62,10 @@ It includes:
|
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
```
|
|
65
|
+
Notes:
|
|
66
|
+
- `open_position_simple` only accepts open/increase parameters and does not support `tpPrice`, `tpSize`, `slPrice`, `slSize` in the same call.
|
|
67
|
+
- If those TP/SL keys are included, the server rejects them as unrecognized fields (strict schema validation).
|
|
68
|
+
- Recommended flow: open with `open_position_simple` first, then use `set_tp_sl` (position-level) or `update_order_tp_sl` (order-level).
|
|
65
69
|
|
|
66
70
|
### `execute_trade`
|
|
67
71
|
```json
|
|
@@ -36,6 +36,10 @@ You are an expert crypto trader using the MYX Protocol. To ensure successful exe
|
|
|
36
36
|
- **Adjust Margin**: \`adjust_margin.adjustAmount\` supports human amount (e.g. "1"), and also supports exact raw amount via \`raw:\` prefix.
|
|
37
37
|
- **TP/SL Updates**: \`update_order_tp_sl\` accepts boolean-like values for \`useOrderCollateral\` and \`isTpSlOrder\`, but pending LIMIT/STOP orders can still be rejected by protocol rules; after fill, prefer \`set_tp_sl\`.
|
|
38
38
|
- **Pool Reads**: \`get_pool_info\` auto-retries with oracle/ticker price when direct on-chain read returns divide-by-zero.
|
|
39
|
+
- **Liquidity Price Input**: \`get_liquidity_info.marketPrice\` accepts raw 30-dec price and human price strings (e.g. \`2172.5\`, \`human:2172.5\`).
|
|
40
|
+
- **close_all_positions Slippage**: accepts both raw 4dp and human percent strings (e.g. \`"100"\`, \`"1.0"\`, \`"1%"\`).
|
|
41
|
+
- **close_position Full Close**: \`size\`/\`collateralAmount\` can use \`ALL\`/\`FULL\`/\`MAX\` to auto-fill exact live raw values from the current position snapshot.
|
|
42
|
+
- **Deposits & Approval**: \`account_deposit\` supports \`autoApprove\` + \`approveMax\`; without auto-approve, allowance errors should be handled via \`check_approval\`.
|
|
39
43
|
- **Examples**: Follow \`TOOL_EXAMPLES.md\` payload patterns when building tool arguments.
|
|
40
44
|
|
|
41
45
|
## 3. Self-Healing
|
package/dist/server.js
CHANGED
|
@@ -352,7 +352,7 @@ function zodSchemaToJsonSchema(zodSchema) {
|
|
|
352
352
|
};
|
|
353
353
|
}
|
|
354
354
|
// ─── MCP Server ───
|
|
355
|
-
const server = new Server({ name: "myx-mcp-trading-server", version: "3.0.
|
|
355
|
+
const server = new Server({ name: "myx-mcp-trading-server", version: "3.0.4" }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
|
|
356
356
|
// List tools
|
|
357
357
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
358
358
|
return {
|
|
@@ -473,7 +473,7 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
|
473
473
|
async function main() {
|
|
474
474
|
const transport = new StdioServerTransport();
|
|
475
475
|
await server.connect(transport);
|
|
476
|
-
logger.info("🚀 MYX Trading MCP Server v3.0.
|
|
476
|
+
logger.info("🚀 MYX Trading MCP Server v3.0.4 running (stdio, pure on-chain, prod ready)");
|
|
477
477
|
}
|
|
478
478
|
main().catch((err) => {
|
|
479
479
|
logger.error("Fatal Server Startup Error", err);
|
|
@@ -2,16 +2,53 @@ import { z } from "zod";
|
|
|
2
2
|
import { resolveClient, getChainId } from "../auth/resolveClient.js";
|
|
3
3
|
import { normalizeAddress } from "../utils/address.js";
|
|
4
4
|
import { finalizeMutationResult } from "../utils/mutationResult.js";
|
|
5
|
+
const MAX_UINT256 = "115792089237316195423570985008687907853269984665640564039457584007913129639935";
|
|
6
|
+
function asBigintOrNull(value) {
|
|
7
|
+
try {
|
|
8
|
+
const normalized = String(value ?? "").trim();
|
|
9
|
+
if (!normalized)
|
|
10
|
+
return null;
|
|
11
|
+
if (!/^-?\d+$/.test(normalized))
|
|
12
|
+
return null;
|
|
13
|
+
return BigInt(normalized);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function readReleaseTime(accountInfo) {
|
|
20
|
+
const data = accountInfo?.data;
|
|
21
|
+
if (Array.isArray(data)) {
|
|
22
|
+
return asBigintOrNull(data[6]) ?? 0n;
|
|
23
|
+
}
|
|
24
|
+
return asBigintOrNull(data?.releaseTime ?? data?.release_time) ?? 0n;
|
|
25
|
+
}
|
|
26
|
+
function readAvailableMarginRaw(raw) {
|
|
27
|
+
if (raw === null || raw === undefined)
|
|
28
|
+
return null;
|
|
29
|
+
if (typeof raw === "object" && "data" in raw) {
|
|
30
|
+
return asBigintOrNull(raw.data);
|
|
31
|
+
}
|
|
32
|
+
return asBigintOrNull(raw);
|
|
33
|
+
}
|
|
34
|
+
function formatUnixTimestamp(timestamp) {
|
|
35
|
+
const numeric = Number(timestamp);
|
|
36
|
+
if (!Number.isFinite(numeric) || numeric <= 0)
|
|
37
|
+
return String(timestamp);
|
|
38
|
+
return `${timestamp.toString()} (${new Date(numeric * 1000).toISOString()})`;
|
|
39
|
+
}
|
|
5
40
|
export const accountDepositTool = {
|
|
6
41
|
name: "account_deposit",
|
|
7
42
|
description: "Deposit funds from wallet into the MYX trading account.",
|
|
8
43
|
schema: {
|
|
9
44
|
amount: z.union([z.string(), z.number()]).describe("Amount to deposit (human-readable or raw units)"),
|
|
10
45
|
tokenAddress: z.string().describe("Token address"),
|
|
46
|
+
autoApprove: z.coerce.boolean().optional().describe("If true, auto-approve token allowance when needed (default false)."),
|
|
47
|
+
approveMax: z.coerce.boolean().optional().describe("If autoApprove=true, approve MaxUint256 instead of exact amount."),
|
|
11
48
|
},
|
|
12
49
|
handler: async (args) => {
|
|
13
50
|
try {
|
|
14
|
-
const { client, signer } = await resolveClient();
|
|
51
|
+
const { client, signer, address } = await resolveClient();
|
|
15
52
|
const chainId = getChainId();
|
|
16
53
|
const tokenAddress = normalizeAddress(args.tokenAddress, "tokenAddress");
|
|
17
54
|
// For deposit, we default to quote decimals (6) as it's the most common use case.
|
|
@@ -19,13 +56,32 @@ export const accountDepositTool = {
|
|
|
19
56
|
const { ensureUnits } = await import("../utils/units.js");
|
|
20
57
|
const { getQuoteDecimals } = await import("../auth/resolveClient.js");
|
|
21
58
|
const amount = ensureUnits(args.amount, getQuoteDecimals(), "amount", { allowImplicitRaw: false });
|
|
59
|
+
let approval = null;
|
|
60
|
+
const needApproval = await client.utils.needsApproval(address, chainId, tokenAddress, amount);
|
|
61
|
+
if (needApproval) {
|
|
62
|
+
if (!args.autoApprove) {
|
|
63
|
+
throw new Error(`Insufficient token allowance for deposit amount ${amount}. ` +
|
|
64
|
+
`Run check_approval (token=${tokenAddress}) or retry with autoApprove=true.`);
|
|
65
|
+
}
|
|
66
|
+
const approveAmount = args.approveMax ? MAX_UINT256 : amount;
|
|
67
|
+
const rawApproval = await client.utils.approveAuthorization({
|
|
68
|
+
chainId,
|
|
69
|
+
quoteAddress: tokenAddress,
|
|
70
|
+
amount: approveAmount,
|
|
71
|
+
});
|
|
72
|
+
approval = await finalizeMutationResult(rawApproval, signer, "account_deposit_approval");
|
|
73
|
+
}
|
|
22
74
|
const raw = await client.account.deposit({
|
|
23
75
|
amount,
|
|
24
76
|
tokenAddress,
|
|
25
77
|
chainId,
|
|
26
78
|
});
|
|
27
79
|
const data = await finalizeMutationResult(raw, signer, "account_deposit");
|
|
28
|
-
|
|
80
|
+
const payload = {
|
|
81
|
+
...data,
|
|
82
|
+
approval: approval ? { performed: true, details: approval } : { performed: false, needApproval: !!needApproval },
|
|
83
|
+
};
|
|
84
|
+
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: payload }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
29
85
|
}
|
|
30
86
|
catch (error) {
|
|
31
87
|
return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
|
|
@@ -49,6 +105,29 @@ export const accountWithdrawTool = {
|
|
|
49
105
|
// Assuming 18 decimals for base and quoteDecimals for quote
|
|
50
106
|
const decimals = args.isQuoteToken ? getQuoteDecimals() : 18;
|
|
51
107
|
const amount = ensureUnits(args.amount, decimals, "amount", { allowImplicitRaw: false });
|
|
108
|
+
const amountRaw = asBigintOrNull(amount);
|
|
109
|
+
if (amountRaw === null || amountRaw <= 0n) {
|
|
110
|
+
throw new Error(`amount must be a positive integer raw value after normalization, got: ${amount}`);
|
|
111
|
+
}
|
|
112
|
+
// Preflight to avoid avoidable AccountInsufficientFreeAmount reverts caused by locked funds.
|
|
113
|
+
const [accountInfoRaw, availableMarginRawResult] = await Promise.all([
|
|
114
|
+
client.account.getAccountInfo(chainId, address, args.poolId).catch(() => null),
|
|
115
|
+
client.account.getAvailableMarginBalance({ poolId: args.poolId, chainId, address }).catch(() => null),
|
|
116
|
+
]);
|
|
117
|
+
const releaseTime = readReleaseTime(accountInfoRaw);
|
|
118
|
+
const availableMarginRaw = readAvailableMarginRaw(availableMarginRawResult);
|
|
119
|
+
const nowSec = BigInt(Math.floor(Date.now() / 1000));
|
|
120
|
+
if (availableMarginRaw !== null && amountRaw > availableMarginRaw) {
|
|
121
|
+
const lockHint = releaseTime > nowSec
|
|
122
|
+
? ` Funds are partially locked until releaseTime=${formatUnixTimestamp(releaseTime)}.`
|
|
123
|
+
: "";
|
|
124
|
+
throw new Error(`Requested withdraw amount ${amountRaw.toString()} exceeds current withdrawable margin ${availableMarginRaw.toString()}.` +
|
|
125
|
+
lockHint);
|
|
126
|
+
}
|
|
127
|
+
if (releaseTime > nowSec && availableMarginRaw !== null && availableMarginRaw <= 0n) {
|
|
128
|
+
throw new Error(`Account has locked funds until releaseTime=${formatUnixTimestamp(releaseTime)}. ` +
|
|
129
|
+
`Retry after unlock or reduce withdraw amount.`);
|
|
130
|
+
}
|
|
52
131
|
const raw = await client.account.withdraw({
|
|
53
132
|
chainId,
|
|
54
133
|
receiver: address,
|
|
@@ -57,7 +136,14 @@ export const accountWithdrawTool = {
|
|
|
57
136
|
isQuoteToken: args.isQuoteToken,
|
|
58
137
|
});
|
|
59
138
|
const data = await finalizeMutationResult(raw, signer, "account_withdraw");
|
|
60
|
-
|
|
139
|
+
const preflight = {
|
|
140
|
+
requestedAmountRaw: amountRaw.toString(),
|
|
141
|
+
availableMarginRaw: availableMarginRaw?.toString() ?? null,
|
|
142
|
+
releaseTime: releaseTime.toString(),
|
|
143
|
+
releaseTimeIso: Number(releaseTime) > 0 ? new Date(Number(releaseTime) * 1000).toISOString() : null,
|
|
144
|
+
locked: releaseTime > nowSec,
|
|
145
|
+
};
|
|
146
|
+
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: { ...data, preflight } }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
61
147
|
}
|
|
62
148
|
catch (error) {
|
|
63
149
|
return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
|
|
@@ -3,15 +3,13 @@ import { resolveClient, getChainId, getQuoteToken } from "../auth/resolveClient.
|
|
|
3
3
|
import { getOraclePrice } from "../services/marketService.js";
|
|
4
4
|
import { ensureUnits } from "../utils/units.js";
|
|
5
5
|
import { finalizeMutationResult } from "../utils/mutationResult.js";
|
|
6
|
-
import {
|
|
6
|
+
import { normalizeSlippagePct4dpFlexible, SLIPPAGE_PCT_4DP_DESC } from "../utils/slippage.js";
|
|
7
7
|
export const closeAllPositionsTool = {
|
|
8
8
|
name: "close_all_positions",
|
|
9
9
|
description: "Emergency: close ALL open positions in a pool at once. Use for risk management.",
|
|
10
10
|
schema: {
|
|
11
11
|
poolId: z.string().describe("Pool ID to close all positions in"),
|
|
12
|
-
slippagePct: z.
|
|
13
|
-
message: "slippagePct must be an integer in [0, 10000] with 4-decimal precision (1 = 0.01%).",
|
|
14
|
-
}).optional().describe(SLIPPAGE_PCT_4DP_DESC),
|
|
12
|
+
slippagePct: z.union([z.string(), z.number()]).optional().describe(`${SLIPPAGE_PCT_4DP_DESC}. Also supports human percent format like "1.0" or "1%".`),
|
|
15
13
|
},
|
|
16
14
|
handler: async (args) => {
|
|
17
15
|
try {
|
|
@@ -28,7 +26,7 @@ export const closeAllPositionsTool = {
|
|
|
28
26
|
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: { message: "No open positions in this pool.", closed: 0 } }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
29
27
|
}
|
|
30
28
|
// 2) 为每个仓位构建平仓参数
|
|
31
|
-
const slippagePct =
|
|
29
|
+
const slippagePct = normalizeSlippagePct4dpFlexible(args.slippagePct ?? "200");
|
|
32
30
|
// 3) We need actual oracle prices to avoid Revert 0x613970e0 (InvalidParameter)
|
|
33
31
|
const oraclePriceReq = await getOraclePrice(client, args.poolId).catch(() => null);
|
|
34
32
|
let fallbackPrice = "0";
|
|
@@ -1,10 +1,27 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { resolveClient } from "../auth/resolveClient.js";
|
|
2
|
+
import { resolveClient, getChainId } from "../auth/resolveClient.js";
|
|
3
3
|
import { closePosition as closePos } from "../services/tradeService.js";
|
|
4
4
|
import { finalizeMutationResult } from "../utils/mutationResult.js";
|
|
5
5
|
import { SLIPPAGE_PCT_4DP_DESC } from "../utils/slippage.js";
|
|
6
6
|
import { verifyTradeOutcome } from "../utils/verification.js";
|
|
7
7
|
import { mapDirection, mapOrderType, mapTriggerType } from "../utils/mappings.js";
|
|
8
|
+
const FULL_CLOSE_MARKERS = new Set(["ALL", "FULL", "MAX"]);
|
|
9
|
+
const INTEGER_RE = /^\d+$/;
|
|
10
|
+
function wantsFullCloseMarker(input) {
|
|
11
|
+
const value = String(input ?? "").trim().toUpperCase();
|
|
12
|
+
return FULL_CLOSE_MARKERS.has(value);
|
|
13
|
+
}
|
|
14
|
+
function readRawPositionField(position, primary, fallback) {
|
|
15
|
+
const first = String(position?.[primary] ?? "").trim();
|
|
16
|
+
if (INTEGER_RE.test(first))
|
|
17
|
+
return first;
|
|
18
|
+
if (fallback) {
|
|
19
|
+
const second = String(position?.[fallback] ?? "").trim();
|
|
20
|
+
if (INTEGER_RE.test(second))
|
|
21
|
+
return second;
|
|
22
|
+
}
|
|
23
|
+
return "";
|
|
24
|
+
}
|
|
8
25
|
export const closePositionTool = {
|
|
9
26
|
name: "close_position",
|
|
10
27
|
description: "Create a decrease order using SDK-native parameters.",
|
|
@@ -14,8 +31,8 @@ export const closePositionTool = {
|
|
|
14
31
|
orderType: z.union([z.number(), z.string()]).describe("Order type: 0/MARKET or 1/LIMIT"),
|
|
15
32
|
triggerType: z.union([z.number(), z.string()]).optional().describe("Trigger type: 0/NONE, 1/GTE, 2/LTE"),
|
|
16
33
|
direction: z.union([z.number(), z.string()]).describe("Position direction: 0/LONG or 1/SHORT"),
|
|
17
|
-
collateralAmount: z.union([z.string(), z.number()]).describe("Collateral amount (human
|
|
18
|
-
size: z.union([z.string(), z.number()]).describe("Position size (human
|
|
34
|
+
collateralAmount: z.union([z.string(), z.number()]).describe("Collateral amount (human/raw). Also supports ALL/FULL/MAX to use live position collateral raw."),
|
|
35
|
+
size: z.union([z.string(), z.number()]).describe("Position size (human/raw). Also supports ALL/FULL/MAX for exact full-close raw size."),
|
|
19
36
|
price: z.union([z.string(), z.number()]).describe("Price (human or 30-dec raw units)"),
|
|
20
37
|
timeInForce: z.coerce.number().int().describe("TimeInForce: 0=GTC, 1=IOC, 2=FOK"),
|
|
21
38
|
postOnly: z.coerce.boolean().describe("Post-only flag"),
|
|
@@ -26,26 +43,57 @@ export const closePositionTool = {
|
|
|
26
43
|
handler: async (args) => {
|
|
27
44
|
try {
|
|
28
45
|
const { client, address, signer } = await resolveClient();
|
|
29
|
-
const
|
|
30
|
-
const
|
|
46
|
+
const chainId = getChainId();
|
|
47
|
+
const preparedArgs = { ...args };
|
|
48
|
+
const poolId = preparedArgs.poolId;
|
|
31
49
|
// Fetch pool detail to get quoteToken for execution fee
|
|
32
50
|
const poolResponse = await client.markets.getMarketDetail({ chainId, poolId });
|
|
33
51
|
const poolData = poolResponse?.data || (poolResponse?.marketId ? poolResponse : null);
|
|
34
52
|
if (!poolData)
|
|
35
53
|
throw new Error(`Could not find pool metadata for ID: ${poolId}`);
|
|
54
|
+
// Precision helper for full close: align with exact raw position values.
|
|
55
|
+
const needAutoSize = wantsFullCloseMarker(preparedArgs.size);
|
|
56
|
+
const needAutoCollateral = wantsFullCloseMarker(preparedArgs.collateralAmount);
|
|
57
|
+
if (needAutoSize || needAutoCollateral) {
|
|
58
|
+
const positionsRes = await client.position.listPositions(address);
|
|
59
|
+
const positions = Array.isArray(positionsRes?.data) ? positionsRes.data : [];
|
|
60
|
+
const positionId = String(preparedArgs.positionId ?? "").trim().toLowerCase();
|
|
61
|
+
const target = positions.find((position) => {
|
|
62
|
+
const pid = String(position?.positionId ?? position?.position_id ?? "").trim().toLowerCase();
|
|
63
|
+
const pool = String(position?.poolId ?? position?.pool_id ?? "").trim().toLowerCase();
|
|
64
|
+
return pid === positionId && pool === String(poolId).toLowerCase();
|
|
65
|
+
});
|
|
66
|
+
if (!target) {
|
|
67
|
+
throw new Error(`Could not find live position snapshot for positionId=${preparedArgs.positionId} in poolId=${poolId}.`);
|
|
68
|
+
}
|
|
69
|
+
if (needAutoSize) {
|
|
70
|
+
const rawSize = readRawPositionField(target, "size", "positionSize");
|
|
71
|
+
if (!rawSize || rawSize === "0") {
|
|
72
|
+
throw new Error(`Resolved position size is empty/zero for positionId=${preparedArgs.positionId}.`);
|
|
73
|
+
}
|
|
74
|
+
preparedArgs.size = `raw:${rawSize}`;
|
|
75
|
+
}
|
|
76
|
+
if (needAutoCollateral) {
|
|
77
|
+
const rawCollateral = readRawPositionField(target, "collateral", "collateralAmount");
|
|
78
|
+
if (!rawCollateral) {
|
|
79
|
+
throw new Error(`Resolved position collateral is empty for positionId=${preparedArgs.positionId}.`);
|
|
80
|
+
}
|
|
81
|
+
preparedArgs.collateralAmount = `raw:${rawCollateral}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
36
84
|
const mappedArgs = {
|
|
37
|
-
...
|
|
38
|
-
direction: mapDirection(
|
|
39
|
-
orderType: mapOrderType(
|
|
40
|
-
triggerType:
|
|
41
|
-
executionFeeToken: poolData.quoteToken ||
|
|
85
|
+
...preparedArgs,
|
|
86
|
+
direction: mapDirection(preparedArgs.direction),
|
|
87
|
+
orderType: mapOrderType(preparedArgs.orderType),
|
|
88
|
+
triggerType: preparedArgs.triggerType !== undefined ? mapTriggerType(preparedArgs.triggerType) : undefined,
|
|
89
|
+
executionFeeToken: poolData.quoteToken || preparedArgs.executionFeeToken
|
|
42
90
|
};
|
|
43
91
|
const raw = await closePos(client, address, mappedArgs);
|
|
44
92
|
const data = await finalizeMutationResult(raw, signer, "close_position");
|
|
45
93
|
const txHash = data.confirmation?.txHash;
|
|
46
94
|
let verification = null;
|
|
47
95
|
if (txHash) {
|
|
48
|
-
verification = await verifyTradeOutcome(client, address,
|
|
96
|
+
verification = await verifyTradeOutcome(client, address, preparedArgs.poolId, txHash);
|
|
49
97
|
}
|
|
50
98
|
const payload = { ...data, verification };
|
|
51
99
|
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: payload }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
@@ -49,7 +49,7 @@ export const manageLiquidityTool = {
|
|
|
49
49
|
name: "manage_liquidity",
|
|
50
50
|
description: "Add or withdraw liquidity from a BASE or QUOTE pool. Success response includes LP naming metadata: base `mBASE.QUOTE`, quote `mQUOTE.BASE`, plus `operatedLpAssetName` based on poolType.",
|
|
51
51
|
schema: {
|
|
52
|
-
action: z.
|
|
52
|
+
action: z.coerce.string().describe("'deposit' or 'withdraw' (aliases: add/remove/increase/decrease; case-insensitive)"),
|
|
53
53
|
poolType: z.enum(["BASE", "QUOTE"]).describe("'BASE' or 'QUOTE'"),
|
|
54
54
|
poolId: z.string().describe("Pool ID or Base Token Address"),
|
|
55
55
|
amount: z.coerce.number().positive().describe("Amount in human-readable units"),
|
|
@@ -62,6 +62,11 @@ export const manageLiquidityTool = {
|
|
|
62
62
|
let { action, poolType, poolId } = args;
|
|
63
63
|
const { amount, slippage } = args;
|
|
64
64
|
const chainId = args.chainId ?? getChainId();
|
|
65
|
+
action = String(action ?? "").trim().toLowerCase();
|
|
66
|
+
const validActions = new Set(["deposit", "withdraw", "add", "remove", "increase", "decrease"]);
|
|
67
|
+
if (!validActions.has(action)) {
|
|
68
|
+
throw new Error(`Invalid action: ${args.action}. Use deposit/withdraw or aliases add/remove/increase/decrease.`);
|
|
69
|
+
}
|
|
65
70
|
// 1. Action Alias Mapping
|
|
66
71
|
if (action === "add" || action === "increase")
|
|
67
72
|
action = "deposit";
|
package/dist/tools/marketInfo.js
CHANGED
|
@@ -3,6 +3,21 @@ import { resolveClient, getChainId } from "../auth/resolveClient.js";
|
|
|
3
3
|
import { getMarketDetail, resolvePool } from "../services/marketService.js";
|
|
4
4
|
import { getPoolInfo, getLiquidityInfo } from "../services/poolService.js";
|
|
5
5
|
import { extractErrorMessage } from "../utils/errorMessage.js";
|
|
6
|
+
import { parseUserPrice30 } from "../utils/units.js";
|
|
7
|
+
const INTEGER_RE = /^\d+$/;
|
|
8
|
+
const DECIMAL_RE = /^\d+(\.\d+)?$/;
|
|
9
|
+
function normalizeMarketPrice30Input(value) {
|
|
10
|
+
const text = String(value ?? "").trim();
|
|
11
|
+
if (!text)
|
|
12
|
+
throw new Error("marketPrice is required.");
|
|
13
|
+
// Keep backward compatibility: plain integers are treated as already-raw 30-dec units.
|
|
14
|
+
if (INTEGER_RE.test(text))
|
|
15
|
+
return text;
|
|
16
|
+
if (!DECIMAL_RE.test(text) && !/^raw:/i.test(text) && !/^human:/i.test(text)) {
|
|
17
|
+
throw new Error("marketPrice must be numeric, or prefixed with raw:/human:.");
|
|
18
|
+
}
|
|
19
|
+
return parseUserPrice30(text, "marketPrice");
|
|
20
|
+
}
|
|
6
21
|
export const getMarketDetailTool = {
|
|
7
22
|
name: "get_market_detail",
|
|
8
23
|
description: "Get detailed information for a specific trading pool (fee rates, open interest, etc.). Supports PoolId, Token Address, or Keywords.",
|
|
@@ -52,7 +67,7 @@ export const getLiquidityInfoTool = {
|
|
|
52
67
|
description: "Get pool liquidity utilization and depth information. Supports PoolId, Token Address, or Keywords.",
|
|
53
68
|
schema: {
|
|
54
69
|
poolId: z.string().describe("Pool ID, Token Address, or Keyword"),
|
|
55
|
-
marketPrice: z.string().
|
|
70
|
+
marketPrice: z.union([z.string(), z.number()]).describe("Current market price. Supports raw 30-dec integer, raw:..., or human price like 2172.5 / human:2172.5."),
|
|
56
71
|
chainId: z.number().int().positive().optional().describe("Optional chainId override"),
|
|
57
72
|
},
|
|
58
73
|
handler: async (args) => {
|
|
@@ -60,7 +75,8 @@ export const getLiquidityInfoTool = {
|
|
|
60
75
|
const { client } = await resolveClient();
|
|
61
76
|
const poolId = await resolvePool(client, args.poolId);
|
|
62
77
|
const chainId = args.chainId ?? getChainId();
|
|
63
|
-
const
|
|
78
|
+
const marketPrice = normalizeMarketPrice30Input(args.marketPrice);
|
|
79
|
+
const data = await getLiquidityInfo(client, poolId, marketPrice, chainId);
|
|
64
80
|
if (!data)
|
|
65
81
|
throw new Error(`Liquidity info for ${poolId} not available.`);
|
|
66
82
|
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
package/dist/utils/slippage.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const SLIPPAGE_PCT_4DP_RE = /^\d+$/;
|
|
2
2
|
export const SLIPPAGE_PCT_4DP_MAX = 10000n;
|
|
3
3
|
export const SLIPPAGE_PCT_4DP_DESC = "Slippage in 4-decimal precision raw units (1 = 0.01%, 10000 = 100%)";
|
|
4
|
+
const SLIPPAGE_PERCENT_HUMAN_RE = /^\d+(\.\d{1,2})?$/;
|
|
4
5
|
export function isValidSlippagePct4dp(value) {
|
|
5
6
|
if (!SLIPPAGE_PCT_4DP_RE.test(value))
|
|
6
7
|
return false;
|
|
@@ -13,3 +14,25 @@ export function normalizeSlippagePct4dp(value, label = "slippagePct") {
|
|
|
13
14
|
}
|
|
14
15
|
return raw;
|
|
15
16
|
}
|
|
17
|
+
export function normalizeSlippagePct4dpFlexible(value, label = "slippagePct") {
|
|
18
|
+
const raw = String(value ?? "").trim();
|
|
19
|
+
if (!raw) {
|
|
20
|
+
throw new Error(`${label} is required.`);
|
|
21
|
+
}
|
|
22
|
+
// Keep backward-compatible behavior: integer values remain raw 4dp units.
|
|
23
|
+
if (isValidSlippagePct4dp(raw)) {
|
|
24
|
+
return raw;
|
|
25
|
+
}
|
|
26
|
+
// Human percent helper: "1.0" / "1.25" / "1%"
|
|
27
|
+
const percentText = raw.endsWith("%") ? raw.slice(0, -1).trim() : raw;
|
|
28
|
+
if (!SLIPPAGE_PERCENT_HUMAN_RE.test(percentText)) {
|
|
29
|
+
throw new Error(`${label} must be raw 4dp integer (e.g. 100=1%) or human percent like "1.0" / "1%".`);
|
|
30
|
+
}
|
|
31
|
+
const [intPart, fracPart = ""] = percentText.split(".");
|
|
32
|
+
const frac2 = (fracPart + "00").slice(0, 2);
|
|
33
|
+
const converted = BigInt(intPart) * 100n + BigInt(frac2);
|
|
34
|
+
if (converted > SLIPPAGE_PCT_4DP_MAX) {
|
|
35
|
+
throw new Error(`${label} must be <= 100% (raw <= 10000).`);
|
|
36
|
+
}
|
|
37
|
+
return converted.toString();
|
|
38
|
+
}
|