@arcadia-finance/mcp-server 0.5.1 → 0.6.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 (55) hide show
  1. package/README.md +58 -52
  2. package/dist/clients/api.js +52 -11
  3. package/dist/clients/chain.js +25 -0
  4. package/dist/config/addresses.js +22 -2
  5. package/dist/config/chains.js +12 -4
  6. package/dist/index.js +36 -134
  7. package/dist/prompts/workflows.js +54 -18
  8. package/dist/resources/guides.js +1 -1
  9. package/dist/tools/aero.js +157 -0
  10. package/dist/tools/dev/send.js +4 -4
  11. package/dist/tools/index.js +6 -0
  12. package/dist/tools/output-schemas.js +103 -29
  13. package/dist/tools/read/account.js +57 -15
  14. package/dist/tools/read/aero-upgrade.js +53 -0
  15. package/dist/tools/read/asset-managers.js +9 -9
  16. package/dist/tools/read/assets.js +9 -9
  17. package/dist/tools/read/guides.js +4 -4
  18. package/dist/tools/read/points.js +4 -4
  19. package/dist/tools/read/pools.js +10 -9
  20. package/dist/tools/read/shapes.js +48 -0
  21. package/dist/tools/read/strategy.js +14 -13
  22. package/dist/tools/read/wallet.js +15 -15
  23. package/dist/tools/write/account/add-liquidity.js +9 -9
  24. package/dist/tools/write/account/aero-upgrade.js +124 -0
  25. package/dist/tools/write/account/borrow.js +5 -5
  26. package/dist/tools/write/account/close.js +8 -8
  27. package/dist/tools/write/account/create.js +3 -3
  28. package/dist/tools/write/account/deleverage.js +4 -4
  29. package/dist/tools/write/account/deposit.js +4 -4
  30. package/dist/tools/write/account/format-response.js +1 -1
  31. package/dist/tools/write/account/remove-liquidity.js +6 -6
  32. package/dist/tools/write/account/repay.js +4 -4
  33. package/dist/tools/write/account/stake.js +5 -5
  34. package/dist/tools/write/account/swap.js +4 -4
  35. package/dist/tools/write/account/withdraw.js +5 -5
  36. package/dist/tools/write/asset-managers/automations.js +14 -14
  37. package/dist/tools/write/asset-managers/intents.js +10 -7
  38. package/dist/tools/write/pool/deposit.js +5 -5
  39. package/dist/tools/write/pool/redeem.js +4 -4
  40. package/dist/tools/write/wallet/approve.js +4 -4
  41. package/dist/tools/write/wallet/upgrade-velo.js +76 -0
  42. package/dist/utils/analytics.js +68 -0
  43. package/dist/utils/http-config.js +4 -4
  44. package/llms-full.txt +114 -77
  45. package/llms.txt +47 -44
  46. package/package.json +8 -4
  47. package/server.json +10 -4
  48. package/skills/clamm-liquidity/SKILL.md +101 -83
  49. package/skills/clamm-liquidity/automation.md +14 -14
  50. package/skills/clamm-liquidity/selection.md +13 -13
  51. package/skills/clamm-liquidity/strategies.md +135 -53
  52. package/skills/openclaw/SKILL.md +3 -3
  53. package/skills/openclaw/arcadia.sh +24 -45
  54. package/skills/openclaw/contracts.md +19 -16
  55. package/dist/utils/tool-naming.js +0 -91
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Response-shape guards shared by the read tools.
3
+ *
4
+ * `Array.isArray(raw) ? raw : []` is the pattern that made a populated
5
+ * account-history response report `{"history":[]}`: the endpoint answered with
6
+ * an object, the guard did not recognise it, and the tool said "nothing here".
7
+ * A read that did not work has to look different from a read that found
8
+ * nothing, so an unrecognised shape throws and the handler surfaces it as
9
+ * `isError` rather than as an empty list.
10
+ */
11
+ /** An array response, or `[]` for an absent one. Throws on anything else. */
12
+ export function expectArray(raw, what) {
13
+ if (Array.isArray(raw))
14
+ return raw;
15
+ // An absent body is a legitimately empty answer; a present body of the wrong
16
+ // shape is not.
17
+ if (raw === null || raw === undefined)
18
+ return [];
19
+ throw new Error(`Unexpected ${what} response shape: ${JSON.stringify(raw).slice(0, 200)}`);
20
+ }
21
+ /**
22
+ * An array response, or one wrapped in the first matching `keys` field.
23
+ *
24
+ * `/assets` answers `{ assets: [...] }`, so a bare `expectArray` would reject a
25
+ * valid body. The part worth keeping is the refusal: `?? []` at the end of a
26
+ * wrapper chain turns an unrecognised body into "no assets", which is the same
27
+ * silent-empty failure as the account-history bug.
28
+ */
29
+ export function expectArrayOrWrapped(raw, what, ...keys) {
30
+ if (Array.isArray(raw))
31
+ return raw;
32
+ if (raw === null || raw === undefined)
33
+ return [];
34
+ if (typeof raw === "object") {
35
+ const obj = raw;
36
+ for (const key of keys) {
37
+ if (!(key in obj))
38
+ continue;
39
+ const value = obj[key];
40
+ if (Array.isArray(value))
41
+ return value;
42
+ // The wrapper is there and carries nothing: an answer, not a bad shape.
43
+ if (value === null || value === undefined)
44
+ return [];
45
+ }
46
+ }
47
+ throw new Error(`Unexpected ${what} response shape: ${JSON.stringify(raw).slice(0, 200)}`);
48
+ }
@@ -1,8 +1,9 @@
1
+ import { expectArray } from "./shapes.js";
1
2
  import { z } from "zod";
2
3
  import { CHAIN_ID_DESCRIPTION } from "../../config/chains.js";
3
4
  import { StrategyListOutput, StrategyDetailOutput, StrategyRecommendationOutput, } from "../output-schemas.js";
4
5
  export function registerStrategyTools(server, api) {
5
- server.registerTool("read.strategy.list", {
6
+ server.registerTool("read_strategy_list", {
6
7
  annotations: {
7
8
  title: "Get Strategies",
8
9
  readOnlyHint: true,
@@ -10,8 +11,8 @@ export function registerStrategyTools(server, api) {
10
11
  idempotentHint: true,
11
12
  openWorldHint: true,
12
13
  },
13
- description: "Get Arcadia LP strategies. Use featured_only=true for curated top strategies (recommended first call). Returns a paginated list with 7d avg APY for each strategy's default range. Increase limit or use offset for pagination. All APY values are decimal fractions (1.0 = 100%, 0.05 = 5%). For full detail on a specific strategy (APY per range width), use read.strategy.info.",
14
- inputSchema: {
14
+ description: "Get Arcadia LP strategies. Use featured_only=true for curated top strategies (recommended first call). Returns a paginated list with 7d avg APY for each strategy's default range. Increase limit or use offset for pagination. All APY values are decimal fractions (1.0 = 100%, 0.05 = 5%). For full detail on a specific strategy (APY per range width), use read_strategy_info.",
15
+ inputSchema: z.object({
15
16
  featured_only: z
16
17
  .boolean()
17
18
  .default(false)
@@ -19,7 +20,7 @@ export function registerStrategyTools(server, api) {
19
20
  limit: z.number().default(25).describe("Max strategies to return (default 25)"),
20
21
  offset: z.number().default(0).describe("Skip first N strategies for pagination"),
21
22
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
22
- },
23
+ }),
23
24
  outputSchema: StrategyListOutput,
24
25
  }, async ({ featured_only, limit, offset, chain_id }) => {
25
26
  try {
@@ -27,7 +28,7 @@ export function registerStrategyTools(server, api) {
27
28
  let total;
28
29
  if (featured_only) {
29
30
  const raw = await api.getFeatured(chain_id);
30
- const all = Array.isArray(raw) ? raw : [];
31
+ const all = expectArray(raw, "featured strategies");
31
32
  // The /featured endpoint currently returns curated Base strategies regardless of
32
33
  // chain_id. Filter by the chain baked into each strategy's url (`/farm/<chainId>/…`)
33
34
  // so we never hand back strategies that belong to a different chain.
@@ -105,7 +106,7 @@ export function registerStrategyTools(server, api) {
105
106
  };
106
107
  }
107
108
  });
108
- server.registerTool("read.strategy.info", {
109
+ server.registerTool("read_strategy_info", {
109
110
  annotations: {
110
111
  title: "Get Strategy Info",
111
112
  readOnlyHint: true,
@@ -113,11 +114,11 @@ export function registerStrategyTools(server, api) {
113
114
  idempotentHint: true,
114
115
  openWorldHint: true,
115
116
  },
116
- description: "Get full detail for a specific LP strategy by ID — includes APY per range width (narrower range = higher APY but more rebalancing cost/risk), pool info, and configuration. Use read.strategy.list to discover strategy IDs. All APY values are decimal fractions (1.0 = 100%, 0.05 = 5%).",
117
- inputSchema: {
117
+ description: "Get full detail for a specific LP strategy by ID: includes APY per range width (narrower range = higher APY but more rebalancing cost/risk), pool info, and configuration. Use read_strategy_list to discover strategy IDs. All APY values are decimal fractions (1.0 = 100%, 0.05 = 5%).",
118
+ inputSchema: z.object({
118
119
  strategy_id: z.number().describe("Strategy ID"),
119
120
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
120
- },
121
+ }),
121
122
  outputSchema: StrategyDetailOutput,
122
123
  }, async ({ strategy_id, chain_id }) => {
123
124
  try {
@@ -139,7 +140,7 @@ export function registerStrategyTools(server, api) {
139
140
  };
140
141
  }
141
142
  });
142
- server.registerTool("read.strategy.recommendation", {
143
+ server.registerTool("read_strategy_recommendation", {
143
144
  annotations: {
144
145
  title: "Get Recommendation",
145
146
  readOnlyHint: true,
@@ -147,11 +148,11 @@ export function registerStrategyTools(server, api) {
147
148
  idempotentHint: true,
148
149
  openWorldHint: true,
149
150
  },
150
- description: "Get a rebalancing recommendation for an Arcadia account — suggests asset changes to optimize yield. Uses 1d APY (not 7d like read.strategy.list), so recommended strategies may differ from the list ranking. APY values are decimal fractions (0.05 = 5%). weekly_earning_difference is in USD.",
151
- inputSchema: {
151
+ description: "Get a rebalancing recommendation for an Arcadia account: suggests asset changes to optimize yield. Uses 1d APY (not 7d like read_strategy_list), so recommended strategies may differ from the list ranking. APY values are decimal fractions (0.05 = 5%). weekly_earning_difference is in USD.",
152
+ inputSchema: z.object({
152
153
  account_address: z.string().describe("Arcadia account address"),
153
154
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
154
- },
155
+ }),
155
156
  outputSchema: StrategyRecommendationOutput,
156
157
  }, async ({ account_address, chain_id }) => {
157
158
  try {
@@ -7,7 +7,7 @@ import { validateAddress, validateChainId } from "../../utils/validation.js";
7
7
  import { WalletBalancesOutput, WalletAllowanceOutput, AccountListOutput, PointsWalletOutput, } from "../output-schemas.js";
8
8
  const MAX_UINT256 = 2n ** 256n - 1n;
9
9
  export function registerWalletTools(server, chains, api) {
10
- server.registerTool("read.wallet.balances", {
10
+ server.registerTool("read_wallet_balances", {
11
11
  annotations: {
12
12
  title: "Get Wallet Balances",
13
13
  readOnlyHint: true,
@@ -15,12 +15,12 @@ export function registerWalletTools(server, chains, api) {
15
15
  idempotentHint: true,
16
16
  openWorldHint: true,
17
17
  },
18
- description: "Get native ETH and ERC20 token balances for a wallet address. Reads directly from chain via RPC multicall. Use before write.account.add_liquidity or write.account.deposit to verify the wallet has sufficient tokens. Returns both raw balance (smallest unit/wei) and formatted (human-readable) per token.",
19
- inputSchema: {
18
+ description: "Get native ETH and ERC20 token balances for a wallet address. Reads directly from chain via RPC multicall. Use before write_account_add_liquidity or write_account_deposit to verify the wallet has sufficient tokens. Returns both raw balance (smallest unit/wei) and formatted (human-readable) per token.",
19
+ inputSchema: z.object({
20
20
  wallet_address: z.string().describe("Wallet address to check balances for"),
21
21
  token_addresses: z.array(z.string()).describe("ERC20 token contract addresses to check"),
22
22
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
23
- },
23
+ }),
24
24
  outputSchema: WalletBalancesOutput,
25
25
  }, async ({ wallet_address, token_addresses, chain_id }) => {
26
26
  try {
@@ -83,7 +83,7 @@ export function registerWalletTools(server, chains, api) {
83
83
  };
84
84
  }
85
85
  });
86
- server.registerTool("read.wallet.allowances", {
86
+ server.registerTool("read_wallet_allowances", {
87
87
  annotations: {
88
88
  title: "Get Token Allowances",
89
89
  readOnlyHint: true,
@@ -91,15 +91,15 @@ export function registerWalletTools(server, chains, api) {
91
91
  idempotentHint: true,
92
92
  openWorldHint: true,
93
93
  },
94
- description: "Check ERC20 token allowances for a spender address. Use before write.wallet.approve to avoid redundant approvals — skip approving if the current allowance is already sufficient.",
95
- inputSchema: {
94
+ description: "Check ERC20 token allowances for a spender address. Use before write_wallet_approve to avoid redundant approvals: skip approving if the current allowance is already sufficient.",
95
+ inputSchema: z.object({
96
96
  owner_address: z.string().describe("Token owner address (the wallet granting approval)"),
97
97
  spender_address: z
98
98
  .string()
99
99
  .describe("Spender address to check allowance for (e.g. Arcadia account address)"),
100
100
  token_addresses: z.array(z.string()).describe("ERC20 token contract addresses to check"),
101
101
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
102
- },
102
+ }),
103
103
  outputSchema: WalletAllowanceOutput,
104
104
  }, async ({ owner_address, spender_address, token_addresses, chain_id }) => {
105
105
  try {
@@ -151,7 +151,7 @@ export function registerWalletTools(server, chains, api) {
151
151
  };
152
152
  }
153
153
  });
154
- server.registerTool("read.wallet.accounts", {
154
+ server.registerTool("read_wallet_accounts", {
155
155
  annotations: {
156
156
  title: "List Wallet Accounts",
157
157
  readOnlyHint: true,
@@ -159,11 +159,11 @@ export function registerWalletTools(server, chains, api) {
159
159
  idempotentHint: true,
160
160
  openWorldHint: true,
161
161
  },
162
- description: "List all Arcadia accounts owned by a wallet address. Returns a summary of each account (address, name). Call read.account.info with a specific account_address for full details like health factor, collateral, and debt.",
163
- inputSchema: {
162
+ description: "List all Arcadia accounts owned by a wallet address. Returns a summary of each account (address, name). Call read_account_info with a specific account_address for full details like health factor, collateral, and debt.",
163
+ inputSchema: z.object({
164
164
  wallet_address: z.string().describe("Wallet address to list accounts for"),
165
165
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
166
- },
166
+ }),
167
167
  outputSchema: AccountListOutput,
168
168
  }, async ({ wallet_address, chain_id }) => {
169
169
  try {
@@ -187,7 +187,7 @@ export function registerWalletTools(server, chains, api) {
187
187
  };
188
188
  }
189
189
  });
190
- server.registerTool("read.wallet.points", {
190
+ server.registerTool("read_wallet_points", {
191
191
  annotations: {
192
192
  title: "Get Wallet Points",
193
193
  readOnlyHint: true,
@@ -196,9 +196,9 @@ export function registerWalletTools(server, chains, api) {
196
196
  openWorldHint: true,
197
197
  },
198
198
  description: "Get Arcadia points balance for a specific wallet address.",
199
- inputSchema: {
199
+ inputSchema: z.object({
200
200
  wallet_address: z.string().describe("Wallet address to get points for"),
201
- },
201
+ }),
202
202
  outputSchema: PointsWalletOutput,
203
203
  }, async ({ wallet_address }) => {
204
204
  try {
@@ -13,7 +13,7 @@ function formatTokenAmount(value, decimals, maxFrac = 8) {
13
13
  return frac ? `${whole}.${frac}` : whole;
14
14
  }
15
15
  export function registerAddLiquidityTool(server, api, chains) {
16
- server.registerTool("write.account.add_liquidity", {
16
+ server.registerTool("write_account_add_liquidity", {
17
17
  annotations: {
18
18
  title: "Build Add Liquidity Transaction",
19
19
  readOnlyHint: false,
@@ -22,15 +22,15 @@ export function registerAddLiquidityTool(server, api, chains) {
22
22
  openWorldHint: true,
23
23
  },
24
24
  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: {
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: z.object({
27
27
  account_address: z.string().describe("Arcadia account address"),
28
28
  wallet_address: z.string().describe("Wallet address of the account owner"),
29
29
  positions: z
30
30
  .array(z.object({
31
31
  strategy_id: z
32
32
  .number()
33
- .describe("From read.strategy.list (or read.strategy.info for full range detail)"),
33
+ .describe("From read_strategy_list (or read_strategy_info for full range detail)"),
34
34
  tick_lower: z
35
35
  .number()
36
36
  .optional()
@@ -51,7 +51,7 @@ export function registerAddLiquidityTool(server, api, chains) {
51
51
  .describe("Token decimals (e.g. 6 for USDC, 18 for WETH). Default 18."),
52
52
  }))
53
53
  .optional()
54
- .describe("Wallet tokens to deposit. Approve each token first (write.wallet.approve). Omit to use only account collateral."),
54
+ .describe("Wallet tokens to deposit. Approve each token first (write_wallet_approve). Omit to use only account collateral."),
55
55
  use_account_assets: z
56
56
  .boolean()
57
57
  .optional()
@@ -64,7 +64,7 @@ export function registerAddLiquidityTool(server, api, chains) {
64
64
  .describe("0 = no borrow, 2 = 2x leverage. Margin accounts only."),
65
65
  slippage: z.number().optional().default(100).describe("Basis points, 100 = 1%"),
66
66
  chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
67
- },
67
+ }),
68
68
  }, async ({ account_address, wallet_address, positions, deposits: walletDeposits, use_account_assets, leverage, slippage, chain_id, }) => {
69
69
  try {
70
70
  const validChainId = validateChainId(chain_id);
@@ -127,7 +127,7 @@ export function registerAddLiquidityTool(server, api, chains) {
127
127
  content: [
128
128
  {
129
129
  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.",
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.",
131
131
  },
132
132
  ],
133
133
  isError: true,
@@ -216,7 +216,7 @@ export function registerAddLiquidityTool(server, api, chains) {
216
216
  content: [
217
217
  {
218
218
  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.",
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.",
220
220
  },
221
221
  ],
222
222
  isError: true,
@@ -228,7 +228,7 @@ export function registerAddLiquidityTool(server, api, chains) {
228
228
  content: [
229
229
  {
230
230
  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.",
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.",
232
232
  },
233
233
  ],
234
234
  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")