@michaleffffff/mcp-trading-server 2.4.1 → 2.4.3

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/README.md CHANGED
@@ -82,6 +82,11 @@ IS_TESTNET=false
82
82
  MAX_TRADE_AMOUNT=5000 # Optional safety constraint limit for AI
83
83
  ```
84
84
 
85
+ Testnet quick mapping:
86
+
87
+ - `Arbitrum Sepolia (421614)`: `BROKER_ADDRESS=0x8f3153C18f698166f5D6124d8ba5B567F5f120f9`, `QUOTE_TOKEN_ADDRESS=0x7E248Ec1721639413A280d9E82e2862Cae2E6E28`
88
+ - `Linea Sepolia (59141)`: `BROKER_ADDRESS=0x0FB08D3A1Ea6bE515fe78D3e0CaEb6990b468Cf3`, `QUOTE_TOKEN_ADDRESS=0xD984fd34f91F92DA0586e1bE82E262fF27DC431b`
89
+
85
90
  ---
86
91
 
87
92
  # Running the Server
@@ -2,14 +2,30 @@ import { MyxClient } from "@myx-trade/sdk";
2
2
  import { JsonRpcProvider, Wallet } from "ethers";
3
3
  import { normalizeAddress } from "../utils/address.js";
4
4
  let cached = null;
5
+ function getDefaultBrokerByChainId(chainId) {
6
+ // Testnet mappings
7
+ if (chainId === 421614)
8
+ return "0x8f3153C18f698166f5D6124d8ba5B567F5f120f9"; // Arbitrum Sepolia
9
+ if (chainId === 59141)
10
+ return "0x0FB08D3A1Ea6bE515fe78D3e0CaEb6990b468Cf3"; // Linea Sepolia
11
+ return "0x8f3153C18f698166f5D6124d8ba5B567F5f120f9";
12
+ }
13
+ function getDefaultQuoteTokenByChainId(chainId) {
14
+ // Testnet mappings
15
+ if (chainId === 421614)
16
+ return "0x7E248Ec1721639413A280d9E82e2862Cae2E6E28"; // Arbitrum Sepolia
17
+ if (chainId === 59141)
18
+ return "0xD984fd34f91F92DA0586e1bE82E262fF27DC431b"; // Linea Sepolia
19
+ return "0xD984fd34f91F92DA0586e1bE82E262fF27DC431b";
20
+ }
5
21
  export async function resolveClient() {
6
22
  if (cached)
7
23
  return cached;
8
24
  const rpcUrl = process.env.RPC_URL || "https://rpc.sepolia.linea.build";
9
25
  const privateKey = process.env.PRIVATE_KEY;
10
- const brokerAddressRaw = process.env.BROKER_ADDRESS || "0xAc6C93eaBDc3DBE4e1B0176914dc2a16f8Fd1800";
11
26
  const chainId = Number(process.env.CHAIN_ID) || 59141;
12
- const quoteTokenRaw = process.env.QUOTE_TOKEN_ADDRESS || "0xD984fd34f91F92DA0586e1bE82E262fF27DC431b";
27
+ const brokerAddressRaw = process.env.BROKER_ADDRESS || getDefaultBrokerByChainId(chainId);
28
+ const quoteTokenRaw = process.env.QUOTE_TOKEN_ADDRESS || getDefaultQuoteTokenByChainId(chainId);
13
29
  const quoteDecimals = Number(process.env.QUOTE_TOKEN_DECIMALS) || 6;
14
30
  if (!rpcUrl)
15
31
  throw new Error("RPC_URL env var is required.");
@@ -44,7 +60,8 @@ export function getChainId() {
44
60
  export function getQuoteToken() {
45
61
  if (cached)
46
62
  return cached.quoteToken;
47
- const tokenRaw = process.env.QUOTE_TOKEN_ADDRESS || "0xD984fd34f91F92DA0586e1bE82E262fF27DC431b";
63
+ const chainId = Number(process.env.CHAIN_ID) || 59141;
64
+ const tokenRaw = process.env.QUOTE_TOKEN_ADDRESS || getDefaultQuoteTokenByChainId(chainId);
48
65
  if (!tokenRaw)
49
66
  throw new Error("QUOTE_TOKEN_ADDRESS env var is required.");
50
67
  return normalizeAddress(tokenRaw, "QUOTE_TOKEN_ADDRESS");
@@ -23,6 +23,15 @@ export async function openPosition(client, address, args) {
23
23
  const chainId = getChainId();
24
24
  const dir = resolveDirection(args.direction);
25
25
  const executionFeeToken = normalizeAddress(args.executionFeeToken, "executionFeeToken");
26
+ // Fetch pool detail to get decimals
27
+ const poolResponse = await client.markets.getMarketDetail({ chainId, poolId: args.poolId });
28
+ const poolData = poolResponse?.data || (poolResponse?.marketId ? poolResponse : null);
29
+ if (!poolData) {
30
+ console.error(`[ERROR] poolResponse for ${args.poolId}:`, JSON.stringify(poolResponse, null, 2));
31
+ throw new Error(`Could not find pool metadata for ID: ${args.poolId}`);
32
+ }
33
+ const baseDecimals = poolData.baseDecimals || 18;
34
+ const quoteDecimals = poolData.quoteDecimals || 6;
26
35
  const orderParams = {
27
36
  chainId,
28
37
  address,
@@ -31,23 +40,23 @@ export async function openPosition(client, address, args) {
31
40
  orderType: args.orderType,
32
41
  triggerType: args.triggerType,
33
42
  direction: dir,
34
- collateralAmount: args.collateralAmount,
35
- size: args.size,
36
- price: args.price,
43
+ collateralAmount: ensureUnits(args.collateralAmount, quoteDecimals, "collateralAmount"),
44
+ size: ensureUnits(args.size, baseDecimals, "size"),
45
+ price: ensureUnits(args.price, 30, "price"),
37
46
  timeInForce: args.timeInForce,
38
47
  postOnly: args.postOnly,
39
- slippagePct: args.slippagePct,
48
+ slippagePct: String(args.slippagePct),
40
49
  executionFeeToken,
41
50
  leverage: args.leverage,
42
51
  };
43
52
  if (args.tpSize)
44
- orderParams.tpSize = args.tpSize;
53
+ orderParams.tpSize = ensureUnits(args.tpSize, baseDecimals, "tpSize");
45
54
  if (args.tpPrice)
46
- orderParams.tpPrice = args.tpPrice;
55
+ orderParams.tpPrice = ensureUnits(args.tpPrice, 30, "tpPrice");
47
56
  if (args.slSize)
48
- orderParams.slSize = args.slSize;
57
+ orderParams.slSize = ensureUnits(args.slSize, baseDecimals, "slSize");
49
58
  if (args.slPrice)
50
- orderParams.slPrice = args.slPrice;
59
+ orderParams.slPrice = ensureUnits(args.slPrice, 30, "slPrice");
51
60
  return client.order.createIncreaseOrder(orderParams, args.tradingFee, args.marketId);
52
61
  }
53
62
  /**
@@ -60,6 +69,15 @@ export async function closePosition(client, address, args) {
60
69
  throw new Error("direction is required (0=LONG, 1=SHORT), must match position direction.");
61
70
  }
62
71
  const dir = resolveDirection(args.direction);
72
+ // Fetch pool detail to get decimals
73
+ const poolResponse = await client.markets.getMarketDetail({ chainId, poolId: args.poolId });
74
+ const poolData = poolResponse?.data || (poolResponse?.marketId ? poolResponse : null);
75
+ if (!poolData) {
76
+ console.error(`[ERROR] poolResponse for ${args.poolId}:`, JSON.stringify(poolResponse, null, 2));
77
+ throw new Error(`Could not find pool metadata for ID: ${args.poolId}`);
78
+ }
79
+ const baseDecimals = poolData.baseDecimals || 18;
80
+ const quoteDecimals = poolData.quoteDecimals || 6;
63
81
  return client.order.createDecreaseOrder({
64
82
  chainId,
65
83
  address,
@@ -68,12 +86,12 @@ export async function closePosition(client, address, args) {
68
86
  orderType: args.orderType,
69
87
  triggerType: args.triggerType,
70
88
  direction: dir,
71
- collateralAmount: args.collateralAmount,
72
- size: args.size,
73
- price: args.price,
89
+ collateralAmount: ensureUnits(args.collateralAmount, quoteDecimals, "collateralAmount"),
90
+ size: ensureUnits(args.size, baseDecimals, "size"),
91
+ price: ensureUnits(args.price, 30, "price"),
74
92
  timeInForce: args.timeInForce,
75
93
  postOnly: args.postOnly,
76
- slippagePct: args.slippagePct,
94
+ slippagePct: String(args.slippagePct),
77
95
  executionFeeToken,
78
96
  leverage: args.leverage,
79
97
  });
@@ -120,14 +138,18 @@ export async function adjustMargin(client, address, args) {
120
138
  if (!/^-?\d+$/.test(adjustAmount)) {
121
139
  throw new Error("adjustAmount must be an integer string in quote token raw units.");
122
140
  }
123
- return client.position.adjustCollateral({
141
+ const params = {
124
142
  poolId: args.poolId,
125
143
  positionId: args.positionId,
126
144
  adjustAmount,
127
145
  quoteToken,
128
146
  chainId,
129
147
  address,
130
- });
148
+ };
149
+ if (args.poolOracleType !== undefined) {
150
+ params.poolOracleType = Number(args.poolOracleType);
151
+ }
152
+ return client.position.adjustCollateral(params);
131
153
  }
132
154
  /**
133
155
  * 平掉所有仓位
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient, getChainId } from "../auth/resolveClient.js";
3
3
  import { normalizeAddress } from "../utils/address.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
4
5
  export const accountDepositTool = {
5
6
  name: "account_deposit",
6
7
  description: "Deposit funds from wallet into the MYX trading account.",
@@ -10,15 +11,16 @@ export const accountDepositTool = {
10
11
  },
11
12
  handler: async (args) => {
12
13
  try {
13
- const { client } = await resolveClient();
14
+ const { client, signer } = await resolveClient();
14
15
  const chainId = getChainId();
15
16
  const tokenAddress = normalizeAddress(args.tokenAddress, "tokenAddress");
16
- const result = await client.account.deposit({
17
+ const raw = await client.account.deposit({
17
18
  amount: args.amount,
18
19
  tokenAddress,
19
20
  chainId,
20
21
  });
21
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: result }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
22
+ const data = await finalizeMutationResult(raw, signer, "account_deposit");
23
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
22
24
  }
23
25
  catch (error) {
24
26
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -35,16 +37,17 @@ export const accountWithdrawTool = {
35
37
  },
36
38
  handler: async (args) => {
37
39
  try {
38
- const { client, address } = await resolveClient();
40
+ const { client, address, signer } = await resolveClient();
39
41
  const chainId = getChainId();
40
- const result = await client.account.withdraw({
42
+ const raw = await client.account.withdraw({
41
43
  chainId,
42
44
  receiver: address,
43
45
  amount: args.amount,
44
46
  poolId: args.poolId,
45
47
  isQuoteToken: args.isQuoteToken,
46
48
  });
47
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: result }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
49
+ const data = await finalizeMutationResult(raw, signer, "account_withdraw");
50
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
48
51
  }
49
52
  catch (error) {
50
53
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient } from "../auth/resolveClient.js";
3
3
  import { adjustMargin as adjustMarginSvc } from "../services/tradeService.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
4
5
  export const adjustMarginTool = {
5
6
  name: "adjust_margin",
6
7
  description: "Adjust the margin (collateral) of an open position.",
@@ -9,12 +10,14 @@ export const adjustMarginTool = {
9
10
  positionId: z.string().describe("Position ID"),
10
11
  adjustAmount: z.string().regex(/^-?\d+$/).describe("Quote token raw units. Positive = add, negative = remove."),
11
12
  quoteToken: z.string().optional().describe("Quote token address"),
13
+ poolOracleType: z.number().optional().describe("Oracle type: 1 for Chainlink, 2 for Pyth"),
12
14
  },
13
15
  handler: async (args) => {
14
16
  try {
15
- const { client, address } = await resolveClient();
16
- const tx = await adjustMarginSvc(client, address, args);
17
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: tx }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
17
+ const { client, address, signer } = await resolveClient();
18
+ const raw = await adjustMarginSvc(client, address, args);
19
+ const data = await finalizeMutationResult(raw, signer, "adjust_margin");
20
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
18
21
  }
19
22
  catch (error) {
20
23
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient, getChainId } from "../auth/resolveClient.js";
3
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
3
4
  export const cancelAllOrdersTool = {
4
5
  name: "cancel_all_orders",
5
6
  description: "Cancel multiple open orders by orderIds.",
@@ -8,10 +9,11 @@ export const cancelAllOrdersTool = {
8
9
  },
9
10
  handler: async (args) => {
10
11
  try {
11
- const { client } = await resolveClient();
12
+ const { client, signer } = await resolveClient();
12
13
  const chainId = getChainId();
13
14
  const orderIds = args.orderIds;
14
- const result = await client.order.cancelAllOrders(orderIds, chainId);
15
+ const raw = await client.order.cancelAllOrders(orderIds, chainId);
16
+ const result = await finalizeMutationResult(raw, signer, "cancel_all_orders");
15
17
  return {
16
18
  content: [{ type: "text", text: JSON.stringify({ status: "success", data: { cancelled: orderIds.length, orderIds, result } }, (_, v) => typeof v === "bigint" ? v.toString() : v, 2) }],
17
19
  };
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient, getChainId } from "../auth/resolveClient.js";
3
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
3
4
  export const cancelOrderTool = {
4
5
  name: "cancel_order",
5
6
  description: "Cancel an open order by its order ID.",
@@ -8,10 +9,11 @@ export const cancelOrderTool = {
8
9
  },
9
10
  handler: async (args) => {
10
11
  try {
11
- const { client } = await resolveClient();
12
+ const { client, signer } = await resolveClient();
12
13
  const chainId = getChainId();
13
- const result = await client.order.cancelOrder(args.orderId, chainId);
14
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: result }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
14
+ const raw = await client.order.cancelOrder(args.orderId, chainId);
15
+ const data = await finalizeMutationResult(raw, signer, "cancel_order");
16
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
15
17
  }
16
18
  catch (error) {
17
19
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient, getChainId, getQuoteToken } from "../auth/resolveClient.js";
3
3
  import { normalizeAddress } from "../utils/address.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
4
5
  const MAX_UINT256 = "115792089237316195423570985008687907853269984665640564039457584007913129639935";
5
6
  export const checkApprovalTool = {
6
7
  name: "check_approval",
@@ -13,18 +14,19 @@ export const checkApprovalTool = {
13
14
  },
14
15
  handler: async (args) => {
15
16
  try {
16
- const { client, address } = await resolveClient();
17
+ const { client, address, signer } = await resolveClient();
17
18
  const chainId = getChainId();
18
19
  const quoteToken = normalizeAddress(args.quoteToken || getQuoteToken(), "quoteToken");
19
20
  const needApproval = await client.utils.needsApproval(address, chainId, quoteToken, args.amount);
20
21
  if (needApproval && args.autoApprove) {
21
22
  const approveAmount = args.approveMax ? MAX_UINT256 : args.amount;
22
- await client.utils.approveAuthorization({
23
+ const raw = await client.utils.approveAuthorization({
23
24
  chainId,
24
25
  quoteAddress: quoteToken,
25
26
  amount: approveAmount,
26
27
  });
27
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: { needApproval: true, approved: true, quoteToken, approvedAmount: approveAmount, approveMax: !!args.approveMax } }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
28
+ const approval = await finalizeMutationResult(raw, signer, "approve_authorization");
29
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: { needApproval: true, approved: true, quoteToken, approvedAmount: approveAmount, approveMax: !!args.approveMax, approval } }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
28
30
  }
29
31
  return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: { needApproval, approved: false, quoteToken } }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
30
32
  }
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { resolveClient, getChainId, getQuoteToken } from "../auth/resolveClient.js";
3
3
  import { getOraclePrice } from "../services/marketService.js";
4
4
  import { ensureUnits } from "../utils/units.js";
5
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
5
6
  export const closeAllPositionsTool = {
6
7
  name: "close_all_positions",
7
8
  description: "Emergency: close ALL open positions in a pool at once. Use for risk management.",
@@ -11,7 +12,7 @@ export const closeAllPositionsTool = {
11
12
  },
12
13
  handler: async (args) => {
13
14
  try {
14
- const { client, address } = await resolveClient();
15
+ const { client, address, signer } = await resolveClient();
15
16
  const chainId = getChainId();
16
17
  // 1) 先获取该池的所有持仓
17
18
  const posResult = await client.position.listPositions(address);
@@ -63,7 +64,8 @@ export const closeAllPositionsTool = {
63
64
  leverage: pos.userLeverage ?? pos.leverage ?? 1,
64
65
  };
65
66
  });
66
- const result = await client.order.closeAllPositions(chainId, closeParams);
67
+ const raw = await client.order.closeAllPositions(chainId, closeParams);
68
+ const result = await finalizeMutationResult(raw, signer, "close_all_positions");
67
69
  return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: { closed: poolPositions.length, result } }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
68
70
  }
69
71
  catch (error) {
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient } from "../auth/resolveClient.js";
3
3
  import { closePosition as closePos } from "../services/tradeService.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
4
5
  export const closePositionTool = {
5
6
  name: "close_position",
6
7
  description: "Create a decrease order using SDK-native parameters.",
@@ -10,20 +11,21 @@ export const closePositionTool = {
10
11
  orderType: z.number().int().min(0).max(3).describe("OrderType enum value"),
11
12
  triggerType: z.number().int().min(0).max(2).describe("TriggerType enum value"),
12
13
  direction: z.union([z.literal(0), z.literal(1)]).describe("0 = LONG, 1 = SHORT"),
13
- collateralAmount: z.string().regex(/^\d+$/).describe("Collateral raw units"),
14
- size: z.string().regex(/^\d+$/).describe("Position size raw units"),
15
- price: z.string().regex(/^\d+$/).describe("Price raw units (30 decimals)"),
14
+ collateralAmount: z.union([z.string(), z.number()]).describe("Collateral amount (human-readable or raw units)"),
15
+ size: z.union([z.string(), z.number()]).describe("Position size (human-readable or raw units)"),
16
+ price: z.union([z.string(), z.number()]).describe("Price (human-readable or 30-dec raw units)"),
16
17
  timeInForce: z.number().int().describe("TimeInForce enum value"),
17
18
  postOnly: z.boolean().describe("Post-only flag"),
18
- slippagePct: z.string().regex(/^\d+$/).describe("Slippage with 4-dec precision raw units"),
19
+ slippagePct: z.union([z.string(), z.number()]).describe("Slippage in BPS (e.g. 100 = 1%)"),
19
20
  executionFeeToken: z.string().describe("Execution fee token address"),
20
21
  leverage: z.number().describe("Leverage"),
21
22
  },
22
23
  handler: async (args) => {
23
24
  try {
24
- const { client, address } = await resolveClient();
25
- const tx = await closePos(client, address, args);
26
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: tx }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
25
+ const { client, address, signer } = await resolveClient();
26
+ const raw = await closePos(client, address, args);
27
+ const data = await finalizeMutationResult(raw, signer, "close_position");
28
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
27
29
  }
28
30
  catch (error) {
29
31
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { createPool } from "../services/poolService.js";
3
+ import { resolveClient } from "../auth/resolveClient.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
3
5
  export const createPerpMarketTool = {
4
6
  name: "create_perp_market",
5
7
  description: "Create a new perpetual contract pool on MYX. IMPORTANT: marketId cannot be randomly generated. It must be a valid 66-character config hash (0x...) tied to a supported quote token (like USDC). Use get_market_list to fetch an existing marketId if you don't have a specific newly allocated one.",
@@ -11,8 +13,10 @@ export const createPerpMarketTool = {
11
13
  try {
12
14
  if (!args.baseToken || !args.marketId)
13
15
  throw new Error("baseToken and marketId are required.");
14
- const result = await createPool(args.baseToken, args.marketId);
15
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: result }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
16
+ const { signer } = await resolveClient();
17
+ const raw = await createPool(args.baseToken, args.marketId);
18
+ const data = await finalizeMutationResult(raw, signer, "create_perp_market");
19
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
16
20
  }
17
21
  catch (error) {
18
22
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,21 +1,95 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient } from "../auth/resolveClient.js";
3
3
  import { openPosition } from "../services/tradeService.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
5
+ const POSITION_ID_RE = /^$|^0x[0-9a-fA-F]{64}$/;
6
+ function toList(input) {
7
+ if (Array.isArray(input))
8
+ return input;
9
+ if (Array.isArray(input?.data))
10
+ return input.data;
11
+ return [];
12
+ }
13
+ function buildPositionFingerprint(rows, poolId) {
14
+ const map = new Map();
15
+ for (const row of rows) {
16
+ if (String(row?.poolId ?? row?.pool_id ?? "") !== poolId)
17
+ continue;
18
+ const id = String(row?.positionId ?? row?.position_id ?? "");
19
+ if (!id)
20
+ continue;
21
+ const fingerprint = JSON.stringify({
22
+ size: String(row?.size ?? ""),
23
+ collateralAmount: String(row?.collateralAmount ?? row?.collateral_amount ?? ""),
24
+ txTime: Number(row?.txTime ?? row?.tx_time ?? 0),
25
+ });
26
+ map.set(id, fingerprint);
27
+ }
28
+ return map;
29
+ }
30
+ function buildOpenOrderSet(rows, poolId) {
31
+ const set = new Set();
32
+ for (const row of rows) {
33
+ if (String(row?.poolId ?? row?.pool_id ?? "") !== poolId)
34
+ continue;
35
+ const id = row?.orderId ?? row?.id ?? row?.order_id;
36
+ if (id !== undefined && id !== null)
37
+ set.add(String(id));
38
+ }
39
+ return set;
40
+ }
41
+ async function snapshotTradeState(client, address, poolId) {
42
+ const [ordersRes, positionsRes] = await Promise.all([
43
+ client.order.getOrders(address).catch(() => null),
44
+ client.position.listPositions(address).catch(() => null),
45
+ ]);
46
+ return {
47
+ openOrders: buildOpenOrderSet(toList(ordersRes), poolId),
48
+ positions: buildPositionFingerprint(toList(positionsRes), poolId),
49
+ };
50
+ }
51
+ function hasTradeEffect(before, after) {
52
+ for (const id of after.openOrders) {
53
+ if (!before.openOrders.has(id))
54
+ return true;
55
+ }
56
+ for (const [id, fp] of after.positions.entries()) {
57
+ if (!before.positions.has(id))
58
+ return true;
59
+ if (before.positions.get(id) !== fp)
60
+ return true;
61
+ }
62
+ return false;
63
+ }
64
+ async function waitForTradeEffect(client, address, poolId, before) {
65
+ const maxAttempts = 8;
66
+ const intervalMs = 1500;
67
+ for (let i = 0; i < maxAttempts; i += 1) {
68
+ const after = await snapshotTradeState(client, address, poolId);
69
+ if (hasTradeEffect(before, after)) {
70
+ return { detected: true, attempts: i + 1 };
71
+ }
72
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
73
+ }
74
+ return { detected: false, attempts: maxAttempts };
75
+ }
4
76
  export const executeTradeTool = {
5
77
  name: "execute_trade",
6
78
  description: "Create an increase order using SDK-native parameters.",
7
79
  schema: {
8
80
  poolId: z.string().describe("Pool ID"),
9
- positionId: z.string().describe("Position ID ('0' for new position)"),
81
+ positionId: z.string().refine((value) => POSITION_ID_RE.test(value), {
82
+ message: "positionId must be empty string for new position, or a bytes32 hex string.",
83
+ }).describe("Position ID: empty string for new position"),
10
84
  orderType: z.number().int().min(0).max(3).describe("OrderType enum value"),
11
85
  triggerType: z.number().int().min(0).max(2).describe("TriggerType enum value"),
12
86
  direction: z.union([z.literal(0), z.literal(1)]).describe("0 = LONG, 1 = SHORT"),
13
- collateralAmount: z.string().regex(/^\d+$/).describe("Quote token raw units"),
14
- size: z.string().regex(/^\d+$/).describe("Position size raw units"),
15
- price: z.string().regex(/^\d+$/).describe("Price raw units (30 decimals)"),
87
+ collateralAmount: z.string().regex(/^\d+$/).describe("Collateral amount (raw units)"),
88
+ size: z.string().regex(/^\d+$/).describe("Position size (raw units)"),
89
+ price: z.string().regex(/^\d+$/).describe("Price (30-decimal raw units)"),
16
90
  timeInForce: z.number().int().describe("TimeInForce enum value"),
17
91
  postOnly: z.boolean().describe("Post-only flag"),
18
- slippagePct: z.string().regex(/^\d+$/).describe("Slippage with 4-dec precision raw units"),
92
+ slippagePct: z.string().regex(/^\d+$/).describe("Slippage in 4-decimal precision raw units"),
19
93
  executionFeeToken: z.string().describe("Execution fee token address"),
20
94
  leverage: z.number().describe("Leverage"),
21
95
  tpSize: z.string().regex(/^\d+$/).optional().describe("TP size raw units"),
@@ -27,9 +101,16 @@ export const executeTradeTool = {
27
101
  },
28
102
  handler: async (args) => {
29
103
  try {
30
- const { client, address } = await resolveClient();
31
- const tx = await openPosition(client, address, args);
32
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: tx }, (k, v) => typeof v === 'bigint' ? v.toString() : v) }] };
104
+ const { client, address, signer } = await resolveClient();
105
+ const before = await snapshotTradeState(client, address, args.poolId);
106
+ const raw = await openPosition(client, address, args);
107
+ const data = await finalizeMutationResult(raw, signer, "execute_trade");
108
+ const effect = await waitForTradeEffect(client, address, args.poolId, before);
109
+ if (!effect.detected) {
110
+ throw new Error(`execute_trade tx confirmed but no order/position change detected in ${effect.attempts} checks.`);
111
+ }
112
+ const payload = { ...data, effect };
113
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: payload }, (k, v) => typeof v === 'bigint' ? v.toString() : v) }] };
33
114
  }
34
115
  catch (error) {
35
116
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { quoteDeposit, quoteWithdraw, baseDeposit, baseWithdraw, getLpPrice, } from "../services/poolService.js";
3
+ import { resolveClient } from "../auth/resolveClient.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
3
5
  export const manageLiquidityTool = {
4
6
  name: "manage_liquidity",
5
7
  description: "Add or withdraw liquidity from a BASE or QUOTE pool.",
@@ -13,20 +15,22 @@ export const manageLiquidityTool = {
13
15
  },
14
16
  handler: async (args) => {
15
17
  try {
18
+ const { signer } = await resolveClient();
16
19
  const { action, poolType, poolId } = args;
17
20
  const { amount, slippage } = args;
18
- let result;
21
+ let raw;
19
22
  if (poolType === "QUOTE") {
20
- result = action === "deposit"
23
+ raw = action === "deposit"
21
24
  ? await quoteDeposit(poolId, amount, slippage, args.chainId)
22
25
  : await quoteWithdraw(poolId, amount, slippage, args.chainId);
23
26
  }
24
27
  else {
25
- result = action === "deposit"
28
+ raw = action === "deposit"
26
29
  ? await baseDeposit(poolId, amount, slippage, args.chainId)
27
30
  : await baseWithdraw(poolId, amount, slippage, args.chainId);
28
31
  }
29
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: result }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
32
+ const data = await finalizeMutationResult(raw, signer, "manage_liquidity");
33
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
30
34
  }
31
35
  catch (error) {
32
36
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient } from "../auth/resolveClient.js";
3
3
  import { setPositionTpSl } from "../services/tradeService.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
4
5
  export const setTpSlTool = {
5
6
  name: "set_tp_sl",
6
7
  description: "Create TP/SL order using SDK-native parameters.",
@@ -20,9 +21,10 @@ export const setTpSlTool = {
20
21
  },
21
22
  handler: async (args) => {
22
23
  try {
23
- const { client, address } = await resolveClient();
24
- const tx = await setPositionTpSl(client, address, args);
25
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: tx }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
24
+ const { client, address, signer } = await resolveClient();
25
+ const raw = await setPositionTpSl(client, address, args);
26
+ const data = await finalizeMutationResult(raw, signer, "set_tp_sl");
27
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
26
28
  }
27
29
  catch (error) {
28
30
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { resolveClient } from "../auth/resolveClient.js";
3
3
  import { updateOrderTpSl } from "../services/tradeService.js";
4
+ import { finalizeMutationResult } from "../utils/mutationResult.js";
4
5
  export const updateOrderTpSlTool = {
5
6
  name: "update_order_tp_sl",
6
7
  description: "Update an existing take profit or stop loss order.",
@@ -19,9 +20,10 @@ export const updateOrderTpSlTool = {
19
20
  },
20
21
  handler: async (args) => {
21
22
  try {
22
- const { client, address } = await resolveClient();
23
- const result = await updateOrderTpSl(client, address, args);
24
- return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: result }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
23
+ const { client, address, signer } = await resolveClient();
24
+ const raw = await updateOrderTpSl(client, address, args);
25
+ const data = await finalizeMutationResult(raw, signer, "update_order_tp_sl");
26
+ return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
25
27
  }
26
28
  catch (error) {
27
29
  return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
@@ -0,0 +1,68 @@
1
+ const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
2
+ const TX_HASH_KEYS = new Set(["hash", "txHash", "transactionHash"]);
3
+ function isObject(value) {
4
+ return !!value && typeof value === "object";
5
+ }
6
+ function findTxHashDeep(input, depth = 0) {
7
+ if (!isObject(input) || depth > 4)
8
+ return undefined;
9
+ for (const [key, value] of Object.entries(input)) {
10
+ if (TX_HASH_KEYS.has(key) && typeof value === "string" && TX_HASH_RE.test(value)) {
11
+ return value;
12
+ }
13
+ }
14
+ for (const value of Object.values(input)) {
15
+ if (Array.isArray(value)) {
16
+ for (const item of value) {
17
+ const found = findTxHashDeep(item, depth + 1);
18
+ if (found)
19
+ return found;
20
+ }
21
+ continue;
22
+ }
23
+ const found = findTxHashDeep(value, depth + 1);
24
+ if (found)
25
+ return found;
26
+ }
27
+ return undefined;
28
+ }
29
+ function assertSdkCode(result, actionName) {
30
+ if (!isObject(result))
31
+ return;
32
+ if (!Object.prototype.hasOwnProperty.call(result, "code"))
33
+ return;
34
+ const code = Number(result.code);
35
+ if (!Number.isFinite(code)) {
36
+ throw new Error(`${actionName} failed: invalid SDK code.`);
37
+ }
38
+ if (code !== 0) {
39
+ const msg = result.msg ?? result.message ?? "unknown error";
40
+ throw new Error(`${actionName} failed: code=${code}, msg=${String(msg)}`);
41
+ }
42
+ }
43
+ export async function finalizeMutationResult(result, signer, actionName) {
44
+ assertSdkCode(result, actionName);
45
+ const txHash = findTxHashDeep(result);
46
+ if (!txHash) {
47
+ return { result };
48
+ }
49
+ const provider = signer?.provider;
50
+ if (!provider?.waitForTransaction) {
51
+ return { result, confirmation: { txHash, status: "submitted" } };
52
+ }
53
+ const receipt = await provider.waitForTransaction(txHash, 1, 120000);
54
+ if (!receipt) {
55
+ throw new Error(`${actionName} failed: tx not confirmed within timeout (${txHash}).`);
56
+ }
57
+ if (receipt.status !== 1) {
58
+ throw new Error(`${actionName} failed on-chain: tx reverted (${txHash}).`);
59
+ }
60
+ return {
61
+ result,
62
+ confirmation: {
63
+ txHash,
64
+ blockNumber: receipt.blockNumber,
65
+ status: receipt.status,
66
+ },
67
+ };
68
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@michaleffffff/mcp-trading-server",
3
- "version": "2.4.1",
3
+ "version": "2.4.3",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "myx-mcp": "dist/server.js"