@arcadia-finance/mcp-server 0.1.0

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.
Files changed (59) hide show
  1. package/LICENSE.md +97 -0
  2. package/README.md +186 -0
  3. package/dist/abis/account.json +1012 -0
  4. package/dist/abis/account_v4.json +1027 -0
  5. package/dist/abis/chainlink.json +509 -0
  6. package/dist/abis/erc20.json +299 -0
  7. package/dist/abis/factory.json +938 -0
  8. package/dist/abis/gauge_helper.json +84 -0
  9. package/dist/abis/index.js +26 -0
  10. package/dist/abis/mainreg.json +1172 -0
  11. package/dist/abis/nftmanager.json +1221 -0
  12. package/dist/abis/nftmanager_v4.json +1297 -0
  13. package/dist/abis/pool.json +2136 -0
  14. package/dist/abis/slipstream_nftmanager.json +1312 -0
  15. package/dist/abis/staked_aero_am.json +1220 -0
  16. package/dist/abis/staked_slipstream_am.json +1131 -0
  17. package/dist/abis/state_viewer.json +365 -0
  18. package/dist/abis/tranche.json +1004 -0
  19. package/dist/abis/wrapped_aero_am.json +1232 -0
  20. package/dist/abis/wrapped_staked_slipstream_am.json +338 -0
  21. package/dist/clients/api.js +189 -0
  22. package/dist/clients/chain.js +30 -0
  23. package/dist/config/addresses.js +94 -0
  24. package/dist/config/chains.js +31 -0
  25. package/dist/index.js +29 -0
  26. package/dist/skills/clamm-liquidity/SKILL.md +167 -0
  27. package/dist/skills/clamm-liquidity/automation.md +138 -0
  28. package/dist/skills/clamm-liquidity/selection.md +183 -0
  29. package/dist/skills/clamm-liquidity/strategies.md +337 -0
  30. package/dist/tools/advanced/account-metadata.js +46 -0
  31. package/dist/tools/advanced/add-liquidity.js +310 -0
  32. package/dist/tools/advanced/close-position.js +208 -0
  33. package/dist/tools/advanced/format-response.js +26 -0
  34. package/dist/tools/advanced/position-actions.js +95 -0
  35. package/dist/tools/advanced/remove-liquidity.js +68 -0
  36. package/dist/tools/advanced/repay-with-collateral.js +66 -0
  37. package/dist/tools/advanced/swap.js +64 -0
  38. package/dist/tools/index.js +52 -0
  39. package/dist/tools/read/accounts.js +243 -0
  40. package/dist/tools/read/allowances.js +86 -0
  41. package/dist/tools/read/assets.js +54 -0
  42. package/dist/tools/read/balances.js +93 -0
  43. package/dist/tools/read/guides.js +59 -0
  44. package/dist/tools/read/points.js +25 -0
  45. package/dist/tools/read/pools.js +48 -0
  46. package/dist/tools/read/protocol.js +94 -0
  47. package/dist/tools/write/approve.js +99 -0
  48. package/dist/tools/write/borrow.js +87 -0
  49. package/dist/tools/write/configure-asset-manager.js +258 -0
  50. package/dist/tools/write/create-account.js +112 -0
  51. package/dist/tools/write/deposit.js +104 -0
  52. package/dist/tools/write/repay.js +56 -0
  53. package/dist/tools/write/set-asset-manager.js +65 -0
  54. package/dist/tools/write/sign-and-send.js +90 -0
  55. package/dist/tools/write/withdraw.js +114 -0
  56. package/dist/types/api.js +5 -0
  57. package/dist/utils/attribution.js +20 -0
  58. package/dist/utils/validation.js +17 -0
  59. package/package.json +67 -0
@@ -0,0 +1,310 @@
1
+ import { z } from "zod";
2
+ import { getPublicClient } from "../../clients/chain.js";
3
+ import { readAccountMetadata } from "./account-metadata.js";
4
+ import { formatAdvancedResponse } from "./format-response.js";
5
+ export function registerAddLiquidityTool(server, api, chains) {
6
+ server.tool("build_add_liquidity_tx", "Multi-step flash-action: atomically combines [deposit from wallet] + [use account collateral] + [swap to optimal ratio] + [mint LP] + [borrow if leveraged] in ONE transaction. Do NOT call build_deposit_tx separately. Capital sources: wallet tokens (deposits array), existing account collateral (use_account_assets=true), or both. Check allowances first (get_allowance), then approve if needed (build_approve_tx). Supports depositing multiple tokens and minting multiple LP positions in one tx. Works with both margin accounts (can leverage) and spot accounts (no leverage). For workflows, call get_guide('strategies'). The returned calldata is time-sensitive — sign and broadcast within 30 seconds. If the transaction reverts due to price movement, rebuild and sign again immediately (retry at least once before giving up). Response includes tenderly_sim_url and tenderly_sim_status for pre-broadcast validation.", {
7
+ account_address: z.string().describe("Arcadia account address"),
8
+ wallet_address: z.string().describe("Wallet address of the account owner"),
9
+ positions: z
10
+ .array(z.object({
11
+ strategy_id: z.number().describe("From get_strategies tool"),
12
+ tick_lower: z
13
+ .number()
14
+ .optional()
15
+ .describe("Lower tick for concentrated range. Omit for full range."),
16
+ tick_upper: z
17
+ .number()
18
+ .optional()
19
+ .describe("Upper tick for concentrated range. Omit for full range."),
20
+ }))
21
+ .describe("LP positions to mint. For a single position, pass one entry."),
22
+ deposits: z
23
+ .array(z.object({
24
+ asset: z.string().describe("Token address to deposit from wallet"),
25
+ amount: z.string().describe("Amount in raw units"),
26
+ decimals: z
27
+ .number()
28
+ .optional()
29
+ .describe("Token decimals (e.g. 6 for USDC, 18 for WETH). Default 18."),
30
+ }))
31
+ .optional()
32
+ .describe("Wallet tokens to deposit. Approve each token first (build_approve_tx). Omit to use only account collateral."),
33
+ use_account_assets: z
34
+ .boolean()
35
+ .optional()
36
+ .default(false)
37
+ .describe("If true, use ALL existing account collateral for LP minting. Fetched automatically."),
38
+ leverage: z
39
+ .number()
40
+ .optional()
41
+ .default(0)
42
+ .describe("0 = no borrow, 2 = 2x leverage. Margin accounts only."),
43
+ slippage: z.number().optional().default(100).describe("Basis points, 100 = 1%"),
44
+ chain_id: z
45
+ .number()
46
+ .default(8453)
47
+ .describe("Chain ID: 8453 (Base), 10 (Optimism), or 130 (Unichain)"),
48
+ }, async ({ account_address, wallet_address, positions, deposits: walletDeposits, use_account_assets, leverage, slippage, chain_id, }) => {
49
+ try {
50
+ const hasDeposits = walletDeposits && walletDeposits.length > 0;
51
+ // Validate: at least one capital source
52
+ if (!hasDeposits && !use_account_assets) {
53
+ return {
54
+ content: [
55
+ {
56
+ type: "text",
57
+ text: "Error: Provide deposits (wallet tokens) and/or use_account_assets=true (account collateral). At least one capital source is required.",
58
+ },
59
+ ],
60
+ isError: true,
61
+ };
62
+ }
63
+ // Auto-detect account version + numeraire
64
+ const { accounts } = await api.getAccounts(chain_id, wallet_address);
65
+ const accountStub = accounts.find((a) => a.account_address.toLowerCase() === account_address.toLowerCase());
66
+ if (!accountStub) {
67
+ return {
68
+ content: [
69
+ {
70
+ type: "text",
71
+ text: `Error: Account ${account_address} not found for wallet ${wallet_address} on chain ${chain_id}.`,
72
+ },
73
+ ],
74
+ isError: true,
75
+ };
76
+ }
77
+ const version = accountStub.creation_version;
78
+ // Auto-detect creditor from account overview (fall back to on-chain reads)
79
+ const overview = (await api
80
+ .getAccountOverview(chain_id, account_address)
81
+ .catch(() => null));
82
+ let creditor;
83
+ if (overview) {
84
+ creditor = overview.creditor ?? "";
85
+ }
86
+ else {
87
+ const client = getPublicClient(chain_id, chains);
88
+ const metadata = await readAccountMetadata(client, account_address);
89
+ creditor = metadata.creditor;
90
+ }
91
+ // Spot vs margin detection
92
+ const isSpot = !creditor || creditor === "0x0000000000000000000000000000000000000000";
93
+ // Guard: spot accounts cannot leverage
94
+ if (isSpot && (leverage ?? 0) > 0) {
95
+ return {
96
+ content: [
97
+ {
98
+ type: "text",
99
+ text: "Error: Spot accounts cannot borrow. Set leverage to 0, or create a margin account (V3) with a creditor (lending pool) using build_create_account_tx.",
100
+ },
101
+ ],
102
+ isError: true,
103
+ };
104
+ }
105
+ // Guard: V4 accounts cannot leverage even with a creditor
106
+ if (version >= 4 && (leverage ?? 0) > 0) {
107
+ return {
108
+ content: [
109
+ {
110
+ type: "text",
111
+ text: "Error: V4 accounts are spot-only and cannot borrow or use leverage. Create a V3 margin account (account_version: 3) with a creditor to use leverage.",
112
+ },
113
+ ],
114
+ isError: true,
115
+ };
116
+ }
117
+ // Fetch assets list (used for numeraire decimals + sell array decimals)
118
+ const rawAssets = await api.getAssets(chain_id);
119
+ const assetObj = rawAssets;
120
+ const assetList = (Array.isArray(rawAssets) ? rawAssets : (assetObj.assets ?? assetObj.data ?? []));
121
+ const decimalsMap = new Map();
122
+ for (const a of assetList) {
123
+ const addr = (a.address ?? a.asset_address ?? "").toLowerCase();
124
+ if (addr && a.decimals != null)
125
+ decimalsMap.set(addr, Number(a.decimals));
126
+ }
127
+ // Resolve numeraire + decimals
128
+ const numeraire = accountStub.numeraire;
129
+ const numeraire_decimals = decimalsMap.get(numeraire?.toLowerCase() ?? "") ?? 18;
130
+ // Strategy lookup for all positions
131
+ const allStrategies = (await api.getStrategies(chain_id));
132
+ const resolvedPositions = [];
133
+ for (const pos of positions) {
134
+ const strategy = allStrategies.find((s) => s.strategy_id === pos.strategy_id);
135
+ if (!strategy) {
136
+ return {
137
+ content: [
138
+ {
139
+ type: "text",
140
+ text: `Error: Strategy ${pos.strategy_id} not found on chain ${chain_id}.`,
141
+ },
142
+ ],
143
+ isError: true,
144
+ };
145
+ }
146
+ resolvedPositions.push({
147
+ strategy,
148
+ tick_lower: pos.tick_lower,
149
+ tick_upper: pos.tick_upper,
150
+ });
151
+ }
152
+ // Minimum margin guard per deposit against first strategy's risk factors
153
+ if (hasDeposits) {
154
+ const firstStrategy = resolvedPositions[0].strategy;
155
+ const riskFactors = firstStrategy.details?.risk_factors;
156
+ if (riskFactors) {
157
+ for (const dep of walletDeposits) {
158
+ const riskEntry = Object.entries(riskFactors).find(([addr]) => addr.toLowerCase() === dep.asset.toLowerCase());
159
+ if (riskEntry) {
160
+ const minMargin = BigInt(riskEntry[1].minimum_margin);
161
+ const depositBig = BigInt(dep.amount);
162
+ if (depositBig < minMargin) {
163
+ const decimals = dep.decimals ?? 18;
164
+ const depFormatted = (Number(depositBig) / 10 ** decimals).toFixed(Math.min(decimals, 8));
165
+ const minFormatted = (Number(minMargin) / 10 ** decimals).toFixed(Math.min(decimals, 8));
166
+ return {
167
+ content: [
168
+ {
169
+ type: "text",
170
+ text: `Error: Deposit ${depFormatted} is below the minimum ${minFormatted} for ${dep.asset} on strategy ${firstStrategy.strategy_id} (raw: ${dep.amount} < ${minMargin.toString()}). Increase the deposit amount.`,
171
+ },
172
+ ],
173
+ isError: true,
174
+ };
175
+ }
176
+ }
177
+ }
178
+ }
179
+ }
180
+ // Build sell array from account assets
181
+ let sell = [];
182
+ if (use_account_assets) {
183
+ if (!overview) {
184
+ return {
185
+ content: [
186
+ {
187
+ type: "text",
188
+ text: "Error: use_account_assets=true but account overview is unavailable (cannot read asset list). Use deposits to deposit from wallet instead.",
189
+ },
190
+ ],
191
+ isError: true,
192
+ };
193
+ }
194
+ const accountAssets = (overview.assets ?? []);
195
+ if (accountAssets.length === 0 && !hasDeposits) {
196
+ return {
197
+ content: [
198
+ {
199
+ type: "text",
200
+ text: "Error: use_account_assets=true but the account has no deposited assets, and no wallet deposits were provided. Deposit assets first via build_deposit_tx or provide deposits.",
201
+ },
202
+ ],
203
+ isError: true,
204
+ };
205
+ }
206
+ if (accountAssets.length > 0) {
207
+ sell = accountAssets.map((a) => ({
208
+ asset_address: a.address,
209
+ amount: String(a.amount),
210
+ decimals: decimalsMap.get(a.address.toLowerCase()) ?? 18,
211
+ asset_id: Number(a.id ?? 0),
212
+ }));
213
+ }
214
+ }
215
+ // Build deposits from wallet
216
+ const deposits = hasDeposits
217
+ ? {
218
+ addresses: walletDeposits.map((d) => d.asset),
219
+ ids: walletDeposits.map(() => 0),
220
+ amounts: walletDeposits.map((d) => d.amount),
221
+ decimals: walletDeposits.map((d) => d.decimals ?? 18),
222
+ }
223
+ : {
224
+ addresses: [],
225
+ ids: [],
226
+ amounts: [],
227
+ decimals: [],
228
+ };
229
+ // Build buy array from positions
230
+ const distribution = 1 / resolvedPositions.length;
231
+ const buy = resolvedPositions.map(({ strategy, tick_lower, tick_upper }) => {
232
+ const entry = {
233
+ asset_address: strategy.asset_address,
234
+ distribution,
235
+ decimals: strategy.asset_decimals,
236
+ strategy_id: strategy.strategy_id,
237
+ };
238
+ if (tick_lower !== undefined && tick_upper !== undefined) {
239
+ entry.ticks = { tick_lower, tick_upper };
240
+ }
241
+ return entry;
242
+ });
243
+ const body = {
244
+ buy,
245
+ sell,
246
+ deposits,
247
+ withdraws: {
248
+ addresses: [],
249
+ ids: [],
250
+ amounts: [],
251
+ decimals: [],
252
+ },
253
+ wallet_address,
254
+ account_address,
255
+ numeraire,
256
+ numeraire_decimals,
257
+ debt: {
258
+ take: isSpot ? false : (leverage ?? 0) > 0,
259
+ leverage: isSpot ? 1 : (leverage ?? 0),
260
+ repay: 0,
261
+ creditor,
262
+ },
263
+ chain_id,
264
+ version,
265
+ action_type: "portfolio.advanced",
266
+ slippage: slippage ?? 100,
267
+ };
268
+ const result = await api.getBundleCalldata(body);
269
+ // Surface simulation failure — do NOT return calldata
270
+ if (result.tenderly_sim_status === "false") {
271
+ const simUrl = result.tenderly_sim_url
272
+ ? `\nTenderly simulation: ${result.tenderly_sim_url}`
273
+ : "";
274
+ const simError = result.tenderly_sim_error
275
+ ? `\nRevert reason: ${result.tenderly_sim_error}`
276
+ : "";
277
+ return {
278
+ content: [
279
+ {
280
+ type: "text",
281
+ text: `Error: Transaction simulation FAILED — do NOT broadcast.${simError}\nCommon causes: insufficient wallet balance, missing token approval, or deposit below minimum margin.${simUrl}`,
282
+ },
283
+ ],
284
+ isError: true,
285
+ };
286
+ }
287
+ const res = result;
288
+ return {
289
+ content: [
290
+ {
291
+ type: "text",
292
+ text: JSON.stringify(formatAdvancedResponse(res, chain_id), null, 2),
293
+ },
294
+ ],
295
+ };
296
+ }
297
+ catch (err) {
298
+ return {
299
+ content: [
300
+ {
301
+ type: "text",
302
+ text: `Error: ${err instanceof Error ? err.message : String(err)}`,
303
+ },
304
+ ],
305
+ isError: true,
306
+ };
307
+ }
308
+ });
309
+ }
310
+ //# sourceMappingURL=add-liquidity.js.map
@@ -0,0 +1,208 @@
1
+ import { z } from "zod";
2
+ import { getPublicClient } from "../../clients/chain.js";
3
+ import { readAccountMetadata } from "./account-metadata.js";
4
+ import { formatAdvancedResponse } from "./format-response.js";
5
+ export function registerClosePositionTool(server, api, chains) {
6
+ server.tool("build_close_position_tx", `Atomic flash-action that closes an Arcadia account position in ONE transaction. Combines up to 3 steps atomically: [burn LP position] + [swap all tokens to a single target asset] + [repay debt]. Tokens remain in the account after closing — use build_withdraw_tx to send them to your wallet.
7
+
8
+ ALWAYS try this tool first when closing/exiting a position. Only fall back to individual tools (build_remove_liquidity_tx, build_swap_tx, build_repay_with_collateral_tx, build_withdraw_tx) if this tool fails.
9
+
10
+ Supports two modes:
11
+ - close_lp_only=true: Burns LP and leaves underlying tokens in the account. Use as step 1 if the full close fails, then call again with close_lp_only=false to swap+repay the remaining tokens.
12
+ - close_lp_only=false (default): Full atomic close — burns LP, swaps everything to receive_assets, repays debt. Remaining tokens stay in the account. Follow up with build_withdraw_tx to send to wallet. Supports multiple receive assets with custom distribution.
13
+
14
+ The returned calldata is time-sensitive — sign and broadcast within 30 seconds. If the transaction reverts due to price movement, rebuild and sign again immediately (retry at least once before giving up). Response includes tenderly_sim_url and tenderly_sim_status for pre-broadcast validation.`, {
15
+ account_address: z.string().describe("Arcadia account address"),
16
+ assets: z
17
+ .array(z.object({
18
+ asset_address: z.string().describe("Token or position manager address"),
19
+ asset_id: z.number().describe("NFT token ID (0 for ERC20 tokens)"),
20
+ amount: z.string().describe("Amount to sell (use '1' for NFT positions)"),
21
+ decimals: z.number().describe("Token decimals (use 1 for NFT positions)"),
22
+ }))
23
+ .describe("Assets to close/sell from the account. For LP positions: asset_address = position manager, asset_id = NFT ID, amount = '1', decimals = 1. For ERC20 tokens: asset_id = 0, amount = full balance, decimals = token decimals. Get these from get_account_info."),
24
+ receive_assets: z
25
+ .array(z.object({
26
+ asset_address: z.string().describe("Target token address (e.g. USDC, WETH)"),
27
+ decimals: z.number().describe("Token decimals of the target asset"),
28
+ distribution: z
29
+ .number()
30
+ .optional()
31
+ .describe("Fraction of proceeds (0-1). Defaults to equal split across all receive assets."),
32
+ }))
33
+ .optional()
34
+ .describe("Target assets to receive after closing. For a single target, pass one entry. Required when close_lp_only=false. Omit for close_lp_only=true."),
35
+ close_lp_only: z
36
+ .boolean()
37
+ .optional()
38
+ .default(false)
39
+ .describe("true = only burn LP positions, leave underlying tokens in account. false = full close (burn + swap + repay)."),
40
+ slippage: z.number().optional().default(100).describe("Basis points, 100 = 1%"),
41
+ chain_id: z
42
+ .number()
43
+ .default(8453)
44
+ .describe("Chain ID: 8453 (Base), 10 (Optimism), or 130 (Unichain)"),
45
+ }, async ({ account_address, assets, receive_assets, close_lp_only, slippage, chain_id }) => {
46
+ try {
47
+ const actionType = close_lp_only ? "account.closing-lp" : "account.closing-position";
48
+ if (!close_lp_only && (!receive_assets || receive_assets.length === 0)) {
49
+ return {
50
+ content: [
51
+ {
52
+ type: "text",
53
+ text: "Error: receive_assets is required for full close (close_lp_only=false). Specify at least one target asset to convert everything to (e.g. USDC or WETH).",
54
+ },
55
+ ],
56
+ isError: true,
57
+ };
58
+ }
59
+ // Look up account metadata (fall back to on-chain reads)
60
+ const overviewRaw = (await api
61
+ .getAccountOverview(chain_id, account_address)
62
+ .catch(() => null));
63
+ let owner;
64
+ let creditor;
65
+ let numeraire;
66
+ let version;
67
+ if (overviewRaw) {
68
+ owner = (overviewRaw.owner ?? "");
69
+ if (!owner) {
70
+ return {
71
+ content: [
72
+ {
73
+ type: "text",
74
+ text: "Error: Could not determine account owner from overview.",
75
+ },
76
+ ],
77
+ isError: true,
78
+ };
79
+ }
80
+ creditor =
81
+ overviewRaw.creditor ?? "0x0000000000000000000000000000000000000000";
82
+ const { accounts } = await api.getAccounts(chain_id, owner);
83
+ const accountStub = accounts.find((a) => a.account_address.toLowerCase() === account_address.toLowerCase());
84
+ numeraire = accountStub?.numeraire ?? "";
85
+ version = accountStub?.creation_version ?? 3;
86
+ }
87
+ else {
88
+ const client = getPublicClient(chain_id, chains);
89
+ const metadata = await readAccountMetadata(client, account_address);
90
+ owner = metadata.owner;
91
+ creditor = metadata.creditor;
92
+ numeraire = metadata.numeraire;
93
+ if (!owner || owner === "0x0000000000000000000000000000000000000000") {
94
+ return {
95
+ content: [
96
+ {
97
+ type: "text",
98
+ text: "Error: Could not determine account owner. The account may not exist on this chain.",
99
+ },
100
+ ],
101
+ isError: true,
102
+ };
103
+ }
104
+ const { accounts } = await api.getAccounts(chain_id, owner);
105
+ const accountStub = accounts.find((a) => a.account_address.toLowerCase() === account_address.toLowerCase());
106
+ version = accountStub?.creation_version ?? 3;
107
+ if (accountStub?.numeraire)
108
+ numeraire = accountStub.numeraire;
109
+ }
110
+ // Resolve numeraire decimals
111
+ const rawAssets = await api.getAssets(chain_id);
112
+ const assetObj = rawAssets;
113
+ const assetList = (Array.isArray(rawAssets) ? rawAssets : (assetObj.assets ?? assetObj.data ?? []));
114
+ let numeraireDecimals = 18;
115
+ for (const a of assetList) {
116
+ const addr = (a.address ?? a.asset_address ?? "").toLowerCase();
117
+ if (addr === numeraire.toLowerCase() && a.decimals != null) {
118
+ numeraireDecimals = Number(a.decimals);
119
+ break;
120
+ }
121
+ }
122
+ // Build buy array from receive_assets
123
+ const defaultDist = receive_assets ? 1 / receive_assets.length : 1;
124
+ const buy = close_lp_only
125
+ ? []
126
+ : receive_assets.map((r) => ({
127
+ asset_address: r.asset_address,
128
+ distribution: r.distribution ?? defaultDist,
129
+ decimals: r.decimals,
130
+ strategy_id: 0,
131
+ }));
132
+ const body = {
133
+ buy,
134
+ sell: assets.map((a) => ({
135
+ asset_address: a.asset_address,
136
+ amount: a.amount,
137
+ decimals: a.decimals,
138
+ asset_id: a.asset_id,
139
+ })),
140
+ deposits: {
141
+ addresses: [],
142
+ ids: [],
143
+ amounts: [],
144
+ decimals: [],
145
+ },
146
+ withdraws: {
147
+ addresses: [],
148
+ ids: [],
149
+ amounts: [],
150
+ decimals: [],
151
+ },
152
+ wallet_address: owner,
153
+ account_address,
154
+ numeraire,
155
+ numeraire_decimals: numeraireDecimals,
156
+ debt: {
157
+ take: false,
158
+ leverage: 0,
159
+ repay: -1,
160
+ creditor,
161
+ },
162
+ chain_id,
163
+ version,
164
+ action_type: actionType,
165
+ slippage: slippage ?? 100,
166
+ };
167
+ const result = await api.getBundleCalldata(body);
168
+ const res = result;
169
+ if (result.tenderly_sim_status === "false") {
170
+ const simUrl = result.tenderly_sim_url
171
+ ? `\nTenderly simulation: ${result.tenderly_sim_url}`
172
+ : "";
173
+ const simError = result.tenderly_sim_error
174
+ ? `\nRevert reason: ${result.tenderly_sim_error}`
175
+ : "";
176
+ return {
177
+ content: [
178
+ {
179
+ type: "text",
180
+ text: `Error: Transaction simulation FAILED — do NOT broadcast.${simError}${simUrl}\n\nIf this was a full close, try close_lp_only=true first to burn the LP, then call again with close_lp_only=false to swap and repay the remaining tokens.`,
181
+ },
182
+ ],
183
+ isError: true,
184
+ };
185
+ }
186
+ return {
187
+ content: [
188
+ {
189
+ type: "text",
190
+ text: JSON.stringify(formatAdvancedResponse(res, chain_id), null, 2),
191
+ },
192
+ ],
193
+ };
194
+ }
195
+ catch (err) {
196
+ return {
197
+ content: [
198
+ {
199
+ type: "text",
200
+ text: `Error: ${err instanceof Error ? err.message : String(err)}`,
201
+ },
202
+ ],
203
+ isError: true,
204
+ };
205
+ }
206
+ });
207
+ }
208
+ //# sourceMappingURL=close-position.js.map
@@ -0,0 +1,26 @@
1
+ import { appendDataSuffix } from "../../utils/attribution.js";
2
+ export function formatAdvancedResponse(result, chainId) {
3
+ const to = (result.fx_call_to ?? "");
4
+ const data = appendDataSuffix((result.calldata ?? ""));
5
+ const response = {
6
+ transaction: { to, data, value: "0", chainId },
7
+ };
8
+ if (result.tenderly_sim_url != null) {
9
+ response.tenderly_sim_url = result.tenderly_sim_url;
10
+ }
11
+ if (result.tenderly_sim_status != null) {
12
+ response.tenderly_sim_status = result.tenderly_sim_status;
13
+ }
14
+ else {
15
+ response.tenderly_sim_status = "unavailable";
16
+ }
17
+ if (result.expected_value_change != null) {
18
+ response.expected_value_change = result.expected_value_change;
19
+ }
20
+ if (result.before != null)
21
+ response.before = result.before;
22
+ if (result.after != null)
23
+ response.after = result.after;
24
+ return response;
25
+ }
26
+ //# sourceMappingURL=format-response.js.map
@@ -0,0 +1,95 @@
1
+ import { z } from "zod";
2
+ import { formatAdvancedResponse } from "./format-response.js";
3
+ export function registerPositionActionsTool(server, api) {
4
+ server.tool("build_position_action_tx", "Flash-action: stake, unstake, or claim rewards for an LP position in one atomic transaction. The stake/unstake direction is auto-detected from asset_address: pass the non-staked position manager to stake, or the staked position manager to unstake. The returned calldata is time-sensitive — sign and broadcast within 30 seconds. If the transaction reverts due to price movement, rebuild and sign again immediately (retry at least once before giving up).", {
5
+ account_address: z.string().describe("Arcadia account address"),
6
+ action: z.enum(["stake", "unstake", "claim"]).describe("Action to perform"),
7
+ asset_address: z.string().describe("Position manager contract address"),
8
+ asset_id: z.number().describe("NFT token ID of the LP position"),
9
+ chain_id: z
10
+ .number()
11
+ .default(8453)
12
+ .describe("Chain ID: 8453 (Base), 10 (Optimism), or 130 (Unichain)"),
13
+ }, async ({ account_address, action, asset_address, asset_id, chain_id }) => {
14
+ try {
15
+ if (action === "claim") {
16
+ const result = await api.getClaimCalldata({
17
+ chain_id,
18
+ account_address,
19
+ asset_address,
20
+ asset_id,
21
+ });
22
+ const claimRes = result;
23
+ if (claimRes.tenderly_sim_status === "false") {
24
+ const simUrl = claimRes.tenderly_sim_url
25
+ ? `\nTenderly simulation: ${claimRes.tenderly_sim_url}`
26
+ : "";
27
+ const simError = claimRes.tenderly_sim_error
28
+ ? `\nRevert reason: ${claimRes.tenderly_sim_error}`
29
+ : "";
30
+ return {
31
+ content: [
32
+ {
33
+ type: "text",
34
+ text: `Error: Transaction simulation FAILED — do NOT broadcast.${simError}${simUrl}`,
35
+ },
36
+ ],
37
+ isError: true,
38
+ };
39
+ }
40
+ return {
41
+ content: [
42
+ {
43
+ type: "text",
44
+ text: JSON.stringify(formatAdvancedResponse(claimRes, chain_id), null, 2),
45
+ },
46
+ ],
47
+ };
48
+ }
49
+ const result = await api.getStakeCalldata({
50
+ chain_id,
51
+ account_address,
52
+ asset_address,
53
+ asset_id,
54
+ });
55
+ const res = result;
56
+ if (res.tenderly_sim_status === "false") {
57
+ const simUrl = res.tenderly_sim_url
58
+ ? `\nTenderly simulation: ${res.tenderly_sim_url}`
59
+ : "";
60
+ const simError = res.tenderly_sim_error
61
+ ? `\nRevert reason: ${res.tenderly_sim_error}`
62
+ : "";
63
+ return {
64
+ content: [
65
+ {
66
+ type: "text",
67
+ text: `Error: Transaction simulation FAILED — do NOT broadcast.${simError}${simUrl}`,
68
+ },
69
+ ],
70
+ isError: true,
71
+ };
72
+ }
73
+ return {
74
+ content: [
75
+ {
76
+ type: "text",
77
+ text: JSON.stringify(formatAdvancedResponse(res, chain_id), null, 2),
78
+ },
79
+ ],
80
+ };
81
+ }
82
+ catch (err) {
83
+ return {
84
+ content: [
85
+ {
86
+ type: "text",
87
+ text: `Error: ${err instanceof Error ? err.message : String(err)}`,
88
+ },
89
+ ],
90
+ isError: true,
91
+ };
92
+ }
93
+ });
94
+ }
95
+ //# sourceMappingURL=position-actions.js.map