@arcadia-finance/mcp-server 0.4.5 → 0.5.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.
- package/README.md +5 -10
- package/dist/clients/api.js +23 -0
- package/dist/config/addresses.js +49 -188
- package/dist/index.js +4 -2
- package/dist/prompts/workflows.js +15 -13
- package/dist/resources/guides.js +1 -1
- package/dist/tools/dev/send.js +7 -5
- package/dist/tools/index.js +4 -14
- package/dist/tools/output-schemas.js +42 -6
- package/dist/tools/read/account.js +80 -42
- package/dist/tools/read/asset-managers.js +138 -113
- package/dist/tools/read/guides.js +3 -3
- package/dist/tools/write/asset-managers/automations.js +241 -0
- package/dist/tools/write/asset-managers/intents.js +247 -0
- package/dist/tools/write/asset-managers/shared.js +0 -26
- package/dist/utils/http-config.js +37 -0
- package/dist/utils/validation.js +16 -0
- package/llms-full.txt +39 -80
- package/llms.txt +9 -14
- package/package.json +1 -1
- package/server.json +2 -2
- package/skills/clamm-liquidity/SKILL.md +90 -69
- package/skills/clamm-liquidity/automation.md +153 -76
- package/skills/clamm-liquidity/selection.md +6 -5
- package/skills/clamm-liquidity/strategies.md +40 -34
- package/skills/openclaw/SKILL.md +3 -3
- package/skills/openclaw/contracts.md +29 -16
- package/dist/tools/write/asset-managers/compounder.js +0 -113
- package/dist/tools/write/asset-managers/cow-swapper.js +0 -50
- package/dist/tools/write/asset-managers/encoding.js +0 -162
- package/dist/tools/write/asset-managers/merkl-operator.js +0 -52
- package/dist/tools/write/asset-managers/rebalancer.js +0 -109
- package/dist/tools/write/asset-managers/set-asset-managers.js +0 -76
- package/dist/tools/write/asset-managers/yield-claimer.js +0 -117
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { appendDataSuffix } from "../../../utils/attribution.js";
|
|
3
|
+
import { validateAddress, validateChainId } from "../../../utils/validation.js";
|
|
4
|
+
import { AutomationsPlanOutput } from "../../output-schemas.js";
|
|
5
|
+
import { AUTOMATION_INTENT, CHAIN_ID_SCHEMA, POSITION_CONTEXT_SCHEMA, positionContext, } from "./intents.js";
|
|
6
|
+
import { formatResult } from "./shared.js";
|
|
7
|
+
const INTENT_REFERENCE = [
|
|
8
|
+
"Intents:",
|
|
9
|
+
"- compound_fees: reinvest earned fees/rewards back into the LP. Optional 'tokens' scopes it per yielding token. A staked reward that is not a pool token is swapped in via CowSwap automatically.",
|
|
10
|
+
"- claim_rewards: claim yield out. config.mode as_earned pays the tokens as-is, convert_to swaps them to config.buy_token via CowSwap. config.convert_tokens converts only a subset and claims the rest as-earned. config.destination account or wallet.",
|
|
11
|
+
"- add_to_lp: fold idle pool-token balances (deposits, rebalance leftovers) back into the LP. Opt-in per token.",
|
|
12
|
+
"- claim_merkl: auto-claim Merkl incentive rewards. Independent of the compounder/claimer/cowswapper triad and needs no position context.",
|
|
13
|
+
"- rebalance: reposition the LP. strategy out_of_range (default), take_profit (runs on the dedicated profit-taker contract), or protocol_owned_liquidity.",
|
|
14
|
+
].join("\n");
|
|
15
|
+
const CONTEXT_NOTE = "Pass position_id (from assets[] in read.account.info) and the backend fills in protocol, is_staked, token0, token1 and reward_tokens for you; anything you pass explicitly wins. claim_merkl needs no position context.";
|
|
16
|
+
const RULES_NOTE = [
|
|
17
|
+
"Rules the backend enforces (a violation is returned as an error, never written on-chain):",
|
|
18
|
+
"- Every yielding token must be assigned to exactly one of compound_fees or claim_rewards. Scoping one to a subset without covering the rest is rejected, and no token may be in both.",
|
|
19
|
+
"- A wallet or custom-recipient payout requires a pure as-earned claim: nothing converted, and every yielding token claimed. Converts settle in the account.",
|
|
20
|
+
"- convert_tokens must be a subset of the claimed tokens, and buy_token cannot be a compounded token, a converted token, or an add_to_lp folded token.",
|
|
21
|
+
"- Each intent kind may appear only once, and a token list must not be empty or name a token the position does not yield.",
|
|
22
|
+
].join("\n");
|
|
23
|
+
function planResult(description, resp, account, chainId, previewOnly = false) {
|
|
24
|
+
// Only an explicit `true` counts as a passing simulation. The proxy returns
|
|
25
|
+
// (url=None, success=False) when it could not run the sim at all (no `owner`),
|
|
26
|
+
// and an absent success field is ambiguous, so neither may read as a green
|
|
27
|
+
// light. An explicit `false` alongside a URL is a real predicted revert.
|
|
28
|
+
const simStatus = !resp.simulation_url
|
|
29
|
+
? "unavailable"
|
|
30
|
+
: resp.simulation_success === true
|
|
31
|
+
? "success"
|
|
32
|
+
: resp.simulation_success === false
|
|
33
|
+
? "failure"
|
|
34
|
+
: "unavailable";
|
|
35
|
+
const base = {
|
|
36
|
+
description,
|
|
37
|
+
valid: resp.valid,
|
|
38
|
+
errors: resp.errors ?? [],
|
|
39
|
+
warnings: resp.warnings ?? [],
|
|
40
|
+
human_summary: resp.human_summary ?? [],
|
|
41
|
+
plan: resp.plan ?? [],
|
|
42
|
+
...(resp.diff ? { diff: resp.diff } : {}),
|
|
43
|
+
...(resp.simulation_url ? { simulation_url: resp.simulation_url } : {}),
|
|
44
|
+
tenderly_sim_status: simStatus,
|
|
45
|
+
};
|
|
46
|
+
const rejected = (detail) => ({
|
|
47
|
+
content: [
|
|
48
|
+
{
|
|
49
|
+
type: "text",
|
|
50
|
+
text: `Automation plan rejected: ${detail}\n\n${JSON.stringify(base, null, 2)}`,
|
|
51
|
+
},
|
|
52
|
+
],
|
|
53
|
+
isError: true,
|
|
54
|
+
});
|
|
55
|
+
// A failed compatibility rule is an error in either mode: the caller must see
|
|
56
|
+
// why and fix the intents.
|
|
57
|
+
if (!resp.valid) {
|
|
58
|
+
const reasons = (resp.errors ?? []).map((e) => `${e.rule}: ${e.reason}`).join("; ");
|
|
59
|
+
return rejected(reasons || "no reason given");
|
|
60
|
+
}
|
|
61
|
+
// Preview does not read chain state, so its calldata only enables the resolved
|
|
62
|
+
// plan: it carries no disable entries for managers the account already has.
|
|
63
|
+
// Broadcasting it would partially apply the requested state while leaving
|
|
64
|
+
// unlisted automations running, and neither the empty-diff guard (no diff on
|
|
65
|
+
// preview) nor the simulation guard (not enriched on preview) would catch it.
|
|
66
|
+
// So preview returns the plan for inspection and no signable transaction.
|
|
67
|
+
// Checked before calldata, which preview never uses: an intent set that
|
|
68
|
+
// legitimately resolves to an empty plan (a single enabled: false intent) must
|
|
69
|
+
// still preview cleanly.
|
|
70
|
+
if (previewOnly) {
|
|
71
|
+
return formatResult({
|
|
72
|
+
...base,
|
|
73
|
+
preview_only: true,
|
|
74
|
+
description: `${description}: preview only, no transaction. Preview does not diff against on-chain state, so its calldata would not disable automations you left out. Re-run with mode "save" to get a transaction.`,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const calldata = resp.calldata;
|
|
78
|
+
if (!calldata) {
|
|
79
|
+
return rejected("the plan produced no calldata (nothing to change?)");
|
|
80
|
+
}
|
|
81
|
+
// An empty diff means the account already matches the request. The backend
|
|
82
|
+
// still returns calldata for it, but that call is setAssetManagers([],[],[]):
|
|
83
|
+
// handing it back would have the caller burn gas on a no-op and report a
|
|
84
|
+
// change that never happened.
|
|
85
|
+
const diff = resp.diff;
|
|
86
|
+
if (diff && !diff.added.length && !diff.removed.length && !diff.updated.length) {
|
|
87
|
+
return formatResult({
|
|
88
|
+
...base,
|
|
89
|
+
no_changes_needed: true,
|
|
90
|
+
description: `${description}: nothing to change, the account already matches this request. No transaction to send.`,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
// A simulation that ran and predicted a revert must not be handed back as a
|
|
94
|
+
// signable transaction, matching the guard on the batched write tools.
|
|
95
|
+
if (simStatus === "failure") {
|
|
96
|
+
return {
|
|
97
|
+
content: [
|
|
98
|
+
{
|
|
99
|
+
type: "text",
|
|
100
|
+
text: `Error: setAssetManagers simulation FAILED, do NOT broadcast.\nTenderly simulation: ${resp.simulation_url}\n\n` +
|
|
101
|
+
JSON.stringify(base, null, 2),
|
|
102
|
+
},
|
|
103
|
+
],
|
|
104
|
+
isError: true,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
return formatResult({
|
|
108
|
+
...base,
|
|
109
|
+
transaction: {
|
|
110
|
+
to: account,
|
|
111
|
+
data: appendDataSuffix(calldata),
|
|
112
|
+
value: "0",
|
|
113
|
+
chainId,
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
function errorResult(err) {
|
|
118
|
+
return {
|
|
119
|
+
content: [
|
|
120
|
+
{
|
|
121
|
+
type: "text",
|
|
122
|
+
text: `Error: ${err instanceof Error ? err.message : String(err)}`,
|
|
123
|
+
},
|
|
124
|
+
],
|
|
125
|
+
isError: true,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
export function registerAutomationsTools(server, api) {
|
|
129
|
+
server.registerTool("write.account.automations", {
|
|
130
|
+
annotations: {
|
|
131
|
+
title: "Configure Account Automations",
|
|
132
|
+
readOnlyHint: false,
|
|
133
|
+
destructiveHint: false,
|
|
134
|
+
idempotentHint: true,
|
|
135
|
+
openWorldHint: true,
|
|
136
|
+
},
|
|
137
|
+
description: "Configure an account's automations from a list of intents and return the unsigned setAssetManagers transaction. " +
|
|
138
|
+
"The backend resolves which asset managers each intent needs, validates that the combination is compatible, encodes the metadata and builds the calldata, so you describe the desired outcome rather than the contracts.\n\n" +
|
|
139
|
+
"With mode 'save' (the default) the intents array is the complete desired state: the backend diffs it against what is currently enabled, so any automation you leave out is DISABLED by the returned transaction. Pass a single intent with enabled: false to turn everything off.\n\n" +
|
|
140
|
+
"Mode 'preview' validates and resolves the intents WITHOUT reading chain state and returns no transaction, because its calldata carries no disable entries and would only partially apply the state. Use it to check a combination is legal or to show a plan; use 'save' to get something signable. To toggle one automation without restating the rest, use write.account.automations_delta.\n\n" +
|
|
141
|
+
INTENT_REFERENCE +
|
|
142
|
+
"\n\n" +
|
|
143
|
+
CONTEXT_NOTE +
|
|
144
|
+
"\n\n" +
|
|
145
|
+
RULES_NOTE +
|
|
146
|
+
"\n\nReturns { valid, errors, warnings, human_summary, plan, diff, transaction }. When a compatibility rule fires the call returns an error and no transaction: read errors[].reason, adjust the intents and retry. " +
|
|
147
|
+
"There is deliberately no transaction when the account already matches the request (no_changes_needed), when the Tenderly simulation predicts a revert (an error), or in preview mode (preview_only). " +
|
|
148
|
+
"Call read.asset_manager.intents first to see which intents this account can enable.",
|
|
149
|
+
outputSchema: AutomationsPlanOutput,
|
|
150
|
+
inputSchema: {
|
|
151
|
+
account_address: z.string().describe("Arcadia account address"),
|
|
152
|
+
intents: z
|
|
153
|
+
.array(AUTOMATION_INTENT)
|
|
154
|
+
.min(1)
|
|
155
|
+
.describe("Complete desired automation state. In save mode anything omitted is disabled, so include every automation to keep. A single intent with enabled: false disables all automations."),
|
|
156
|
+
mode: z
|
|
157
|
+
.enum(["save", "preview"])
|
|
158
|
+
.default("save")
|
|
159
|
+
.describe("save diffs against on-chain state and returns a signable transaction that also disables anything omitted. preview resolves and validates only, returning a plan and no transaction."),
|
|
160
|
+
...POSITION_CONTEXT_SCHEMA,
|
|
161
|
+
chain_id: CHAIN_ID_SCHEMA,
|
|
162
|
+
},
|
|
163
|
+
}, async (params) => {
|
|
164
|
+
try {
|
|
165
|
+
const chainId = validateChainId(params.chain_id);
|
|
166
|
+
const account = validateAddress(params.account_address, "account_address");
|
|
167
|
+
const body = { intents: params.intents, ...positionContext(params) };
|
|
168
|
+
const resp = params.mode === "preview"
|
|
169
|
+
? await api.previewAutomations(account, chainId, body)
|
|
170
|
+
: await api.saveAutomations(account, chainId, body);
|
|
171
|
+
const kinds = params.intents.map((i) => i.kind).join(", ");
|
|
172
|
+
return planResult(`Configure automations on ${account} (${kinds})`, resp, account, chainId, params.mode === "preview");
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
return errorResult(err);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
server.registerTool("write.account.automations_delta", {
|
|
179
|
+
annotations: {
|
|
180
|
+
title: "Change Account Automations (Delta)",
|
|
181
|
+
readOnlyHint: false,
|
|
182
|
+
destructiveHint: false,
|
|
183
|
+
idempotentHint: true,
|
|
184
|
+
openWorldHint: true,
|
|
185
|
+
},
|
|
186
|
+
description: "Apply an explicit change to an account's automations and return the unsigned setAssetManagers transaction. " +
|
|
187
|
+
"Unlike write.account.automations this is a delta, not a full desired state: automations you do not mention are left untouched. Use it to switch one automation on or off without restating the others.\n\n" +
|
|
188
|
+
"The enable array takes intents to switch on (same shapes as write.account.automations). To turn an automation OFF, call read.asset_manager.current, take the address of the manager serving it, and pass that address in the disable array: an intent with enabled: false in `enable` is rejected because the backend would ignore it. Superseded or unreadable managers still set on the account are force-disabled in the same transaction regardless.\n\n" +
|
|
189
|
+
INTENT_REFERENCE +
|
|
190
|
+
"\n\n" +
|
|
191
|
+
CONTEXT_NOTE +
|
|
192
|
+
"\n\n" +
|
|
193
|
+
RULES_NOTE,
|
|
194
|
+
outputSchema: AutomationsPlanOutput,
|
|
195
|
+
inputSchema: {
|
|
196
|
+
account_address: z.string().describe("Arcadia account address"),
|
|
197
|
+
enable: z
|
|
198
|
+
.array(AUTOMATION_INTENT)
|
|
199
|
+
.default([])
|
|
200
|
+
.describe("Intents to switch on. Leave empty when only disabling. This array cannot turn anything off: an entry with enabled: false is rejected, use `disable` instead."),
|
|
201
|
+
disable: z
|
|
202
|
+
.array(z.string())
|
|
203
|
+
.default([])
|
|
204
|
+
.describe("Asset-manager addresses to switch off, as returned by read.asset_manager.current."),
|
|
205
|
+
...POSITION_CONTEXT_SCHEMA,
|
|
206
|
+
chain_id: CHAIN_ID_SCHEMA,
|
|
207
|
+
},
|
|
208
|
+
}, async (params) => {
|
|
209
|
+
try {
|
|
210
|
+
const chainId = validateChainId(params.chain_id);
|
|
211
|
+
const account = validateAddress(params.account_address, "account_address");
|
|
212
|
+
if (params.enable.length === 0 && params.disable.length === 0) {
|
|
213
|
+
throw new Error("Pass at least one intent in `enable` or one address in `disable`.");
|
|
214
|
+
}
|
|
215
|
+
// The backend resolves only enabled intents, so an `enabled: false` entry
|
|
216
|
+
// here would be dropped and the delta would silently do nothing. Turning
|
|
217
|
+
// an automation off is done by address via `disable`.
|
|
218
|
+
const disabledEntries = params.enable.filter((i) => i.enabled === false);
|
|
219
|
+
if (disabledEntries.length > 0) {
|
|
220
|
+
const kinds = disabledEntries.map((i) => i.kind).join(", ");
|
|
221
|
+
throw new Error(`enable[] cannot carry enabled: false (got ${kinds}); it would be ignored and change nothing. ` +
|
|
222
|
+
`To turn an automation off, call read.asset_manager.current, take the address of the manager serving it, ` +
|
|
223
|
+
`and pass that address in \`disable\`. Alternatively call write.account.automations with the full set of intents you want kept.`);
|
|
224
|
+
}
|
|
225
|
+
const disable = params.disable.map((a, i) => validateAddress(a, `disable[${i}]`));
|
|
226
|
+
const resp = await api.applyAutomationsDelta(account, chainId, {
|
|
227
|
+
enable: params.enable,
|
|
228
|
+
disable,
|
|
229
|
+
...positionContext(params),
|
|
230
|
+
});
|
|
231
|
+
const parts = [
|
|
232
|
+
params.enable.length ? `enable ${params.enable.map((i) => i.kind).join(", ")}` : "",
|
|
233
|
+
disable.length ? `disable ${disable.length} manager(s)` : "",
|
|
234
|
+
].filter(Boolean);
|
|
235
|
+
return planResult(`Change automations on ${account} (${parts.join("; ")})`, resp, account, chainId);
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
return errorResult(err);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { CHAIN_ID_DESCRIPTION } from "../../../config/chains.js";
|
|
3
|
+
// Zod mirrors of the backend's intent union
|
|
4
|
+
// (fallback-asset-managers/app/services/automation_config/intents.py).
|
|
5
|
+
// The backend is the single source of truth for resolution, compatibility
|
|
6
|
+
// validation and metadata encoding; these schemas only shape the wire body.
|
|
7
|
+
const YIELD_TOKEN = z.enum(["token0", "token1", "reward"]);
|
|
8
|
+
const POOL_TOKEN = z.enum(["token0", "token1"]);
|
|
9
|
+
const ENABLED = z
|
|
10
|
+
.boolean()
|
|
11
|
+
.default(true)
|
|
12
|
+
.describe("False disables this intent's managers instead of enabling them.");
|
|
13
|
+
const POSITION_ID = z
|
|
14
|
+
.number()
|
|
15
|
+
.int()
|
|
16
|
+
.optional()
|
|
17
|
+
.describe("LP position (NFT) id this intent applies to. Also used to auto-fetch position context.");
|
|
18
|
+
const CompoundFeesIntent = z.object({
|
|
19
|
+
kind: z.literal("compound_fees"),
|
|
20
|
+
enabled: ENABLED,
|
|
21
|
+
position_id: POSITION_ID,
|
|
22
|
+
tokens: z
|
|
23
|
+
.array(YIELD_TOKEN)
|
|
24
|
+
.optional()
|
|
25
|
+
.describe("Which tokens' yield to reinvest. Omit for all yielding tokens. 'reward' only exists on a staked position whose reward token is not a pool token. " +
|
|
26
|
+
"Every yielding token must be assigned to either compound_fees or claim_rewards, so if you scope this to a subset you must add a claim_rewards intent covering the rest."),
|
|
27
|
+
});
|
|
28
|
+
const ClaimRewardsIntent = z.object({
|
|
29
|
+
kind: z.literal("claim_rewards"),
|
|
30
|
+
enabled: ENABLED,
|
|
31
|
+
position_id: POSITION_ID,
|
|
32
|
+
config: z
|
|
33
|
+
.object({
|
|
34
|
+
mode: z
|
|
35
|
+
.enum(["as_earned", "convert_to"])
|
|
36
|
+
.default("as_earned")
|
|
37
|
+
.describe("as_earned pays out the claimed tokens as-is; convert_to swaps them to buy_token via CowSwap. Use convert_tokens to convert only some of them."),
|
|
38
|
+
destination: z
|
|
39
|
+
.enum(["account", "wallet"])
|
|
40
|
+
.default("account")
|
|
41
|
+
.describe("Payout target ('wallet' is the owner EOA). A wallet payout is only allowed for a pure as-earned claim: nothing converted, and every yielding token claimed. " +
|
|
42
|
+
"Any convert, or a claim scoped to a subset of tokens, must use 'account' because CowSwap settles there."),
|
|
43
|
+
buy_token: z
|
|
44
|
+
.string()
|
|
45
|
+
.optional()
|
|
46
|
+
.describe("ERC20 to swap into. Required whenever any token is being converted. It cannot be a token you also compound, one of the tokens being converted, or a token folded by add_to_lp."),
|
|
47
|
+
recipient: z
|
|
48
|
+
.string()
|
|
49
|
+
.optional()
|
|
50
|
+
.describe("Explicit payout address. Overrides destination when set, and is subject to the same pure-as-earned rule as a wallet payout unless it equals the account address."),
|
|
51
|
+
tokens: z
|
|
52
|
+
.array(YIELD_TOKEN)
|
|
53
|
+
.optional()
|
|
54
|
+
.describe("Which tokens' yield to claim out. Omit for all yielding tokens. A token cannot be both claimed and compounded, and every yielding token must be assigned to one of the two."),
|
|
55
|
+
convert_tokens: z
|
|
56
|
+
.array(YIELD_TOKEN)
|
|
57
|
+
.optional()
|
|
58
|
+
.describe("Subset of this intent's claimed tokens to swap to buy_token; the rest are claimed as-earned. Must be a subset of `tokens`. " +
|
|
59
|
+
"Omit to defer to mode (convert_to converts all claimed tokens, as_earned converts none). Use this for a partial convert, e.g. tokens: ['token0','reward'] with convert_tokens: ['reward'] swaps only the reward and claims token0 as-is."),
|
|
60
|
+
})
|
|
61
|
+
.default({}),
|
|
62
|
+
});
|
|
63
|
+
const AddToLpIntent = z.object({
|
|
64
|
+
kind: z.literal("add_to_lp"),
|
|
65
|
+
enabled: ENABLED,
|
|
66
|
+
position_id: POSITION_ID,
|
|
67
|
+
tokens: z
|
|
68
|
+
.array(POOL_TOKEN)
|
|
69
|
+
.optional()
|
|
70
|
+
.describe("Which pool tokens' idle account balance to fold into the LP. Omit for both. Folding is opt-in per token, and a folded token cannot be the buy_token of a claim_rewards convert."),
|
|
71
|
+
});
|
|
72
|
+
const ClaimMerklIntent = z.object({
|
|
73
|
+
kind: z.literal("claim_merkl"),
|
|
74
|
+
enabled: ENABLED,
|
|
75
|
+
position_id: POSITION_ID,
|
|
76
|
+
config: z
|
|
77
|
+
.object({
|
|
78
|
+
destination: z.enum(["account", "wallet"]).default("account"),
|
|
79
|
+
reward_recipient: z
|
|
80
|
+
.string()
|
|
81
|
+
.optional()
|
|
82
|
+
.describe("Explicit recipient address. Overrides destination when set."),
|
|
83
|
+
})
|
|
84
|
+
.default({}),
|
|
85
|
+
});
|
|
86
|
+
const OutOfRangeStrategy = z.object({
|
|
87
|
+
kind: z.literal("out_of_range"),
|
|
88
|
+
optimal_token0_ratio: z
|
|
89
|
+
.number()
|
|
90
|
+
.int()
|
|
91
|
+
.min(0)
|
|
92
|
+
.max(1_000_000)
|
|
93
|
+
.default(500_000)
|
|
94
|
+
.describe("Target token0 composition after a rebalance, 1e6-scaled: 500000 = 50% (balanced, the default), 750000 = 75% token0, 0 = all token1."),
|
|
95
|
+
trigger_lower_tick_ratio: z
|
|
96
|
+
.number()
|
|
97
|
+
.int()
|
|
98
|
+
.default(0)
|
|
99
|
+
.describe("Offset from tick_lower as a fraction of the position's tick range, 1e6-scaled. This is TICK distance, not price: 50000 shifts the trigger by 5% of (tick_upper - tick_lower) ticks, which is not 5% of price. " +
|
|
100
|
+
"0 = trigger exactly at the boundary. Positive (e.g. 50000) puts the trigger outside the position so price must travel further beyond the range before rebalancing. Negative (e.g. -50000) puts it inside, firing preemptively while price is still in range."),
|
|
101
|
+
trigger_upper_tick_ratio: z
|
|
102
|
+
.number()
|
|
103
|
+
.int()
|
|
104
|
+
.default(0)
|
|
105
|
+
.describe("Same as trigger_lower_tick_ratio, for tick_upper. The two are independent, so asymmetric configs are valid (e.g. lower -50000, upper 0 rebalances early on the downside but only at the boundary on the upside)."),
|
|
106
|
+
min_rebalance_time: z
|
|
107
|
+
.number()
|
|
108
|
+
.int()
|
|
109
|
+
.default(3600)
|
|
110
|
+
.describe("Cooldown in seconds between rebalances."),
|
|
111
|
+
max_rebalance_time: z
|
|
112
|
+
.number()
|
|
113
|
+
.int()
|
|
114
|
+
.default(10 ** 12)
|
|
115
|
+
.describe("Seconds before a rebalance is forced. Default is effectively disabled."),
|
|
116
|
+
});
|
|
117
|
+
const POLStrategy = z.object({
|
|
118
|
+
kind: z.literal("protocol_owned_liquidity"),
|
|
119
|
+
initial_range: z.number().int().default(200_000),
|
|
120
|
+
base_range: z.number().int().default(50_000),
|
|
121
|
+
k1: z.number().int().default(0),
|
|
122
|
+
k2: z.number().int().default(0),
|
|
123
|
+
rebalance_threshold: z.number().int().default(25_000),
|
|
124
|
+
limit_order_withdrawal_threshold: z.number().int().default(50_000),
|
|
125
|
+
fraction_excess_to_limit_order: z.number().int().default(500_000),
|
|
126
|
+
deadzone: z.number().int().default(20_000),
|
|
127
|
+
target_token0_ratio: z.number().int().default(500_000),
|
|
128
|
+
});
|
|
129
|
+
const TakeProfitStrategy = z.object({
|
|
130
|
+
kind: z.literal("take_profit"),
|
|
131
|
+
profit_token: z.enum(["token0", "token1"]).default("token0"),
|
|
132
|
+
take_profit_trigger_type: z.enum(["", "fixed", "relative"]).default("fixed"),
|
|
133
|
+
take_profit_trigger_threshold: z.number().int().default(0),
|
|
134
|
+
take_profit_reposition_mode: z.enum(["", "anchor_tick", "shift_range"]).default("anchor_tick"),
|
|
135
|
+
has_reversal: z.boolean().default(false),
|
|
136
|
+
reversal_trigger_type: z.enum(["", "fixed", "relative"]).default(""),
|
|
137
|
+
reversal_trigger_threshold: z.number().int().default(0),
|
|
138
|
+
reversal_reposition_mode: z.enum(["", "anchor_tick", "shift_range"]).default(""),
|
|
139
|
+
});
|
|
140
|
+
const RebalanceIntent = z.object({
|
|
141
|
+
kind: z.literal("rebalance"),
|
|
142
|
+
enabled: ENABLED,
|
|
143
|
+
position_id: POSITION_ID,
|
|
144
|
+
strategy: z
|
|
145
|
+
.discriminatedUnion("kind", [OutOfRangeStrategy, POLStrategy, TakeProfitStrategy])
|
|
146
|
+
.default({ kind: "out_of_range" })
|
|
147
|
+
.describe("out_of_range repositions when price leaves the range; take_profit runs on the dedicated profit-taker contract; protocol_owned_liquidity is the POL strategy."),
|
|
148
|
+
max_tolerance: z
|
|
149
|
+
.number()
|
|
150
|
+
.int()
|
|
151
|
+
.min(0)
|
|
152
|
+
.max(10 ** 18)
|
|
153
|
+
.optional()
|
|
154
|
+
.describe("Max price deviation (MEV/slippage cap), 1e18-scaled: 1e18 = 100%, so 5000000000000000 = 0.5% (the default) and 50000000000000000 = 5%. Omit for the pool's default. AAA pools are floored at 5%."),
|
|
155
|
+
min_liquidity_ratio: z
|
|
156
|
+
.number()
|
|
157
|
+
.int()
|
|
158
|
+
.min(0)
|
|
159
|
+
.max(10 ** 18)
|
|
160
|
+
.optional()
|
|
161
|
+
.describe("Min fraction of liquidity that must survive a rebalance, 1e18-scaled: 990000000000000000 = 99% (the default), i.e. at most 1% value loss. Omit for the default."),
|
|
162
|
+
});
|
|
163
|
+
export const AUTOMATION_INTENT = z
|
|
164
|
+
.discriminatedUnion("kind", [
|
|
165
|
+
CompoundFeesIntent,
|
|
166
|
+
ClaimRewardsIntent,
|
|
167
|
+
AddToLpIntent,
|
|
168
|
+
ClaimMerklIntent,
|
|
169
|
+
RebalanceIntent,
|
|
170
|
+
])
|
|
171
|
+
.describe("One user-facing automation intent.");
|
|
172
|
+
// The read tools report a position's protocol in the dex_protocol vocabulary
|
|
173
|
+
// (slipstream, staked_slipstream_v3, uniV3, ...) which folds staking into the
|
|
174
|
+
// name. The backend splits those into protocol + is_staked, so accept both
|
|
175
|
+
// spellings here and translate rather than making callers do it.
|
|
176
|
+
const DEX_PROTOCOL_TO_CONTEXT = {
|
|
177
|
+
slipstream: { protocol: "slipstream_v1", is_staked: false },
|
|
178
|
+
slipstream_v2: { protocol: "slipstream_v2", is_staked: false },
|
|
179
|
+
slipstream_v3: { protocol: "slipstream_v3", is_staked: false },
|
|
180
|
+
staked_slipstream: { protocol: "slipstream_v1", is_staked: true },
|
|
181
|
+
staked_slipstream_v2: { protocol: "slipstream_v2", is_staked: true },
|
|
182
|
+
staked_slipstream_v3: { protocol: "slipstream_v3", is_staked: true },
|
|
183
|
+
uniV3: { protocol: "uniswap_v3", is_staked: false },
|
|
184
|
+
uniV4: { protocol: "uniswap_v4", is_staked: false },
|
|
185
|
+
};
|
|
186
|
+
// The canonical names plus the dex_protocol spellings, deduped: slipstream_v2 and
|
|
187
|
+
// slipstream_v3 are spelled the same in both vocabularies and must not appear twice
|
|
188
|
+
// in the published schema enum.
|
|
189
|
+
const PROTOCOL_VALUES = [
|
|
190
|
+
...new Set([
|
|
191
|
+
"slipstream_v1",
|
|
192
|
+
"slipstream_v2",
|
|
193
|
+
"slipstream_v3",
|
|
194
|
+
"uniswap_v3",
|
|
195
|
+
"uniswap_v4",
|
|
196
|
+
...Object.keys(DEX_PROTOCOL_TO_CONTEXT),
|
|
197
|
+
]),
|
|
198
|
+
];
|
|
199
|
+
// Position context. The backend auto-fetches anything omitted when position_id
|
|
200
|
+
// is supplied, and anything explicitly passed wins over the fetched value.
|
|
201
|
+
export const POSITION_CONTEXT_SCHEMA = {
|
|
202
|
+
position_id: z
|
|
203
|
+
.number()
|
|
204
|
+
.int()
|
|
205
|
+
.optional()
|
|
206
|
+
.describe("LP position (NFT) id, as listed in assets[] by read.account.info. Supply this and the backend fetches protocol, staked flag, tokens and reward tokens for you. Strongly preferred over passing the position fields by hand."),
|
|
207
|
+
protocol: z
|
|
208
|
+
.enum(PROTOCOL_VALUES)
|
|
209
|
+
.optional()
|
|
210
|
+
.describe("Position's DEX protocol. Only needed when position_id is omitted. Accepts the dex_protocol values the read tools return (slipstream, staked_slipstream_v3, uniV3, ...), which imply is_staked, as well as the canonical slipstream_v1 / uniswap_v3 spellings."),
|
|
211
|
+
is_staked: z
|
|
212
|
+
.boolean()
|
|
213
|
+
.optional()
|
|
214
|
+
.describe("Whether the LP position is staked. Implied by a staked_* protocol value."),
|
|
215
|
+
token0: z.string().optional().describe("Pool token0 address."),
|
|
216
|
+
token1: z.string().optional().describe("Pool token1 address."),
|
|
217
|
+
reward_tokens: z.array(z.string()).optional().describe("Staking reward token addresses."),
|
|
218
|
+
owner: z
|
|
219
|
+
.string()
|
|
220
|
+
.optional()
|
|
221
|
+
.describe("Account owner EOA. Used to resolve wallet payout targets."),
|
|
222
|
+
};
|
|
223
|
+
export const CHAIN_ID_SCHEMA = z.number().default(8453).describe(CHAIN_ID_DESCRIPTION);
|
|
224
|
+
/** Strip undefined position-context fields so the backend's auto-fetch kicks in. */
|
|
225
|
+
export function positionContext(params) {
|
|
226
|
+
const ctx = {};
|
|
227
|
+
if (params.position_id !== undefined)
|
|
228
|
+
ctx.position_id = params.position_id;
|
|
229
|
+
if (params.protocol !== undefined) {
|
|
230
|
+
const translated = DEX_PROTOCOL_TO_CONTEXT[params.protocol];
|
|
231
|
+
ctx.protocol = translated ? translated.protocol : params.protocol;
|
|
232
|
+
if (translated)
|
|
233
|
+
ctx.is_staked = translated.is_staked;
|
|
234
|
+
}
|
|
235
|
+
// An explicit is_staked always wins over the one implied by the protocol spelling.
|
|
236
|
+
if (params.is_staked !== undefined)
|
|
237
|
+
ctx.is_staked = params.is_staked;
|
|
238
|
+
if (params.token0 !== undefined)
|
|
239
|
+
ctx.token0 = params.token0;
|
|
240
|
+
if (params.token1 !== undefined)
|
|
241
|
+
ctx.token1 = params.token1;
|
|
242
|
+
if (params.reward_tokens !== undefined)
|
|
243
|
+
ctx.reward_tokens = params.reward_tokens;
|
|
244
|
+
if (params.owner !== undefined)
|
|
245
|
+
ctx.owner = params.owner;
|
|
246
|
+
return ctx;
|
|
247
|
+
}
|
|
@@ -1,29 +1,3 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
const PROTOCOL_TO_AM_KEY = {
|
|
3
|
-
slipstream: "slipstreamV1",
|
|
4
|
-
slipstream_v2: "slipstreamV2",
|
|
5
|
-
slipstream_v3: "slipstreamV3",
|
|
6
|
-
staked_slipstream: "slipstreamV1",
|
|
7
|
-
staked_slipstream_v2: "slipstreamV2",
|
|
8
|
-
staked_slipstream_v3: "slipstreamV3",
|
|
9
|
-
uniV3: "uniV3",
|
|
10
|
-
uniV4: "uniV4",
|
|
11
|
-
};
|
|
12
|
-
export function dexProtocolToAmKey(protocol) {
|
|
13
|
-
return PROTOCOL_TO_AM_KEY[protocol];
|
|
14
|
-
}
|
|
15
|
-
export const DEX_PROTOCOL_SCHEMA = z
|
|
16
|
-
.enum([
|
|
17
|
-
"slipstream",
|
|
18
|
-
"slipstream_v2",
|
|
19
|
-
"slipstream_v3",
|
|
20
|
-
"staked_slipstream",
|
|
21
|
-
"staked_slipstream_v2",
|
|
22
|
-
"staked_slipstream_v3",
|
|
23
|
-
"uniV3",
|
|
24
|
-
"uniV4",
|
|
25
|
-
])
|
|
26
|
-
.describe("DEX protocol of the LP position — used to resolve the correct asset manager address.");
|
|
27
1
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
28
2
|
export function formatResult(result) {
|
|
29
3
|
return {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Listen port from PORT env. Throws at startup so a bad PORT does not silently break binding. */
|
|
2
|
+
export function parseListenPort(raw) {
|
|
3
|
+
const n = parseInt(raw ?? "3000", 10);
|
|
4
|
+
if (!Number.isFinite(n) || n < 1 || n > 65535) {
|
|
5
|
+
throw new Error(`Invalid PORT: "${raw ?? ""}". Expected an integer from 1 to 65535.`);
|
|
6
|
+
}
|
|
7
|
+
return n;
|
|
8
|
+
}
|
|
9
|
+
/** Max requests per minute from RATE_LIMIT_RPM. Warns and falls back to 60 on invalid input. */
|
|
10
|
+
export function parseRateLimitRpm(raw) {
|
|
11
|
+
const n = parseInt(raw ?? "60", 10);
|
|
12
|
+
if (!Number.isFinite(n) || n < 1) {
|
|
13
|
+
console.warn(`Invalid RATE_LIMIT_RPM "${raw ?? ""}", using default 60`);
|
|
14
|
+
return 60;
|
|
15
|
+
}
|
|
16
|
+
return Math.min(n, 1_000_000);
|
|
17
|
+
}
|
|
18
|
+
/** Enables Express req.ip when behind proxies. TRUST_PROXY: "1", "true", or a hop count ("2"). */
|
|
19
|
+
export function applyTrustProxyFromEnv(app, raw) {
|
|
20
|
+
const hops = parseTrustProxyHopCount(raw);
|
|
21
|
+
if (hops === undefined)
|
|
22
|
+
return;
|
|
23
|
+
app.set("trust proxy", hops);
|
|
24
|
+
}
|
|
25
|
+
export function parseTrustProxyHopCount(raw) {
|
|
26
|
+
if (!raw?.trim())
|
|
27
|
+
return undefined;
|
|
28
|
+
const t = raw.trim().toLowerCase();
|
|
29
|
+
if (t === "true" || t === "1" || t === "yes")
|
|
30
|
+
return 1;
|
|
31
|
+
const n = parseInt(raw, 10);
|
|
32
|
+
if (!Number.isFinite(n) || n < 1 || n > 32) {
|
|
33
|
+
console.warn(`Invalid TRUST_PROXY "${raw.trim()}". Expected 1–32 hops or true/1/yes. Rate limits will use socket IP only.`);
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
return n;
|
|
37
|
+
}
|
package/dist/utils/validation.js
CHANGED
|
@@ -14,3 +14,19 @@ export function validateChainId(chainId) {
|
|
|
14
14
|
}
|
|
15
15
|
return chainId;
|
|
16
16
|
}
|
|
17
|
+
/** ABI-encoded calldata: 0x plus pairs of hex digits (empty calldata is 0x). */
|
|
18
|
+
export function validateHexCalldata(data, label = "data") {
|
|
19
|
+
const d = data.trim();
|
|
20
|
+
if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(d)) {
|
|
21
|
+
throw new Error(`Invalid ${label}: expected hex calldata starting with 0x and an even number of hex digits after the prefix.`);
|
|
22
|
+
}
|
|
23
|
+
return d;
|
|
24
|
+
}
|
|
25
|
+
/** Wei amount as a decimal string (avoids ambiguous BigInt() on partial hex). */
|
|
26
|
+
export function parseWeiDecimalString(s, label = "value") {
|
|
27
|
+
const t = s.trim();
|
|
28
|
+
if (!/^\d+$/.test(t)) {
|
|
29
|
+
throw new Error(`Invalid ${label}: expected a non-negative decimal wei string (digits only), e.g. "0" or "1000000000000000000".`);
|
|
30
|
+
}
|
|
31
|
+
return BigInt(t);
|
|
32
|
+
}
|