@arcadia-finance/mcp-server 0.5.2 → 0.6.1

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 (53) hide show
  1. package/README.md +47 -42
  2. package/dist/clients/api.js +52 -5
  3. package/dist/clients/chain.js +1 -1
  4. package/dist/config/addresses.js +16 -3
  5. package/dist/index.js +36 -134
  6. package/dist/prompts/workflows.js +56 -18
  7. package/dist/resources/guides.js +1 -1
  8. package/dist/tools/aero.js +157 -0
  9. package/dist/tools/dev/send.js +4 -4
  10. package/dist/tools/index.js +6 -0
  11. package/dist/tools/output-schemas.js +105 -29
  12. package/dist/tools/read/account.js +13 -13
  13. package/dist/tools/read/aero-upgrade.js +53 -0
  14. package/dist/tools/read/asset-managers.js +9 -9
  15. package/dist/tools/read/assets.js +7 -7
  16. package/dist/tools/read/guides.js +4 -4
  17. package/dist/tools/read/points.js +4 -4
  18. package/dist/tools/read/pools.js +8 -8
  19. package/dist/tools/read/strategy.js +18 -14
  20. package/dist/tools/read/wallet.js +15 -15
  21. package/dist/tools/write/account/add-liquidity.js +131 -12
  22. package/dist/tools/write/account/aero-upgrade.js +124 -0
  23. package/dist/tools/write/account/borrow.js +5 -5
  24. package/dist/tools/write/account/close.js +8 -8
  25. package/dist/tools/write/account/create.js +3 -3
  26. package/dist/tools/write/account/deleverage.js +4 -4
  27. package/dist/tools/write/account/deposit.js +4 -4
  28. package/dist/tools/write/account/format-response.js +1 -1
  29. package/dist/tools/write/account/remove-liquidity.js +6 -6
  30. package/dist/tools/write/account/repay.js +4 -4
  31. package/dist/tools/write/account/stake.js +5 -5
  32. package/dist/tools/write/account/swap.js +4 -4
  33. package/dist/tools/write/account/withdraw.js +5 -5
  34. package/dist/tools/write/asset-managers/automations.js +14 -14
  35. package/dist/tools/write/asset-managers/intents.js +10 -7
  36. package/dist/tools/write/pool/deposit.js +5 -5
  37. package/dist/tools/write/pool/redeem.js +4 -4
  38. package/dist/tools/write/wallet/approve.js +4 -4
  39. package/dist/tools/write/wallet/upgrade-velo.js +76 -0
  40. package/dist/utils/analytics.js +68 -0
  41. package/dist/utils/http-config.js +4 -4
  42. package/llms-full.txt +83 -46
  43. package/llms.txt +47 -44
  44. package/package.json +8 -4
  45. package/server.json +4 -4
  46. package/skills/clamm-liquidity/SKILL.md +100 -82
  47. package/skills/clamm-liquidity/automation.md +14 -14
  48. package/skills/clamm-liquidity/selection.md +13 -13
  49. package/skills/clamm-liquidity/strategies.md +135 -53
  50. package/skills/openclaw/SKILL.md +3 -3
  51. package/skills/openclaw/arcadia.sh +24 -45
  52. package/skills/openclaw/contracts.md +11 -10
  53. package/dist/utils/tool-naming.js +0 -91
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { ArcadiaApiError } from "../../../clients/api.js";
2
3
  import { CHAIN_ID_DESCRIPTION } from "../../../config/chains.js";
3
4
  import { getPublicClient } from "../../../clients/chain.js";
4
5
  import { readAccountMetadata } from "./metadata.js";
@@ -6,6 +7,91 @@ import { formatBatchedResponse, isSimulationFailed } from "./format-response.js"
6
7
  import { TOKENS } from "../../../config/addresses.js";
7
8
  import { validateAddress, validateChainId } from "../../../utils/validation.js";
8
9
  import { BatchedTransactionOutput } from "../../output-schemas.js";
10
+ function formatUsd(value) {
11
+ const digits = Math.abs(value) >= 1 ? { maximumFractionDigits: 2 } : { maximumSignificantDigits: 4 };
12
+ return `${value.toLocaleString("en-US", digits)} USD`;
13
+ }
14
+ function refusalMessage(err) {
15
+ if (!(err instanceof ArcadiaApiError) || err.status !== 400)
16
+ return undefined;
17
+ const body = err.body;
18
+ if (body === null || typeof body !== "object")
19
+ return undefined;
20
+ const message = body.message;
21
+ return typeof message === "string" ? message : undefined;
22
+ }
23
+ function describePriceCheck(check, tokenSymbols) {
24
+ const name = (addr) => tokenSymbols.get(addr.toLowerCase()) ?? addr;
25
+ if (check.status === "off_market") {
26
+ if (typeof check.deviation_bps !== "number") {
27
+ throw new Error(`Malformed price check for pool ${check.pool}: off_market without deviation_bps.`);
28
+ }
29
+ const pct = Math.abs(check.deviation_bps) / 100;
30
+ return `Pool ${check.pool} (${name(check.token0)}/${name(check.token1)}): pool price is ${pct}% off market.`;
31
+ }
32
+ if (!check.unpriced_token_name) {
33
+ throw new Error(`Malformed price check for pool ${check.pool}: unpriced without unpriced_token_name.`);
34
+ }
35
+ const parts = [
36
+ `Pool ${check.pool} (${name(check.token0)}/${name(check.token1)}): no price information for ${check.unpriced_token_name}, so the pool price cannot be verified.`,
37
+ ];
38
+ if (check.implied_usd_price != null) {
39
+ parts.push(`The pool implies a price of ${formatUsd(check.implied_usd_price)}.`);
40
+ }
41
+ if (check.swap_spend_usd != null) {
42
+ parts.push(`The position swaps about ${formatUsd(check.swap_spend_usd)} at that price.`);
43
+ }
44
+ return parts.join(" ");
45
+ }
46
+ const PriceCheckAcknowledgement = z.discriminatedUnion("status", [
47
+ z.object({
48
+ pool: z.string(),
49
+ status: z.literal("off_market"),
50
+ deviation_bps: z.number(),
51
+ unpriced_token: z.null(),
52
+ }),
53
+ z.object({
54
+ pool: z.string(),
55
+ status: z.literal("unpriced"),
56
+ deviation_bps: z.null(),
57
+ unpriced_token: z.string(),
58
+ }),
59
+ ]);
60
+ function acknowledgementFor(check) {
61
+ if (check.status === "off_market") {
62
+ if (typeof check.deviation_bps !== "number") {
63
+ throw new Error(`Malformed price check for pool ${check.pool}: off_market without deviation_bps.`);
64
+ }
65
+ return {
66
+ pool: check.pool,
67
+ status: "off_market",
68
+ deviation_bps: check.deviation_bps,
69
+ unpriced_token: null,
70
+ };
71
+ }
72
+ if (!check.unpriced_token) {
73
+ throw new Error(`Malformed price check for pool ${check.pool}: unpriced without unpriced_token.`);
74
+ }
75
+ return {
76
+ pool: check.pool,
77
+ status: "unpriced",
78
+ deviation_bps: null,
79
+ unpriced_token: check.unpriced_token,
80
+ };
81
+ }
82
+ function isCovered(flagged, accepted) {
83
+ return accepted.some((a) => {
84
+ if (a.pool.toLowerCase() !== flagged.pool.toLowerCase())
85
+ return false;
86
+ if (a.status === "off_market" && flagged.status === "off_market") {
87
+ return Math.abs(flagged.deviation_bps) <= Math.abs(a.deviation_bps);
88
+ }
89
+ if (a.status === "unpriced" && flagged.status === "unpriced") {
90
+ return a.unpriced_token.toLowerCase() === flagged.unpriced_token.toLowerCase();
91
+ }
92
+ return false;
93
+ });
94
+ }
9
95
  function formatTokenAmount(value, decimals, maxFrac = 8) {
10
96
  const str = value.toString().padStart(decimals + 1, "0");
11
97
  const whole = str.slice(0, -decimals);
@@ -13,7 +99,7 @@ function formatTokenAmount(value, decimals, maxFrac = 8) {
13
99
  return frac ? `${whole}.${frac}` : whole;
14
100
  }
15
101
  export function registerAddLiquidityTool(server, api, chains) {
16
- server.registerTool("write.account.add_liquidity", {
102
+ server.registerTool("write_account_add_liquidity", {
17
103
  annotations: {
18
104
  title: "Build Add Liquidity Transaction",
19
105
  readOnlyHint: false,
@@ -22,15 +108,15 @@ export function registerAddLiquidityTool(server, api, chains) {
22
108
  openWorldHint: true,
23
109
  },
24
110
  outputSchema: BatchedTransactionOutput,
25
- description: "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 write.account.deposit separately. Capital sources: wallet tokens (deposits array), existing account collateral (use_account_assets=true), or both. Check allowances first (read.wallet.allowances), then approve if needed (write.wallet.approve). 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 read.guides('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. expected_value_change is in raw units of the account's numeraire token (6 decimals for USDC, 18 for WETH). Negative = cost to open, positive = value gained. Compare before.total_account_value and after.total_account_value for the full picture.",
26
- inputSchema: {
111
+ description: "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 write_account_deposit separately. Capital sources: wallet tokens (deposits array), existing account collateral (use_account_assets=true), or both. Check allowances first (read_wallet_allowances), then approve if needed (write_wallet_approve). 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 read_guides('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), passing only the accept_price_checks the user already confirmed. Response includes tenderly_sim_url and tenderly_sim_status for pre-broadcast validation. expected_value_change is in raw units of the account's numeraire token (6 decimals for USDC, 18 for WETH). Negative = cost to open, positive = value gained. Compare before.total_account_value and after.total_account_value for the full picture. If a pool's price is off market or one of its tokens has no price, the tool returns the price warnings, an accept_price_checks list and NO transaction. Show the warnings to the user and call again with that accept_price_checks list only after the user explicitly confirms they accept them. If a later call returns new warnings, even on a rebuild, show them and get a new confirmation before passing their list. The acknowledgement never bypasses a backend refusal.",
112
+ inputSchema: z.object({
27
113
  account_address: z.string().describe("Arcadia account address"),
28
114
  wallet_address: z.string().describe("Wallet address of the account owner"),
29
115
  positions: z
30
116
  .array(z.object({
31
117
  strategy_id: z
32
118
  .number()
33
- .describe("From read.strategy.list (or read.strategy.info for full range detail)"),
119
+ .describe("From read_strategy_list (or read_strategy_info for full range detail)"),
34
120
  tick_lower: z
35
121
  .number()
36
122
  .optional()
@@ -51,7 +137,7 @@ export function registerAddLiquidityTool(server, api, chains) {
51
137
  .describe("Token decimals (e.g. 6 for USDC, 18 for WETH). Default 18."),
52
138
  }))
53
139
  .optional()
54
- .describe("Wallet tokens to deposit. Approve each token first (write.wallet.approve). Omit to use only account collateral."),
140
+ .describe("Wallet tokens to deposit. Approve each token first (write_wallet_approve). Omit to use only account collateral."),
55
141
  use_account_assets: z
56
142
  .boolean()
57
143
  .optional()
@@ -63,9 +149,13 @@ export function registerAddLiquidityTool(server, api, chains) {
63
149
  .default(0)
64
150
  .describe("0 = no borrow, 2 = 2x leverage. Margin accounts only."),
65
151
  slippage: z.number().optional().default(100).describe("Basis points, 100 = 1%"),
152
+ accept_price_checks: z
153
+ .array(PriceCheckAcknowledgement)
154
+ .optional()
155
+ .describe("The accept_price_checks list returned with the price warnings of a previous call, passed unchanged and only after the user has explicitly confirmed those warnings. Never set it on the first call."),
66
156
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
67
- },
68
- }, async ({ account_address, wallet_address, positions, deposits: walletDeposits, use_account_assets, leverage, slippage, chain_id, }) => {
157
+ }),
158
+ }, async ({ account_address, wallet_address, positions, deposits: walletDeposits, use_account_assets, leverage, slippage, accept_price_checks, chain_id, }) => {
69
159
  try {
70
160
  const validChainId = validateChainId(chain_id);
71
161
  const validAccount = validateAddress(account_address, "account_address");
@@ -127,7 +217,7 @@ export function registerAddLiquidityTool(server, api, chains) {
127
217
  content: [
128
218
  {
129
219
  type: "text",
130
- text: "Error: Spot accounts cannot borrow. Set leverage to 0, or create a margin account (V3) with a creditor (lending pool) using write.account.create.",
220
+ text: "Error: Spot accounts cannot borrow. Set leverage to 0, or create a margin account (V3) with a creditor (lending pool) using write_account_create.",
131
221
  },
132
222
  ],
133
223
  isError: true,
@@ -216,7 +306,7 @@ export function registerAddLiquidityTool(server, api, chains) {
216
306
  content: [
217
307
  {
218
308
  type: "text",
219
- text: "Error: use_account_assets=true but account overview is unavailable and no wallet deposits were provided. Provide deposits or deposit assets first via write.account.deposit.",
309
+ text: "Error: use_account_assets=true but account overview is unavailable and no wallet deposits were provided. Provide deposits or deposit assets first via write_account_deposit.",
220
310
  },
221
311
  ],
222
312
  isError: true,
@@ -228,7 +318,7 @@ export function registerAddLiquidityTool(server, api, chains) {
228
318
  content: [
229
319
  {
230
320
  type: "text",
231
- text: "Error: use_account_assets=true but the account has no deposited assets, and no wallet deposits were provided. Deposit assets first via write.account.deposit or provide deposits.",
321
+ text: "Error: use_account_assets=true but the account has no deposited assets, and no wallet deposits were provided. Deposit assets first via write_account_deposit or provide deposits.",
232
322
  },
233
323
  ],
234
324
  isError: true,
@@ -295,9 +385,15 @@ export function registerAddLiquidityTool(server, api, chains) {
295
385
  version,
296
386
  action_type: "portfolio.advanced",
297
387
  slippage: slippage ?? 100,
388
+ price_checks_supported: true,
298
389
  };
299
390
  const result = await api.getBundleCalldata(body);
300
391
  const res = result;
392
+ const priceChecks = (res.price_checks ?? []);
393
+ const flagged = priceChecks.filter((c) => c.status !== "ok");
394
+ const warnings = flagged.map((c) => describePriceCheck(c, tokenSymbols));
395
+ const acknowledgements = flagged.map(acknowledgementFor);
396
+ const warningText = warnings.length > 0 ? `\nPrice warnings:\n${warnings.join("\n")}` : "";
301
397
  // Surface simulation failure — do NOT return calldata
302
398
  if (isSimulationFailed(res.tenderly_sim_status)) {
303
399
  const simUrl = res.tenderly_sim_url
@@ -310,13 +406,36 @@ export function registerAddLiquidityTool(server, api, chains) {
310
406
  content: [
311
407
  {
312
408
  type: "text",
313
- text: `Error: Transaction simulation FAILED — do NOT broadcast.${simError}\nCommon causes: insufficient wallet balance, missing token approval, or deposit below minimum margin.${simUrl}`,
409
+ text: `Error: Transaction simulation FAILED. Do NOT broadcast.${simError}\nCommon causes: insufficient wallet balance, missing token approval, or deposit below minimum margin.${simUrl}${warningText}`,
410
+ },
411
+ ],
412
+ isError: true,
413
+ };
414
+ }
415
+ const uncovered = acknowledgements.filter((a) => !isCovered(a, accept_price_checks ?? []));
416
+ if (uncovered.length > 0) {
417
+ const changed = accept_price_checks
418
+ ? " The price checks changed since the user confirmed them."
419
+ : "";
420
+ return {
421
+ content: [
422
+ {
423
+ type: "text",
424
+ text: `Error: Price warnings, no transaction returned.${changed} Show these warnings to the user. Call again with accept_price_checks set to the list below only after the user explicitly confirms they accept them.${warningText}\naccept_price_checks: ${JSON.stringify(acknowledgements)}`,
314
425
  },
315
426
  ],
316
427
  isError: true,
317
428
  };
318
429
  }
319
430
  const response = formatBatchedResponse(res, chain_id, "Add liquidity to LP position");
431
+ if (priceChecks.length > 0)
432
+ response.price_checks = priceChecks;
433
+ if (priceChecks.some((c) => c.status === "unpriced") &&
434
+ res.expected_change_status === false &&
435
+ res.expected_value_change == null) {
436
+ response.expected_value_change_unavailable =
437
+ "No price information for a token, so the value change cannot be computed.";
438
+ }
320
439
  return {
321
440
  content: [
322
441
  {
@@ -332,7 +451,7 @@ export function registerAddLiquidityTool(server, api, chains) {
332
451
  content: [
333
452
  {
334
453
  type: "text",
335
- text: `Error: ${err instanceof Error ? err.message : String(err)}`,
454
+ text: `Error: ${refusalMessage(err) ?? (err instanceof Error ? err.message : String(err))}`,
336
455
  },
337
456
  ],
338
457
  isError: true,
@@ -0,0 +1,124 @@
1
+ import { z } from "zod";
2
+ import { validateAddress } from "../../../utils/validation.js";
3
+ import { aeroErrorResult, formatUpgradePlan, simulationReverted, validateAeroChain, } from "../../aero.js";
4
+ import { AeroUpgradeOutput } from "../../output-schemas.js";
5
+ const BATCH_MAX_ACCOUNTS = 10;
6
+ const choiceSchema = z.object({
7
+ position_manager: z.string().describe("The position's source.position_manager"),
8
+ position_id: z.number().int().describe("The position's source.position_id"),
9
+ pool: z.string().describe("The chosen option's pool"),
10
+ });
11
+ function choiceStrings(choices) {
12
+ if (!choices || choices.length === 0)
13
+ return undefined;
14
+ return choices.map((c) => `${validateAddress(c.position_manager, "choices[].position_manager")}:${c.position_id}:${validateAddress(c.pool, "choices[].pool")}`);
15
+ }
16
+ export function registerAeroUpgradeTool(server, api) {
17
+ server.registerTool("write_account_aero_upgrade", {
18
+ annotations: {
19
+ title: "Build Aero Upgrade Transaction",
20
+ readOnlyHint: false,
21
+ destructiveHint: false,
22
+ idempotentHint: true,
23
+ openWorldHint: true,
24
+ },
25
+ outputSchema: AeroUpgradeOutput,
26
+ description: "Upgrade one Arcadia account to Aero (MetadexCL V1) in one flashAction: every Slipstream V1/V2/V3 position (dex_protocol slipstream*, staked or not, see read_account_info) moves to the Aero CL pool with the same pair and variant at the same range and tick spacing (when Aero has no pool at that tick spacing, the user picks another one), and every unit of old AERO (loose, in rewards, in an old-AERO pair) becomes the new AERO. Returns the plan and, when anything can go now, the unsigned transaction. Only the account owner can sign it. " +
27
+ "The backend decides what moves: report items[].status and items[].reason as given, never decide eligibility yourself. status ready: sign transaction. choices_required: some position has status choose with options[] (every Aero pool on its pair, with apy, tvl_usd, is_new, tick_spacing, range_widened, default and disabled_reason); ask the user to pick one whose disabled_reason is null, then call again with it in choices so one transaction moves everything. The transaction returned with choices_required moves only the ready items: sign it alone only when the user wants to leave the choose positions where they are. waiting: each item's reason says why (pool_not_on_aero, staking_not_open, target_price_mismatch, account_unhealthy, ...); a waiting item with an option whose disabled_reason is null can still move with that pick, so ask the user; do not retry in a loop. not_open: the AERO upgrade contract does not accept deposits at the moment. A 422 saying a pool is not selectable: drop that pick, call again without it and ask the user again. " +
28
+ "Pass accounts (up to 10) instead of account_address for one plan per account; the accounts share one AERO upgrade budget. multisends groups the accounts that got a transaction, in order: a Safe signs one MultiSend per group (each below max_gas_per_tx). After it confirms, reconnect managers_to_reconnect with write_account_automations and verify with read_account_info (next_steps). " +
29
+ "Spot and margin accounts can hold Aero positions, staked or not. Chains: 8453 (Base, default), 10 (Optimism) and 4663 (Robinhood, which has nothing to upgrade). Calldata is time-sensitive: sign promptly, rebuild on a price revert. After a transaction confirms, pass its block as min_block on the next call so the plan is not built on older state. When the transaction's simulation reverts the tool returns the plan with an error and no transaction; tenderly_sim_status unavailable means Tenderly did not answer: call once more before signing. A plan without a transaction can still show tenderly_sim_status failure: the account's health or a lending pool limit refused the move, and the items wait on account_unhealthy or exposure_limit; report those reasons and do not rebuild.",
30
+ inputSchema: z.object({
31
+ account_address: z
32
+ .string()
33
+ .optional()
34
+ .describe("Arcadia account to upgrade. Pass this or accounts, not both."),
35
+ accounts: z
36
+ .array(z.string())
37
+ .min(1)
38
+ .max(BATCH_MAX_ACCOUNTS)
39
+ .optional()
40
+ .describe(`Up to ${BATCH_MAX_ACCOUNTS} Arcadia accounts of one owner: one plan and transaction each`),
41
+ choices: z
42
+ .array(choiceSchema)
43
+ .optional()
44
+ .describe("Pool picks for positions with status choose (or waiting with a selectable option), from a previous call's options (disabled_reason null)"),
45
+ slippage: z
46
+ .number()
47
+ .int()
48
+ .min(1)
49
+ .max(1000)
50
+ .optional()
51
+ .describe("Price band the mint accepts, in bps. Omit for the backend default: 150, or 500 when the owner is a contract (a Safe)."),
52
+ min_block: z
53
+ .number()
54
+ .int()
55
+ .min(0)
56
+ .optional()
57
+ .describe("Block of the transaction you just confirmed, so the plan reads state at or after it"),
58
+ chain_id: z
59
+ .number()
60
+ .default(8453)
61
+ .describe("Chain ID: 8453 (Base), 10 (Optimism) or 4663 (Robinhood, nothing to upgrade)"),
62
+ }),
63
+ }, async ({ account_address, accounts, choices, slippage, min_block, chain_id }) => {
64
+ try {
65
+ if ((account_address === undefined) === (accounts === undefined)) {
66
+ throw new Error("Pass exactly one of account_address and accounts.");
67
+ }
68
+ if (accounts !== undefined &&
69
+ (accounts.length === 0 || accounts.length > BATCH_MAX_ACCOUNTS)) {
70
+ throw new Error(`accounts takes 1 to ${BATCH_MAX_ACCOUNTS} Arcadia accounts.`);
71
+ }
72
+ const chainId = validateAeroChain(chain_id);
73
+ const picks = choiceStrings(choices);
74
+ let response;
75
+ if (account_address !== undefined) {
76
+ const plan = await api.getAeroUpgradePlan({
77
+ chain_id: chainId,
78
+ account_address: validateAddress(account_address, "account_address"),
79
+ choices: picks,
80
+ slippage,
81
+ min_block,
82
+ });
83
+ response = formatUpgradePlan(plan, chainId);
84
+ if (plan.calls.length > 0 && simulationReverted(plan.simulation)) {
85
+ return {
86
+ content: [{ type: "text", text: JSON.stringify(response, null, 2) }],
87
+ isError: true,
88
+ };
89
+ }
90
+ }
91
+ else {
92
+ const batch = await api.postAeroUpgradeBatch({
93
+ chain_id: chainId,
94
+ accounts: accounts.map((a) => validateAddress(a, "accounts[]")),
95
+ choices: picks,
96
+ slippage,
97
+ min_block,
98
+ });
99
+ const results = batch.results.map((result) => result.status === "error" ? result : formatUpgradePlan(result, chainId));
100
+ const withTx = new Set(results.filter((r) => "transaction" in r).map((r) => r.account_address));
101
+ const multisends = batch.multisends
102
+ .map((group) => group.filter((account) => withTx.has(account)))
103
+ .filter((group) => group.length > 0);
104
+ response = {
105
+ description: `Upgrade ${accounts.length} account${accounts.length === 1 ? "" : "s"} to Aero: ${withTx.size} transaction${withTx.size === 1 ? "" : "s"} to sign`,
106
+ chain_id: batch.chain_id,
107
+ max_gas_per_tx: batch.max_gas_per_tx,
108
+ multisends,
109
+ results,
110
+ next_steps: [
111
+ "Each result's transaction is a flashAction on its own account. multisends lists the accounts with a transaction in groups: a Safe signs one MultiSend per group, in order, with the transactions of that group's accounts. A result with status error or without a transaction is reported as is.",
112
+ ],
113
+ };
114
+ }
115
+ return {
116
+ content: [{ type: "text", text: JSON.stringify(response, null, 2) }],
117
+ structuredContent: response,
118
+ };
119
+ }
120
+ catch (err) {
121
+ return aeroErrorResult(err);
122
+ }
123
+ });
124
+ }
@@ -6,7 +6,7 @@ import { appendDataSuffix } from "../../../utils/attribution.js";
6
6
  import { validateAddress } from "../../../utils/validation.js";
7
7
  import { SimpleTransactionOutput } from "../../output-schemas.js";
8
8
  export function registerBorrowTool(server, _chains, api) {
9
- server.registerTool("write.account.borrow", {
9
+ server.registerTool("write_account_borrow", {
10
10
  annotations: {
11
11
  title: "Build Borrow Transaction",
12
12
  readOnlyHint: false,
@@ -15,8 +15,8 @@ export function registerBorrowTool(server, _chains, api) {
15
15
  openWorldHint: false,
16
16
  },
17
17
  outputSchema: SimpleTransactionOutput,
18
- description: "Build an unsigned transaction to borrow from an Arcadia lending pool against account collateral. NOT needed for leveraged LP — write.account.add_liquidity handles borrowing internally when leverage > 0. Only works with margin accounts (created with a creditor/lending pool). Spot accounts (no creditor) cannot borrow — the tool will validate this and reject. Before borrowing, verify the account has positive free margin via read.account.info: collateral_value must exceed used_margin.",
19
- inputSchema: {
18
+ description: "Build an unsigned transaction to borrow from an Arcadia lending pool against account collateral. NOT needed for leveraged LP: write_account_add_liquidity handles borrowing internally when leverage > 0. Only works with margin accounts (created with a creditor/lending pool). Spot accounts (no creditor) cannot borrow: the tool will validate this and reject. Before borrowing, verify the account has positive free margin via read_account_info: collateral_value must exceed used_margin.",
19
+ inputSchema: z.object({
20
20
  pool_address: z
21
21
  .string()
22
22
  .describe("Lending pool: LP_WETH=0x803ea69c7e87D1d6C86adeB40CB636cC0E6B98E2, LP_USDC=0x3ec4a293Fb906DD2Cd440c20dECB250DeF141dF1, LP_CBBTC=0xa37E9b4369dc20940009030BfbC2088F09645e3B"),
@@ -24,7 +24,7 @@ export function registerBorrowTool(server, _chains, api) {
24
24
  amount: z.string().describe("Amount in raw units"),
25
25
  to: z.string().describe("Address to receive borrowed tokens"),
26
26
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
27
- },
27
+ }),
28
28
  }, async (params) => {
29
29
  try {
30
30
  const validAccount = validateAddress(params.account_address, "account_address");
@@ -38,7 +38,7 @@ export function registerBorrowTool(server, _chains, api) {
38
38
  content: [
39
39
  {
40
40
  type: "text",
41
- text: "Error: This account has no creditor (spot account) and cannot borrow. Create a margin account with a creditor (lending pool) using write.account.create.",
41
+ text: "Error: This account has no creditor (spot account) and cannot borrow. Create a margin account with a creditor (lending pool) using write_account_create.",
42
42
  },
43
43
  ],
44
44
  isError: true,
@@ -6,7 +6,7 @@ import { formatBatchedResponse, isSimulationFailed } from "./format-response.js"
6
6
  import { validateAddress, validateChainId } from "../../../utils/validation.js";
7
7
  import { BatchedTransactionOutput } from "../../output-schemas.js";
8
8
  export function registerCloseTool(server, api, chains) {
9
- server.registerTool("write.account.close", {
9
+ server.registerTool("write_account_close", {
10
10
  annotations: {
11
11
  title: "Build Close Position Transaction",
12
12
  readOnlyHint: false,
@@ -15,16 +15,16 @@ export function registerCloseTool(server, api, chains) {
15
15
  openWorldHint: true,
16
16
  },
17
17
  outputSchema: BatchedTransactionOutput,
18
- description: `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 write.account.withdraw to send them to your wallet.
18
+ description: `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 write_account_withdraw to send them to your wallet.
19
19
 
20
- ALWAYS try this tool first when closing/exiting a position. Only fall back to individual tools (write.account.remove_liquidity, write.account.swap, write.account.deleverage, write.account.withdraw) if this tool fails.
20
+ ALWAYS try this tool first when closing/exiting a position. Only fall back to individual tools (write_account_remove_liquidity, write_account_swap, write_account_deleverage, write_account_withdraw) if this tool fails.
21
21
 
22
22
  Supports two modes:
23
23
  - 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.
24
- - 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 write.account.withdraw to send to wallet. Supports multiple receive assets with custom distribution.
24
+ - 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 write_account_withdraw to send to wallet. Supports multiple receive assets with custom distribution.
25
25
 
26
26
  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.`,
27
- inputSchema: {
27
+ inputSchema: z.object({
28
28
  account_address: z.string().describe("Arcadia account address"),
29
29
  assets: z
30
30
  .array(z.object({
@@ -33,7 +33,7 @@ The returned calldata is time-sensitive — sign and broadcast within 30 seconds
33
33
  amount: z.string().describe("Amount to sell (use '1' for NFT positions)"),
34
34
  decimals: z.number().describe("Token decimals (use 1 for NFT positions)"),
35
35
  }))
36
- .describe("Assets to close/sell from the account. IMPORTANT: For LP positions (NFTs), always use amount='1' and decimals=1 — do NOT pass the liquidity amount. asset_address = position manager, asset_id = NFT token ID. For ERC20 tokens: asset_id = 0, amount = full balance in raw units, decimals = real token decimals. Get all values from read.account.info."),
36
+ .describe("Assets to close/sell from the account. IMPORTANT: For LP positions (NFTs), always use amount='1' and decimals=1: do NOT pass the liquidity amount. asset_address = position manager, asset_id = NFT token ID. For ERC20 tokens: asset_id = 0, amount = full balance in raw units, decimals = real token decimals. Get all values from read_account_info."),
37
37
  receive_assets: z
38
38
  .array(z.object({
39
39
  asset_address: z.string().describe("Target token address (e.g. USDC, WETH)"),
@@ -52,7 +52,7 @@ The returned calldata is time-sensitive — sign and broadcast within 30 seconds
52
52
  .describe("true = only burn LP positions, leave underlying tokens in account. false = full close (burn + swap + repay)."),
53
53
  slippage: z.number().optional().default(100).describe("Basis points, 100 = 1%"),
54
54
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
55
- },
55
+ }),
56
56
  }, async ({ account_address, assets, receive_assets, close_lp_only, slippage, chain_id }) => {
57
57
  try {
58
58
  const validChainId = validateChainId(chain_id);
@@ -210,7 +210,7 @@ The returned calldata is time-sensitive — sign and broadcast within 30 seconds
210
210
  catch (err) {
211
211
  const msg = err instanceof Error ? err.message : String(err);
212
212
  const hint = msg.includes("500") || msg.includes("Web3")
213
- ? " This usually means the position (asset_id) does not exist in the account. Verify with read.account.info first."
213
+ ? " This usually means the position (asset_id) does not exist in the account. Verify with read_account_info first."
214
214
  : "";
215
215
  return {
216
216
  content: [{ type: "text", text: `Error: ${msg}${hint}` }],
@@ -27,7 +27,7 @@ export function computeAccountAddress(factoryAddress, userSalt, walletAddress, i
27
27
  return getAddress(slice(raw, 12));
28
28
  }
29
29
  export function registerCreateTool(server, chains) {
30
- server.registerTool("write.account.create", {
30
+ server.registerTool("write_account_create", {
31
31
  annotations: {
32
32
  title: "Build Create Account Transaction",
33
33
  readOnlyHint: false,
@@ -37,7 +37,7 @@ export function registerCreateTool(server, chains) {
37
37
  },
38
38
  outputSchema: SimpleTransactionOutput,
39
39
  description: "Build an unsigned transaction to create a new Arcadia account via the Factory contract. account_version: 3 with creditor → V3 margin account (can borrow/leverage). account_version: 0 or 4 → V4 spot account (no borrowing, creditor is ignored, any ERC20 allowed). Returns the predicted account address (deterministic via CREATE2).",
40
- inputSchema: {
40
+ inputSchema: z.object({
41
41
  salt: z.number().describe("Unique salt (uint32) for deterministic account address"),
42
42
  wallet_address: z
43
43
  .string()
@@ -51,7 +51,7 @@ export function registerCreateTool(server, chains) {
51
51
  .optional()
52
52
  .describe("Lending pool address for V3 margin account. Ignored for V4 spot accounts (version 0 or 4)."),
53
53
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
54
- },
54
+ }),
55
55
  }, async (params) => {
56
56
  try {
57
57
  const validChainId = validateChainId(params.chain_id);
@@ -4,7 +4,7 @@ import { formatBatchedResponse, isSimulationFailed } from "./format-response.js"
4
4
  import { validateAddress } from "../../../utils/validation.js";
5
5
  import { BatchedTransactionOutput } from "../../output-schemas.js";
6
6
  export function registerDeleverageTool(server, api) {
7
- server.registerTool("write.account.deleverage", {
7
+ server.registerTool("write_account_deleverage", {
8
8
  annotations: {
9
9
  title: "Build Deleverage Transaction",
10
10
  readOnlyHint: false,
@@ -13,8 +13,8 @@ export function registerDeleverageTool(server, api) {
13
13
  openWorldHint: true,
14
14
  },
15
15
  outputSchema: BatchedTransactionOutput,
16
- description: "Multi-step flash-action: sells account collateral to the debt token and repays in one atomic transaction — no wallet tokens needed. To repay from wallet tokens instead, use write.account.repay. NOTE: If you are closing a position (remove LP + swap + repay + withdraw), prefer write.account.close which batches everything atomically. Only use this tool for standalone repayment while keeping the position active. 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 — if tenderly_sim_status is 'false', do NOT broadcast the transaction.",
17
- inputSchema: {
16
+ description: "Multi-step flash-action: sells account collateral to the debt token and repays in one atomic transaction: no wallet tokens needed. To repay from wallet tokens instead, use write_account_repay. NOTE: If you are closing a position (remove LP + swap + repay + withdraw), prefer write_account_close which batches everything atomically. Only use this tool for standalone repayment while keeping the position active. 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: if tenderly_sim_status is 'false', do NOT broadcast the transaction.",
17
+ inputSchema: z.object({
18
18
  account_address: z.string().describe("Arcadia account address"),
19
19
  amount_in: z.string().describe("Collateral amount to sell (raw units)"),
20
20
  asset_from: z.string().describe("Collateral token to sell"),
@@ -22,7 +22,7 @@ export function registerDeleverageTool(server, api) {
22
22
  creditor: z.string().describe("Lending pool address"),
23
23
  slippage: z.number().optional().default(100).describe("Basis points, 100 = 1%"),
24
24
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
25
- },
25
+ }),
26
26
  }, async ({ account_address, amount_in, asset_from, numeraire, creditor, slippage, chain_id }) => {
27
27
  try {
28
28
  validateAddress(account_address, "account_address");
@@ -7,7 +7,7 @@ import { appendDataSuffix } from "../../../utils/attribution.js";
7
7
  import { validateAddress, validateChainId } from "../../../utils/validation.js";
8
8
  import { SimpleTransactionOutput } from "../../output-schemas.js";
9
9
  export function registerDepositTool(server, chains) {
10
- server.registerTool("write.account.deposit", {
10
+ server.registerTool("write_account_deposit", {
11
11
  annotations: {
12
12
  title: "Build Deposit Transaction",
13
13
  readOnlyHint: false,
@@ -16,8 +16,8 @@ export function registerDepositTool(server, chains) {
16
16
  openWorldHint: false,
17
17
  },
18
18
  outputSchema: SimpleTransactionOutput,
19
- description: "Build an unsigned transaction to deposit assets into an Arcadia account as collateral. Supports ERC20 tokens and ERC721 NFTs (LP positions). NOT needed before write.account.add_liquidity — that tool deposits from wallet atomically. Ensure the account is approved first (call read.wallet.allowances to check, then write.wallet.approve if needed). Account version is auto-detected on-chain (override with account_version if needed).",
20
- inputSchema: {
19
+ description: "Build an unsigned transaction to deposit assets into an Arcadia account as collateral. Supports ERC20 tokens and ERC721 NFTs (LP positions). NOT needed before write_account_add_liquidity: that tool deposits from wallet atomically. Ensure the account is approved first (call read_wallet_allowances to check, then write_wallet_approve if needed). Account version is auto-detected on-chain (override with account_version if needed).",
20
+ inputSchema: z.object({
21
21
  account_address: z.string().describe("Arcadia account address"),
22
22
  asset_addresses: z.array(z.string()).describe("Token contract addresses to deposit"),
23
23
  asset_amounts: z.array(z.string()).describe("Amounts in raw units/wei, one per asset"),
@@ -34,7 +34,7 @@ export function registerDepositTool(server, chains) {
34
34
  .optional()
35
35
  .describe("Override account version (3 or 4). Auto-detected on-chain if omitted."),
36
36
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
37
- },
37
+ }),
38
38
  }, async (params) => {
39
39
  try {
40
40
  if (params.asset_addresses.length !== params.asset_amounts.length) {
@@ -5,7 +5,7 @@ import { appendDataSuffix } from "../../../utils/attribution.js";
5
5
  export function isSimulationFailed(status) {
6
6
  return status === false || status === "false";
7
7
  }
8
- function normalizeSimStatus(status) {
8
+ export function normalizeSimStatus(status) {
9
9
  if (status === true || status === "true")
10
10
  return "success";
11
11
  if (status === false || status === "false")
@@ -4,7 +4,7 @@ import { formatBatchedResponse, isSimulationFailed } from "./format-response.js"
4
4
  import { validateAddress } from "../../../utils/validation.js";
5
5
  import { BatchedTransactionOutput } from "../../output-schemas.js";
6
6
  export function registerRemoveLiquidityTool(server, api) {
7
- server.registerTool("write.account.remove_liquidity", {
7
+ server.registerTool("write_account_remove_liquidity", {
8
8
  annotations: {
9
9
  title: "Build Remove Liquidity Transaction",
10
10
  readOnlyHint: false,
@@ -15,18 +15,18 @@ export function registerRemoveLiquidityTool(server, api) {
15
15
  outputSchema: BatchedTransactionOutput,
16
16
  description: `Flash-action: PARTIALLY decreases liquidity from an LP position. The position remains open with reduced liquidity; underlying tokens stay in the account.
17
17
 
18
- For FULL position exit (burn LP + swap + repay + withdraw), use write.account.close instead — it batches everything into one atomic transaction.
18
+ For FULL position exit (burn LP + swap + repay + withdraw), use write_account_close instead: it batches everything into one atomic transaction.
19
19
 
20
20
  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.`,
21
- inputSchema: {
21
+ inputSchema: z.object({
22
22
  account_address: z.string().describe("Arcadia account address"),
23
23
  asset_address: z.string().describe("Position manager contract"),
24
24
  asset_id: z.number().describe("NFT token ID"),
25
25
  adjustment: z
26
26
  .string()
27
- .describe("Liquidity amount to remove (raw uint128 value as string). Must be less than total liquidity — for full removal use write.account.close."),
27
+ .describe("Liquidity amount to remove (raw uint128 value as string). Must be less than total liquidity: for full removal use write_account_close."),
28
28
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
29
- },
29
+ }),
30
30
  }, async ({ account_address, asset_address, asset_id, adjustment, chain_id }) => {
31
31
  try {
32
32
  validateAddress(account_address, "account_address");
@@ -70,7 +70,7 @@ The returned calldata is time-sensitive — sign and broadcast within 30 seconds
70
70
  catch (err) {
71
71
  const msg = err instanceof Error ? err.message : String(err);
72
72
  const hint = msg.includes("500") || msg.includes("Web3")
73
- ? " This usually means the position (asset_id) does not exist in the account. Verify with read.account.info first."
73
+ ? " This usually means the position (asset_id) does not exist in the account. Verify with read_account_info first."
74
74
  : "";
75
75
  return {
76
76
  content: [{ type: "text", text: `Error: ${msg}${hint}` }],
@@ -6,7 +6,7 @@ import { appendDataSuffix } from "../../../utils/attribution.js";
6
6
  import { validateAddress } from "../../../utils/validation.js";
7
7
  import { SimpleTransactionOutput } from "../../output-schemas.js";
8
8
  export function registerRepayTool(server, _chains) {
9
- server.registerTool("write.account.repay", {
9
+ server.registerTool("write_account_repay", {
10
10
  annotations: {
11
11
  title: "Build Repay Transaction",
12
12
  readOnlyHint: false,
@@ -15,8 +15,8 @@ export function registerRepayTool(server, _chains) {
15
15
  openWorldHint: false,
16
16
  },
17
17
  outputSchema: SimpleTransactionOutput,
18
- description: "Repay debt to an Arcadia lending pool using tokens from the wallet (requires ERC20 allowance). To repay using account collateral instead (no wallet tokens needed), use write.account.deleverage. Check allowance first (read.wallet.allowances), then approve the pool if needed (write.wallet.approve). Check outstanding debt with read.account.info.",
19
- inputSchema: {
18
+ description: "Repay debt to an Arcadia lending pool using tokens from the wallet (requires ERC20 allowance). To repay using account collateral instead (no wallet tokens needed), use write_account_deleverage. Check allowance first (read_wallet_allowances), then approve the pool if needed (write_wallet_approve). Check outstanding debt with read_account_info.",
19
+ inputSchema: z.object({
20
20
  pool_address: z
21
21
  .string()
22
22
  .describe("Lending pool address. Base: LP_WETH=0x803ea69c7e87D1d6C86adeB40CB636cC0E6B98E2, LP_USDC=0x3ec4a293Fb906DD2Cd440c20dECB250DeF141dF1, LP_CBBTC=0xa37E9b4369dc20940009030BfbC2088F09645e3B"),
@@ -25,7 +25,7 @@ export function registerRepayTool(server, _chains) {
25
25
  .string()
26
26
  .describe("Amount in raw units, or 'max_uint256' to repay all debt in full"),
27
27
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
28
- },
28
+ }),
29
29
  }, async (params) => {
30
30
  try {
31
31
  const validAccount = validateAddress(params.account_address, "account_address");