@sherwoodagent/cli 0.65.0 → 0.65.2
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/dist/{addresses-FXTJXDI7.js → addresses-J2LMGUCT.js} +2 -2
- package/dist/{agent-IVESTCYM.js → agent-AETROOEW.js} +2 -2
- package/dist/{chat-SL4O7Y3C.js → chat-JSSTSE4K.js} +6 -6
- package/dist/{chunk-OKGTNYYW.js → chunk-A6TOJEUD.js} +2 -2
- package/dist/{chunk-VAOCUQMY.js → chunk-GWMTAW6A.js} +10 -5
- package/dist/{chunk-VAOCUQMY.js.map → chunk-GWMTAW6A.js.map} +1 -1
- package/dist/{chunk-D4AQBGF4.js → chunk-IL43IMOC.js} +2 -2
- package/dist/{chunk-7INQASHO.js → chunk-O4G3SBCI.js} +2 -2
- package/dist/{chunk-2H6IGGKN.js → chunk-RHRLYVKM.js} +2 -2
- package/dist/chunk-RHRLYVKM.js.map +1 -0
- package/dist/{chunk-J42NNFUV.js → chunk-RO26TXXE.js} +39 -20
- package/dist/chunk-RO26TXXE.js.map +1 -0
- package/dist/{chunk-HE3NY4JJ.js → chunk-UCQEEF3Z.js} +2 -2
- package/dist/{chunk-AQNHSYJ7.js → chunk-VYF2TXPX.js} +2 -2
- package/dist/{eas-5VIHTS3N.js → eas-K4ZBACYN.js} +3 -3
- package/dist/{governor-UBUNIO3U.js → governor-2CDSMSG7.js} +3 -3
- package/dist/index.js +185 -154
- package/dist/index.js.map +1 -1
- package/dist/{ipfs-IGXLLJCF.js → ipfs-FAYWUCS2.js} +2 -2
- package/dist/{price-3BXZKK6B.js → price-LCTECRQP.js} +2 -2
- package/dist/{research-RL2ASMQ5.js → research-FUQOQWKK.js} +5 -5
- package/dist/{research-N3R5MU6Q.js → research-XEXTHDT3.js} +2 -2
- package/dist/{session-FPQGAMSS.js → session-FJB2RV2X.js} +6 -6
- package/dist/{trade-AJNB4ULF.js → trade-U7H5IFH6.js} +7 -7
- package/dist/{xmtp-MR6OJ76L.js → xmtp-6NJ4PW6L.js} +3 -3
- package/package.json +1 -1
- package/dist/chunk-2H6IGGKN.js.map +0 -1
- package/dist/chunk-J42NNFUV.js.map +0 -1
- /package/dist/{addresses-FXTJXDI7.js.map → addresses-J2LMGUCT.js.map} +0 -0
- /package/dist/{agent-IVESTCYM.js.map → agent-AETROOEW.js.map} +0 -0
- /package/dist/{chat-SL4O7Y3C.js.map → chat-JSSTSE4K.js.map} +0 -0
- /package/dist/{chunk-OKGTNYYW.js.map → chunk-A6TOJEUD.js.map} +0 -0
- /package/dist/{chunk-D4AQBGF4.js.map → chunk-IL43IMOC.js.map} +0 -0
- /package/dist/{chunk-7INQASHO.js.map → chunk-O4G3SBCI.js.map} +0 -0
- /package/dist/{chunk-HE3NY4JJ.js.map → chunk-UCQEEF3Z.js.map} +0 -0
- /package/dist/{chunk-AQNHSYJ7.js.map → chunk-VYF2TXPX.js.map} +0 -0
- /package/dist/{eas-5VIHTS3N.js.map → eas-K4ZBACYN.js.map} +0 -0
- /package/dist/{governor-UBUNIO3U.js.map → governor-2CDSMSG7.js.map} +0 -0
- /package/dist/{ipfs-IGXLLJCF.js.map → ipfs-FAYWUCS2.js.map} +0 -0
- /package/dist/{price-3BXZKK6B.js.map → price-LCTECRQP.js.map} +0 -0
- /package/dist/{research-RL2ASMQ5.js.map → research-FUQOQWKK.js.map} +0 -0
- /package/dist/{research-N3R5MU6Q.js.map → research-XEXTHDT3.js.map} +0 -0
- /package/dist/{session-FPQGAMSS.js.map → session-FJB2RV2X.js.map} +0 -0
- /package/dist/{trade-AJNB4ULF.js.map → trade-U7H5IFH6.js.map} +0 -0
- /package/dist/{xmtp-MR6OJ76L.js.map → xmtp-6NJ4PW6L.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/providers/moonwell.ts","../src/commands/strategy-template.ts","../src/lib/clone.ts","../src/grid/strategy-abi.ts","../src/lib/batch.ts","../src/lib/calldata.ts","../../sdk/dist/types.js","../../sdk/dist/errors.js","../../sdk/dist/abis.js","../../sdk/dist/addresses.js","../../sdk/dist/encoders/vault.js","../../sdk/dist/encoders/governor.js","../../sdk/dist/encoders/factory.js","../../sdk/dist/encoders/strategy.js","../../sdk/dist/encoders/identity.js","../../sdk/dist/encoders/eas.js","../../sdk/dist/encoders/guardian.js","../../sdk/dist/reads/syndicates.js","../src/strategies/moonwell-supply-template.ts","../src/strategies/venice-inference-template.ts","../src/strategies/aerodrome-lp-template.ts","../src/strategies/wsteth-moonwell-template.ts","../src/strategies/mamo-yield-template.ts","../src/strategies/portfolio-template.ts","../src/strategies/hyperliquid-perp-template.ts","../src/strategies/hyperliquid-grid-template.ts","../src/lib/subgraph.ts","../src/commands/venice.ts","../src/commands/allowance.ts","../src/strategies/allowance-disburse.ts","../src/commands/identity.ts","../src/commands/proposal.ts","../src/lib/format.ts","../src/lib/simulate.ts","../src/lib/risk.ts","../src/commands/governor.ts","../src/commands/guardian-delegate.ts","../src/commands/grid.ts","../src/grid/loop.ts","../src/grid/manager.ts","../src/grid/portfolio.ts","../src/grid/paths.ts","../src/grid/config.ts","../src/grid/hedge.ts","../src/grid/executor.ts","../src/grid/onchain-executor.ts","../src/grid/cloid.ts","../src/grid/backtest.ts","../src/grid/backtest-portfolio.ts","../src/grid/historical-data-loader.ts","../src/grid/backtest-hedge.ts","../src/grid/sweep.ts"],"sourcesContent":["#!/usr/bin/env node\n// Load .env if present (dev convenience — production uses ~/.sherwood/config.json)\nimport { config as loadDotenv } from \"dotenv\";\ntry { loadDotenv(); } catch {};\nimport { createRequire } from \"node:module\";\nconst require = createRequire(import.meta.url);\n// `CLI_VERSION_BUILD` is injected by tsup at build time (see tsup.config.ts) so\n// the bundled/standalone binary never reads ../package.json at runtime — that\n// path is unresolvable inside bun's compiled virtual filesystem and crashes the\n// binary on startup. The require fallback keeps `tsx src/index.ts` (dev) working.\nconst CLI_VERSION: string =\n process.env.CLI_VERSION_BUILD || require(\"../package.json\").version;\nimport { Command, Option } from \"commander\";\nimport { parseUnits, formatUnits, isAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { input, confirm, select } from \"@inquirer/prompts\";\nimport { setNetwork, getNetwork, VALID_NETWORKS, withNetwork } from \"./lib/network.js\";\nimport { getExplorerUrl, getChain } from \"./lib/network.js\";\nimport type { Network } from \"./lib/network.js\";\nimport { TOKENS } from \"./lib/addresses.js\";\nimport { getPublicClient, getAccount, formatContractError } from \"./lib/client.js\";\nimport { ERC20_ABI } from \"./lib/abis.js\";\nimport { MoonwellProvider } from \"./providers/moonwell.js\";\nimport { UniswapProvider } from \"./providers/uniswap.js\";\nimport { registerStrategyTemplateCommands } from \"./commands/strategy-template.js\";\nimport * as vaultLib from \"./lib/vault.js\";\nimport * as factoryLib from \"./lib/factory.js\";\nimport * as subgraphLib from \"./lib/subgraph.js\";\n// registryLib removed — strategy registry is deprecated, replaced by template commands\nimport { uploadMetadata } from \"./lib/ipfs.js\";\nimport type { SyndicateMetadata } from \"./lib/ipfs.js\";\nimport { registerVeniceCommands } from \"./commands/venice.js\";\nimport { registerAllowanceCommands } from \"./commands/allowance.js\";\nimport { registerIdentityCommands } from \"./commands/identity.js\";\nimport { registerProposalCommands } from \"./commands/proposal.js\";\nimport { registerGovernorCommands } from \"./commands/governor.js\";\nimport { registerGuardianCommands } from \"./commands/guardian-delegate.js\";\nimport { setTextRecord, getTextRecord, resolveVaultSyndicate, resolveSyndicate, searchSyndicateAcrossChains } from \"./lib/ens.js\";\nimport * as easLib from \"./lib/eas.js\";\nimport { EAS_SCHEMAS } from \"./lib/addresses.js\";\nimport {\n setCalldataOnly,\n isCalldataOnly,\n emitCalldata,\n} from \"./lib/calldata.js\";\nimport {\n encodeIdentityMint,\n encodeJoinRequest,\n encodeApproveAgent,\n encodeDeposit,\n encodeRedeem,\n encodeCreateSyndicate,\n encodeApproveDepositor,\n encodeRegisterAgent,\n type ChainId,\n} from \"@sherwoodagent/sdk\";\n\n// XMTP shells out to @xmtp/cli binary — lazy-load to avoid breaking\n// non-chat commands if the CLI is not installed.\nasync function loadXmtp() {\n return import(\"./lib/xmtp.js\");\n}\n// Lazy-load cron module (only needed for openclaw agents)\nasync function loadCron() {\n return import(\"./lib/cron.js\");\n}\nimport { cacheGroupId, getCachedGroupId, setChainContract, getChainContracts, loadConfig, setPrivateKey, getAgentId, setConfigRpcUrl, getNotifyTo, setNotifyTo, setUniswapApiKey, getUniswapApiKey, setVeniceApiKey, getVeniceApiKey, setAnthropicApiKey, addSyndicate, getSyndicates, setPrimarySyndicate, getPrimarySyndicate } from \"./lib/config.js\";\nimport { isTestnet } from \"./lib/network.js\";\n\n// ── Theme ──\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\nfunction validateAddress(value: string, name: string): Address {\n if (!isAddress(value)) {\n console.error(chalk.red(`Invalid ${name} address: ${value}`));\n process.exit(1);\n }\n return value as Address;\n}\n\n/** Set vault address from --vault flag or fall back to config. */\nfunction resolveVault(opts: { vault?: string }) {\n if (opts.vault) {\n vaultLib.setVaultAddress(validateAddress(opts.vault, \"vault\"));\n }\n // If no --vault flag, getVaultAddress() in vault.ts reads from config\n}\n\nconst program = new Command();\n\nprogram\n .name(\"sherwood\")\n .description(\"CLI for agent-managed investment syndicates\")\n .version(CLI_VERSION)\n .addOption(\n new Option(\"--chain <network>\", \"Target network\")\n .choices(VALID_NETWORKS)\n .default(\"base\"),\n )\n .option(\"--testnet\", \"Alias for --chain base-sepolia (deprecated)\", false)\n .option(\n \"--calldata-only\",\n \"Print unsigned EIP-5792 calldata as JSON instead of signing/sending (for external signers — no private key required)\",\n false,\n )\n .hook(\"preAction\", (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n setCalldataOnly(Boolean(opts.calldataOnly));\n let network: string = opts.chain;\n if (opts.testnet) {\n process.env.ENABLE_TESTNET = \"true\";\n if (network !== \"base\") {\n console.warn(\n chalk.yellow(\"[warn] --testnet ignored, --chain takes precedence\"),\n );\n } else {\n network = \"base-sepolia\";\n }\n }\n setNetwork(network as Network);\n if (getNetwork() !== \"base\") {\n console.log(chalk.yellow(`[${getNetwork()}]`));\n }\n });\n\n// ── Syndicate commands ──\nconst syndicate = program.command(\"syndicate\");\n\nsyndicate\n .command(\"create\")\n .description(\"Create a new syndicate via the factory (interactive)\")\n .option(\"--subdomain <name>\", \"ENS subdomain (skip prompt)\")\n .option(\"--name <name>\", \"Syndicate name (skip prompt)\")\n .option(\"--agent-id <id>\", \"ERC-8004 agent identity token ID (skip prompt)\")\n .option(\"--asset <symbol-or-address>\", \"Vault asset: USDC, WETH, or a token address\")\n .option(\"--description <text>\", \"Short description\")\n .option(\"--metadata-uri <uri>\", \"Override metadata URI (skip IPFS upload)\")\n .option(\"--open-deposits\", \"Allow anyone to deposit (default: whitelist only)\")\n .option(\"--public-chat\", \"Enable dashboard spectator mode\", false)\n .option(\"-y, --yes\", \"Skip confirmation prompt (non-interactive mode)\", false)\n .action(async (opts) => {\n try {\n // ── Header ──\n console.log();\n console.log(LABEL(\" ◆ Create Syndicate\"));\n SEP();\n\n // --calldata-only has no wallet to display (no private key); show network only.\n if (!isCalldataOnly()) {\n const wallet = getAccount();\n console.log(DIM(` Wallet: ${wallet.address}`));\n }\n console.log(DIM(` Network: ${getChain().name}`));\n SEP();\n\n // ── Gather inputs (prompt if not provided via flags) ──\n\n const savedAgentId = getAgentId();\n\n const nonInteractive = opts.yes;\n\n const name = opts.name || (nonInteractive\n ? (() => { throw new Error(\"--name is required in non-interactive mode (-y)\"); })()\n : await input({\n message: G(\"Syndicate name\"),\n validate: (v: string) => v.length > 0 || \"Name is required\",\n }));\n\n const subdomain = opts.subdomain || (nonInteractive\n ? name.toLowerCase().replace(/\\s+/g, \"-\").replace(/[^a-z0-9-]/g, \"\")\n : await input({\n message: G(\"ENS subdomain\"),\n default: name.toLowerCase().replace(/\\s+/g, \"-\").replace(/[^a-z0-9-]/g, \"\"),\n validate: (v: string) => v.length >= 3 || \"Must be at least 3 characters\",\n }));\n\n const description = opts.description || (nonInteractive\n ? `${name} — a Sherwood syndicate`\n : await input({\n message: G(\"Description\"),\n default: `${name} — a Sherwood syndicate`,\n }));\n\n const agentIdStr = opts.agentId || (savedAgentId\n ? (nonInteractive\n ? String(savedAgentId)\n : await input({ message: G(\"Agent ID (ERC-8004)\"), default: String(savedAgentId) }))\n : (nonInteractive\n ? \"0\"\n : await input({ message: G(\"Agent ID (ERC-8004)\"), validate: (v: string) => /^\\d+$/.test(v) || \"Must be a number\" }))\n );\n\n const openDeposits = opts.openDeposits !== undefined ? opts.openDeposits : (nonInteractive\n ? false\n : await confirm({\n message: G(\"Open deposits? (anyone can deposit, no whitelist)\"),\n default: false,\n }));\n\n // ── Resolve asset ──\n // Supported symbols (testnet + mainnet). Will expand on mainnet launch.\n const ASSET_SYMBOLS: Record<string, Address> = {\n USDC: TOKENS().USDC,\n WETH: TOKENS().WETH,\n };\n\n let asset: Address;\n if (opts.asset) {\n const upper = opts.asset.toUpperCase();\n if (ASSET_SYMBOLS[upper]) {\n asset = ASSET_SYMBOLS[upper];\n } else if (opts.asset.startsWith(\"0x\") && opts.asset.length === 42) {\n asset = opts.asset as Address;\n } else {\n const supported = Object.keys(ASSET_SYMBOLS).join(\", \");\n console.error(chalk.red(` Unknown asset \"${opts.asset}\". Use a symbol (${supported}) or a 0x address.`));\n process.exit(1);\n }\n } else if (nonInteractive) {\n // Default to WETH on chains without USDC, otherwise USDC\n asset = TOKENS().USDC !== \"0x0000000000000000000000000000000000000000\"\n ? ASSET_SYMBOLS.USDC\n : ASSET_SYMBOLS.WETH;\n } else {\n // Interactive prompt\n const assetChoice = await select({\n message: G(\"Vault asset (what token do depositors provide?)\"),\n choices: [\n { name: \"USDC\", value: \"USDC\", description: \"USD Coin (6 decimals)\" },\n { name: \"WETH\", value: \"WETH\", description: \"Wrapped Ether (18 decimals)\" },\n ],\n });\n asset = ASSET_SYMBOLS[assetChoice];\n }\n\n const publicClient = getPublicClient();\n const [decimals, assetSymbol] = await Promise.all([\n publicClient.readContract({ address: asset, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n publicClient.readContract({ address: asset, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n ]);\n const symbol = `sw${assetSymbol}`;\n\n // ── Confirmation ──\n console.log();\n console.log(LABEL(\" ◆ Review\"));\n SEP();\n console.log(W(` Name: ${BOLD(name)}`));\n console.log(W(` ENS: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Description: ${DIM(description)}`));\n console.log(W(` Agent ID: #${agentIdStr}`));\n console.log(W(` Asset: ${assetSymbol} (${asset.slice(0, 10)}...)`));\n console.log(W(` Share token: ${symbol}`));\n console.log(W(` Open deposits: ${openDeposits ? chalk.yellow(\"yes (anyone can deposit)\") : G(\"no (whitelist)\")}`));\n SEP();\n\n if (!nonInteractive) {\n const go = await confirm({ message: G(\"Deploy syndicate?\"), default: true });\n if (!go) {\n console.log(DIM(\" Cancelled.\"));\n return;\n }\n }\n\n // ── Upload metadata to IPFS ──\n let metadataURI = opts.metadataUri || \"\";\n\n if (!metadataURI) {\n const spinner = ora({ text: W(\"Uploading metadata to IPFS...\"), color: \"green\" }).start();\n try {\n const metadata: SyndicateMetadata = {\n schema: \"sherwood/syndicate/v1\",\n name,\n description,\n chain: getChain().name,\n strategies: [],\n terms: {\n feeModel: \"none\",\n },\n links: {},\n };\n metadataURI = await uploadMetadata(metadata);\n spinner.succeed(G(`Metadata pinned: ${DIM(metadataURI)}`));\n } catch (err) {\n spinner.warn(chalk.yellow(`IPFS upload failed — using inline metadata`));\n const json = JSON.stringify({ name, description, subdomain, asset: assetSymbol, openDeposits, createdBy: \"@sherwoodagent/cli\" });\n metadataURI = `data:application/json;base64,${Buffer.from(json).toString(\"base64\")}`;\n }\n }\n\n // --calldata-only: emit the unsigned createSyndicate calldata and stop,\n // before the subdomain idempotency check (which reads getAccount()).\n // Owner-stake bonding (guardianRegistry.prepareOwnerStake) is a separate\n // prerequisite — see the action note.\n if (isCalldataOnly()) {\n emitCalldata(\n encodeCreateSyndicate(\n {\n creatorAgentId: agentIdStr,\n metadataURI,\n asset,\n name,\n symbol,\n openDeposits,\n subdomain,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n // ── Idempotent check: resume if subdomain already exists ──\n const existingId = await factoryLib.subdomainExists(subdomain);\n if (existingId !== null) {\n const existingInfo = await factoryLib.getSyndicate(existingId);\n const callerAddress = getAccount().address.toLowerCase();\n\n if (existingInfo.creator.toLowerCase() !== callerAddress) {\n console.error(chalk.red(`\\n ✖ Subdomain '${subdomain}' is already taken by another syndicate.\\n`));\n process.exit(1);\n }\n\n // Partial completion — creator already deployed, resume post-deploy steps\n console.log(chalk.yellow(`\\n ⚠ Syndicate '${subdomain}' already exists — resuming setup...\\n`));\n\n const spinner = ora({ text: W(\"Resuming setup...\"), color: \"green\" }).start();\n\n // Save to config\n const chainId = getChain().id;\n setChainContract(chainId, \"vault\", existingInfo.vault);\n addSyndicate(chainId, { subdomain, vault: existingInfo.vault, role: \"creator\" });\n setPrimarySyndicate(chainId, subdomain);\n\n // Register creator as agent (if not already)\n spinner.text = W(\"Checking agent registration...\");\n try {\n vaultLib.setVaultAddress(existingInfo.vault);\n const isAlreadyAgent = await vaultLib.isAgent(getAccount().address);\n if (!isAlreadyAgent) {\n spinner.text = W(\"Registering creator as agent...\");\n await vaultLib.registerAgent(BigInt(agentIdStr), getAccount().address);\n }\n } catch { /* non-fatal */ }\n\n // Create XMTP group (if not already)\n spinner.text = W(\"Checking chat group...\");\n try {\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n try {\n await xmtp.getGroup(xmtpClient, subdomain);\n // Group exists, skip\n } catch {\n // No group — create one\n spinner.text = W(\"Creating chat group...\");\n const groupId = await xmtp.createSyndicateGroup(xmtpClient, subdomain, opts.publicChat);\n await setTextRecord(subdomain, \"xmtpGroupId\", groupId, existingInfo.vault as Address);\n cacheGroupId(subdomain, groupId);\n }\n } catch {\n console.warn(chalk.yellow(\"\\n ⚠ Could not set up XMTP chat group\"));\n }\n\n // Register crons\n try {\n const cron = await loadCron();\n cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n } catch { /* non-fatal */ }\n\n spinner.stop();\n console.log();\n console.log(LABEL(\" ◆ Syndicate Setup Resumed\"));\n SEP();\n console.log(W(` ID: ${G(`#${existingId}`)}`));\n console.log(W(` Vault: ${G(existingInfo.vault)}`));\n console.log(W(` ENS: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Chat: ${DIM(`sherwood chat ${subdomain}`)}`));\n const refParam = getAgentId() ? `?ref=${getAgentId()}` : \"\";\n console.log(W(` Share: ${G(`https://sherwood.sh/syndicate/${subdomain}${refParam}`)}`));\n SEP();\n console.log(G(\" ✓ Syndicate saved to ~/.sherwood/config.json (set as primary)\"));\n console.log();\n return;\n }\n\n // ── Deploy (fresh syndicate) ──\n const spinner = ora({ text: W(\"Deploying vault via factory...\"), color: \"green\" }).start();\n\n const result = await factoryLib.createSyndicate({\n creatorAgentId: BigInt(agentIdStr),\n metadataURI,\n asset,\n name,\n symbol,\n openDeposits,\n subdomain,\n });\n\n // Auto-save vault address + syndicate membership to config\n const chainId = getChain().id;\n setChainContract(chainId, \"vault\", result.vault);\n addSyndicate(chainId, { subdomain, vault: result.vault, role: \"creator\" });\n setPrimarySyndicate(chainId, subdomain);\n\n // ── Register creator as agent on the vault ──\n // Brief delay to let the RPC node sync its nonce after createSyndicate tx\n await new Promise((r) => setTimeout(r, 2000));\n spinner.text = W(\"Registering creator as agent...\");\n try {\n vaultLib.setVaultAddress(result.vault);\n const creatorAddress = getAccount().address;\n await vaultLib.registerAgent(\n BigInt(agentIdStr),\n creatorAddress, // agentAddress = creator EOA (direct execution)\n );\n } catch (regErr) {\n // Non-fatal — creator can register later via `syndicate add`\n console.warn(chalk.yellow(\"\\n ⚠ Could not auto-register creator as agent — register manually with `syndicate add`\"));\n }\n\n spinner.text = W(\"Setting up chat...\");\n\n // Create XMTP group for syndicate chat\n try {\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n const groupId = await xmtp.createSyndicateGroup(xmtpClient, subdomain, opts.publicChat);\n cacheGroupId(subdomain, groupId);\n try {\n await setTextRecord(subdomain, \"xmtpGroupId\", groupId, result.vault as Address);\n } catch { /* ENS not available on all chains */ }\n } catch {\n console.warn(chalk.yellow(\"\\n ⚠ Could not create XMTP chat group\"));\n console.warn(chalk.dim(` Recover later with: sherwood chat ${subdomain} init`));\n }\n\n // ── Auto-register participation crons ──\n try {\n const cron = await loadCron();\n const cronResult = cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n if (cronResult.isOpenClaw && cronResult.registered) {\n console.log(G(\" ✓ Participation crons registered (15m check + hourly summary)\"));\n } else if (!cronResult.isOpenClaw) {\n console.log(DIM(\" Tip: Set up a scheduled process to run `sherwood session check \" + subdomain + \"` periodically\"));\n }\n } catch { /* non-fatal */ }\n\n spinner.stop();\n\n // ── Success ──\n console.log();\n console.log(LABEL(\" ◆ Syndicate Created\"));\n SEP();\n console.log(W(` ID: ${G(`#${result.syndicateId}`)}`));\n console.log(W(` Vault: ${G(result.vault)}`));\n console.log(W(` ENS: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Metadata: ${DIM(metadataURI.length > 50 ? metadataURI.slice(0, 50) + \"...\" : metadataURI)}`));\n console.log(W(` Explorer: ${DIM(getExplorerUrl(result.hash))}`));\n console.log(W(` Chat: ${DIM(`sherwood chat ${subdomain}`)}`));\n const refParam = getAgentId() ? `?ref=${getAgentId()}` : \"\";\n console.log(W(` Share: ${G(`https://sherwood.sh/syndicate/${subdomain}${refParam}`)}`));\n SEP();\n console.log(G(\" ✓ Syndicate saved to ~/.sherwood/config.json (set as primary)\"));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"list\")\n .description(\"List active syndicates (queries subgraph, falls back to on-chain)\")\n .option(\"--creator <address>\", \"Filter by creator address\")\n .option(\"--all-chains\", \"Aggregate active syndicates across all supported chains (on-chain only)\")\n .action(async (opts) => {\n const spinner = ora(\"Loading syndicates...\").start();\n try {\n // Each row carries an optional `chain` so the --all-chains output can\n // tell users which network a syndicate lives on.\n type Row = {\n id: string | bigint;\n vault: string;\n creator: string;\n metadataURI: string;\n createdAt: string | bigint;\n totalDeposits?: string;\n totalWithdrawals?: string;\n subdomain?: string;\n chain?: Network;\n };\n let syndicates: Row[] = [];\n\n if (opts.allChains) {\n // Subgraph is single-chain; on-chain only when iterating networks.\n const includeTestnets = process.env.ENABLE_TESTNET === \"true\";\n const targets = VALID_NETWORKS.filter((n) => includeTestnets || ![\"base-sepolia\", \"robinhood-testnet\", \"hyperevm-testnet\"].includes(n));\n for (const net of targets) {\n spinner.text = `Loading from ${net}...`;\n try {\n const rows = await withNetwork(net, () => factoryLib.getActiveSyndicates());\n for (const s of rows) {\n syndicates.push({\n id: s.id.toString(),\n vault: s.vault,\n creator: s.creator,\n metadataURI: s.metadataURI,\n createdAt: s.createdAt.toString(),\n subdomain: s.subdomain,\n chain: net,\n });\n }\n } catch {\n // Skip flaky chain RPCs rather than failing the whole listing.\n }\n }\n if (opts.creator) {\n const c = String(opts.creator).toLowerCase();\n syndicates = syndicates.filter((s) => s.creator.toLowerCase() === c);\n }\n } else if (process.env.SUBGRAPH_URL) {\n const result = await subgraphLib.getActiveSyndicates(opts.creator);\n syndicates = result;\n } else {\n const result = await factoryLib.getActiveSyndicates();\n syndicates = result.map((s) => ({\n id: s.id.toString(),\n vault: s.vault,\n creator: s.creator,\n metadataURI: s.metadataURI,\n createdAt: s.createdAt.toString(),\n subdomain: s.subdomain,\n }));\n }\n\n spinner.stop();\n\n if (syndicates.length === 0) {\n console.log(chalk.dim(\"No active syndicates found.\"));\n return;\n }\n\n console.log();\n console.log(chalk.bold(`Active Syndicates (${syndicates.length})`));\n if (!process.env.SUBGRAPH_URL && !opts.allChains) {\n console.log(chalk.dim(\" (Set SUBGRAPH_URL for faster indexed queries)\"));\n }\n if (opts.allChains) {\n console.log(chalk.dim(\" (Aggregated across chains via on-chain factory calls; SUBGRAPH_URL is single-chain only)\"));\n }\n console.log(chalk.dim(\"─\".repeat(70)));\n\n for (const s of syndicates) {\n const ts = typeof s.createdAt === \"string\" ? Number(s.createdAt) : Number(s.createdAt);\n const date = new Date(ts * 1000).toLocaleDateString();\n const ensName = s.subdomain ? `${s.subdomain}.sherwoodagent.eth` : \"\";\n const chainTag = s.chain ? chalk.dim(`[${s.chain}] `) : \"\";\n console.log(` ${chainTag}#${s.id} ${chalk.bold(ensName || String(s.vault))}`);\n if (ensName) console.log(` Vault: ${chalk.cyan(String(s.vault))}`);\n console.log(` Creator: ${s.creator}`);\n console.log(` Created: ${date}`);\n if (s.totalDeposits) {\n console.log(` Deposits: ${s.totalDeposits} USDC`);\n }\n if (s.metadataURI) {\n console.log(` Metadata: ${chalk.dim(s.metadataURI)}`);\n }\n console.log();\n }\n } catch (err) {\n spinner.fail(\"Failed to load syndicates\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"info\")\n .description(\"Display syndicate details by ID or subdomain\")\n .argument(\"<id>\", \"Syndicate ID or subdomain name\")\n .action(async (idStr) => {\n const spinner = ora(\"Loading syndicate info...\").start();\n try {\n let id: bigint;\n let crossChainHint: { network: Network; others: Network[] } | null = null;\n let infoOverride: factoryLib.SyndicateInfo | null = null;\n\n if (/^\\d+$/.test(idStr)) {\n id = BigInt(idStr);\n } else {\n // Try active chain first; on miss, scan all enabled chains so users\n // who default to base can still inspect a HyperEVM syndicate.\n try {\n const resolved = await resolveSyndicate(idStr);\n id = resolved.id;\n } catch {\n spinner.text = `Searching across chains...`;\n const hits = await searchSyndicateAcrossChains(idStr);\n if (hits.length === 0) {\n spinner.fail(`Syndicate \"${idStr}\" not found on any supported chain`);\n process.exit(1);\n }\n // Prefer active chain hit, else first hit.\n const active = getNetwork();\n const primary = hits.find((h) => h.network === active) ?? hits[0];\n id = primary.result.id;\n // Read the syndicate from the chain it actually lives on (NOT the\n // active chain) so vault stats etc. don't blow up trying to read a\n // non-existent vault on the active chain.\n infoOverride = await withNetwork(primary.network, () =>\n factoryLib.getSyndicate(primary.result.id),\n );\n crossChainHint = {\n network: primary.network,\n others: hits.filter((h) => h.network !== primary.network).map((h) => h.network),\n };\n }\n }\n const info = infoOverride ?? (await factoryLib.getSyndicate(id));\n spinner.stop();\n if (crossChainHint) {\n const others = crossChainHint.others.length > 0\n ? ` (also on: ${crossChainHint.others.join(\", \")})`\n : \"\";\n console.log(chalk.yellow(` Found on chain: ${chalk.bold(crossChainHint.network)}${others}`));\n console.log(chalk.dim(` Re-run with --chain ${crossChainHint.network} to interact with this syndicate.`));\n console.log();\n }\n\n if (!info.vault || info.vault === \"0x0000000000000000000000000000000000000000\") {\n console.log(chalk.red(`Syndicate #${id} not found.`));\n process.exit(1);\n }\n\n const date = new Date(Number(info.createdAt) * 1000).toLocaleDateString();\n console.log();\n console.log(chalk.bold(`Syndicate #${info.id}`));\n console.log(chalk.dim(\"─\".repeat(40)));\n if (info.subdomain) {\n console.log(` ENS: ${chalk.bold(`${info.subdomain}.sherwoodagent.eth`)}`);\n }\n console.log(` Vault: ${chalk.cyan(info.vault)}`);\n console.log(` Creator: ${info.creator}`);\n console.log(` Created: ${date}`);\n console.log(` Active: ${info.active ? chalk.green(\"yes\") : chalk.red(\"no\")}`);\n if (info.metadataURI) {\n console.log(` Metadata: ${chalk.dim(info.metadataURI)}`);\n }\n\n // Show XMTP group ID if cached\n if (info.subdomain) {\n const xmtpGroupId = getCachedGroupId(info.subdomain);\n if (xmtpGroupId) {\n console.log(` XMTP Group: ${chalk.cyan(xmtpGroupId)}`);\n }\n }\n\n // Also show vault info — when the syndicate lives on a different\n // chain than the active one, read the vault on its actual chain.\n vaultLib.setVaultAddress(info.vault);\n const vaultInfo = crossChainHint\n ? await withNetwork(crossChainHint.network, () => vaultLib.getVaultInfo())\n : await vaultLib.getVaultInfo();\n console.log();\n console.log(chalk.bold(\" Vault Stats\"));\n console.log(` Total Assets: ${vaultInfo.totalAssets}`);\n console.log(` Agent Count: ${vaultInfo.agentCount}`);\n console.log(` Redemptions Locked: ${vaultInfo.redemptionsLocked}`);\n console.log(` Management Fee: ${Number(vaultInfo.managementFeeBps) / 100}%`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load syndicate info\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"update-metadata\")\n .description(\"Update syndicate metadata (creator only)\")\n .requiredOption(\"--id <id>\", \"Syndicate ID\")\n .option(\"--name <name>\", \"Syndicate name\")\n .option(\"--description <text>\", \"Short description\")\n .option(\"--uri <uri>\", \"Direct metadata URI (skips IPFS upload)\")\n .action(async (opts) => {\n const spinner = ora({ text: W(\"Loading syndicate...\"), color: \"green\" }).start();\n try {\n const syndicateId = BigInt(opts.id);\n let metadataURI = opts.uri;\n\n if (!metadataURI) {\n const info = await factoryLib.getSyndicate(syndicateId);\n if (!info.vault || info.vault === \"0x0000000000000000000000000000000000000000\") {\n spinner.fail(`Syndicate #${opts.id} not found.`);\n process.exit(1);\n }\n\n const name = opts.name || info.subdomain;\n const description = opts.description || `${name} — a Sherwood syndicate on ${info.subdomain}.sherwoodagent.eth`;\n\n spinner.text = W(\"Uploading metadata to IPFS...\");\n const metadata: SyndicateMetadata = {\n schema: \"sherwood/syndicate/v1\",\n name,\n description,\n chain: getChain().name,\n strategies: [],\n terms: {},\n links: {},\n };\n metadataURI = await uploadMetadata(metadata);\n spinner.text = W(\"Updating on-chain metadata...\");\n }\n\n const hash = await factoryLib.updateMetadata(syndicateId, metadataURI);\n spinner.succeed(G(`Metadata updated`));\n console.log(DIM(` IPFS: ${metadataURI}`));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Metadata update failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"approve-depositor\")\n .description(\"Approve an address to deposit (owner only)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .requiredOption(\"--depositor <address>\", \"Address to approve\")\n .action(async (opts) => {\n resolveVault(opts);\n const depositor = validateAddress(opts.depositor, \"depositor\");\n if (isCalldataOnly()) {\n emitCalldata(\n encodeApproveDepositor(\n { vault: vaultLib.getVaultAddress(), depositor },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n const spinner = ora(\"Approving depositor...\").start();\n try {\n const hash = await vaultLib.approveDepositor(depositor);\n spinner.succeed(`Depositor approved: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Approval failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"remove-depositor\")\n .description(\"Remove an address from the depositor whitelist (owner only)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .requiredOption(\"--depositor <address>\", \"Address to remove\")\n .action(async (opts) => {\n resolveVault(opts);\n const spinner = ora(\"Removing depositor...\").start();\n try {\n const depositor = validateAddress(opts.depositor, \"depositor\");\n const hash = await vaultLib.removeDepositor(depositor);\n spinner.succeed(`Depositor removed: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Removal failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"add\")\n .description(\"Register an agent on a syndicate vault (creator only)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--agent-id <id>\", \"Agent's ERC-8004 identity token ID (resolved from wallet if omitted)\")\n .requiredOption(\"--wallet <address>\", \"Agent wallet address\")\n .action(async (opts) => {\n // --calldata-only: emit registerAgent calldata. Requires --agent-id (the\n // wallet-based auto-lookup is skipped in calldata mode) and runs before any\n // signer-dependent path.\n if (isCalldataOnly()) {\n resolveVault(opts);\n const agentWallet = validateAddress(opts.wallet, \"wallet\");\n if (!opts.agentId) {\n console.error(\n chalk.red(\n \"--calldata-only requires --agent-id (auto-lookup from wallet is skipped in calldata mode)\",\n ),\n );\n process.exit(1);\n }\n emitCalldata(\n encodeRegisterAgent(\n {\n vault: vaultLib.getVaultAddress(),\n agentAddress: agentWallet,\n agentId: BigInt(opts.agentId),\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const spinner = ora(\"Verifying creator...\").start();\n try {\n // Resolve vault address from --vault flag or config\n resolveVault(opts);\n const vaultAddress = vaultLib.getVaultAddress();\n\n // Verify caller is the syndicate creator\n const { creator, subdomain } = await resolveVaultSyndicate(vaultAddress);\n const callerAddress = getAccount().address.toLowerCase();\n if (creator.toLowerCase() !== callerAddress) {\n spinner.fail(\"Only the syndicate creator can add agents\");\n process.exit(1);\n }\n\n const agentWallet = validateAddress(opts.wallet, \"wallet\");\n\n // Resolve agent ID: use --agent-id if provided, otherwise look up from wallet\n let agentId: bigint;\n if (opts.agentId) {\n agentId = BigInt(opts.agentId);\n } else {\n const { AGENT_REGISTRY } = await import(\"./lib/addresses.js\");\n const registry = AGENT_REGISTRY().IDENTITY_REGISTRY;\n\n // Chains without ERC-8004 (e.g. HyperEVM) — contract skips identity check\n if (registry === \"0x0000000000000000000000000000000000000000\") {\n agentId = 0n;\n } else {\n spinner.text = \"Looking up ERC-8004 identity from wallet...\";\n const client = getPublicClient();\n\n const balance = await client.readContract({\n address: registry,\n abi: [{\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n }] as const,\n functionName: \"balanceOf\",\n args: [agentWallet],\n }) as bigint;\n\n if (balance === 0n) {\n spinner.fail(\"Agent wallet does not own an ERC-8004 identity NFT\");\n console.error(chalk.dim(\" Mint one first: sherwood identity mint --name <name>\"));\n process.exit(1);\n }\n\n const tokenId = await client.readContract({\n address: registry,\n abi: [{\n name: \"tokenOfOwnerByIndex\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }, { name: \"index\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n }] as const,\n functionName: \"tokenOfOwnerByIndex\",\n args: [agentWallet, 0n],\n }) as bigint;\n\n agentId = tokenId;\n console.log(chalk.dim(` Resolved agent ID: #${agentId}`));\n }\n }\n\n spinner.text = \"Registering agent...\";\n const hash = await vaultLib.registerAgent(agentId, agentWallet);\n spinner.succeed(`Agent registered: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n\n // Auto-add agent to XMTP chat group\n try {\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n const group = await xmtp.getGroup(xmtpClient, subdomain);\n await xmtp.addMember(group, opts.wallet);\n await xmtp.sendEnvelope(group, {\n type: \"AGENT_REGISTERED\",\n agent: { erc8004Id: Number(agentId), address: opts.wallet },\n syndicate: subdomain,\n timestamp: Math.floor(Date.now() / 1000),\n });\n console.log(chalk.dim(` Added to chat: ${subdomain}`));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not add agent to chat group\"));\n console.warn(chalk.dim(` If no group exists, run: sherwood chat ${subdomain} init`));\n }\n } catch (err) {\n spinner.fail(\"Registration failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"share\")\n .description(\"Print the shareable dashboard URL for your syndicate\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain (default: primary)\")\n .action(async (opts) => {\n try {\n const subdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (!subdomain) {\n console.error(chalk.red(\" No syndicate configured. Pass --subdomain <name> or run 'syndicate create/join' first.\"));\n process.exit(1);\n }\n\n // Verify syndicate exists on-chain\n const syndicateInfo = await resolveSyndicate(subdomain);\n\n const agentId = getAgentId();\n const refParam = agentId ? `?ref=${agentId}` : \"\";\n const dashboardUrl = `https://sherwood.sh/syndicate/${subdomain}${refParam}`;\n\n console.log();\n console.log(LABEL(\" ◆ Share Your Syndicate\"));\n SEP();\n console.log(W(` Dashboard: ${G(dashboardUrl)}`));\n console.log(W(` ENS: ${DIM(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Vault: ${DIM(syndicateInfo.vault)}`));\n console.log(W(` Join CLI: ${DIM(`sherwood syndicate join --subdomain ${subdomain}`)}`));\n SEP();\n\n // Try to copy to clipboard (optional — uses pbcopy/xclip if available)\n try {\n const { exec } = await import(\"node:child_process\");\n const platform = (await import(\"node:os\")).platform();\n const cmd = platform === \"darwin\" ? \"pbcopy\" : \"xclip -selection clipboard\";\n const proc = exec(cmd);\n proc.stdin?.write(dashboardUrl);\n proc.stdin?.end();\n console.log(G(\" ✓ Dashboard URL copied to clipboard\"));\n } catch {\n // clipboard not available — no problem\n }\n console.log();\n } catch (err) {\n console.error(chalk.red(` ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n// ── EAS Join Request / Approval Commands ──\n\nsyndicate\n .command(\"join\")\n .description(\"Request to join a syndicate (creates an EAS attestation)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain to join\")\n .option(\"--ref <agentId>\", \"Referrer agent ID (from invite link)\")\n .option(\"--message <text>\", \"Message to the creator\", \"Requesting to join your syndicate\")\n .action(async (opts) => {\n const spinner = ora(\"Resolving syndicate...\").start();\n try {\n const subdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (!subdomain) {\n spinner.fail(\"No syndicate configured. Pass --subdomain <name> or run 'syndicate create' first.\");\n process.exit(1);\n }\n\n const agentId = getAgentId();\n if (!agentId) {\n spinner.fail(\"No agent identity found. Run 'sherwood identity mint' first.\");\n process.exit(1);\n }\n\n let syndicate: Awaited<ReturnType<typeof resolveSyndicate>>;\n try {\n syndicate = await resolveSyndicate(subdomain);\n } catch {\n // Active chain doesn't have it — see if it lives elsewhere.\n spinner.text = \"Searching across chains...\";\n const hits = await searchSyndicateAcrossChains(subdomain);\n spinner.fail(`Syndicate \"${subdomain}\" not found on ${getNetwork()}`);\n if (hits.length === 0) {\n console.error(chalk.red(` Not found on any supported chain.`));\n } else if (hits.length === 1) {\n console.error(chalk.yellow(` Found on chain: ${chalk.bold(hits[0].network)}`));\n console.error(chalk.dim(` Re-run: sherwood --chain ${hits[0].network} syndicate join --subdomain ${subdomain}`));\n } else {\n const chains = hits.map((h) => h.network).join(\", \");\n console.error(chalk.yellow(` Found on chains: ${chalk.bold(chains)}`));\n console.error(chalk.dim(` Specify which chain to join with --chain <network>.`));\n }\n process.exit(1);\n }\n\n // --calldata-only: emit the unsigned join-request attestation and stop\n // before any signer-dependent path (membership checks read getAccount()).\n if (isCalldataOnly()) {\n const referrerAgentId = opts.ref ? parseInt(opts.ref, 10) : undefined;\n spinner.stop();\n emitCalldata(\n encodeJoinRequest(\n {\n syndicateId: syndicate.id,\n agentId: BigInt(agentId),\n vault: syndicate.vault,\n creator: syndicate.creator,\n message: opts.message,\n referrerAgentId,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const callerAddress = getAccount().address;\n\n // Check if already registered as an agent on this vault\n spinner.text = \"Checking membership...\";\n vaultLib.setVaultAddress(syndicate.vault);\n const alreadyAgent = await vaultLib.isAgent(callerAddress);\n if (alreadyAgent) {\n spinner.succeed(\"You are already a registered agent on this syndicate\");\n // Still ensure XMTP identity is ready\n try {\n const xmtp = await loadXmtp();\n await xmtp.getXmtpClient();\n console.log(chalk.dim(\" XMTP identity ready\"));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not initialize XMTP identity\"));\n }\n // Auto-register participation crons (idempotent)\n try {\n const cron = await loadCron();\n const cronResult = cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n if (cronResult.isOpenClaw && cronResult.registered) {\n console.log(chalk.green(\" ✓ Participation crons registered\"));\n } else if (!cronResult.isOpenClaw) {\n console.log(chalk.dim(\" Tip: Set up a scheduled process to run `sherwood session check \" + subdomain + \"` periodically\"));\n }\n } catch { /* non-fatal */ }\n return;\n }\n\n // Check for existing pending join request\n spinner.text = \"Checking pending requests...\";\n const pendingRequests = await easLib.queryJoinRequests(syndicate.creator);\n const existingRequest = pendingRequests.find(\n (r) => r.attester.toLowerCase() === callerAddress.toLowerCase()\n && r.decoded.vault.toLowerCase() === syndicate.vault.toLowerCase(),\n );\n if (existingRequest) {\n spinner.succeed(\"You already have a pending join request for this syndicate\");\n console.log(chalk.dim(` Attestation: ${existingRequest.uid}`));\n console.log(chalk.dim(` Submitted: ${new Date(existingRequest.time * 1000).toLocaleString()}`));\n // Still ensure XMTP identity is ready\n try {\n const xmtp = await loadXmtp();\n await xmtp.getXmtpClient();\n console.log(chalk.dim(\" XMTP identity ready\"));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not initialize XMTP identity\"));\n }\n return;\n }\n\n spinner.text = \"Creating join request attestation...\";\n const referrerAgentId = opts.ref ? parseInt(opts.ref, 10) : undefined;\n const { uid, hash } = await easLib.createJoinRequest(\n syndicate.id,\n BigInt(agentId),\n syndicate.vault,\n syndicate.creator,\n opts.message,\n referrerAgentId,\n );\n\n // Pre-register XMTP identity so the creator can add us to the group on approval\n try {\n spinner.text = \"Registering XMTP identity...\";\n const xmtp = await loadXmtp();\n await xmtp.getXmtpClient();\n spinner.succeed(\"Join request created (XMTP identity ready)\");\n } catch {\n spinner.succeed(\"Join request created\");\n console.warn(chalk.yellow(\" ⚠ Could not initialize XMTP identity — creator may not be able to auto-add you to chat\"));\n }\n\n // Save syndicate membership + set as primary\n addSyndicate(getChain().id, { subdomain, vault: syndicate.vault, role: \"agent\" });\n setPrimarySyndicate(getChain().id, subdomain);\n\n // Auto-register participation crons (will HEARTBEAT_OK until approved)\n try {\n const cron = await loadCron();\n const cronResult = cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n if (cronResult.isOpenClaw && cronResult.registered) {\n console.log(G(\" ✓ Participation crons registered (will activate after approval)\"));\n } else if (!cronResult.isOpenClaw) {\n console.log(DIM(\" Tip: Set up a scheduled process to run `sherwood session check \" + subdomain + \"` periodically\"));\n }\n } catch { /* non-fatal */ }\n\n console.log();\n console.log(LABEL(\" ◆ Join Request Submitted\"));\n SEP();\n console.log(W(` Syndicate: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Agent ID: #${agentId}`));\n console.log(W(` Creator: ${DIM(syndicate.creator)}`));\n console.log(W(` Attestation: ${DIM(uid)}`));\n console.log(W(` EAS Scan: ${DIM(easLib.getEasScanUrl(uid))}`));\n // EAS tx ran on Base (Base-Sepolia for testnet) regardless of --chain.\n console.log(W(` Explorer: ${DIM(easLib.getEasExplorerUrl(hash))}`));\n SEP();\n console.log(G(\" ✓ Syndicate saved to ~/.sherwood/config.json (set as primary)\"));\n console.log(G(\" ✓ The creator can review with:\"));\n console.log(DIM(` sherwood syndicate requests --subdomain ${subdomain}`));\n console.log();\n } catch (err) {\n spinner.fail(\"Join request failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"requests\")\n .description(\"View pending join requests for a syndicate (creator only)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .action(async (opts) => {\n const spinner = ora(\"Loading join requests...\").start();\n try {\n let creatorAddress: Address;\n let subdomain: string;\n let syndicateVault: Address;\n\n // Resolve syndicate: --subdomain > primary syndicate > --vault > config vault\n const resolvedSubdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (resolvedSubdomain) {\n const syndicateInfo = await resolveSyndicate(resolvedSubdomain);\n creatorAddress = syndicateInfo.creator;\n subdomain = resolvedSubdomain;\n syndicateVault = syndicateInfo.vault as Address;\n } else {\n resolveVault(opts);\n syndicateVault = vaultLib.getVaultAddress();\n const syndicateInfo = await resolveVaultSyndicate(syndicateVault);\n creatorAddress = syndicateInfo.creator;\n subdomain = syndicateInfo.subdomain;\n }\n\n // Verify caller is creator\n const callerAddress = getAccount().address.toLowerCase();\n if (creatorAddress.toLowerCase() !== callerAddress) {\n spinner.fail(\"Only the syndicate creator can view join requests\");\n process.exit(1);\n }\n\n spinner.text = \"Querying EAS attestations...\";\n const [allRequests, approvals] = await Promise.all([\n easLib.queryJoinRequests(creatorAddress),\n easLib.queryApprovals(creatorAddress),\n ]);\n\n // Filter out agents that have already been approved for the same vault\n const approvedKeys = new Set(\n approvals\n .filter((a) => a.decoded.vault.toLowerCase() === syndicateVault.toLowerCase())\n .map((a) => a.decoded.agentId.toString()),\n );\n const requests = allRequests.filter(\n (r) => !approvedKeys.has(r.decoded.agentId.toString())\n && r.decoded.vault.toLowerCase() === syndicateVault.toLowerCase(),\n );\n\n spinner.stop();\n\n if (requests.length === 0) {\n console.log(DIM(\"\\n No pending join requests.\\n\"));\n return;\n }\n\n console.log();\n console.log(LABEL(` ◆ Pending Join Requests (${requests.length})`));\n SEP();\n\n for (let i = 0; i < requests.length; i++) {\n const req = requests[i];\n const date = new Date(req.time * 1000).toLocaleString();\n const referrer = easLib.parseReferrer(req.decoded.message);\n const cleanMessage = easLib.stripReferrerPrefix(req.decoded.message);\n console.log(W(` ${i + 1}. Agent #${req.decoded.agentId} ${DIM(`(${req.attester})`)}`));\n console.log(DIM(` Message: \"${cleanMessage}\"`));\n if (referrer !== null) {\n console.log(G(` Referred by: Agent #${referrer}`));\n }\n console.log(DIM(` Requested: ${date}`));\n console.log(DIM(` Attestation: ${req.uid}`));\n console.log();\n }\n\n console.log(G(\" To approve:\"));\n console.log(DIM(` sherwood syndicate approve --agent-id <id> --wallet <addr>`));\n console.log(G(\" To reject:\"));\n console.log(DIM(` sherwood syndicate reject --attestation <uid>`));\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load requests\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"approve\")\n .description(\"Approve an agent join request (registers agent + creates EAS approval)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain (alternative to --vault)\")\n .requiredOption(\"--agent-id <id>\", \"Agent's ERC-8004 identity token ID\")\n .requiredOption(\"--wallet <address>\", \"Agent wallet address\")\n .action(async (opts) => {\n const spinner = ora(\"Verifying creator...\").start();\n try {\n // Resolve vault: --subdomain > primary syndicate > --vault > config vault\n const approveSubdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (approveSubdomain && !opts.vault) {\n const syndicateInfo = await resolveSyndicate(approveSubdomain);\n vaultLib.setVaultAddress(syndicateInfo.vault);\n } else {\n resolveVault(opts);\n }\n const vaultAddress = vaultLib.getVaultAddress();\n\n const agentWallet = validateAddress(opts.wallet, \"wallet\");\n\n // Verify caller is creator\n const { creator, subdomain, id: syndicateId } = await resolveVaultSyndicate(vaultAddress);\n\n // --calldata-only: emit registerAgent (syndicate chain) + AGENT_APPROVED\n // attest (Base) before any signer-dependent path.\n if (isCalldataOnly()) {\n spinner.stop();\n emitCalldata(\n encodeApproveAgent(\n {\n syndicateId,\n agentId: BigInt(opts.agentId),\n vault: vaultAddress,\n agentAddress: agentWallet,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const callerAddress = getAccount().address.toLowerCase();\n if (creator.toLowerCase() !== callerAddress) {\n spinner.fail(\"Only the syndicate creator can approve agents\");\n process.exit(1);\n }\n\n // 1. Register agent on-chain (same as syndicate add)\n spinner.text = \"Registering agent on vault...\";\n let agentWasRegistered = false;\n try {\n const regHash = await vaultLib.registerAgent(\n BigInt(opts.agentId),\n agentWallet,\n );\n agentWasRegistered = true;\n console.log(DIM(` Agent registered: ${getExplorerUrl(regHash)}`));\n } catch (regErr) {\n const msg = regErr instanceof Error ? regErr.message : String(regErr);\n if (msg.includes(\"0xe098d3ee\") || msg.includes(\"AgentAlreadyRegistered\")) {\n console.log(DIM(\" Agent already registered on vault — skipping\"));\n } else {\n throw regErr;\n }\n }\n\n // Brief delay after on-chain registration to let the RPC node sync its nonce\n if (agentWasRegistered) {\n await new Promise((r) => setTimeout(r, 2000));\n }\n\n // 2. Create AGENT_APPROVED attestation (skip if one already exists)\n spinner.text = \"Checking for existing approval...\";\n const existingApprovals = await easLib.queryApprovals(getAccount().address);\n const alreadyApproved = existingApprovals.find(\n (a) => a.decoded.agentId === BigInt(opts.agentId) && a.decoded.vault.toLowerCase() === vaultAddress.toLowerCase(),\n );\n\n let approvalUid: `0x${string}`;\n if (alreadyApproved) {\n approvalUid = alreadyApproved.uid;\n console.log(DIM(` Approval attestation already exists — skipping`));\n } else {\n spinner.text = \"Creating approval attestation...\";\n const result = await easLib.createApproval(\n syndicateId,\n BigInt(opts.agentId),\n vaultAddress,\n agentWallet,\n );\n approvalUid = result.uid;\n }\n\n // 3. Auto-add agent to XMTP chat group\n try {\n spinner.text = \"Adding to chat...\";\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n const group = await xmtp.getGroup(xmtpClient, subdomain);\n await xmtp.addMember(group, opts.wallet);\n await xmtp.sendEnvelope(group, {\n type: \"AGENT_REGISTERED\",\n agent: { erc8004Id: Number(opts.agentId), address: opts.wallet },\n syndicate: subdomain,\n timestamp: Math.floor(Date.now() / 1000),\n });\n console.log(DIM(` Added to chat: ${subdomain}`));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not add agent to chat group\"));\n console.warn(chalk.dim(` If no group exists, run: sherwood chat ${subdomain} init`));\n }\n\n spinner.succeed(\"Agent approved and registered\");\n console.log();\n console.log(LABEL(\" ◆ Agent Approved\"));\n SEP();\n console.log(W(` Agent ID: #${opts.agentId}`));\n console.log(W(` Wallet: ${G(opts.wallet)}`));\n console.log(W(` Approval: ${DIM(approvalUid)}`));\n console.log(W(` EAS Scan: ${DIM(easLib.getEasScanUrl(approvalUid))}`));\n SEP();\n } catch (err) {\n spinner.fail(\"Approval failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"reject\")\n .description(\"Reject a join request by revoking its attestation\")\n .requiredOption(\"--attestation <uid>\", \"Join request attestation UID to revoke\")\n .action(async (opts) => {\n const spinner = ora(\"Revoking attestation...\").start();\n try {\n // Revoke on Base / Base-Sepolia regardless of --chain — syndicate\n // join attestations always live on the EAS chain, not the syndicate's\n // chain.\n const hash = await easLib.revokeJoinRequest(opts.attestation as `0x${string}`);\n spinner.succeed(\"Join request rejected\");\n console.log(DIM(` ${easLib.getEasExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Rejection failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"leave\")\n .description(\"Leave a syndicate — removes participation crons and session state\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain to leave\")\n .action(async (opts) => {\n const subdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (!subdomain) {\n console.error(chalk.red(\" No syndicate configured. Pass --subdomain <name>.\"));\n process.exit(1);\n }\n const spinner = ora(\"Cleaning up...\").start();\n try {\n // 1. Remove participation crons (if OpenClaw)\n let cronsRemoved = false;\n try {\n const cron = await loadCron();\n const result = cron.unregisterSyndicateCrons(subdomain, isTestnet());\n cronsRemoved = result.removed;\n } catch { /* non-fatal */ }\n\n // 2. Reset session state\n const { resetSession } = await import(\"./lib/session.js\");\n resetSession(subdomain);\n\n spinner.succeed(\"Left syndicate\");\n if (cronsRemoved) {\n console.log(G(\" ✓ Participation crons removed\"));\n }\n console.log(G(\" ✓ Session state cleared\"));\n console.log();\n console.log(chalk.dim(\" Note: This does not remove you on-chain. To exit your position:\"));\n console.log(chalk.dim(\" sherwood vault balance — check your LP share balance\"));\n console.log(chalk.dim(\" Redeem shares via the vault contract or dashboard\"));\n console.log();\n } catch (err) {\n spinner.fail(\"Leave failed\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"set-primary\")\n .description(\"Set the active syndicate for CLI commands (auto-used when --subdomain is omitted)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain\")\n .option(\"--vault <address>\", \"Vault address\")\n .action(async (opts) => {\n try {\n const chainId = getChain().id;\n const memberships = getSyndicates(chainId);\n\n if (!opts.subdomain && !opts.vault) {\n // List syndicates and show which is primary\n const primary = getPrimarySyndicate(chainId);\n if (memberships.length === 0) {\n console.log(DIM(\"\\n No syndicates saved. Create or join one first.\\n\"));\n return;\n }\n console.log();\n console.log(LABEL(\" ◆ Your Syndicates\"));\n SEP();\n for (const m of memberships) {\n const isPrimary = primary?.subdomain === m.subdomain;\n const marker = isPrimary ? G(\" ★\") : \"\";\n console.log(W(` ${m.subdomain}.sherwoodagent.eth${marker} ${DIM(`(${m.role})`)}`));\n console.log(DIM(` vault: ${m.vault}`));\n }\n SEP();\n if (memberships.length > 1) {\n console.log(DIM(\" Switch with: sherwood syndicate set-primary --subdomain <name>\"));\n }\n console.log();\n return;\n }\n\n let target: string | undefined;\n\n if (opts.subdomain) {\n // Verify it's in our list\n const found = memberships.find((m) => m.subdomain === opts.subdomain);\n if (!found) {\n // Resolve on-chain to verify it exists, then add it\n const syndicateInfo = await resolveSyndicate(opts.subdomain);\n addSyndicate(chainId, { subdomain: opts.subdomain, vault: syndicateInfo.vault, role: \"agent\" });\n }\n target = opts.subdomain;\n } else if (opts.vault) {\n // Find by vault address\n const found = memberships.find(\n (m) => m.vault.toLowerCase() === opts.vault.toLowerCase(),\n );\n if (found) {\n target = found.subdomain;\n } else {\n // Resolve on-chain\n const syndicateInfo = await resolveVaultSyndicate(validateAddress(opts.vault, \"vault\"));\n addSyndicate(chainId, { subdomain: syndicateInfo.subdomain, vault: opts.vault, role: \"agent\" });\n target = syndicateInfo.subdomain;\n }\n }\n\n if (!target) {\n console.error(chalk.red(\" Could not resolve syndicate. Pass --subdomain or --vault.\"));\n process.exit(1);\n }\n\n setPrimarySyndicate(chainId, target);\n console.log(G(`\\n ✓ Primary syndicate set to ${target}.sherwoodagent.eth\\n`));\n } catch (err) {\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n// ── Vault commands ──\nconst vaultCmd = program.command(\"vault\");\n\nvaultCmd\n .command(\"deposit\")\n .description(\"Deposit into a vault\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .requiredOption(\"--amount <amount>\", \"Amount to deposit (in asset units)\")\n .option(\"--use-eth\", \"Auto-wrap ETH → WETH before depositing (for WETH vaults)\")\n .option(\"--receiver <address>\", \"Depositor / share receiver (required with --calldata-only)\")\n .action(async (opts) => {\n resolveVault(opts);\n const decimals = await vaultLib.getAssetDecimals();\n const amount = parseUnits(opts.amount, decimals);\n\n // --calldata-only: emit (optional wrap) + approve + deposit calldata. Needs\n // an explicit --receiver (no wallet to infer it from). With --use-eth on a\n // WETH vault, a WETH.deposit{value:shortfall}() wrap leg is prepended; the\n // shortfall is computed from the receiver's current WETH balance.\n if (isCalldataOnly()) {\n if (!opts.receiver) {\n console.error(\n chalk.red(\n \"--calldata-only requires --receiver <address> (the depositor / share receiver)\",\n ),\n );\n process.exit(1);\n }\n const receiver = validateAddress(opts.receiver, \"receiver\");\n const asset = await vaultLib.getAssetAddress();\n const assetSymbol = (await getPublicClient().readContract({\n address: asset,\n abi: ERC20_ABI,\n functionName: \"symbol\",\n })) as string;\n let currentWethBalance: bigint | undefined;\n if (opts.useEth) {\n currentWethBalance = (await getPublicClient().readContract({\n address: asset,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [receiver],\n })) as bigint;\n }\n try {\n emitCalldata(\n encodeDeposit(\n {\n vault: vaultLib.getVaultAddress(),\n receiver,\n asset,\n assetSymbol,\n assetDecimals: decimals,\n assets: amount,\n wrapEth: Boolean(opts.useEth),\n currentWethBalance,\n },\n getChain().id as ChainId,\n ),\n );\n } catch (err) {\n // e.g. --use-eth on a non-WETH vault — the encoder rejects it.\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n return;\n }\n\n // Pre-flight checks — catch issues before submitting transactions\n try {\n if (!opts.useEth) {\n await vaultLib.preflightDeposit(amount);\n }\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}\\n`));\n process.exit(1);\n }\n\n const spinner = ora(`Depositing ${opts.amount}...`).start();\n try {\n let hash;\n if (opts.useEth) {\n spinner.text = `Wrapping ETH + depositing ${opts.amount}...`;\n hash = await vaultLib.depositWithEthWrap(amount);\n } else {\n hash = await vaultLib.deposit(amount);\n }\n spinner.succeed(`Deposited: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Deposit failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nvaultCmd\n .command(\"info\")\n .description(\"Display vault state\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .action(async (opts) => {\n resolveVault(opts);\n const spinner = ora(\"Loading vault info...\").start();\n try {\n const info = await vaultLib.getVaultInfo();\n spinner.stop();\n console.log();\n console.log(chalk.bold(\"Vault Info\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Address: ${info.address}`);\n console.log(` Total Assets: ${info.totalAssets}`);\n console.log(` Agent Count: ${info.agentCount}`);\n console.log(` Redemptions Locked: ${info.redemptionsLocked}`);\n console.log(` Management Fee: ${Number(info.managementFeeBps) / 100}%`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load vault info\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nvaultCmd\n .command(\"balance\")\n .description(\"Show LP share balance and asset value\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--address <address>\", \"Address to check (default: your wallet)\")\n .action(async (opts) => {\n resolveVault(opts);\n const spinner = ora(\"Loading balance...\").start();\n try {\n const balance = await vaultLib.getBalance(opts.address as Address | undefined);\n spinner.stop();\n console.log();\n console.log(chalk.bold(\"LP Position\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Shares: ${balance.shares.toString()}`);\n console.log(` Asset Value: ${balance.assetsValue}`);\n console.log(` % of Vault: ${balance.percentOfVault}`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nvaultCmd\n .command(\"redeem\")\n .description(\"Redeem vault shares for the underlying asset (ERC-4626)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--shares <amount>\", \"Shares to redeem in whole-share units (default: all)\")\n .option(\"--receiver <address>\", \"Receiver of the underlying asset (default: your wallet)\")\n .option(\"--owner <address>\", \"Share owner whose shares burn (required with --calldata-only)\")\n .action(async (opts) => {\n resolveVault(opts);\n\n // Vault shares use (assetDecimals + _decimalsOffset) where offset = assetDecimals.\n // For USDC (6) this is 12. Treat --shares as whole-share units and scale by decimals * 2.\n const assetDecimals = await vaultLib.getAssetDecimals();\n const shareDecimals = assetDecimals * 2;\n\n // --calldata-only: emit redeem calldata. Needs explicit --shares (auto-\"all\"\n // reads your on-chain balance) and --owner (the share holder).\n if (isCalldataOnly()) {\n if (!opts.shares) {\n console.error(\n chalk.red(\n \"--calldata-only requires --shares (auto-'all' needs your on-chain share balance)\",\n ),\n );\n process.exit(1);\n }\n if (!opts.owner) {\n console.error(\n chalk.red(\n \"--calldata-only requires --owner <address> (the share holder whose shares burn)\",\n ),\n );\n process.exit(1);\n }\n const owner = validateAddress(opts.owner, \"owner\");\n const receiver = opts.receiver\n ? validateAddress(opts.receiver, \"receiver\")\n : owner;\n emitCalldata(\n encodeRedeem(\n {\n vault: vaultLib.getVaultAddress(),\n receiver,\n owner,\n shares: parseUnits(opts.shares, shareDecimals),\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n let shares: bigint;\n try {\n if (opts.shares) {\n shares = parseUnits(opts.shares, shareDecimals);\n } else {\n shares = await vaultLib.getShareBalance();\n if (shares === 0n) {\n console.error(chalk.red(\"\\n ✖ No shares to redeem.\\n\"));\n process.exit(1);\n }\n }\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}\\n`));\n process.exit(1);\n }\n\n if (opts.receiver && !isAddress(opts.receiver)) {\n console.error(chalk.red(`\\n ✖ Invalid receiver address: ${opts.receiver}\\n`));\n process.exit(1);\n }\n\n try {\n await vaultLib.preflightRedeem(shares);\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}\\n`));\n process.exit(1);\n }\n\n const sharesDisplay = formatUnits(shares, shareDecimals);\n const spinner = ora(`Redeeming ${sharesDisplay} shares...`).start();\n try {\n const { hash, assetsOut } = await vaultLib.redeem(\n shares,\n opts.receiver as Address | undefined,\n );\n spinner.succeed(`Redeemed: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n console.log(` Assets received: ${formatUnits(assetsOut, assetDecimals)}`);\n } catch (err) {\n spinner.fail(\"Redeem failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n// ── Strategy commands ──\nconst strategy = program.command(\"strategy\").description(\"Strategy templates — list, clone, propose\");\nregisterStrategyTemplateCommands(strategy);\n\n// ── Provider info ──\nprogram\n .command(\"providers\")\n .description(\"List available DeFi providers\")\n .action(async () => {\n const { MessariProvider, NansenProvider } = await import(\"./providers/research/index.js\");\n const providers = [new MoonwellProvider(), new UniswapProvider(), new MessariProvider(), new NansenProvider()];\n for (const p of providers) {\n const info = p.info();\n console.log(`\\n${info.name} (${info.type})`);\n console.log(` Capabilities: ${info.capabilities.join(\", \")}`);\n console.log(` Chains: ${info.supportedChains.map((c) => c.name).join(\", \")}`);\n }\n });\n\n// ── Chat commands (lazy-loaded — requires @xmtp/cli binary) ──\ntry {\n const { registerChatCommands } = await import(\"./commands/chat.js\");\n registerChatCommands(program);\n} catch {\n program\n .command(\"chat <name> [action] [actionArgs...]\")\n .description(\"Syndicate chat (XMTP) — requires @xmtp/cli\")\n .action(() => {\n console.error(chalk.red(\"XMTP CLI not available.\"));\n console.error(chalk.dim(\"Install with: npm install -g @xmtp/cli\"));\n console.error(chalk.dim(\"Or reinstall: npm i -g @sherwoodagent/cli\"));\n process.exit(1);\n });\n}\n\n// ── Session commands ──\nconst { registerSessionCommands } = await import(\"./commands/session.js\");\nregisterSessionCommands(program);\n\n// ── Venice commands ──\nregisterVeniceCommands(program);\n\n// ── Allowance commands ──\nregisterAllowanceCommands(program);\n\n// ── Identity commands ──\nregisterIdentityCommands(program);\n\n// ── Proposal commands ──\nregisterProposalCommands(program);\n\n// ── Governor commands ──\nregisterGovernorCommands(program);\n\n// ── Guardian delegation commands (V1.5) ──\nregisterGuardianCommands(program);\n\n// ── Research commands ──\nconst { registerResearchCommands } = await import(\"./commands/research.js\");\nregisterResearchCommands(program);\n\n// ── Agent commands ──\nconst { registerAgentCommands } = await import(\"./commands/agent.js\");\nregisterAgentCommands(program);\n\n// ── Trade commands ──\nconst { registerTradeCommands } = await import(\"./commands/trade.js\");\nregisterTradeCommands(program);\n\n// ── Grid commands ──\nimport { registerGridCommand } from './commands/grid.js';\nregisterGridCommand(program);\n\n// ── Config commands ──\nconst configCmd = program.command(\"config\");\n\nconfigCmd\n .command(\"set\")\n .description(\"Save settings to ~/.sherwood/config.json (persists across sessions)\")\n .option(\"--private-key <key>\", \"Wallet private key (0x-prefixed)\")\n .option(\"--vault <address>\", \"Default SyndicateVault address\")\n .option(\"--rpc <url>\", \"Custom RPC URL for the active --chain network\")\n .option(\"--notify-to <id>\", \"Destination for cron summaries (Telegram chat ID, phone, etc.)\")\n .option(\"--uniswap-api-key <key>\", \"Uniswap Trading API key (from developers.uniswap.org)\")\n .option(\"--venice-api-key <key>\", \"Venice AI inference API key\")\n .option(\"--anthropic-api-key <key>\", \"Anthropic Claude API key (for LLM judge)\")\n .option(\"--xmtp-group <subdomain:groupId>\", \"Cache an XMTP group ID for a syndicate (e.g. my-fund:abc123)\")\n .action((opts) => {\n let saved = false;\n\n if (opts.privateKey) {\n setPrivateKey(opts.privateKey);\n const account = getAccount();\n console.log(chalk.green(\"Private key saved to ~/.sherwood/config.json\"));\n console.log(chalk.dim(` Wallet: ${account.address}`));\n saved = true;\n }\n\n if (opts.vault) {\n const chainId = getChain().id;\n setChainContract(chainId, \"vault\", opts.vault);\n console.log(chalk.green(`Vault saved to ~/.sherwood/config.json (chain ${chainId})`));\n console.log(chalk.dim(` Vault: ${opts.vault}`));\n saved = true;\n }\n\n if (opts.rpc) {\n const network = getNetwork();\n setConfigRpcUrl(network, opts.rpc);\n console.log(chalk.green(`RPC URL saved for ${network}`));\n console.log(chalk.dim(` RPC: ${opts.rpc}`));\n saved = true;\n }\n\n if (opts.notifyTo) {\n setNotifyTo(opts.notifyTo);\n console.log(chalk.green(\"Notify destination saved to ~/.sherwood/config.json\"));\n console.log(chalk.dim(` Notify to: ${opts.notifyTo}`));\n saved = true;\n }\n\n if (opts.uniswapApiKey) {\n setUniswapApiKey(opts.uniswapApiKey);\n console.log(chalk.green(\"Uniswap API key saved to ~/.sherwood/config.json\"));\n saved = true;\n }\n\n if (opts.veniceApiKey) {\n setVeniceApiKey(opts.veniceApiKey);\n console.log(chalk.green(\"Venice API key saved to ~/.sherwood/config.json\"));\n saved = true;\n }\n\n if (opts.anthropicApiKey) {\n setAnthropicApiKey(opts.anthropicApiKey);\n console.log(chalk.green(\"Anthropic API key saved to ~/.sherwood/config.json\"));\n saved = true;\n }\n\n if (opts.xmtpGroup) {\n const parts = opts.xmtpGroup.split(\":\");\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n console.log(chalk.red(\"Format: --xmtp-group <subdomain>:<groupId>\"));\n process.exit(1);\n }\n cacheGroupId(parts[0], parts[1]);\n console.log(chalk.green(`XMTP group ID cached for ${parts[0]}`));\n console.log(chalk.dim(` Group ID: ${parts[1]}`));\n saved = true;\n }\n\n if (!saved) {\n console.log(chalk.red(\"Provide at least one of: --private-key, --vault, --rpc, --notify-to, --uniswap-api-key, --venice-api-key, --anthropic-api-key, --xmtp-group\"));\n process.exit(1);\n }\n });\n\nconfigCmd\n .command(\"show\")\n .description(\"Display current config for the active network\")\n .action(() => {\n const network = getNetwork();\n const chainId = getChain().id;\n const contracts = getChainContracts(chainId);\n const config = loadConfig();\n const customRpc = config.rpc?.[network];\n\n console.log();\n console.log(chalk.bold(`Sherwood Config`));\n console.log(chalk.dim(\"─\".repeat(50)));\n console.log(` Network: ${chalk.cyan(network)} (chain ${chainId})`);\n console.log(` RPC: ${customRpc ? chalk.green(customRpc) : chalk.dim(\"default\")}`);\n console.log(` Wallet: ${config.privateKey ? chalk.green(\"configured\") : chalk.dim(\"not set\")}`);\n console.log(` Agent ID: ${config.agentId ?? chalk.dim(\"not set\")}`);\n console.log(` Vault: ${contracts.vault ?? chalk.dim(\"not set\")}`);\n console.log(` Uniswap: ${getUniswapApiKey() ? chalk.green(\"API key configured\") : chalk.dim(\"not set\")}`);\n console.log(` Venice: ${getVeniceApiKey() ? chalk.green(\"API key configured\") : chalk.dim(\"not set\")}`);\n\n // Show XMTP group IDs\n const groupEntries = Object.entries(config.groupCache || {}).filter(([, v]) => v);\n if (groupEntries.length > 0) {\n console.log();\n console.log(chalk.bold(\" XMTP Groups\"));\n for (const [sub, gid] of groupEntries) {\n console.log(` ${sub}: ${chalk.cyan(gid)}`);\n }\n }\n\n console.log();\n console.log(chalk.dim(\" Config file: ~/.sherwood/config.json\"));\n console.log();\n });\n\nprogram.parse();\n","// TODO: Not yet implemented. All methods throw \"Not implemented\".\n// This provider is registered but non-functional.\n\nimport type { Address, Chain } from \"viem\";\nimport { base, baseSepolia } from \"viem/chains\";\nimport type { LendingProvider, ProviderInfo, DepositParams, BorrowParams, RepayParams, WithdrawParams, TxResult, LendingPosition } from \"../types.js\";\nimport { MOONWELL as getMoonwell } from \"../lib/addresses.js\";\n\nexport class MoonwellProvider implements LendingProvider {\n info(): ProviderInfo {\n return {\n name: \"moonwell\",\n type: \"lending\",\n capabilities: [\n \"lend.deposit\",\n \"lend.borrow\",\n \"lend.repay\",\n \"lend.withdraw\",\n \"lend.positions\",\n ],\n supportedChains: [base, baseSepolia],\n };\n }\n\n async depositCollateral(params: DepositParams): Promise<TxResult> {\n // TODO: Build and send tx via viem\n throw new Error(\"Not implemented — wire up viem client\");\n }\n\n async borrow(params: BorrowParams): Promise<TxResult> {\n throw new Error(\"Not implemented\");\n }\n\n async repay(params: RepayParams): Promise<TxResult> {\n throw new Error(\"Not implemented\");\n }\n\n async withdrawCollateral(params: WithdrawParams): Promise<TxResult> {\n throw new Error(\"Not implemented\");\n }\n\n async getPosition(account: Address): Promise<LendingPosition> {\n throw new Error(\"Not implemented\");\n }\n}\n","/**\n * Strategy template commands — clone, build calls, propose, rebalance, status.\n *\n * Replaces the old strategy registry commands with template-based workflow:\n * sherwood strategy list — show available templates\n * sherwood strategy clone — clone + initialize a template\n * sherwood strategy propose — clone + init + build calls + submit proposal (all-in-one)\n * sherwood strategy status — read portfolio allocations + state\n * sherwood strategy rebalance — sell-all/re-buy at current target weights (Portfolio only)\n */\n\nimport type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { parseUnits, formatUnits, isAddress, erc20Abi, encodeAbiParameters, decodeAbiParameters } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { writeFileSync, mkdirSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nimport { getPublicClient, getAccount, writeContractWithRetry, waitForReceipt, formatContractError } from \"../lib/client.js\";\nimport { getChain, getExplorerUrl, getNetwork, CHAIN_REGISTRY } from \"../lib/network.js\";\nimport { getCachedSwapRoute, cacheSwapRoute, type SwapRoute } from \"../lib/config.js\";\nimport { TOKENS, MOONWELL, VENICE, AERODROME, UNISWAP, STRATEGY_TEMPLATES, SYNTHRA, CHAINLINK } from \"../lib/addresses.js\";\nimport { BASE_STRATEGY_ABI, PORTFOLIO_STRATEGY_ABI, SYNDICATE_VAULT_ABI, HYPERLIQUID_PERP_STRATEGY_ABI } from \"../lib/abis.js\";\nimport { cloneTemplate } from \"../lib/clone.js\";\nimport { HYPERLIQUID_GRID_STRATEGY_ABI } from \"../grid/strategy-abi.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\nimport { formatBatch } from \"../lib/batch.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeStrategyDeploy, encodePropose, type ChainId } from \"@sherwoodagent/sdk\";\n\nimport * as moonwellBuilder from \"../strategies/moonwell-supply-template.js\";\nimport * as veniceBuilder from \"../strategies/venice-inference-template.js\";\nimport * as aerodromeBuilder from \"../strategies/aerodrome-lp-template.js\";\nimport * as wstethBuilder from \"../strategies/wsteth-moonwell-template.js\";\nimport * as mamoBuilder from \"../strategies/mamo-yield-template.js\";\nimport * as portfolioBuilder from \"../strategies/portfolio-template.js\";\nimport * as hyperliquidPerpBuilder from \"../strategies/hyperliquid-perp-template.js\";\nimport * as hyperliquidGridBuilder from \"../strategies/hyperliquid-grid-template.js\";\n\nimport { concat, numberToHex, size } from \"viem\";\n\nconst ZERO: Address = \"0x0000000000000000000000000000000000000000\";\n\n// ── Uniswap V3 swap routing helpers ──\n\n/**\n * Encode Uniswap V3 packed path: token (20 bytes) + fee (3 bytes) + token (20 bytes) [+ fee + token ...]\n */\nfunction encodeV3Path(tokens: Address[], fees: number[]): Hex {\n if (tokens.length !== fees.length + 1) throw new Error(\"tokens.length must be fees.length + 1\");\n const parts: Hex[] = [];\n for (let i = 0; i < tokens.length; i++) {\n parts.push(tokens[i].toLowerCase() as Hex);\n if (i < fees.length) {\n // fee as 3 bytes (uint24)\n parts.push(numberToHex(fees[i], { size: 3 }));\n }\n }\n return concat(parts);\n}\n\n/**\n * Build swapExtraData for the UniswapSwapAdapter.\n *\n * Mode 0 — single-hop: 0x00 + abi.encode(uint24 fee)\n * Mode 1 — multi-hop: 0x01 + abi.encode(bytes path)\n *\n * For Synthra (Robinhood), extraData is just abi.encode(uint24 fee) with no mode prefix.\n */\nfunction buildSwapExtraData(\n network: string,\n tokenIn: Address,\n tokenOut: Address,\n feeTier: number,\n hop?: { via: Address; feeIn: number; feeOut: number },\n): Hex {\n if (network === \"robinhood-testnet\") {\n // SynthraDirectAdapter: plain abi.encode(uint24 fee)\n return encodeAbiParameters([{ type: \"uint24\" }], [feeTier]);\n }\n\n if (hop) {\n // Multi-hop: tokenIn → hop.via → tokenOut\n const path = encodeV3Path([tokenIn, hop.via, tokenOut], [hop.feeIn, hop.feeOut]);\n const encoded = encodeAbiParameters([{ type: \"bytes\" }], [path]);\n return `0x01${encoded.slice(2)}` as Hex;\n }\n\n // Single-hop: mode 0\n const encoded = encodeAbiParameters([{ type: \"uint24\" }], [feeTier]);\n return `0x00${encoded.slice(2)}` as Hex;\n}\n\n/**\n * Auto-detect swap route for a token pair on Uniswap V3.\n * Returns { direct: true, feeTier } or { direct: false, hop } or null if no route found.\n */\nasync function detectSwapRoute(\n asset: Address,\n token: Address,\n preferredFeeTier: number,\n): Promise<{ extraData: Hex; routeDesc: string } | null> {\n const network = getNetwork();\n if (network === \"robinhood-testnet\") {\n return {\n extraData: buildSwapExtraData(network, asset, token, preferredFeeTier),\n routeDesc: `direct (fee ${preferredFeeTier})`,\n };\n }\n\n const chainId = CHAIN_REGISTRY[network].chain.id;\n\n // Check config cache first\n const cached = getCachedSwapRoute(chainId, asset, token);\n if (cached) {\n const extraData = cached.hop\n ? buildSwapExtraData(network, asset, token, 0, {\n via: cached.hop.via as Address,\n feeIn: cached.hop.feeIn,\n feeOut: cached.hop.feeOut,\n })\n : buildSwapExtraData(network, asset, token, cached.feeTier);\n const desc = cached.hop\n ? `cached multi-hop: ${cached.hop.feeIn}→WETH→${cached.hop.feeOut}`\n : `cached direct (fee ${cached.feeTier})`;\n return { extraData, routeDesc: desc };\n }\n\n const publicClient = getPublicClient();\n const quoterAddr = UNISWAP().QUOTER_V2;\n const quoterAbi = [{\n type: \"function\",\n name: \"quoteExactInputSingle\",\n inputs: [{ type: \"tuple\", components: [\n { type: \"address\", name: \"tokenIn\" },\n { type: \"address\", name: \"tokenOut\" },\n { type: \"uint256\", name: \"amountIn\" },\n { type: \"uint24\", name: \"fee\" },\n { type: \"uint160\", name: \"sqrtPriceLimitX96\" },\n ]}],\n outputs: [\n { type: \"uint256\" }, { type: \"uint160\" }, { type: \"uint32\" }, { type: \"uint256\" },\n ],\n stateMutability: \"nonpayable\",\n }] as const;\n\n // 1. Try direct at preferred fee tier\n const testAmount = asset.toLowerCase() === TOKENS().USDC.toLowerCase() ? 1_000_000n : 1_000_000_000_000_000n; // 1 USDC or 0.001 WETH\n const feeTiers = [preferredFeeTier, 10000, 3000, 500].filter((v, i, a) => a.indexOf(v) === i);\n\n for (const fee of feeTiers) {\n try {\n await publicClient.simulateContract({\n address: quoterAddr,\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [{ tokenIn: asset, tokenOut: token, amountIn: testAmount, fee, sqrtPriceLimitX96: 0n }],\n });\n cacheSwapRoute(chainId, asset, token, { mode: \"direct\", feeTier: fee, detectedAt: Math.floor(Date.now() / 1000) });\n return {\n extraData: buildSwapExtraData(network, asset, token, fee),\n routeDesc: `direct (fee ${fee})`,\n };\n } catch {\n // No pool at this fee tier\n }\n }\n\n // 2. Try multi-hop via WETH\n const weth = TOKENS().WETH;\n if (asset.toLowerCase() === weth.toLowerCase()) return null; // Already tried direct with WETH\n\n // Find best USDC→WETH fee\n let bestAssetToWethFee: number | null = null;\n for (const fee of [500, 3000, 10000]) {\n try {\n await publicClient.simulateContract({\n address: quoterAddr,\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [{ tokenIn: asset, tokenOut: weth, amountIn: testAmount, fee, sqrtPriceLimitX96: 0n }],\n });\n bestAssetToWethFee = fee;\n break; // 500 is cheapest, prefer it\n } catch {}\n }\n if (!bestAssetToWethFee) return null;\n\n // Find best WETH→token fee\n const wethTestAmount = 1_000_000_000_000_000n; // 0.001 WETH\n for (const fee of feeTiers) {\n try {\n await publicClient.simulateContract({\n address: quoterAddr,\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [{ tokenIn: weth, tokenOut: token, amountIn: wethTestAmount, fee, sqrtPriceLimitX96: 0n }],\n });\n const hop = { via: weth, feeIn: bestAssetToWethFee, feeOut: fee };\n cacheSwapRoute(chainId, asset, token, { mode: \"multi-hop\", feeTier: 0, hop, detectedAt: Math.floor(Date.now() / 1000) });\n return {\n extraData: buildSwapExtraData(network, asset, token, 0, hop),\n routeDesc: `multi-hop: ${bestAssetToWethFee}→WETH→${fee}`,\n };\n } catch {}\n }\n\n return null; // No route found\n}\n\n// ── Template definitions ──\n\ninterface TemplateDef {\n name: string;\n key: string;\n description: string;\n addressKey: keyof ReturnType<typeof STRATEGY_TEMPLATES>;\n}\n\nconst TEMPLATES: TemplateDef[] = [\n {\n name: \"Moonwell Supply\",\n key: \"moonwell-supply\",\n description: \"Supply tokens to Moonwell lending market, earn yield\",\n addressKey: \"MOONWELL_SUPPLY\",\n },\n {\n name: \"Aerodrome LP\",\n key: \"aerodrome-lp\",\n description: \"Provide liquidity on Aerodrome DEX + optional gauge staking\",\n addressKey: \"AERODROME_LP\",\n },\n {\n name: \"Venice Inference\",\n key: \"venice-inference\",\n description: \"Stake VVV for sVVV — Venice private AI inference\",\n addressKey: \"VENICE_INFERENCE\",\n },\n {\n name: \"wstETH Moonwell Yield\",\n key: \"wsteth-moonwell\",\n description: \"WETH → wstETH → Moonwell — stack Lido + lending yield\",\n addressKey: \"WSTETH_MOONWELL\",\n },\n {\n name: \"Mamo Yield\",\n key: \"mamo-yield\",\n description: \"Deposit into Mamo for optimized yield across Moonwell + Morpho vaults\",\n addressKey: \"MAMO_YIELD\",\n },\n {\n name: \"Portfolio\",\n key: \"portfolio\",\n description: \"Weighted portfolio of tokens (stock tokens, crypto) with rebalancing\",\n addressKey: \"PORTFOLIO\",\n },\n {\n name: \"Hyperliquid Perp\",\n key: \"hyperliquid-perp\",\n description: \"Leveraged perp trading on Hyperliquid via HyperEVM precompiles\",\n addressKey: \"HYPERLIQUID_PERP\",\n },\n {\n name: \"Hyperliquid Grid\",\n key: \"hyperliquid-grid\",\n description: \"ATR-based grid trading on Hyperliquid via HyperEVM precompiles\",\n addressKey: \"HYPERLIQUID_GRID\",\n },\n];\n\nfunction resolveTemplate(key: string): { def: TemplateDef; address: Address } {\n const def = TEMPLATES.find((t) => t.key === key);\n if (!def) {\n console.error(chalk.red(`Unknown template: ${key}`));\n console.error(chalk.dim(`Available: ${TEMPLATES.map((t) => t.key).join(\", \")}`));\n process.exit(1);\n }\n const address = STRATEGY_TEMPLATES()[def.addressKey];\n if (address === ZERO) {\n console.error(chalk.red(`Template \"${def.name}\" not deployed on this network.`));\n process.exit(1);\n }\n return { def, address };\n}\n\n// ── Helpers for building init data per template ──\n\n/**\n * Pure (no-RPC) derivation of the assets a propose call will pull from the\n * vault. Mirrors the asset/amount slice of `buildInitDataForTemplate` so the\n * propose preflight can balance-check the vault BEFORE clone + init burns\n * any gas. Returns one entry per token the vault has to fund — single\n * entry for most templates, two for aerodrome-lp (tokenA + tokenB).\n *\n * Templates whose amount is `0n` (hyperliquid-perp / -grid in dynamic-all\n * mode, wsteth-moonwell without --amount) intentionally return entries\n * with `amount === 0n`; the caller short-circuits on those.\n *\n * Keep in sync with `buildInitDataForTemplate` per-branch logic. Diverging\n * here only weakens the preflight guard — the real values still come from\n * `buildInitDataForTemplate`, so we'd just miss a warning, never produce\n * an inconsistent on-chain call.\n */\nfunction computeProposalAssetChecks(\n templateKey: string,\n opts: Record<string, string | boolean | undefined>,\n): { asset: Address; amount: bigint; label: string }[] {\n if (templateKey === \"moonwell-supply\" || templateKey === \"mamo-yield\") {\n if (!opts.amount) return [];\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: token.toUpperCase() }];\n }\n\n if (templateKey === \"venice-inference\") {\n if (!opts.amount) return [];\n const assetSymbol = (opts.asset as string) || \"USDC\";\n const asset = resolveToken(assetSymbol);\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: assetSymbol.toUpperCase() }];\n }\n\n if (templateKey === \"aerodrome-lp\") {\n // Aerodrome needs both legs of the pair funded. We can't compute the\n // per-leg parseUnits without a decimals() RPC, so we fall back to a\n // raw-units balance check (vault must hold at least `amountA` raw of\n // tokenA AND `amountB` raw of tokenB). Worst case: a stricter check\n // than needed, never permissive.\n if (!opts.tokenA || !opts.tokenB || !opts.amountA || !opts.amountB) return [];\n // amountA/amountB are human strings — without decimals we can't normalize.\n // Skip the precise check for aerodrome and let buildInitDataForTemplate\n // handle errors. (Other templates cover the common --amount footgun.)\n return [];\n }\n\n if (templateKey === \"wsteth-moonwell\") {\n if (!opts.amount) return []; // dynamic-all mode\n return [{\n asset: TOKENS().WETH,\n amount: parseUnits(opts.amount as string, 18),\n label: \"WETH\",\n }];\n }\n\n if (templateKey === \"portfolio\") {\n if (!opts.amount) return [];\n const defaultAsset = getNetwork() === \"robinhood-testnet\" ? \"WETH\" : \"USDC\";\n const assetSymbol = (opts.asset as string) || defaultAsset;\n const asset = resolveToken(assetSymbol);\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: assetSymbol.toUpperCase() }];\n }\n\n if (templateKey === \"hyperliquid-perp\" || templateKey === \"hyperliquid-grid\") {\n if (!opts.amount) return []; // dynamic-all mode — skip check\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: token.toUpperCase() }];\n }\n\n return [];\n}\n\nasync function buildInitDataForTemplate(\n templateKey: string,\n opts: Record<string, string | boolean | undefined>,\n vault: Address,\n): Promise<{ initData: Hex; asset: Address; assetAmount: bigint; extraApprovals?: { token: Address; amount: bigint }[] }> {\n if (templateKey === \"moonwell-supply\") {\n if (!opts.amount) {\n console.error(chalk.red(\"--amount is required for moonwell-supply template\"));\n process.exit(1);\n }\n const token = (opts.token as string) || \"USDC\";\n const underlying = resolveToken(token);\n const mToken = resolveMToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n const supplyAmount = parseUnits(opts.amount as string, decimals);\n const minRedeem = parseUnits((opts.minRedeem as string) || opts.amount as string, decimals);\n\n return {\n initData: moonwellBuilder.buildInitData(underlying, mToken, supplyAmount, minRedeem),\n asset: underlying,\n assetAmount: supplyAmount,\n };\n }\n\n if (templateKey === \"venice-inference\") {\n if (!opts.amount) {\n console.error(chalk.red(\"--amount is required for venice-inference template\"));\n process.exit(1);\n }\n const assetSymbol = (opts.asset as string) || \"USDC\";\n const asset = resolveToken(assetSymbol);\n const vvv = VENICE().VVV;\n const isDirect = asset.toLowerCase() === vvv.toLowerCase();\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n const assetAmount = parseUnits(opts.amount as string, decimals);\n const agent = (opts.agent as Address) || getAccount().address;\n const isSingleHop = !!opts.singleHop;\n\n // Auto-quote minVVV if not specified (non-direct paths only)\n let minVVV = 0n;\n if (!isDirect) {\n if (opts.minVvv) {\n minVVV = parseUnits(opts.minVvv as string, 18);\n } else {\n // Quote expected VVV out and apply 5% slippage\n const publicClient = getPublicClient();\n const aeroRouterAbi = [{\n name: \"getAmountsOut\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"routes\", type: \"tuple[]\", components: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"stable\", type: \"bool\" },\n { name: \"factory\", type: \"address\" },\n ]},\n ],\n outputs: [{ name: \"amounts\", type: \"uint256[]\" }],\n }] as const;\n\n const routes = isSingleHop\n ? [{ from: asset, to: vvv, stable: false, factory: AERODROME().FACTORY }]\n : [\n { from: asset, to: TOKENS().WETH, stable: false, factory: AERODROME().FACTORY },\n { from: TOKENS().WETH, to: vvv, stable: false, factory: AERODROME().FACTORY },\n ];\n\n try {\n const amounts = await publicClient.readContract({\n address: AERODROME().ROUTER,\n abi: aeroRouterAbi,\n functionName: \"getAmountsOut\",\n args: [assetAmount, routes],\n });\n const expectedVVV = amounts[amounts.length - 1];\n // 5% slippage: minVVV = expectedVVV * 95 / 100\n minVVV = (expectedVVV * 95n) / 100n;\n console.log(chalk.dim(` Auto-quoted minVVV: ${(Number(minVVV) / 1e18).toFixed(4)} VVV (5% slippage on ~${(Number(expectedVVV) / 1e18).toFixed(4)} VVV)`));\n } catch {\n console.error(chalk.red(\"Could not quote USDC→VVV price. Pass --min-vvv <amount> manually.\"));\n process.exit(1);\n }\n }\n }\n\n const params: veniceBuilder.VeniceInferenceInitParams = {\n asset,\n weth: isDirect ? ZERO : TOKENS().WETH,\n vvv,\n sVVV: VENICE().STAKING,\n aeroRouter: isDirect ? ZERO : AERODROME().ROUTER,\n aeroFactory: isDirect ? ZERO : AERODROME().FACTORY,\n agent,\n assetAmount,\n minVVV,\n deadlineOffset: 300n,\n singleHop: isSingleHop,\n };\n\n return {\n initData: veniceBuilder.buildInitData(params),\n asset,\n assetAmount,\n };\n }\n\n if (templateKey === \"aerodrome-lp\") {\n for (const flag of [\"tokenA\", \"tokenB\", \"amountA\", \"amountB\", \"lpToken\"]) {\n if (!opts[flag]) {\n console.error(chalk.red(`--${flag.replace(/([A-Z])/g, \"-$1\").toLowerCase()} is required for aerodrome-lp template`));\n process.exit(1);\n }\n }\n const tokenA = opts.tokenA as Address;\n const tokenB = opts.tokenB as Address;\n const publicClient = getPublicClient();\n const [decimalsA, decimalsB] = await Promise.all([\n publicClient.readContract({ address: tokenA, abi: erc20Abi, functionName: \"decimals\" }),\n publicClient.readContract({ address: tokenB, abi: erc20Abi, functionName: \"decimals\" }),\n ]);\n const amountA = parseUnits(opts.amountA as string, decimalsA);\n const amountB = parseUnits(opts.amountB as string, decimalsB);\n const minAOut = parseUnits((opts.minAOut as string) || \"0\", decimalsA);\n const minBOut = parseUnits((opts.minBOut as string) || \"0\", decimalsB);\n\n const params: aerodromeBuilder.AerodromeLPInitParams = {\n tokenA,\n tokenB,\n stable: !!opts.stable,\n factory: AERODROME().FACTORY,\n router: AERODROME().ROUTER,\n gauge: (opts.gauge as Address) || ZERO,\n lpToken: opts.lpToken as Address,\n amountADesired: amountA,\n amountBDesired: amountB,\n amountAMin: amountA, // use desired as min for now\n amountBMin: amountB,\n minAmountAOut: minAOut,\n minAmountBOut: minBOut,\n };\n\n return {\n initData: aerodromeBuilder.buildInitData(params),\n asset: tokenA,\n assetAmount: amountA,\n extraApprovals: [{ token: tokenB, amount: amountB }],\n };\n }\n\n if (templateKey === \"wsteth-moonwell\") {\n const supplyAmount = opts.amount ? parseUnits(opts.amount as string, 18) : 0n; // WETH = 18 decimals; 0 => use full vault balance at execute time\n const slippageBps = BigInt((opts.slippage as string) || \"500\"); // default 5% slippage\n // Per-unit rates (1e18-scaled) — Aerodrome wstETH/WETH stable pool trades\n // near 1:1, so default the expected rate to 1e18. Slippage cuts from that.\n // Rates scale with amountIn at execute time → dynamic-all mode is safe.\n const ONE = 10n ** 18n;\n const minWstethOutPerWeth = (ONE * (10000n - slippageBps)) / 10000n;\n const minWethOutPerWsteth = (ONE * (10000n - slippageBps)) / 10000n;\n\n const params: wstethBuilder.WstETHMoonwellInitParams = {\n weth: TOKENS().WETH,\n wsteth: TOKENS().wstETH,\n mwsteth: MOONWELL().mWstETH,\n aeroRouter: AERODROME().ROUTER,\n aeroFactory: AERODROME().FACTORY,\n chainlinkWstethEthFeed: CHAINLINK().WSTETH_ETH_FEED,\n supplyAmount,\n minWstethOutPerWeth,\n minWethOutPerWsteth,\n deadlineOffset: 300n,\n };\n\n return {\n initData: wstethBuilder.buildInitData(params),\n asset: TOKENS().WETH,\n assetAmount: supplyAmount,\n };\n }\n\n if (templateKey === \"mamo-yield\") {\n if (!opts.amount) {\n console.error(chalk.red(\"--amount is required for mamo-yield template\"));\n process.exit(1);\n }\n if (!opts.mamoFactory) {\n console.error(chalk.red(\"--mamo-factory is required for mamo-yield template\"));\n process.exit(1);\n }\n const token = (opts.token as string) || \"USDC\";\n const underlying = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n const amount = parseUnits(opts.amount as string, decimals);\n const minRedeemAmount = parseUnits((opts.minRedeem as string) || opts.amount as string, decimals);\n\n return {\n initData: mamoBuilder.buildInitData(underlying, opts.mamoFactory as Address, minRedeemAmount),\n asset: underlying,\n assetAmount: amount,\n };\n }\n\n if (templateKey === \"portfolio\") {\n if (!opts.amount) { console.error(chalk.red(\"--amount is required for portfolio template\")); process.exit(1); }\n if (!opts.tokens || !opts.weights) {\n console.error(chalk.red(\"--tokens and --weights are required for portfolio template\"));\n console.error(chalk.dim(\" --tokens: comma-separated token addresses or symbols\"));\n console.error(chalk.dim(\" --weights: comma-separated bps (must sum to 10000)\"));\n process.exit(1);\n }\n const tokens = TOKENS();\n const defaultAsset = getNetwork() === \"robinhood-testnet\" ? \"WETH\" : \"USDC\";\n const assetSymbol = (opts.asset as string) || defaultAsset;\n const asset = resolveToken(assetSymbol);\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n const totalAmount = parseUnits(opts.amount as string, decimals);\n const maxSlippageBps = Number((opts.maxSlippage as string) || \"500\");\n const feeTier = (opts.feeTier as string) || \"3000\";\n\n const tokenAddrs = (opts.tokens as string).split(\",\").map((t) => {\n const trimmed = t.trim();\n if (isAddress(trimmed)) return trimmed as Address;\n const allTokens = tokens as Record<string, Address>;\n const resolved = allTokens[trimmed.toUpperCase()];\n if (resolved && resolved !== ZERO) return resolved;\n console.error(chalk.red(`Unknown token: ${trimmed}`)); process.exit(1);\n });\n const weightsBps = (opts.weights as string).split(\",\").map((w) => Number(w.trim()));\n if (tokenAddrs.length !== weightsBps.length) { console.error(chalk.red(\"--tokens and --weights must have same length\")); process.exit(1); }\n if (weightsBps.reduce((a, b) => a + b, 0) !== 10000) { console.error(chalk.red(`Weights must sum to 10000`)); process.exit(1); }\n\n const swapAdapter = (opts.swapAdapter as Address) || resolveSwapAdapter();\n const chainlinkVerifier = CHAINLINK().VERIFIER_PROXY;\n\n // Auto-detect swap routes for each token\n console.log(chalk.dim(\" Detecting swap routes...\"));\n const allocations: portfolioBuilder.BasketAllocation[] = [];\n for (let i = 0; i < tokenAddrs.length; i++) {\n const token = tokenAddrs[i];\n const route = await detectSwapRoute(asset, token, Number(feeTier));\n if (!route) {\n console.error(chalk.red(`No swap route found for ${token}. No Uniswap V3 pool (direct or via WETH).`));\n process.exit(1);\n }\n console.log(chalk.dim(` ${token.slice(0, 10)}... → ${route.routeDesc}`));\n allocations.push({\n token, weightBps: weightsBps[i],\n swapExtraData: route.extraData,\n // Default Chainlink Data Streams report decimals: 18 for crypto pairs,\n // 8 for tokenized stocks. Tokenized-stock baskets should override\n // explicitly via the CLI flag once exposed; 18 keeps current crypto\n // baskets (TSLA/AMZN/NFLX on Robinhood Chain are 18-dec) correct.\n priceDecimals: 18,\n });\n }\n return {\n initData: portfolioBuilder.buildInitData(asset, swapAdapter, chainlinkVerifier, allocations, totalAmount, maxSlippageBps),\n asset, assetAmount: totalAmount,\n };\n }\n\n if (templateKey === \"hyperliquid-perp\") {\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n // Omit --amount to use the vault's full asset balance at execute time (dynamic-all mode).\n const depositAmount = opts.amount ? parseUnits(opts.amount as string, decimals) : 0n;\n const leverage = Number((opts.leverage as string) || \"10\");\n const assetIndex = Number((opts.assetIndex as string) || \"0\");\n const maxPosition = parseUnits((opts.maxPosition as string) || \"100000\", decimals);\n const maxTradesDay = Number((opts.maxTradesPerDay as string) || \"50\");\n return {\n initData: hyperliquidPerpBuilder.buildInitData(asset, depositAmount, assetIndex, leverage, maxPosition, maxTradesDay),\n asset, assetAmount: depositAmount,\n };\n }\n\n if (templateKey === \"hyperliquid-grid\") {\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n const depositAmount = opts.amount ? parseUnits(opts.amount as string, decimals) : 0n;\n const leverage = Number((opts.leverage as string) || \"5\");\n const maxOrderSize = parseUnits((opts.maxOrderSize as string) || \"10000\", decimals);\n const maxOrdersPerTick = Number((opts.maxOrdersPerTick as string) || \"20\");\n const assetIndices = ((opts.assetIndices as string) || \"0\")\n .split(\",\")\n .map((s) => Number(s.trim()))\n .filter((n) => !Number.isNaN(n));\n return {\n initData: hyperliquidGridBuilder.buildInitData(asset, depositAmount, leverage, maxOrderSize, maxOrdersPerTick, assetIndices),\n asset, assetAmount: depositAmount,\n };\n }\n\n throw new Error(`No init builder for template: ${templateKey}`);\n}\n\nfunction buildCallsForTemplate(\n templateKey: string,\n clone: Address,\n asset: Address,\n assetAmount: bigint,\n extraApprovals?: { token: Address; amount: bigint }[],\n): { executeCalls: BatchCall[]; settleCalls: BatchCall[] } {\n if (templateKey === \"moonwell-supply\") {\n return {\n executeCalls: moonwellBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: moonwellBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"venice-inference\") {\n return {\n executeCalls: veniceBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: veniceBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"aerodrome-lp\") {\n const tokenB = extraApprovals?.[0]?.token ?? ZERO;\n const amountB = extraApprovals?.[0]?.amount ?? 0n;\n return {\n executeCalls: aerodromeBuilder.buildExecuteCalls(clone, asset, assetAmount, tokenB, amountB),\n settleCalls: aerodromeBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"wsteth-moonwell\") {\n return {\n executeCalls: wstethBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: wstethBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"mamo-yield\") {\n return {\n executeCalls: mamoBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: mamoBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"portfolio\") {\n return {\n executeCalls: portfolioBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: portfolioBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"hyperliquid-perp\") {\n return {\n executeCalls: hyperliquidPerpBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: hyperliquidPerpBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"hyperliquid-grid\") {\n return {\n executeCalls: hyperliquidGridBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: hyperliquidGridBuilder.buildSettleCalls(clone),\n };\n }\n\n throw new Error(`No call builder for template: ${templateKey}`);\n}\n\n// ── Token resolution ──\n\nfunction resolveSwapAdapter(): Address {\n const network = getNetwork();\n if (network === \"robinhood-testnet\") {\n if (SYNTHRA().ROUTER === ZERO) { console.error(chalk.red(\"Synthra DEX not available\")); process.exit(1); }\n return \"0xdae81cDCfcB14c56fCeB788A147Fcd6CbEdfEeca\" as Address;\n }\n const adapterAddr = UNISWAP().SWAP_ADAPTER;\n if (adapterAddr !== ZERO) return adapterAddr;\n console.error(chalk.red(\"UniswapSwapAdapter not deployed yet. Use --swap-adapter to specify manually.\"));\n process.exit(1);\n}\n\nfunction resolveToken(symbolOrAddress: string): Address {\n if (isAddress(symbolOrAddress)) return symbolOrAddress as Address;\n const upper = symbolOrAddress.toUpperCase();\n const tokens = TOKENS();\n const tokenMap: Record<string, Address> = {\n USDC: tokens.USDC,\n WETH: tokens.WETH,\n DAI: tokens.DAI,\n AERO: tokens.AERO,\n VVV: VENICE().VVV,\n };\n const addr = tokenMap[upper];\n if (!addr || addr === ZERO) {\n console.error(chalk.red(`Unknown token: ${symbolOrAddress}`));\n process.exit(1);\n }\n return addr;\n}\n\nfunction resolveMToken(tokenSymbol: string): Address {\n const upper = tokenSymbol.toUpperCase();\n const moonwell = MOONWELL();\n const mTokenMap: Record<string, Address> = {\n USDC: moonwell.mUSDC,\n WETH: moonwell.mWETH,\n };\n const addr = mTokenMap[upper];\n if (!addr || addr === ZERO) {\n console.error(chalk.red(`No Moonwell market for: ${tokenSymbol}`));\n process.exit(1);\n }\n return addr;\n}\n\nfunction serializeCalls(calls: BatchCall[]): string {\n return JSON.stringify(\n calls.map((c) => ({\n target: c.target,\n data: c.data,\n value: c.value.toString(),\n })),\n null,\n 2,\n );\n}\n\n// ── Commands ──\n\nexport function registerStrategyTemplateCommands(strategy: Command): void {\n // ── strategy list ──\n\n strategy\n .command(\"list\")\n .description(\"List available strategy templates\")\n .action(() => {\n const templates = STRATEGY_TEMPLATES();\n const network = getNetwork();\n\n console.log();\n console.log(chalk.bold(\"Strategy Templates\"), chalk.dim(`(${network})`));\n console.log(chalk.dim(\"─\".repeat(60)));\n\n let availableCount = 0;\n for (const t of TEMPLATES) {\n const addr = templates[t.addressKey];\n if (addr !== ZERO) {\n availableCount++;\n console.log();\n console.log(` ${chalk.bold(t.name)} (${chalk.cyan(t.key)})`);\n console.log(` ${t.description}`);\n console.log(` Template: ${chalk.green(addr)}`);\n }\n }\n\n if (availableCount === 0) {\n console.log();\n console.log(chalk.yellow(\" No strategy templates deployed on this network.\"));\n }\n\n const unavailable = TEMPLATES.filter((t) => templates[t.addressKey] === ZERO);\n if (unavailable.length > 0) {\n console.log();\n console.log(chalk.dim(` Not available on ${network}:`));\n for (const t of unavailable) {\n console.log(chalk.dim(` ${t.name} (${t.key})`));\n }\n }\n\n console.log();\n console.log(chalk.dim(\"Clone a template: sherwood strategy clone <template> --vault <addr> ...\"));\n console.log(chalk.dim(\"Full proposal: sherwood strategy propose <template> --vault <addr> ...\"));\n console.log();\n });\n\n // ── strategy clone ──\n\n strategy\n .command(\"clone\")\n .description(\"Clone a strategy template and initialize it\")\n .argument(\"<template>\", \"Template: moonwell-supply, aerodrome-lp, venice-inference, wsteth-moonwell, mamo-yield, portfolio, hyperliquid-perp, hyperliquid-grid\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n // moonwell-supply / wsteth-moonwell\n .option(\"--amount <n>\", \"Asset amount to deploy\")\n .option(\"--min-redeem <n>\", \"Min asset on settlement (Moonwell)\")\n .option(\"--token <symbol>\", \"Asset token symbol (default: USDC)\")\n // venice-inference\n .option(\"--asset <symbol>\", \"Asset token (USDC, VVV, or address)\")\n .option(\"--agent <address>\", \"Agent wallet (Venice, default: your wallet)\")\n .option(\"--min-vvv <n>\", \"Min VVV from swap (Venice)\")\n .option(\"--single-hop\", \"Single-hop Aerodrome swap (Venice)\")\n // aerodrome-lp\n .option(\"--token-a <address>\", \"Token A (Aerodrome)\")\n .option(\"--token-b <address>\", \"Token B (Aerodrome)\")\n .option(\"--amount-a <n>\", \"Token A amount (Aerodrome)\")\n .option(\"--amount-b <n>\", \"Token B amount (Aerodrome)\")\n .option(\"--stable\", \"Stable pool (Aerodrome)\")\n .option(\"--gauge <address>\", \"Gauge address (Aerodrome)\")\n .option(\"--lp-token <address>\", \"LP token address (Aerodrome)\")\n .option(\"--min-a-out <n>\", \"Min token A on settle (Aerodrome)\")\n .option(\"--min-b-out <n>\", \"Min token B on settle (Aerodrome)\")\n // wsteth-moonwell\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (wstETH, default: 500 = 5%)\")\n // mamo-yield\n .option(\"--mamo-factory <address>\", \"Mamo StrategyFactory address (Mamo)\")\n // portfolio\n .option(\"--tokens <list>\", \"Comma-separated token addresses or symbols (Portfolio)\")\n .option(\"--weights <list>\", \"Comma-separated weights in bps, must sum to 10000 (Portfolio)\")\n .option(\"--max-slippage <bps>\", \"Max slippage bps (Portfolio, default: 500)\")\n .option(\"--fee-tier <n>\", \"Pool fee tier (Portfolio, default: 3000)\")\n .option(\"--swap-adapter <address>\", \"Swap adapter address (Portfolio)\")\n // hyperliquid-perp\n .option(\"--leverage <number>\", \"Leverage multiplier (Hyperliquid Perp, default: 10)\")\n .option(\"--asset-index <number>\", \"Perp asset index (Hyperliquid Perp, default: 0 for BTC)\")\n .option(\"--max-position <amount>\", \"Max position size in USD (Hyperliquid Perp, default: 100000)\")\n .option(\"--max-trades-per-day <n>\", \"Max trades per day (Hyperliquid Perp, default: 50)\")\n .option(\"--max-order-size <amount>\", \"Max single-order size in asset units (Hyperliquid Grid, default: 10000)\")\n .option(\"--max-orders-per-tick <n>\", \"Max orders per tick (Hyperliquid Grid, default: 20)\")\n .option(\"--asset-indices <list>\", \"Comma-separated perp asset indices (Hyperliquid Grid, default: 0)\")\n .action(async (templateKey: string, opts) => {\n const vault = opts.vault as Address;\n if (!isAddress(vault)) {\n console.error(chalk.red(\"Invalid vault address\"));\n process.exit(1);\n }\n\n const { def, address: templateAddr } = resolveTemplate(templateKey);\n\n // 1. Clone\n const cloneSpinner = ora(`Cloning ${def.name} template...`).start();\n let clone: Address;\n let cloneHash: Hex;\n try {\n const result = await cloneTemplate(templateAddr);\n clone = result.clone;\n cloneHash = result.hash;\n cloneSpinner.succeed(`Cloned: ${chalk.green(clone)}`);\n console.log(chalk.dim(` Tx: ${getExplorerUrl(cloneHash)}`));\n } catch (err) {\n cloneSpinner.fail(\"Clone failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 2. Initialize\n const initSpinner = ora(\"Initializing strategy...\").start();\n try {\n const { initData } = await buildInitDataForTemplate(templateKey, opts, vault);\n const account = getAccount();\n\n const initHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"initialize\",\n args: [vault, account.address, initData],\n });\n\n const receipt = await waitForReceipt(initHash);\n if (receipt.status === \"reverted\") {\n throw new Error(\"Initialize transaction reverted on-chain\");\n }\n initSpinner.succeed(\"Initialized\");\n } catch (err) {\n initSpinner.fail(\"Initialize failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 3. HyperCore registration (grid + perp)\n // BaseStrategy.initialize() writes address(this) to slot 0 (_hcSelf). HC\n // reads slot 0 post-block via FirstStorageSlot variant — no nonce\n // derivation needed.\n if (templateKey === \"hyperliquid-grid\" || templateKey === \"hyperliquid-perp\") {\n const hcSpinner = ora(\"Registering clone with HyperCore...\").start();\n try {\n const account = getAccount();\n const hcHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: templateKey === \"hyperliquid-grid\" ? HYPERLIQUID_GRID_STRATEGY_ABI : HYPERLIQUID_PERP_STRATEGY_ABI,\n functionName: \"finalizeForHyperCore\",\n args: [0n, 1, 0n], // token=USDC, variant=FirstStorageSlot(1), nonce unused\n });\n await waitForReceipt(hcHash);\n hcSpinner.succeed(\"HyperCore registration sent (active after next block)\");\n } catch (err) {\n hcSpinner.warn(\"HyperCore registration failed — run finalizeForHyperCore manually\");\n console.error(chalk.yellow(formatContractError(err)));\n }\n }\n\n console.log();\n console.log(chalk.bold(\"Strategy clone ready:\"), chalk.green(clone));\n console.log(chalk.dim(\"Use this address in your proposal batch calls.\"));\n console.log();\n });\n\n // ── strategy init ──\n\n strategy\n .command(\"init\")\n .description(\"Initialize an already-deployed but uninitialized strategy clone\")\n .argument(\"<template>\", \"Template: moonwell-supply, aerodrome-lp, venice-inference, wsteth-moonwell, mamo-yield, portfolio, hyperliquid-perp, hyperliquid-grid\")\n .requiredOption(\"--clone <address>\", \"Clone address to initialize\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n // moonwell-supply / wsteth-moonwell\n .option(\"--amount <n>\", \"Asset amount to deploy\")\n .option(\"--min-redeem <n>\", \"Min asset on settlement (Moonwell)\")\n .option(\"--token <symbol>\", \"Asset token symbol (default: USDC)\")\n // venice-inference\n .option(\"--asset <symbol>\", \"Asset token (USDC, VVV, or address)\")\n .option(\"--agent <address>\", \"Agent wallet (Venice, default: your wallet)\")\n .option(\"--min-vvv <n>\", \"Min VVV from swap (Venice)\")\n .option(\"--single-hop\", \"Single-hop Aerodrome swap (Venice)\")\n // aerodrome-lp\n .option(\"--token-a <address>\", \"Token A (Aerodrome)\")\n .option(\"--token-b <address>\", \"Token B (Aerodrome)\")\n .option(\"--amount-a <n>\", \"Token A amount (Aerodrome)\")\n .option(\"--amount-b <n>\", \"Token B amount (Aerodrome)\")\n .option(\"--stable\", \"Stable pool (Aerodrome)\")\n .option(\"--gauge <address>\", \"Gauge address (Aerodrome)\")\n .option(\"--lp-token <address>\", \"LP token address (Aerodrome)\")\n .option(\"--min-a-out <n>\", \"Min token A on settle (Aerodrome)\")\n .option(\"--min-b-out <n>\", \"Min token B on settle (Aerodrome)\")\n // wsteth-moonwell\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (wstETH, default: 500 = 5%)\")\n // mamo-yield\n .option(\"--mamo-factory <address>\", \"Mamo StrategyFactory address (Mamo)\")\n // portfolio\n .option(\"--tokens <list>\", \"Comma-separated token addresses or symbols (Portfolio)\")\n .option(\"--weights <list>\", \"Comma-separated weights in bps, must sum to 10000 (Portfolio)\")\n .option(\"--max-slippage <bps>\", \"Max slippage bps (Portfolio, default: 500)\")\n .option(\"--fee-tier <n>\", \"Pool fee tier (Portfolio, default: 3000)\")\n .option(\"--swap-adapter <address>\", \"Swap adapter address (Portfolio)\")\n // hyperliquid-perp\n .option(\"--leverage <number>\", \"Leverage multiplier (Hyperliquid Perp, default: 10)\")\n .option(\"--asset-index <number>\", \"Perp asset index (Hyperliquid Perp, default: 0 for BTC)\")\n .option(\"--max-position <amount>\", \"Max position size in USD (Hyperliquid Perp, default: 100000)\")\n .option(\"--max-trades-per-day <n>\", \"Max trades per day (Hyperliquid Perp, default: 50)\")\n .option(\"--max-order-size <amount>\", \"Max single-order size in asset units (Hyperliquid Grid, default: 10000)\")\n .option(\"--max-orders-per-tick <n>\", \"Max orders per tick (Hyperliquid Grid, default: 20)\")\n .option(\"--asset-indices <list>\", \"Comma-separated perp asset indices (Hyperliquid Grid, default: 0)\")\n .action(async (templateKey: string, opts) => {\n const clone = opts.clone as Address;\n const vault = opts.vault as Address;\n if (!isAddress(clone)) {\n console.error(chalk.red(\"Invalid clone address\"));\n process.exit(1);\n }\n if (!isAddress(vault)) {\n console.error(chalk.red(\"Invalid vault address\"));\n process.exit(1);\n }\n\n resolveTemplate(templateKey); // validate template exists\n\n // Check if already initialized\n const publicClient = getPublicClient();\n const currentVault = await publicClient.readContract({\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"vault\",\n }) as Address;\n\n if (currentVault !== \"0x0000000000000000000000000000000000000000\") {\n console.error(chalk.red(`Clone already initialized (vault: ${currentVault})`));\n process.exit(1);\n }\n\n const initSpinner = ora(\"Initializing strategy clone...\").start();\n try {\n const { initData } = await buildInitDataForTemplate(templateKey, opts, vault);\n const account = getAccount();\n\n const initHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"initialize\",\n args: [vault, account.address, initData],\n });\n\n const receipt = await waitForReceipt(initHash);\n if (receipt.status === \"reverted\") {\n throw new Error(\"Initialize transaction reverted on-chain\");\n }\n initSpinner.succeed(\"Initialized\");\n console.log(chalk.dim(` Tx: ${getExplorerUrl(initHash)}`));\n } catch (err) {\n initSpinner.fail(\"Initialize failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Verify\n const verifiedVault = await publicClient.readContract({\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"vault\",\n }) as Address;\n\n console.log();\n console.log(chalk.bold(\"Clone initialized:\"), chalk.green(clone));\n console.log(` Vault: ${chalk.green(verifiedVault)}`);\n console.log(` Proposer: ${chalk.green(getAccount().address)}`);\n console.log();\n });\n\n // ── strategy propose ──\n\n strategy\n .command(\"propose\")\n .description(\"Clone + init + build calls + submit governance proposal (all-in-one)\")\n .argument(\"<template>\", \"Template: moonwell-supply, aerodrome-lp, venice-inference, wsteth-moonwell, mamo-yield, portfolio, hyperliquid-perp, hyperliquid-grid\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .option(\"--write-calls <dir>\", \"Write execute/settle JSON to directory (skip proposal submission)\")\n // proposal metadata (required unless --write-calls)\n .option(\"--name <name>\", \"Proposal name\")\n .option(\"--description <text>\", \"Proposal description\")\n .option(\"--performance-fee <bps>\", \"Agent fee in bps\")\n .option(\"--duration <duration>\", \"Strategy duration (7d, 24h, etc.)\")\n // external-signer (--calldata-only) flow\n .option(\"--proposer <address>\", \"Proposer/agent address (required for --calldata-only — the external signer)\")\n .option(\"--metadata-uri <uri>\", \"Metadata URI (required for --calldata-only — IPFS pin needs a signer)\")\n .option(\"--salt <bytes32>\", \"CREATE2 salt for the deterministic clone (--calldata-only; default: derived from inputs)\")\n // template-specific (same as clone)\n .option(\"--amount <n>\", \"Asset amount to deploy\")\n .option(\"--min-redeem <n>\", \"Min asset on settlement (Moonwell)\")\n .option(\"--token <symbol>\", \"Asset token symbol (default: USDC)\")\n .option(\"--asset <symbol>\", \"Asset token (USDC, VVV, or address)\")\n .option(\"--agent <address>\", \"Agent wallet (Venice, default: your wallet)\")\n .option(\"--min-vvv <n>\", \"Min VVV from swap (Venice)\")\n .option(\"--single-hop\", \"Single-hop Aerodrome swap (Venice)\")\n .option(\"--token-a <address>\", \"Token A (Aerodrome)\")\n .option(\"--token-b <address>\", \"Token B (Aerodrome)\")\n .option(\"--amount-a <n>\", \"Token A amount (Aerodrome)\")\n .option(\"--amount-b <n>\", \"Token B amount (Aerodrome)\")\n .option(\"--stable\", \"Stable pool (Aerodrome)\")\n .option(\"--gauge <address>\", \"Gauge address (Aerodrome)\")\n .option(\"--lp-token <address>\", \"LP token address (Aerodrome)\")\n .option(\"--min-a-out <n>\", \"Min token A on settle (Aerodrome)\")\n .option(\"--min-b-out <n>\", \"Min token B on settle (Aerodrome)\")\n // wsteth-moonwell\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (wstETH, default: 500 = 5%)\")\n // mamo-yield\n .option(\"--mamo-factory <address>\", \"Mamo StrategyFactory address (Mamo)\")\n // portfolio\n .option(\"--tokens <list>\", \"Comma-separated token addresses or symbols (Portfolio)\")\n .option(\"--weights <list>\", \"Comma-separated weights in bps, must sum to 10000 (Portfolio)\")\n .option(\"--max-slippage <bps>\", \"Max slippage bps (Portfolio, default: 500)\")\n .option(\"--fee-tier <n>\", \"Pool fee tier (Portfolio, default: 3000)\")\n .option(\"--swap-adapter <address>\", \"Swap adapter address (Portfolio)\")\n // hyperliquid-perp\n .option(\"--leverage <number>\", \"Leverage multiplier (Hyperliquid Perp, default: 10)\")\n .option(\"--asset-index <number>\", \"Perp asset index (Hyperliquid Perp, default: 0 for BTC)\")\n .option(\"--max-position <amount>\", \"Max position size in USD (Hyperliquid Perp, default: 100000)\")\n .option(\"--max-trades-per-day <n>\", \"Max trades per day (Hyperliquid Perp, default: 50)\")\n .option(\"--max-order-size <amount>\", \"Max single-order size in asset units (Hyperliquid Grid, default: 10000)\")\n .option(\"--max-orders-per-tick <n>\", \"Max orders per tick (Hyperliquid Grid, default: 20)\")\n .option(\"--asset-indices <list>\", \"Comma-separated perp asset indices (Hyperliquid Grid, default: 0)\")\n .action(async (templateKey: string, opts) => {\n const vault = opts.vault as Address;\n if (!isAddress(vault)) {\n console.error(chalk.red(\"Invalid vault address\"));\n process.exit(1);\n }\n\n const { def, address: templateAddr } = resolveTemplate(templateKey);\n\n // --calldata-only: deploy the clone DETERMINISTICALLY (CREATE2 via\n // StrategyFactory) so its address is known up front, then emit BOTH the\n // clone+init tx and the propose tx as unsigned calldata. propose only\n // stores the strategy address (it doesn't call the clone), so the two txs\n // just need to land before the proposal executes. Template-agnostic — the\n // only per-template piece is initData. Closes the #387 keyless gap.\n if (isCalldataOnly()) {\n // Note: --name / --description are NOT required here — in calldata-only\n // mode the proposal metadata is supplied via --metadata-uri (the JSON it\n // points at carries the name/description). They have no effect on the\n // emitted calldata, so requiring them would just be a dead gate.\n const missing: string[] = [];\n if (!opts.proposer) missing.push(\"--proposer <address> (the external signer)\");\n if (!opts.metadataUri) missing.push(\"--metadata-uri <uri> (IPFS pin needs a signer)\");\n if (!opts.performanceFee) missing.push(\"--performance-fee <bps>\");\n if (!opts.duration) missing.push(\"--duration <d>\");\n if (missing.length > 0) {\n console.error(chalk.red(`--calldata-only requires: ${missing.join(\", \")}`));\n process.exit(1);\n }\n const proposer = opts.proposer as Address;\n if (!isAddress(proposer)) {\n console.error(chalk.red(\"Invalid --proposer address\"));\n process.exit(1);\n }\n const performanceFeeBps = Number(opts.performanceFee);\n if (!Number.isInteger(performanceFeeBps) || performanceFeeBps < 0 || performanceFeeBps > 10000) {\n console.error(chalk.red(\"--performance-fee must be an integer 0-10000 (bps)\"));\n process.exit(1);\n }\n\n // Read-only preflight (no private key needed). Fail fast instead of\n // emitting calldata that will revert: cloneAndInitDeterministic + propose\n // both require the proposer to be a registered agent of the vault, and a\n // sub-balance vault reverts at execute. (The template-allowlist and\n // proposer == msg.sender checks can't be done off-chain — the emitted\n // note covers them: don't broadcast tx 2 unless tx 1 confirms.)\n try {\n const publicClient = getPublicClient();\n const [isRegistered, paused] = await Promise.all([\n publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"isAgent\",\n args: [proposer],\n }) as Promise<boolean>,\n publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"paused\",\n }) as Promise<boolean>,\n ]);\n if (!isRegistered) {\n console.error(\n chalk.red(\n `--proposer ${proposer} is not a registered agent on ${vault}; cloneAndInitDeterministic and propose will both revert.`,\n ),\n );\n console.error(chalk.yellow(` Register first: sherwood syndicate approve --wallet ${proposer}`));\n process.exit(1);\n }\n if (paused) {\n console.error(chalk.red(`Vault ${vault} is paused — the proposal would revert.`));\n process.exit(1);\n }\n for (const check of computeProposalAssetChecks(templateKey, opts)) {\n if (check.amount === 0n) continue;\n const [balance, decimals] = await Promise.all([\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [vault],\n }) as Promise<bigint>,\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"decimals\",\n }) as Promise<number>,\n ]);\n if (balance < check.amount) {\n console.error(\n chalk.red(\n `Vault ${vault} holds ${formatUnits(balance, decimals)} ${check.label} but the proposal needs ${formatUnits(check.amount, decimals)} ${check.label}.`,\n ),\n );\n console.error(chalk.yellow(` Hint: --amount is in human units (e.g. \"10\" = 10 ${check.label}), not raw decimals.`));\n process.exit(1);\n }\n }\n } catch (err) {\n console.error(chalk.red(`Preflight read failed: ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n // The venice builder defaults its agent to the signer's wallet; pin it to\n // the proposer so buildInitDataForTemplate never reaches for getAccount()\n // (there's no private key in calldata-only mode).\n if (!opts.agent) opts.agent = proposer;\n\n const { parseDuration } = await import(\"../lib/governor.js\");\n const strategyDuration = parseDuration(opts.duration as string);\n const chainId = getChain().id as ChainId;\n\n try {\n const built = await buildInitDataForTemplate(templateKey, opts, vault);\n const deploy = encodeStrategyDeploy(\n {\n template: templateAddr,\n vault,\n proposer,\n initData: built.initData,\n salt: opts.salt as Hex | undefined,\n },\n chainId,\n );\n const { executeCalls, settleCalls } = buildCallsForTemplate(\n templateKey, deploy.clone, built.asset, built.assetAmount, built.extraApprovals,\n );\n const proposeAction = encodePropose(\n {\n vault,\n strategy: deploy.clone,\n metadataURI: opts.metadataUri as string,\n performanceFeeBps,\n strategyDuration,\n executeCalls,\n settlementCalls: settleCalls,\n },\n chainId,\n );\n emitCalldata({\n txs: [...deploy.txs, ...proposeAction.txs],\n preconditions: [...deploy.preconditions, ...proposeAction.preconditions],\n // Surface the deterministic clone + salt as structured fields (also\n // baked into tx 2's `strategy` arg + the execute/settle calls).\n clone: deploy.clone,\n salt: deploy.salt,\n description:\n `Keyless ${def.name} proposal on ${vault}: (1) deploy clone at ${deploy.clone} ` +\n `(deterministic CREATE2, salt ${deploy.salt}); (2) governor.propose referencing it.`,\n note:\n \"Broadcast SEQUENTIALLY: send tx 1 (cloneAndInitDeterministic) and WAIT for it to confirm, then send tx 2 (propose). \" +\n \"If tx 1 reverts — proposer not a registered agent, proposer != tx-1 signer, template not allowlisted, or vault unregistered — do NOT send tx 2: it would create a proposal referencing an undeployed strategy. \" +\n \"Send tx 1 from the --proposer wallet (the factory requires proposer == msg.sender, and msg.sender must be a vault owner/agent). \" +\n \"The clone address is pinned by (factory, template, vault, salt) and is already baked into tx 2 + the execute/settle calls. \" +\n \"The factory binds the salt to the vault and only the vault's owner/agents may deploy there, so the predicted address can't be front-run.\",\n } as Parameters<typeof emitCalldata>[0]);\n } catch (err) {\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n return;\n }\n\n // 0. Preflight — bail out before burning gas on clone + init for a\n // proposal the governor will refuse anyway. Two read-only checks,\n // no gas cost.\n const account = getAccount();\n const preflightSpinner = ora(\"Preflight checks...\").start();\n try {\n const publicClient = getPublicClient();\n\n // (a) Signer must be a registered active agent on this vault.\n const isRegistered = await publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"isAgent\",\n args: [account.address],\n });\n if (!isRegistered) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(\n chalk.red(\n ` Signer ${account.address} is not a registered agent on ${vault}.\\n` +\n ` Register first via: sherwood syndicate approve --wallet ${account.address}`,\n ),\n );\n process.exit(1);\n }\n\n // (b) Vault must not be paused (deposits + governance ops would revert).\n const paused = await publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"paused\",\n });\n if (paused) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(chalk.red(` Vault ${vault} is paused. Cannot propose.`));\n process.exit(1);\n }\n\n // (c) Vault must hold enough of the proposal's asset to fund execute.\n // Catches the most common --amount footgun (passing raw decimal\n // units, e.g. 10000000, when the CLI already applies parseUnits\n // and the vault only holds 10 USDC). Without this guard the\n // proposal still passes propose+vote but `_pullFromVault` reverts\n // at execute with \"ERC20: transfer amount exceeds balance\".\n const checks = computeProposalAssetChecks(templateKey, opts);\n for (const check of checks) {\n if (check.amount === 0n) continue;\n const [balance, decimals] = await Promise.all([\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [vault],\n }) as Promise<bigint>,\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"decimals\",\n }) as Promise<number>,\n ]);\n if (balance < check.amount) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(\n chalk.red(\n ` Vault ${vault} holds ${formatUnits(balance, decimals)} ${check.label} ` +\n `but proposal requires ${formatUnits(check.amount, decimals)} ${check.label}.`,\n ),\n );\n console.error(\n chalk.yellow(\n ` Hint: --amount is in human units (e.g. \\\"10\\\" = 10 ${check.label}), not raw decimals.`,\n ),\n );\n process.exit(1);\n }\n }\n\n preflightSpinner.succeed(\"Preflight OK\");\n } catch (err) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 1. Clone\n const cloneSpinner = ora(`Cloning ${def.name} template...`).start();\n let clone: Address;\n try {\n const result = await cloneTemplate(templateAddr);\n clone = result.clone;\n cloneSpinner.succeed(`Cloned: ${chalk.green(clone)}`);\n console.log(chalk.dim(` Tx: ${getExplorerUrl(result.hash)}`));\n } catch (err) {\n cloneSpinner.fail(\"Clone failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 2. Initialize\n const initSpinner = ora(\"Initializing strategy...\").start();\n let asset: Address;\n let assetAmount: bigint;\n let extraApprovals: { token: Address; amount: bigint }[] | undefined;\n try {\n const built = await buildInitDataForTemplate(templateKey, opts, vault);\n asset = built.asset;\n assetAmount = built.assetAmount;\n extraApprovals = built.extraApprovals;\n\n // account hoisted above during preflight — reuse.\n const initHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"initialize\",\n args: [vault, account.address, built.initData],\n });\n\n const initReceipt = await waitForReceipt(initHash);\n if (initReceipt.status === \"reverted\") {\n throw new Error(\"Initialize transaction reverted on-chain\");\n }\n initSpinner.succeed(\"Initialized\");\n } catch (err) {\n initSpinner.fail(\"Initialize failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 2b. HyperCore registration (grid + perp) — hard prerequisite before propose.\n // BaseStrategy.initialize() writes address(this) to slot 0 (_hcSelf). HC\n // reads slot 0 post-block via FirstStorageSlot variant. Without\n // registration the proposal will execute but the bridge can't credit\n // HC spot, burning a governance cycle on a doomed batch.\n if (templateKey === \"hyperliquid-grid\" || templateKey === \"hyperliquid-perp\") {\n const hcSpinner = ora(\"Registering clone with HyperCore...\").start();\n try {\n const hcHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: templateKey === \"hyperliquid-grid\" ? HYPERLIQUID_GRID_STRATEGY_ABI : HYPERLIQUID_PERP_STRATEGY_ABI,\n functionName: \"finalizeForHyperCore\",\n args: [0n, 1, 0n], // token=USDC, variant=FirstStorageSlot(1), nonce unused\n });\n await waitForReceipt(hcHash);\n hcSpinner.succeed(\"HyperCore registration sent (active after next block)\");\n } catch (err) {\n hcSpinner.fail(\"HyperCore registration failed — aborting proposal submission\");\n console.error(chalk.red(formatContractError(err)));\n console.error(\n chalk.yellow(\n `Retry by calling finalizeForHyperCore(0, 1, 0) on ${clone}, then re-run propose.`,\n ),\n );\n process.exit(1);\n }\n }\n\n // 3. Build batch calls\n const { executeCalls, settleCalls } = buildCallsForTemplate(\n templateKey, clone, asset, assetAmount, extraApprovals,\n );\n\n console.log();\n console.log(chalk.bold(`Execute calls (${executeCalls.length}):`));\n console.log(formatBatch(executeCalls));\n console.log(chalk.bold(`Settle calls (${settleCalls.length}):`));\n console.log(formatBatch(settleCalls));\n\n // 4. Write files or submit proposal\n if (opts.writeCalls) {\n const dir = resolve(opts.writeCalls as string);\n mkdirSync(dir, { recursive: true });\n\n const execPath = resolve(dir, \"execute.json\");\n const settlePath = resolve(dir, \"settle.json\");\n writeFileSync(execPath, serializeCalls(executeCalls));\n writeFileSync(settlePath, serializeCalls(settleCalls));\n\n console.log();\n console.log(chalk.green(`Execute calls: ${execPath}`));\n console.log(chalk.green(`Settle calls: ${settlePath}`));\n console.log(chalk.green(`Clone address: ${clone}`));\n console.log();\n console.log(chalk.dim(\"Submit with:\"));\n console.log(chalk.dim(` sherwood proposal create \\\\`));\n console.log(chalk.dim(` --vault ${vault} \\\\`));\n console.log(chalk.dim(` --name \"...\" --description \"...\" \\\\`));\n console.log(chalk.dim(` --performance-fee 0 --duration 7d \\\\`));\n console.log(chalk.dim(` --execute-calls ${execPath} \\\\`));\n console.log(chalk.dim(` --settle-calls ${settlePath}`));\n\n if (templateKey === \"venice-inference\") {\n console.log();\n console.log(chalk.yellow(\"Reminder: before settlement, agent must approve repayment:\"));\n console.log(chalk.yellow(` asset.approve(${clone}, <repaymentAmount>)`));\n console.log(chalk.yellow(\" Agent can update repayment via strategy.updateParams(newRepayment, 0, 0)\"));\n }\n\n console.log();\n return;\n }\n\n // Direct proposal submission requires metadata flags\n if (!opts.name || !opts.performanceFee || !opts.duration) {\n console.error(chalk.red(\"Missing --name, --performance-fee, or --duration. Use --write-calls to skip proposal submission.\"));\n process.exit(1);\n }\n\n // Lazy import governor to avoid pulling it in for --write-calls path\n const { propose } = await import(\"../lib/governor.js\");\n const { pinJSON } = await import(\"../lib/ipfs.js\");\n const { parseDuration } = await import(\"../lib/governor.js\");\n\n const performanceFeeBps = BigInt(opts.performanceFee as string);\n if (performanceFeeBps < 0n || performanceFeeBps > 10000n) {\n console.error(chalk.red(\"--performance-fee must be 0-10000 (basis points)\"));\n process.exit(1);\n }\n const strategyDuration = parseDuration(opts.duration as string);\n // account already hoisted at preflight.\n\n const metaSpinner = ora(\"Pinning metadata to IPFS...\").start();\n let metadataURI: string;\n try {\n const metadata = {\n name: opts.name,\n description: opts.description || \"\",\n proposer: account.address,\n vault,\n strategyClone: clone,\n template: def.key,\n performanceFeeBps: Number(performanceFeeBps),\n strategyDuration: Number(strategyDuration),\n createdAt: new Date().toISOString(),\n };\n metadataURI = await pinJSON(metadata, opts.name as string);\n metaSpinner.succeed(`Metadata pinned: ${metadataURI}`);\n } catch (err) {\n metaSpinner.fail(\"IPFS pin failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Submit proposal with the freshly-cloned strategy address. Under the\n // strategy-on-proposal model the strategy is set immutably at propose\n // time — no separate bind step. If the strategy doesn't implement\n // `positionValue()` (legacy clones, perp-only) the vault's runtime\n // try/catch falls back to queue-only redemptions during execution.\n const proposeSpinner = ora(\"Submitting proposal...\").start();\n try {\n const { hash, proposalId } = await propose(\n vault,\n clone,\n metadataURI,\n performanceFeeBps,\n strategyDuration,\n executeCalls,\n settleCalls,\n );\n proposeSpinner.succeed(`Proposal #${proposalId} created — strategy=${clone} set on proposal`);\n console.log(`Proposal #${proposalId}`);\n console.log(chalk.dim(` Tx: ${getExplorerUrl(hash)}`));\n console.log(chalk.dim(` Clone: ${clone}`));\n } catch (err) {\n proposeSpinner.fail(\"Proposal failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n if (templateKey === \"venice-inference\") {\n console.log();\n console.log(chalk.yellow(\"Next steps:\"));\n console.log(chalk.yellow(\" 1. After execution: sherwood venice provision\"));\n console.log(chalk.yellow(\" 2. Use inference: sherwood venice infer --model <id> --prompt '...'\"));\n console.log(chalk.yellow(\" 3. Before settlement: approve repayment (principal + profit):\"));\n console.log(chalk.yellow(` asset.approve(${clone}, <repaymentAmount>)`));\n }\n\n console.log();\n });\n\n // ── strategy status ──\n\n strategy\n .command(\"status\")\n .description(\"Show portfolio strategy status — allocations, balances, drift, PnL (Portfolio only)\")\n .argument(\"<clone>\", \"Strategy clone address\")\n .option(\"--json\", \"Output machine-readable JSON for agent consumption\")\n .action(async (cloneArg: string, opts) => {\n if (!isAddress(cloneArg)) {\n console.error(chalk.red(\"Invalid clone address\"));\n process.exit(1);\n }\n const clone = cloneArg as Address;\n const publicClient = getPublicClient();\n const network = getNetwork();\n const jsonMode = !!opts.json;\n\n const spinner = jsonMode ? null : ora(\"Reading strategy state...\").start();\n try {\n // Read strategy state + swap extra data (for fee tiers)\n const [stateRaw, vault, proposer, assetAddr, totalAmount, maxSlippage, allocations, swapExtraData] = await Promise.all([\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"state\" }),\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"vault\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"proposer\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"asset\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"totalAmount\" }) as Promise<bigint>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"maxSlippageBps\" }) as Promise<bigint>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"getAllocations\" }) as Promise<readonly { token: Address; targetWeightBps: bigint; tokenAmount: bigint; investedAmount: bigint }[]>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"getSwapExtraData\" }) as Promise<readonly `0x${string}`[]>,\n ]);\n\n const stateNames = [\"Pending\", \"Executed\", \"Settled\"];\n const stateStr = stateNames[Number(stateRaw)] || `Unknown(${stateRaw})`;\n\n // Read asset decimals & symbol\n const [assetDecimals, assetSymbol] = await Promise.all([\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"decimals\" }),\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"symbol\" }),\n ]);\n\n // Read current token balances & symbols in parallel\n const tokenReads = allocations.map((a) => Promise.all([\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"balanceOf\", args: [clone] }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"symbol\" }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"decimals\" }),\n ]));\n const tokenData = await Promise.all(tokenReads);\n\n // Read asset balance held by strategy\n const assetBalance = await publicClient.readContract({\n address: assetAddr,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [clone],\n });\n\n // Extract fee tiers from swapExtraData (abi.encode(uint24 fee))\n const feeTiers = swapExtraData.map((data) => {\n try {\n const [fee] = decodeAbiParameters([{ type: \"uint24\" }], data);\n return Number(fee) > 0 && Number(fee) <= 100000 ? Number(fee) : 3000;\n } catch {\n return 3000;\n }\n });\n\n // Fetch prices (graceful — continues without if unavailable)\n let prices: (import(\"../lib/price.js\").TokenPrice | null)[] = [];\n let priceSource: \"uniswap\" | \"synthra\" | null = null;\n try {\n const { getTokenPricesInAsset } = await import(\"../lib/price.js\");\n prices = await getTokenPricesInAsset({\n tokens: allocations.map((a, i) => ({\n token: a.token,\n tokenDecimals: tokenData[i][2] as number,\n feeTier: feeTiers[i],\n })),\n asset: assetAddr,\n assetDecimals,\n });\n priceSource = prices.find((p) => p !== null)?.source ?? null;\n } catch {\n // Prices unavailable — continue with balance-only\n }\n\n const pricesAvailable = prices.some((p) => p !== null);\n\n // Compute enriched allocation data\n const assetBalanceNum = Number(formatUnits(assetBalance as bigint, assetDecimals));\n let totalPortfolioValue = assetBalanceNum;\n let totalInvested = 0n;\n\n interface AllocStatus {\n token: Address;\n symbol: string;\n decimals: number;\n targetWeightBps: number;\n balance: string;\n balanceRaw: string;\n investedAmount: string;\n currentPrice: number | null;\n currentValue: number | null;\n actualWeightBps: number | null;\n driftBps: number | null;\n pnl: number | null;\n pnlPct: number | null;\n }\n\n const allocStatuses: AllocStatus[] = allocations.map((alloc, i) => {\n const [balance, symbol, decimals] = tokenData[i];\n const balanceNum = Number(formatUnits(balance as bigint, decimals));\n const investedNum = Number(formatUnits(alloc.investedAmount, assetDecimals));\n totalInvested += alloc.investedAmount;\n\n const price = prices[i];\n let currentValue: number | null = null;\n\n if (price) {\n currentValue = balanceNum * price.price;\n totalPortfolioValue += currentValue;\n }\n\n return {\n token: alloc.token,\n symbol: symbol as string,\n decimals: decimals as number,\n targetWeightBps: Number(alloc.targetWeightBps),\n balance: formatUnits(balance as bigint, decimals),\n balanceRaw: (balance as bigint).toString(),\n investedAmount: formatUnits(alloc.investedAmount, assetDecimals),\n currentPrice: price?.price ?? null,\n currentValue,\n actualWeightBps: null, // computed after totals\n driftBps: null,\n pnl: currentValue !== null ? currentValue - investedNum : null,\n pnlPct: currentValue !== null && investedNum > 0\n ? ((currentValue - investedNum) / investedNum) * 100\n : null,\n };\n });\n\n // Second pass: compute actual weights and drift (needs totalPortfolioValue)\n let maxDriftBps = 0;\n let maxDriftToken = \"\";\n if (pricesAvailable && totalPortfolioValue > 0) {\n for (const a of allocStatuses) {\n if (a.currentValue !== null) {\n a.actualWeightBps = Math.round((a.currentValue / totalPortfolioValue) * 10000);\n a.driftBps = a.actualWeightBps - a.targetWeightBps;\n if (Math.abs(a.driftBps) > Math.abs(maxDriftBps)) {\n maxDriftBps = a.driftBps;\n maxDriftToken = a.symbol;\n }\n }\n }\n }\n\n // Total PnL\n const totalInvestedNum = Number(formatUnits(totalInvested, assetDecimals));\n const totalPnl = pricesAvailable ? totalPortfolioValue - totalInvestedNum : null;\n const totalPnlPct = totalPnl !== null && totalInvestedNum > 0\n ? (totalPnl / totalInvestedNum) * 100\n : null;\n\n spinner?.succeed(\"Strategy state loaded\");\n\n // ── JSON output ──\n if (jsonMode) {\n const result = {\n clone,\n vault,\n proposer,\n state: stateStr,\n network,\n asset: { address: assetAddr, symbol: assetSymbol as string, decimals: assetDecimals as number },\n totalDeployed: formatUnits(totalAmount, assetDecimals),\n maxSlippageBps: Number(maxSlippage),\n assetBalance: formatUnits(assetBalance as bigint, assetDecimals),\n pricesAvailable,\n priceSource,\n portfolio: {\n totalValue: pricesAvailable ? totalPortfolioValue : null,\n totalPnl,\n totalPnlPct,\n },\n allocations: allocStatuses,\n maxDriftBps: pricesAvailable ? maxDriftBps : null,\n maxDriftToken: pricesAvailable ? maxDriftToken : null,\n timestamp: new Date().toISOString(),\n };\n process.stdout.write(JSON.stringify(result) + \"\\n\");\n return;\n }\n\n // ── Human-friendly output ──\n const stateColor = stateStr === \"Executed\" ? chalk.green : stateStr === \"Settled\" ? chalk.blue : chalk.yellow;\n\n console.log();\n console.log(chalk.bold(\"Portfolio Strategy Status\"));\n console.log(chalk.dim(\"─\".repeat(70)));\n console.log(` Clone: ${chalk.cyan(clone)}`);\n console.log(` Vault: ${chalk.cyan(vault)}`);\n console.log(` Proposer: ${chalk.cyan(proposer)}`);\n console.log(` State: ${stateColor(stateStr)}`);\n console.log(` Asset: ${assetSymbol} (${assetAddr})`);\n console.log(` Deployed: ${formatUnits(totalAmount, assetDecimals)} ${assetSymbol}`);\n console.log(` Max Slip: ${Number(maxSlippage) / 100}%`);\n console.log(` Asset held: ${formatUnits(assetBalance as bigint, assetDecimals)} ${assetSymbol}`);\n\n if (pricesAvailable) {\n const pvStr = totalPortfolioValue.toFixed(6);\n const pnlStr = totalPnl !== null ? (totalPnl >= 0 ? \"+\" : \"\") + totalPnl.toFixed(6) : \"n/a\";\n const pnlPctStr = totalPnlPct !== null ? (totalPnlPct >= 0 ? \"+\" : \"\") + totalPnlPct.toFixed(1) + \"%\" : \"\";\n const pnlColor = totalPnl !== null && totalPnl >= 0 ? chalk.green : chalk.red;\n console.log(` Value: ${pvStr} ${assetSymbol} | PnL: ${pnlColor(`${pnlStr} (${pnlPctStr})`)}`);\n console.log(` Price src: ${priceSource}`);\n }\n\n console.log();\n console.log(chalk.bold(\"Allocations\"));\n console.log(chalk.dim(\"─\".repeat(70)));\n\n if (pricesAvailable) {\n // Price-enriched table\n console.log(\n chalk.dim(\" Token\".padEnd(10)) +\n chalk.dim(\"Target\".padEnd(9)) +\n chalk.dim(\"Actual\".padEnd(9)) +\n chalk.dim(\"Drift\".padEnd(8)) +\n chalk.dim(\"Value\".padEnd(16)) +\n chalk.dim(\"PnL\".padEnd(16)) +\n chalk.dim(\"Balance\"),\n );\n\n for (const a of allocStatuses) {\n const targetStr = (a.targetWeightBps / 100).toFixed(1) + \"%\";\n const actualStr = a.actualWeightBps !== null ? (a.actualWeightBps / 100).toFixed(1) + \"%\" : \"—\";\n const driftStr = a.driftBps !== null\n ? (a.driftBps >= 0 ? \"+\" : \"\") + a.driftBps\n : \"—\";\n const driftColor = a.driftBps !== null\n ? (Math.abs(a.driftBps) > 500 ? chalk.red : Math.abs(a.driftBps) > 200 ? chalk.yellow : chalk.dim)\n : chalk.dim;\n const valueStr = a.currentValue !== null ? a.currentValue.toFixed(6) : \"—\";\n const pnlPctStr = a.pnlPct !== null ? (a.pnlPct >= 0 ? \"+\" : \"\") + a.pnlPct.toFixed(1) + \"%\" : \"—\";\n const pnlColor = a.pnlPct !== null ? (a.pnlPct >= 0 ? chalk.green : chalk.red) : chalk.dim;\n\n console.log(\n ` ${chalk.bold(a.symbol.padEnd(8))}` +\n `${targetStr.padEnd(9)}` +\n `${actualStr.padEnd(9)}` +\n `${driftColor(driftStr.toString().padEnd(8))}` +\n `${valueStr.padEnd(16)}` +\n `${pnlColor(pnlPctStr.padEnd(16))}` +\n `${a.balance}`,\n );\n }\n } else {\n // Balance-only table (no prices available)\n console.log(chalk.dim(\" Prices unavailable — showing raw balances only.\"));\n console.log();\n console.log(\n chalk.dim(\" Token\".padEnd(12)) +\n chalk.dim(\"Weight\".padEnd(10)) +\n chalk.dim(\"Invested\".padEnd(18)) +\n chalk.dim(\"Balance\".padEnd(18)) +\n chalk.dim(\"Address\"),\n );\n\n for (const a of allocStatuses) {\n const weightPct = (a.targetWeightBps / 100).toFixed(1) + \"%\";\n console.log(\n ` ${chalk.bold(a.symbol.padEnd(10))}` +\n `${weightPct.padEnd(10)}` +\n `${a.investedAmount.padEnd(18)}` +\n `${a.balance.padEnd(18)}` +\n `${chalk.dim(a.token)}`,\n );\n }\n }\n\n console.log(chalk.dim(\"─\".repeat(70)));\n console.log(` Total invested: ${formatUnits(totalInvested, assetDecimals)} ${assetSymbol}`);\n\n if (pricesAvailable && maxDriftToken) {\n const absMaxDrift = Math.abs(maxDriftBps);\n const driftColor = absMaxDrift > 500 ? chalk.red : absMaxDrift > 200 ? chalk.yellow : chalk.green;\n console.log(` Max drift: ${driftColor(`${maxDriftBps > 0 ? \"+\" : \"\"}${maxDriftBps} bps`)} (${maxDriftToken})`);\n }\n\n if (stateStr === \"Executed\") {\n console.log();\n console.log(chalk.dim(\"Rebalance: sherwood strategy rebalance \" + clone));\n console.log(chalk.dim(\"With new weights: sherwood strategy rebalance \" + clone + \" --new-weights 2500,2500,2000,1500,1500\"));\n }\n\n console.log();\n } catch (err) {\n spinner?.fail(\"Failed to read strategy state\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── strategy rebalance ──\n\n strategy\n .command(\"rebalance\")\n .description(\"Rebalance a portfolio strategy — sell all positions, re-buy at target weights (Portfolio only)\")\n .argument(\"<clone>\", \"Strategy clone address\")\n .option(\"--new-weights <list>\", \"Comma-separated new weights in bps (must sum to 10000). Updates weights before rebalancing.\")\n .option(\"--max-slippage <bps>\", \"New max slippage bps (used with --new-weights)\")\n .option(\"--dry-run\", \"Show what would happen without executing\")\n .action(async (cloneArg: string, opts) => {\n if (!isAddress(cloneArg)) {\n console.error(chalk.red(\"Invalid clone address\"));\n process.exit(1);\n }\n const clone = cloneArg as Address;\n const publicClient = getPublicClient();\n const account = getAccount();\n const chain = getChain();\n\n // 1. Verify strategy state\n const verifySpinner = ora(\"Verifying strategy state...\").start();\n try {\n const [stateRaw, proposer, assetAddr, allocations] = await Promise.all([\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"state\" }),\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"proposer\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"asset\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"getAllocations\" }) as Promise<readonly { token: Address; targetWeightBps: bigint; tokenAmount: bigint; investedAmount: bigint }[]>,\n ]);\n\n // Check state\n if (Number(stateRaw) !== 1) { // State.Executed = 1\n const stateNames = [\"Pending\", \"Executed\", \"Settled\"];\n verifySpinner.fail(`Strategy is ${stateNames[Number(stateRaw)] || \"Unknown\"}, must be Executed to rebalance`);\n process.exit(1);\n }\n\n // Check proposer\n if (proposer.toLowerCase() !== account.address.toLowerCase()) {\n verifySpinner.fail(`Only the proposer (${proposer}) can rebalance. Your wallet: ${account.address}`);\n process.exit(1);\n }\n\n const [assetDecimals, assetSymbol] = await Promise.all([\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"decimals\" }),\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"symbol\" }),\n ]);\n\n // Read current balances\n const tokenReads = allocations.map((a) => Promise.all([\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"balanceOf\", args: [clone] }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"symbol\" }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"decimals\" }),\n ]));\n const tokenData = await Promise.all(tokenReads);\n\n verifySpinner.succeed(\"Strategy is Executed — ready to rebalance\");\n\n // Show current allocations\n console.log();\n console.log(chalk.bold(\"Current Allocations\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (let i = 0; i < allocations.length; i++) {\n const alloc = allocations[i];\n const [balance, symbol, decimals] = tokenData[i];\n const weightPct = (Number(alloc.targetWeightBps) / 100).toFixed(1) + \"%\";\n console.log(\n ` ${chalk.bold((symbol as string).padEnd(8))} ` +\n `${weightPct.padEnd(8)} ` +\n `bal: ${formatUnits(balance as bigint, decimals)}`,\n );\n }\n\n // Parse new weights if provided\n let newWeightsBps: number[] | undefined;\n if (opts.newWeights) {\n newWeightsBps = (opts.newWeights as string).split(\",\").map((w) => Number(w.trim()));\n if (newWeightsBps.length !== allocations.length) {\n console.error(chalk.red(`--new-weights must have ${allocations.length} values (one per token)`));\n process.exit(1);\n }\n const weightSum = newWeightsBps.reduce((a, b) => a + b, 0);\n if (weightSum !== 10000) {\n console.error(chalk.red(`Weights must sum to 10000, got ${weightSum}`));\n process.exit(1);\n }\n\n console.log();\n console.log(chalk.bold(\"New Target Weights\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (let i = 0; i < allocations.length; i++) {\n const [, symbol] = tokenData[i];\n const oldPct = (Number(allocations[i].targetWeightBps) / 100).toFixed(1);\n const newPct = (newWeightsBps[i] / 100).toFixed(1);\n const arrow = oldPct !== newPct ? chalk.yellow(\"→\") : chalk.dim(\"→\");\n console.log(` ${chalk.bold((symbol as string).padEnd(8))} ${oldPct}% ${arrow} ${newPct}%`);\n }\n }\n\n if (opts.dryRun) {\n console.log();\n console.log(chalk.yellow(\"Dry run — no transactions sent.\"));\n console.log(chalk.dim(\"The rebalance would:\"));\n console.log(chalk.dim(\" 1. Sell all current token positions back to \" + assetSymbol));\n console.log(chalk.dim(\" 2. Re-buy at \" + (newWeightsBps ? \"new\" : \"current\") + \" target weights\"));\n console.log();\n return;\n }\n\n // 2. Update weights first (if specified)\n if (newWeightsBps) {\n const maxSlip = Number((opts.maxSlippage as string) || \"0\");\n const swapData = await publicClient.readContract({\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"getSwapExtraData\",\n }) as Hex[];\n\n const updateSpinner = ora(\"Updating target weights...\").start();\n try {\n const innerData = encodeAbiParameters(\n [{ type: \"uint256[]\" }, { type: \"uint256\" }, { type: \"bytes[]\" }],\n [newWeightsBps.map((w: number) => BigInt(w)), BigInt(maxSlip), swapData],\n );\n\n const updateHash = await writeContractWithRetry({\n account,\n chain,\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"updateParams\",\n args: [innerData],\n });\n\n const receipt = await waitForReceipt(updateHash);\n if (receipt.status === \"reverted\") throw new Error(\"updateParams reverted\");\n updateSpinner.succeed(\"Target weights updated\");\n console.log(chalk.dim(` Tx: ${getExplorerUrl(updateHash)}`));\n } catch (err) {\n updateSpinner.fail(\"Failed to update weights\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n }\n\n // 3. Execute rebalance\n const rebalanceSpinner = ora(\"Rebalancing portfolio (sell all → re-buy at targets)...\").start();\n try {\n const rebalanceHash = await writeContractWithRetry({\n account,\n chain,\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"rebalance\",\n });\n\n const receipt = await waitForReceipt(rebalanceHash);\n if (receipt.status === \"reverted\") throw new Error(\"rebalance() reverted on-chain\");\n rebalanceSpinner.succeed(\"Portfolio rebalanced\");\n console.log(chalk.dim(` Tx: ${getExplorerUrl(rebalanceHash)}`));\n } catch (err) {\n rebalanceSpinner.fail(\"Rebalance failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 4. Show updated balances\n const postSpinner = ora(\"Reading updated allocations...\").start();\n const postAllocations = await publicClient.readContract({\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"getAllocations\",\n }) as readonly { token: Address; targetWeightBps: bigint; tokenAmount: bigint; investedAmount: bigint }[];\n\n const postReads = postAllocations.map((a) => Promise.all([\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"balanceOf\", args: [clone] }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"symbol\" }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"decimals\" }),\n ]));\n const postData = await Promise.all(postReads);\n postSpinner.succeed(\"Updated allocations\");\n\n console.log();\n console.log(chalk.bold(\"Post-Rebalance Allocations\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (let i = 0; i < postAllocations.length; i++) {\n const alloc = postAllocations[i];\n const [balance, symbol, decimals] = postData[i];\n const weightPct = (Number(alloc.targetWeightBps) / 100).toFixed(1) + \"%\";\n const investedStr = formatUnits(alloc.investedAmount, assetDecimals);\n console.log(\n ` ${chalk.bold((symbol as string).padEnd(8))} ` +\n `${weightPct.padEnd(8)} ` +\n `invested: ${investedStr.padEnd(14)} ` +\n `bal: ${formatUnits(balance as bigint, decimals)}`,\n );\n }\n\n console.log();\n console.log(chalk.green(\"✓ Rebalance complete\"));\n console.log();\n } catch (err: any) {\n if (err.code === \"ERR_MODULE_NOT_FOUND\" || err instanceof TypeError) throw err;\n verifySpinner.fail(\"Pre-flight check failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * ERC-1167 minimal proxy cloning from TypeScript.\n *\n * Mirrors OpenZeppelin's Clones.clone() — constructs the creation\n * bytecode for a minimal proxy and deploys via a raw transaction.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { concat } from \"viem\";\nimport { getAccount, sendTxWithRetry, waitForReceipt } from \"./client.js\";\nimport { getChain } from \"./network.js\";\n\n/**\n * Deploy an ERC-1167 minimal proxy clone of a template contract.\n *\n * @param template - Address of the deployed template (implementation)\n * @returns The clone address and deployment tx hash.\n */\nexport async function cloneTemplate(\n template: Address,\n): Promise<{ clone: Address; hash: Hex }> {\n // ERC-1167 creation code (matches OpenZeppelin Clones.sol):\n // Init code: 3d602d80600a3d3981f3\n // Runtime code: 363d3d373d3d3d363d73 <address> 5af43d82803e903d91602b57fd5bf3\n const creationCode = concat([\n \"0x3d602d80600a3d3981f3363d3d373d3d3d363d73\",\n template,\n \"0x5af43d82803e903d91602b57fd5bf3\",\n ]);\n\n const account = getAccount();\n const chain = getChain();\n\n const hash = await sendTxWithRetry({\n account,\n chain,\n data: creationCode as Hex,\n value: 0n,\n });\n\n const receipt = await waitForReceipt(hash);\n\n if (!receipt.contractAddress) {\n throw new Error(`Clone deployment failed — no contract address in receipt (tx: ${hash})`);\n }\n\n return { clone: receipt.contractAddress, hash };\n}\n","/**\n * Minimal ABI for HyperliquidGridStrategy: updateParams (proposer-callable\n * entrypoint) + maxOrdersPerTick getter for read-side chunking.\n */\nexport const HYPERLIQUID_GRID_STRATEGY_ABI = [\n {\n type: 'function',\n name: 'updateParams',\n inputs: [{ name: 'data', type: 'bytes' }],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n name: 'maxOrdersPerTick',\n inputs: [],\n outputs: [{ type: 'uint32' }],\n stateMutability: 'view',\n },\n {\n // Registers the clone with HyperCore so ERC-20 USDC transfers auto-credit\n // HC spot. Call post-init with variant=1 (FirstStorageSlot) and nonce=0.\n // _initialize() already wrote address(this) to slot 0 (_hcSelf); HC reads\n // it post-block to confirm the contract address.\n type: 'function',\n name: 'finalizeForHyperCore',\n inputs: [\n { name: 'token', type: 'uint64' },\n { name: 'variant', type: 'uint8' },\n { name: 'createNonce', type: 'uint64' },\n ],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n] as const;\n","/**\n * Types and helpers for batch call construction.\n *\n * Calls go directly to vault.executeBatch() — no separate executor contract.\n */\n\nimport type { Address, Hex } from \"viem\";\n\nexport interface BatchCall {\n target: Address;\n data: Hex;\n value: bigint;\n}\n\n/**\n * Format a batch for human-readable display (CLI output before simulation).\n */\nexport function formatBatch(calls: BatchCall[]): string {\n return calls\n .map((call, i) => {\n const selector = call.data.slice(0, 10);\n return ` ${i + 1}. ${call.target} :: ${selector}... (${call.value > 0n ? call.value + \" wei\" : \"no value\"})`;\n })\n .join(\"\\n\");\n}\n","/**\n * `--calldata-only` support.\n *\n * When the global `--calldata-only` flag is set, state-changing commands build\n * the unsigned EIP-5792-style calldata via the shared `@sherwoodagent/sdk`\n * encoders and print it as JSON instead of signing/sending — so an external\n * signer (MetaMask Agent Wallet, Frame, Privy, …) that can't export a private\n * key can take the final step. Output matches the HTTP API's `/v1/prepare/*`\n * envelope (the SDK `PreparedAction` shape).\n */\nimport type { PreparedAction } from \"@sherwoodagent/sdk\";\n\nlet _calldataOnly = false;\n\n/** Set by the root preAction hook from the global `--calldata-only` flag. */\nexport function setCalldataOnly(value: boolean): void {\n _calldataOnly = value;\n}\n\nexport function isCalldataOnly(): boolean {\n return _calldataOnly;\n}\n\n/**\n * Print a PreparedAction as pretty JSON. Each tx is `{ to, data, value, chainId }`\n * with a hex `value` (EIP-5792). `chainId` is per-tx, so multi-chain flows\n * (e.g. approve-agent: registerAgent on the syndicate chain + attest on Base)\n * are explicit.\n */\nexport function emitCalldata(action: PreparedAction): void {\n process.stdout.write(JSON.stringify(action, null, 2) + \"\\n\");\n}\n","export const CHAIN_IDS = {\n BASE: 8453,\n HYPEREVM: 999,\n ROBINHOOD_L2: 46630,\n};\nexport const SUPPORTED_CHAIN_IDS = [\n CHAIN_IDS.BASE,\n CHAIN_IDS.HYPEREVM,\n CHAIN_IDS.ROBINHOOD_L2,\n];\nexport function isSupportedChainId(value) {\n return SUPPORTED_CHAIN_IDS.includes(value);\n}\nexport const PROPOSAL_STATES = [\n \"Draft\",\n \"Pending\",\n \"GuardianReview\",\n \"Approved\",\n \"Rejected\",\n \"Cancelled\",\n \"Vetoed\",\n \"Executed\",\n \"Settled\",\n];\n","export class SdkError extends Error {\n code;\n cause;\n constructor(code, message, cause) {\n super(message);\n this.code = code;\n this.cause = cause;\n this.name = \"SdkError\";\n }\n}\nexport const usage = (message) => new SdkError(\"USAGE\", message);\nexport const unsupported = (message) => new SdkError(\"UNSUPPORTED\", message);\nexport const unavailable = (message, cause) => new SdkError(\"UNAVAILABLE\", message, cause);\nexport const internal = (message, cause) => new SdkError(\"INTERNAL\", message, cause);\nexport const notFound = (message) => new SdkError(\"NOT_FOUND\", message);\n","// Minimal ABI fragments for the v1 SDK encoders + reads.\n// Source of truth: cli/src/lib/abis.ts. Keep in lockstep.\nexport const SYNDICATE_VAULT_ABI = [\n // ERC-4626\n {\n name: \"deposit\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"assets\", type: \"uint256\" },\n { name: \"receiver\", type: \"address\" },\n ],\n outputs: [{ name: \"shares\", type: \"uint256\" }],\n },\n {\n name: \"redeem\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"shares\", type: \"uint256\" },\n { name: \"receiver\", type: \"address\" },\n { name: \"owner\", type: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"requestRedeem\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"shares\", type: \"uint256\" },\n { name: \"owner\", type: \"address\" },\n ],\n outputs: [{ name: \"requestId\", type: \"uint256\" }],\n },\n // Reads\n {\n name: \"asset\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n {\n name: \"totalAssets\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"totalSupply\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"decimals\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint8\" }],\n },\n {\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"account\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"owner\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n {\n name: \"governor\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n {\n name: \"redemptionsLocked\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"paused\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"openDeposits\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"getAgentCount\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"isApprovedDepositor\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"depositor\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n // Owner-side write surface\n {\n name: \"approveDepositor\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"depositor\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"removeDepositor\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"depositor\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"registerAgent\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"agentAddress\", type: \"address\" },\n { name: \"agentId\", type: \"uint256\" },\n ],\n outputs: [],\n },\n];\nexport const SYNDICATE_GOVERNOR_ABI = [\n // Propose (multi-arg). Order MUST match contract: vault, strategy,\n // metadataURI, performanceFeeBps, strategyDuration, executeCalls,\n // settlementCalls, coProposers.\n {\n name: \"propose\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"vault\", type: \"address\" },\n { name: \"strategy\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"performanceFeeBps\", type: \"uint256\" },\n { name: \"strategyDuration\", type: \"uint256\" },\n {\n name: \"executeCalls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n {\n name: \"settlementCalls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n {\n name: \"coProposers\",\n type: \"tuple[]\",\n components: [\n { name: \"agent\", type: \"address\" },\n { name: \"splitBps\", type: \"uint256\" },\n ],\n },\n ],\n outputs: [{ name: \"proposalId\", type: \"uint256\" }],\n },\n // Lifecycle writes\n {\n name: \"vote\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"proposalId\", type: \"uint256\" },\n { name: \"support\", type: \"uint8\" },\n ],\n outputs: [],\n },\n {\n name: \"executeProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"settleProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"cancelProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"vetoProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n // Emergency settlement (GovernorEmergency, V1.5). `unstick` is the\n // owner-instant pre-committed-calls path; `emergencySettleWithCalls` commits\n // a new calldata hash and opens a guardian-reviewed window. The removed\n // `emergencySettle` is intentionally absent — it is not on the deployed impl.\n {\n name: \"unstick\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"emergencySettleWithCalls\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"proposalId\", type: \"uint256\" },\n {\n name: \"calls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n ],\n outputs: [],\n },\n // Parameter setters (GovernorParameters, V1.5 — owner-instant, no timelock).\n { name: \"setVotingPeriod\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setExecutionWindow\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setVetoThresholdBps\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setMaxPerformanceFeeBps\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setMaxStrategyDuration\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setCooldownPeriod\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setProtocolFeeBps\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n // Reads\n {\n name: \"getProposal\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n components: [\n { name: \"id\", type: \"uint256\" },\n { name: \"proposer\", type: \"address\" },\n { name: \"vault\", type: \"address\" },\n { name: \"strategy\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"performanceFeeBps\", type: \"uint256\" },\n { name: \"strategyDuration\", type: \"uint256\" },\n { name: \"votesFor\", type: \"uint256\" },\n { name: \"votesAgainst\", type: \"uint256\" },\n { name: \"votesAbstain\", type: \"uint256\" },\n { name: \"snapshotTimestamp\", type: \"uint256\" },\n { name: \"voteEnd\", type: \"uint256\" },\n { name: \"reviewEnd\", type: \"uint256\" },\n { name: \"executeBy\", type: \"uint256\" },\n { name: \"executedAt\", type: \"uint256\" },\n { name: \"state\", type: \"uint8\" },\n { name: \"vetoThresholdBps\", type: \"uint256\" },\n ],\n },\n ],\n },\n {\n name: \"getProposalState\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint8\" }],\n },\n {\n name: \"getActiveProposal\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"vault\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"proposalCount\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"getGovernorParams\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n components: [\n { name: \"votingPeriod\", type: \"uint256\" },\n { name: \"executionWindow\", type: \"uint256\" },\n { name: \"vetoThresholdBps\", type: \"uint256\" },\n { name: \"maxPerformanceFeeBps\", type: \"uint256\" },\n { name: \"cooldownPeriod\", type: \"uint256\" },\n { name: \"collaborationWindow\", type: \"uint256\" },\n { name: \"maxCoProposers\", type: \"uint256\" },\n { name: \"minStrategyDuration\", type: \"uint256\" },\n { name: \"maxStrategyDuration\", type: \"uint256\" },\n ],\n },\n ],\n },\n {\n name: \"protocolFeeBps\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"guardianFeeBps\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"protocolFeeRecipient\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n];\nexport const SYNDICATE_FACTORY_ABI = [\n {\n name: \"createSyndicate\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"creatorAgentId\", type: \"uint256\" },\n {\n name: \"config\",\n type: \"tuple\",\n components: [\n { name: \"metadataURI\", type: \"string\" },\n { name: \"asset\", type: \"address\" },\n { name: \"name\", type: \"string\" },\n { name: \"symbol\", type: \"string\" },\n { name: \"openDeposits\", type: \"bool\" },\n { name: \"subdomain\", type: \"string\" },\n ],\n },\n ],\n outputs: [\n { name: \"syndicateId\", type: \"uint256\" },\n { name: \"vault\", type: \"address\" },\n ],\n },\n {\n name: \"syndicateCount\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"subdomainToSyndicate\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"subdomain\", type: \"string\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"vaultToSyndicate\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"vault\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"syndicates\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"uint256\" }],\n outputs: [\n { name: \"id\", type: \"uint256\" },\n { name: \"vault\", type: \"address\" },\n { name: \"creator\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"createdAt\", type: \"uint256\" },\n { name: \"active\", type: \"bool\" },\n { name: \"subdomain\", type: \"string\" },\n ],\n },\n {\n name: \"getAllActiveSyndicates\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple[]\",\n components: [\n { name: \"id\", type: \"uint256\" },\n { name: \"vault\", type: \"address\" },\n { name: \"creator\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"createdAt\", type: \"uint256\" },\n { name: \"active\", type: \"bool\" },\n { name: \"subdomain\", type: \"string\" },\n ],\n },\n ],\n },\n];\nexport const GUARDIAN_REGISTRY_ABI = [\n // Guardian stake\n {\n name: \"stakeAsGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"amount\", type: \"uint256\" },\n { name: \"agentId\", type: \"uint256\" },\n ],\n outputs: [],\n },\n {\n name: \"requestUnstakeGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [],\n outputs: [],\n },\n {\n name: \"cancelUnstakeGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [],\n outputs: [],\n },\n {\n name: \"claimUnstakeGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [],\n outputs: [],\n },\n // Delegation\n {\n name: \"delegateStake\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"delegate\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [],\n },\n {\n name: \"requestUnstakeDelegation\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"delegate\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"cancelUnstakeDelegation\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"delegate\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"claimUnstakeDelegation\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"delegate\", type: \"address\" }],\n outputs: [],\n },\n // Commission\n {\n name: \"setCommission\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"bps\", type: \"uint16\" }],\n outputs: [],\n },\n // Claims\n {\n name: \"claimProposalReward\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"claimDelegatorProposalReward\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"delegate\", type: \"address\" },\n { name: \"proposalId\", type: \"uint256\" },\n ],\n outputs: [],\n },\n // Reads\n {\n name: \"guardianStake\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"guardian\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"isActiveGuardian\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"guardian\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n];\nexport const ERC20_ABI = [\n {\n name: \"approve\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"allowance\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"account\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"decimals\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint8\" }],\n },\n {\n name: \"symbol\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\" }],\n },\n];\n// ── ERC-8004 Identity Registry (Agent0) ──\n//\n// Only the `register(string agentURI, MetadataEntry[] metadata)` overload — the\n// one Agent0's `registerOnChain()` actually calls for on-chain data-URI mints.\n// agentURI is a base64 `data:application/json` URI; metadata is `[]` for a basic\n// agent. Selector 0x8ea42286.\nexport const IDENTITY_REGISTRY_ABI = [\n {\n name: \"register\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"agentURI\", type: \"string\" },\n {\n name: \"metadata\",\n type: \"tuple[]\",\n components: [\n { name: \"metadataKey\", type: \"string\" },\n { name: \"metadataValue\", type: \"bytes\" },\n ],\n },\n ],\n outputs: [{ name: \"agentId\", type: \"uint256\" }],\n },\n];\n// ── EAS (Ethereum Attestation Service) — `attest` only ──\n//\n// Used for SYNDICATE_JOIN_REQUEST and AGENT_APPROVED coordination attestations,\n// which always live on Base. Selector 0xf17325e7.\nexport const EAS_ABI = [\n {\n name: \"attest\",\n type: \"function\",\n stateMutability: \"payable\",\n inputs: [\n {\n name: \"request\",\n type: \"tuple\",\n components: [\n { name: \"schema\", type: \"bytes32\" },\n {\n name: \"data\",\n type: \"tuple\",\n components: [\n { name: \"recipient\", type: \"address\" },\n { name: \"expirationTime\", type: \"uint64\" },\n { name: \"revocable\", type: \"bool\" },\n { name: \"refUID\", type: \"bytes32\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n ],\n },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n },\n];\n// StrategyFactory — atomic clone+initialize wrapper for strategy templates.\n// `cloneAndInitDeterministic` deploys the ERC-1167 clone via CREATE2, so the\n// clone address is predictable BEFORE the tx is mined (see\n// `predictStrategyCloneAddress` in encoders/strategy.ts). This is what unblocks\n// keyless / external-signer strategy proposals (issue #387): the proposal's\n// executeCalls + the `strategy` arg can be built against the predicted address\n// up front, so deploy + propose can both be emitted as unsigned calldata.\nexport const STRATEGY_FACTORY_ABI = [\n {\n name: \"cloneAndInit\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"template\", type: \"address\" },\n { name: \"vault\", type: \"address\" },\n { name: \"proposer\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n ],\n outputs: [{ name: \"clone\", type: \"address\" }],\n },\n {\n name: \"cloneAndInitDeterministic\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"template\", type: \"address\" },\n { name: \"vault\", type: \"address\" },\n { name: \"proposer\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"salt\", type: \"bytes32\" },\n ],\n outputs: [{ name: \"clone\", type: \"address\" }],\n },\n {\n name: \"syndicateFactory\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n];\n","import { CHAIN_IDS } from \"./types.js\";\nimport { unsupported } from \"./errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ZERO_BYTES32 = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n// Base EAS predeploy + registered Sherwood coordination schema UIDs. Shared\n// across any chain whose attestations are pinned to Base.\nconst BASE_EAS = {\n chainId: CHAIN_IDS.BASE,\n address: \"0x4200000000000000000000000000000000000021\",\n schemas: {\n joinRequest: \"0x1e7ce17b16233977ba913b156033e98f52029f4bee273a4abefe6c15ce11d5ef\",\n agentApproved: \"0x1013f7b38f433b2a93fc5ac162482813081c64edd67cea9b5a90698531ddb607\",\n },\n};\nconst NO_EAS = {\n chainId: CHAIN_IDS.BASE,\n address: ZERO_ADDRESS,\n schemas: { joinRequest: ZERO_BYTES32, agentApproved: ZERO_BYTES32 },\n};\n// Source of truth for each chain: contracts/chains/{chainId}.json.\n// Mirror manually until cli/contracts/sdk all share a generated table.\nconst BASE = {\n chainId: CHAIN_IDS.BASE,\n name: \"Base\",\n slug: \"base\",\n sherwood: {\n factory: \"0xAC74EC56858d7F1f7618c8e77F65Fc26aDf33c82\",\n governor: \"0x9Fd3c87B34F254e3c5652A0394B9780c2F05d367\",\n guardianRegistry: \"0x49E4163b5e4b23F8f3d469Cf6fa197FB6b06A26E\",\n vaultImpl: \"0xfce4bcE08E9C047E4736f75C2B8557e2754Ce36A\",\n batchExecutorLib: \"0xbC79FbD5036C1Cc4A9d10BDf8628BF09a558496E\",\n // Not yet deployed on Base — fill in `STRATEGY_FACTORY` from\n // contracts/chains/8453.json when it lands (issue #387).\n strategyFactory: ZERO_ADDRESS,\n },\n identityRegistry: \"0x8004A169FB4a3325136EB29fA0ceB6D2e539a432\",\n eas: BASE_EAS,\n tokens: {\n usdc: {\n address: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n symbol: \"USDC\",\n decimals: 6,\n },\n weth: {\n address: \"0x4200000000000000000000000000000000000006\",\n symbol: \"WETH\",\n decimals: 18,\n },\n },\n explorer: \"https://basescan.org\",\n rpcs: [\"https://mainnet.base.org\"],\n};\nconst HYPEREVM = {\n chainId: CHAIN_IDS.HYPEREVM,\n name: \"HyperEVM\",\n slug: \"hyperevm\",\n sherwood: {\n factory: \"0xd05Ae0E8bcf13075C29817c805d6Cc14F214393a\",\n governor: \"0x67AD3D5F3d127Ef923Fd6f67b178633c408D3fd3\",\n guardianRegistry: \"0x8b5710EB4e2fA639F364Dcc3F3B30c8f12F460b9\",\n vaultImpl: \"0x2cbBe36Cf907A2BB410bacB0e4Fd632C7b012846\",\n batchExecutorLib: \"0x2c454bEF1b09c8a306a7058b8B510bF0DfF7179D\",\n strategyFactory: ZERO_ADDRESS,\n },\n // ERC-8004 identity is minted on Base; HyperEVM syndicates reference the\n // Base-minted token id. Coordination attestations are pinned to Base EAS.\n identityRegistry: ZERO_ADDRESS,\n eas: BASE_EAS,\n tokens: {\n usdc: {\n address: \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\",\n symbol: \"USDC\",\n decimals: 6,\n },\n },\n explorer: \"https://hyperliquid.cloud.blockscout.com\",\n rpcs: [\"https://rpc.hyperliquid.xyz/evm\"],\n};\nconst ROBINHOOD_L2 = {\n chainId: CHAIN_IDS.ROBINHOOD_L2,\n name: \"Robinhood L2 Testnet\",\n slug: \"robinhood-l2\",\n sherwood: {\n factory: \"0x6d026e2f5Ff0C34A01690EC46Cb601B8fF391985\",\n governor: \"0xd882056ba6b0aEd8908c541884B327121E2f2C9C\",\n // Robinhood L2 doesn't have a guardian registry yet; use zero so callers\n // get a clear UNSUPPORTED rather than a confusing revert downstream.\n guardianRegistry: \"0x0000000000000000000000000000000000000000\",\n vaultImpl: \"0xF4720523325f9A4546F43391484DCd1D28dFc266\",\n batchExecutorLib: \"0x1493f5a7E5d82e1e56c34e2Ba300f56F97186017\",\n strategyFactory: ZERO_ADDRESS,\n },\n // No ERC-8004 registry and no EAS path on Robinhood L2.\n identityRegistry: ZERO_ADDRESS,\n eas: NO_EAS,\n tokens: {},\n explorer: \"https://explorer-robinhood-l2.t.conduit.xyz\",\n rpcs: [\"https://rpc-robinhood-l2.t.conduit.xyz\"],\n};\nconst REGISTRY = {\n [CHAIN_IDS.BASE]: BASE,\n [CHAIN_IDS.HYPEREVM]: HYPEREVM,\n [CHAIN_IDS.ROBINHOOD_L2]: ROBINHOOD_L2,\n};\nexport function getDeployment(chainId) {\n const entry = REGISTRY[chainId];\n if (!entry)\n throw unsupported(`No Sherwood deployment for chain ${chainId}`);\n return entry;\n}\nexport function listDeployments() {\n return Object.values(REGISTRY);\n}\n/** Network slug for join-request message prefixes (e.g. 8453 → \"base\"). */\nexport function chainSlug(chainId) {\n return getDeployment(chainId).slug;\n}\n","import { encodeFunctionData, getAddress, maxUint256 } from \"viem\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { usage } from \"../errors.js\";\n/** Minimal WETH9 `deposit()` (payable) fragment — for the ETH→WETH wrap leg. */\nconst WETH_ABI = [\n {\n name: \"deposit\",\n type: \"function\",\n stateMutability: \"payable\",\n inputs: [],\n outputs: [],\n },\n];\nconst ZERO_VALUE = \"0x0\";\nfunction toHexValue(value) {\n return `0x${value.toString(16)}`;\n}\nfunction encodeApproveTx(token, spender, amount, chainId) {\n return {\n to: token,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [spender, amount],\n }),\n value: ZERO_VALUE,\n chainId,\n };\n}\nfunction encodeDepositTx(vault, assets, receiver, chainId) {\n return {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"deposit\",\n args: [assets, receiver],\n }),\n value: ZERO_VALUE,\n chainId,\n };\n}\n/**\n * Encode the calldata for an ERC-4626 vault deposit.\n *\n * Returns 1–2 transactions:\n * - If `currentAllowance` is provided and >= `assets`, only the `deposit` tx.\n * - Otherwise, an `approve(spender=vault, amount=assets)` tx followed by the\n * `deposit` tx. Agents that already have an unlimited allowance can drop\n * the first tx after checking the `allowance` precondition.\n *\n * The SDK never reads chain state — pass `currentAllowance` if you want a\n * precise plan; otherwise expect the conservative two-tx default.\n */\nexport function encodeDeposit(args, chainId) {\n if (args.assets <= 0n) {\n throw usage(\"`assets` must be > 0\");\n }\n const vault = getAddress(args.vault);\n const receiver = getAddress(args.receiver);\n const asset = getAddress(args.asset);\n const txs = [];\n // Optional ETH→WETH wrap leg (WETH vaults only). Prepended so the wrap lands\n // before the approve/deposit. Wraps only the shortfall when a balance is given.\n let wrapped = false;\n if (args.wrapEth) {\n const weth = getDeployment(chainId).tokens.weth;\n if (!weth || getAddress(weth.address) !== asset) {\n throw usage(\"`wrapEth` is only valid for WETH vaults — the vault asset must be the chain's WETH.\");\n }\n const held = args.currentWethBalance ?? 0n;\n const shortfall = held >= args.assets ? 0n : args.assets - held;\n if (shortfall > 0n) {\n txs.push({\n to: asset,\n data: encodeFunctionData({ abi: WETH_ABI, functionName: \"deposit\", args: [] }),\n value: toHexValue(shortfall),\n chainId,\n });\n wrapped = true;\n }\n }\n const needsApprove = args.currentAllowance === undefined || args.currentAllowance < args.assets;\n if (needsApprove) {\n txs.push(encodeApproveTx(asset, vault, maxUint256, chainId));\n }\n txs.push(encodeDepositTx(vault, args.assets, receiver, chainId));\n const minDecimal = formatUnits(args.assets, args.assetDecimals);\n let description;\n if (wrapped) {\n description = needsApprove\n ? `Wrap ETH→WETH, approve ${args.assetSymbol} for ${vault}, then deposit ${minDecimal} ${args.assetSymbol}.`\n : `Wrap ETH→WETH, then deposit ${minDecimal} ${args.assetSymbol}.`;\n }\n else {\n description = needsApprove\n ? `Approve ${args.assetSymbol} for ${vault}, then deposit ${minDecimal} ${args.assetSymbol}.`\n : `Deposit ${minDecimal} ${args.assetSymbol} into ${vault}.`;\n }\n return {\n txs,\n preconditions: [\n {\n type: \"balance\",\n asset,\n assetSymbol: args.assetSymbol,\n min: args.assets.toString(),\n minDecimal,\n },\n {\n type: \"allowance\",\n token: asset,\n spender: vault,\n min: args.assets.toString(),\n minDecimal,\n },\n { type: \"vault-not-locked\", vault },\n { type: \"depositor-approved\", vault, depositor: receiver },\n ],\n description,\n note: \"Both txs are gated by vault state. If `redemptionsLocked()` is true the deposit reverts unless live NAV is available; check the vault read endpoint before broadcasting.\",\n };\n}\n/** Internal: decimal-string formatter so we don't pull in a heavy dep. */\nfunction formatUnits(value, decimals) {\n if (decimals === 0)\n return value.toString();\n const negative = value < 0n;\n const abs = negative ? -value : value;\n const str = abs.toString().padStart(decimals + 1, \"0\");\n const head = str.slice(0, str.length - decimals);\n const tail = str.slice(str.length - decimals).replace(/0+$/, \"\");\n const out = tail.length > 0 ? `${head}.${tail}` : head;\n return negative ? `-${out}` : out;\n}\n// Re-export for tests / callers that want to pre-format previews.\nexport { formatUnits };\n// Tiny helpers exported for the API layer to convert plan-level UnsignedTx\n// into the on-the-wire JSON shape with a hex `value`. Kept here so encoders\n// own their wire representation end to end.\nexport { toHexValue };\nexport function encodeRedeem(args, chainId) {\n if (args.shares <= 0n)\n throw usage(\"`shares` must be > 0\");\n const vault = getAddress(args.vault);\n const receiver = getAddress(args.receiver);\n const owner = getAddress(args.owner);\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"redeem\",\n args: [args.shares, receiver, owner],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [\n { type: \"vault-not-locked\", vault },\n ],\n description: `Redeem ${args.shares.toString()} shares of ${vault} → ${receiver}.`,\n note: \"Synchronous path. Reverts if the vault has an active proposal AND live NAV is unavailable; in that case use /prepare/request-redeem (queue path) instead.\",\n };\n}\nexport function encodeRequestRedeem(args, chainId) {\n if (args.shares <= 0n)\n throw usage(\"`shares` must be > 0\");\n const vault = getAddress(args.vault);\n const owner = getAddress(args.owner);\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"requestRedeem\",\n args: [args.shares, owner],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [],\n description: `Queue a redeem request for ${args.shares.toString()} shares of ${vault}.`,\n note: \"Only callable while `redemptionsLocked() == true`. Shares are escrowed in the per-vault queue; claim with the queue's `claim(requestId)` once the proposal settles.\",\n };\n}\n// ── Owner-side admin encoders ─────────────────────────────\nexport function encodeApproveDepositor(args, chainId) {\n const vault = getAddress(args.vault);\n const depositor = getAddress(args.depositor);\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"approveDepositor\",\n args: [depositor],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [],\n description: `Approve depositor ${depositor} on vault ${vault}.`,\n note: \"Vault owner only.\",\n };\n}\nexport function encodeRegisterAgent(args, chainId) {\n const vault = getAddress(args.vault);\n const agentAddress = getAddress(args.agentAddress);\n const id = typeof args.agentId === \"bigint\" ? args.agentId : BigInt(args.agentId);\n if (id < 0n)\n throw usage(\"`agentId` must be a non-negative integer\");\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"registerAgent\",\n args: [agentAddress, id],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [],\n description: `Register agent ${agentAddress} (id ${id.toString()}) on vault ${vault}.`,\n note: \"Vault owner only. The ERC-8004 NFT must be owned by `agentAddress` or by the vault owner at registration time.\",\n };\n}\n","import { encodeFunctionData, getAddress, isAddress } from \"viem\";\nimport { SYNDICATE_GOVERNOR_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { usage } from \"../errors.js\";\nconst ZERO_VALUE = \"0x0\";\nexport const VOTE_TYPES = {\n For: 0,\n Against: 1,\n Abstain: 2,\n};\nfunction governorTx(chainId, data) {\n return {\n to: getDeployment(chainId).sherwood.governor,\n data,\n value: ZERO_VALUE,\n chainId,\n };\n}\nfunction parseProposalId(value) {\n if (typeof value === \"bigint\") {\n if (value < 0n)\n throw usage(\"`proposalId` must be a non-negative integer\");\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0) {\n throw usage(\"`proposalId` must be a non-negative integer\");\n }\n return BigInt(value);\n }\n if (!/^\\d+$/.test(value)) {\n throw usage(`\\`proposalId\\` must be a non-negative integer string, got \"${value}\"`);\n }\n return BigInt(value);\n}\nexport function encodeVote(args, chainId) {\n const support = VOTE_TYPES[args.vote];\n if (support === undefined) {\n throw usage(`Unsupported vote \"${args.vote}\" — must be one of: ${Object.keys(VOTE_TYPES).join(\", \")}`);\n }\n const proposalId = parseProposalId(args.proposalId);\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"vote\",\n args: [proposalId, support],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Vote ${args.vote} on proposal ${proposalId.toString()}.`,\n note: \"Voter must hold ERC20Votes shares of the vault at the proposal's snapshot timestamp; double-voting reverts. Use the proposal read endpoint to check `voteEnd` first.\",\n };\n}\nfunction lifecycleAction(fn, proposalId, chainId, description, note) {\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: fn,\n args: [proposalId],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description,\n note,\n };\n}\nexport function encodeExecute(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"executeProposal\", id, chainId, `Execute proposal ${id.toString()} (open the strategy).`, \"Reverts if the proposal is not in the `Approved` state. Check `state == Approved` via the proposal read endpoint first.\");\n}\nexport function encodeSettle(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"settleProposal\", id, chainId, `Settle proposal ${id.toString()} (close the strategy and distribute fees).`, \"Proposer can settle anytime; anyone can settle after the strategy duration elapses.\");\n}\nexport function encodeCancel(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"cancelProposal\", id, chainId, `Cancel proposal ${id.toString()} (proposer-only).`, \"Only the proposer can cancel, and only while the proposal is in `Pending`, `GuardianReview`, or `Approved`.\");\n}\nexport function encodeVeto(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"vetoProposal\", id, chainId, `Veto proposal ${id.toString()} (vault-owner only, only while \\`Pending\\`).`, \"Vault owner only. Reverts after the proposal enters `GuardianReview`. To block at that point, depend on guardian block-quorum.\");\n}\nexport { parseProposalId };\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nfunction validateBatchCall(call, scope, idx) {\n if (!call || typeof call !== \"object\") {\n throw usage(`\\`${scope}[${idx}]\\` must be an object`);\n }\n const c = call;\n if (typeof c.target !== \"string\" || !isAddress(c.target)) {\n throw usage(`\\`${scope}[${idx}].target\\` must be a 0x-prefixed address`);\n }\n if (typeof c.data !== \"string\" || !/^0x[0-9a-fA-F]*$/.test(c.data)) {\n throw usage(`\\`${scope}[${idx}].data\\` must be a 0x-prefixed hex string`);\n }\n let value;\n if (typeof c.value === \"string\") {\n if (!/^\\d+$/.test(c.value)) {\n throw usage(`\\`${scope}[${idx}].value\\` must be a non-negative integer string`);\n }\n value = BigInt(c.value);\n }\n else if (typeof c.value === \"bigint\") {\n if (c.value < 0n) {\n throw usage(`\\`${scope}[${idx}].value\\` must be non-negative`);\n }\n value = c.value;\n }\n else if (c.value === undefined || c.value === null) {\n value = 0n;\n }\n else {\n throw usage(`\\`${scope}[${idx}].value\\` must be a non-negative integer string (or omitted for 0)`);\n }\n return { target: getAddress(c.target), data: c.data, value };\n}\nexport function encodePropose(args, chainId) {\n const vault = getAddress(args.vault);\n const strategy = args.strategy === ZERO_ADDRESS ? ZERO_ADDRESS : getAddress(args.strategy);\n if (typeof args.metadataURI !== \"string\" || args.metadataURI.length === 0) {\n throw usage(\"`metadataURI` must be a non-empty string (e.g. ipfs://...)\");\n }\n if (!Number.isInteger(args.performanceFeeBps) ||\n args.performanceFeeBps < 0 ||\n args.performanceFeeBps > 10_000) {\n throw usage(\"`performanceFeeBps` must be an integer in [0, 10000]\");\n }\n const strategyDuration = typeof args.strategyDuration === \"bigint\"\n ? args.strategyDuration\n : BigInt(args.strategyDuration);\n if (strategyDuration <= 0n) {\n throw usage(\"`strategyDuration` must be > 0 (seconds)\");\n }\n if (!Array.isArray(args.executeCalls)) {\n throw usage(\"`executeCalls` must be an array of {target, data, value} objects\");\n }\n if (!Array.isArray(args.settlementCalls)) {\n throw usage(\"`settlementCalls` must be an array of {target, data, value} objects\");\n }\n const executeCalls = args.executeCalls.map((c, i) => validateBatchCall(c, \"executeCalls\", i));\n const settlementCalls = args.settlementCalls.map((c, i) => validateBatchCall(c, \"settlementCalls\", i));\n const coProposers = (args.coProposers ?? []).map((cp, i) => {\n if (!cp || typeof cp !== \"object\") {\n throw usage(`\\`coProposers[${i}]\\` must be an object`);\n }\n const agent = cp.agent;\n const splitBps = cp.splitBps;\n if (typeof agent !== \"string\" || !isAddress(agent)) {\n throw usage(`\\`coProposers[${i}].agent\\` must be a 0x-prefixed address`);\n }\n let bps;\n if (typeof splitBps === \"string\" && /^\\d+$/.test(splitBps)) {\n bps = BigInt(splitBps);\n }\n else if (typeof splitBps === \"bigint\") {\n bps = splitBps;\n }\n else if (typeof splitBps === \"number\" && Number.isInteger(splitBps) && splitBps >= 0) {\n bps = BigInt(splitBps);\n }\n else {\n throw usage(`\\`coProposers[${i}].splitBps\\` must be a non-negative integer (string, number, or bigint)`);\n }\n if (bps < 0n || bps > 10000n) {\n throw usage(`\\`coProposers[${i}].splitBps\\` must be in [0, 10000]`);\n }\n return { agent: getAddress(agent), splitBps: bps };\n });\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"propose\",\n args: [\n vault,\n strategy,\n args.metadataURI,\n BigInt(args.performanceFeeBps),\n strategyDuration,\n executeCalls,\n settlementCalls,\n coProposers,\n ],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [\n { type: \"vault-not-locked\", vault },\n ],\n description: `Propose a strategy on ${vault} (duration ${strategyDuration.toString()}s, fee ${args.performanceFeeBps} bps).`,\n note: \"Reverts if the vault has an active proposal (cooldown not elapsed). The strategy address is immutable post-propose; pass address(0) to opt out of live NAV. `coProposers[].splitBps` total must satisfy contract-side constraints.\",\n };\n}\n// ── Emergency settlement (GovernorEmergency, V1.5) ───────\nexport function encodeUnstick(args, chainId) {\n const id = parseProposalId(args.proposalId);\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"unstick\",\n args: [id],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Unstick proposal ${id.toString()} — run its governance-approved settlement calls (owner-instant, no funds beyond the approved calls).`,\n note: \"Vault-owner only. Valid only when the proposal is Executed AND its strategy duration has elapsed. Runs the proposal's pre-committed settlement calls and finalizes settlement; no owner stake required. Reverts if those calls revert — if they can't succeed, open an emergency-settle with custom unwind calls instead.\",\n };\n}\nexport function encodeEmergencySettle(args, chainId) {\n const id = parseProposalId(args.proposalId);\n if (!Array.isArray(args.calls)) {\n throw usage(\"`calls` must be an array of {target, data, value} objects\");\n }\n const calls = args.calls.map((c, i) => validateBatchCall(c, \"calls\", i));\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"emergencySettleWithCalls\",\n args: [id, calls],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Open an emergency-settle review on proposal ${id.toString()} with ${calls.length} unwind call(s).`,\n note: \"Vault-owner only, requires bonded owner stake. Does NOT execute immediately — it commits the calls' hash and opens a guardian-reviewed window (default ~24h). After the window, finalize with finalizeEmergencySettle; guardians can block within it (owner stake burned on block-quorum).\",\n };\n}\n// ── Parameter setters (GovernorParameters, V1.5) ─────────\nfunction parseUintArg(value, label) {\n if (typeof value === \"bigint\") {\n if (value < 0n)\n throw usage(`\\`${label}\\` must be a non-negative integer`);\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0) {\n throw usage(`\\`${label}\\` must be a non-negative integer`);\n }\n return BigInt(value);\n }\n if (!/^\\d+$/.test(value)) {\n throw usage(`\\`${label}\\` must be a non-negative integer string, got \"${value}\"`);\n }\n return BigInt(value);\n}\n/**\n * Maps a friendly parameter name to its on-chain setter. Every setter takes a\n * single uint256 and is owner-instant (V1.5 dropped the on-chain timelock).\n */\nconst GOVERNOR_PARAM_SETTERS = {\n votingPeriod: \"setVotingPeriod\",\n executionWindow: \"setExecutionWindow\",\n vetoThresholdBps: \"setVetoThresholdBps\",\n maxPerformanceFeeBps: \"setMaxPerformanceFeeBps\",\n maxStrategyDuration: \"setMaxStrategyDuration\",\n cooldownPeriod: \"setCooldownPeriod\",\n protocolFeeBps: \"setProtocolFeeBps\",\n};\nexport function encodeGovernorParam(args, chainId) {\n const fn = GOVERNOR_PARAM_SETTERS[args.param];\n if (!fn) {\n throw usage(`Unknown governor param \"${args.param}\" — must be one of: ${Object.keys(GOVERNOR_PARAM_SETTERS).join(\", \")}`);\n }\n const value = parseUintArg(args.value, args.param);\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: fn,\n args: [value],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Set governor parameter ${args.param} = ${value.toString()}.`,\n note: \"Owner-only (the owner multisig). V1.5 has no on-chain parameter timelock — the change applies immediately on this call. Bounds are validated on-chain; out-of-range values revert. Setting a non-zero protocolFeeBps reverts unless protocolFeeRecipient is already set.\",\n };\n}\n","import { encodeFunctionData, getAddress } from \"viem\";\nimport { SYNDICATE_FACTORY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { usage } from \"../errors.js\";\nconst ZERO_VALUE = \"0x0\";\nconst SUBDOMAIN_RE = /^[a-z0-9-]{1,63}$/;\nexport function encodeCreateSyndicate(args, chainId) {\n if (typeof args.metadataURI !== \"string\" || args.metadataURI.length === 0) {\n throw usage(\"`metadataURI` must be a non-empty string (e.g. ipfs://...)\");\n }\n if (typeof args.name !== \"string\" || args.name.length === 0) {\n throw usage(\"`name` must be a non-empty string\");\n }\n if (typeof args.symbol !== \"string\" || args.symbol.length === 0) {\n throw usage(\"`symbol` must be a non-empty string\");\n }\n if (typeof args.openDeposits !== \"boolean\") {\n throw usage(\"`openDeposits` must be a boolean\");\n }\n if (!SUBDOMAIN_RE.test(args.subdomain)) {\n throw usage(\"`subdomain` must match /^[a-z0-9-]{1,63}$/ (lowercase letters, digits, hyphens)\");\n }\n const asset = getAddress(args.asset);\n const creatorAgentId = typeof args.creatorAgentId === \"bigint\"\n ? args.creatorAgentId\n : BigInt(args.creatorAgentId);\n if (creatorAgentId < 0n)\n throw usage(\"`creatorAgentId` must be non-negative\");\n const factory = getDeployment(chainId).sherwood.factory;\n const data = encodeFunctionData({\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"createSyndicate\",\n args: [\n creatorAgentId,\n {\n metadataURI: args.metadataURI,\n asset,\n name: args.name,\n symbol: args.symbol,\n openDeposits: args.openDeposits,\n subdomain: args.subdomain,\n },\n ],\n });\n return {\n txs: [{ to: factory, data, value: ZERO_VALUE, chainId }],\n preconditions: [\n // Creator must own the ERC-8004 NFT for `creatorAgentId` and have\n // pre-staked the owner bond via guardianRegistry.prepareOwnerStake.\n // No on-chain check from the SDK side — agent verifies upstream.\n ],\n description: `Create syndicate \"${args.subdomain}\" with ${args.openDeposits ? \"open\" : \"whitelisted\"} deposits.`,\n note: \"Caller must own the ERC-8004 NFT for `creatorAgentId` and must have called `guardianRegistry.prepareOwnerStake` first to bond the owner stake. The factory's `createSyndicate` deploys a vault proxy + binds the owner stake atomically.\",\n };\n}\n","import { concatHex, encodeAbiParameters, encodeFunctionData, encodePacked, getAddress, getCreate2Address, isHex, keccak256, } from \"viem\";\nimport { STRATEGY_FACTORY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { unavailable, usage } from \"../errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ZERO_VALUE = \"0x0\";\n// ERC-1167 minimal-proxy creation code, split around the 20-byte implementation\n// address. Byte-identical to OpenZeppelin `Clones.sol` (the same bytes\n// `StrategyFactory.cloneAndInitDeterministic` deploys via CREATE2), so the\n// CREATE2 address derived from it matches `Clones.predictDeterministicAddress`.\nconst ERC1167_PREFIX = \"0x3d602d80600a3d3981f3363d3d373d3d3d363d73\";\nconst ERC1167_SUFFIX = \"0x5af43d82803e903d91602b57fd5bf3\";\n/**\n * Predict the CREATE2 address of an ERC-1167 clone of `template` deployed by\n * `factory` with `salt`. Mirrors OpenZeppelin `Clones.predictDeterministicAddress`.\n *\n * Pure — no RPC. The clone is deterministic in `(factory, template, salt)`\n * ONLY; it does NOT depend on `vault`/`proposer`. See `deriveStrategySalt` and\n * the note in `encodeStrategyDeploy` for the front-running implication.\n */\nexport function predictStrategyCloneAddress(factory, template, salt) {\n const initCode = concatHex([\n ERC1167_PREFIX,\n getAddress(template),\n ERC1167_SUFFIX,\n ]);\n return getCreate2Address({\n from: getAddress(factory),\n salt,\n bytecode: initCode,\n });\n}\n/**\n * Default CREATE2 salt for a strategy deploy: a keccak of the inputs. Two deploys\n * with identical `(vault, proposer, template, initData)` collide (the second\n * `cloneAndInitDeterministic` reverts, address already taken) — pass an explicit\n * `salt` to re-deploy the same parameters (e.g. propose → cancel → re-propose).\n */\nexport function deriveStrategySalt(vault, proposer, template, initData) {\n return keccak256(encodePacked([\"address\", \"address\", \"address\", \"bytes\"], [getAddress(vault), getAddress(proposer), getAddress(template), initData]));\n}\n/**\n * The actual CREATE2 salt the factory uses: `keccak256(abi.encode(vault, salt))`.\n *\n * `StrategyFactory.cloneAndInitDeterministic` folds the vault into the salt so\n * the predicted address lives in a per-vault namespace; combined with the\n * factory's `_authClone(vault)` gate (only the vault's owner/agents may deploy),\n * a front-runner who reads `salt` from the mempool cannot occupy the address.\n * This MUST stay byte-identical to the on-chain fold or predictions diverge from\n * the deployed address.\n */\nexport function effectiveStrategySalt(vault, salt) {\n return keccak256(encodeAbiParameters([{ type: \"address\" }, { type: \"bytes32\" }], [getAddress(vault), salt]));\n}\nfunction requireSalt(value) {\n if (typeof value !== \"string\" || !isHex(value) || value.length !== 66) {\n throw usage(\"`salt` must be a 0x-prefixed 32-byte hex string (66 chars)\");\n }\n return value;\n}\n/**\n * Encode `StrategyFactory.cloneAndInitDeterministic(template, vault, proposer,\n * initData, salt)` — one unsigned tx that atomically clones the template via\n * CREATE2 and initializes it. Returns the predicted clone address so the caller\n * can build the proposal's `strategy` arg + executeCalls/settlementCalls against\n * it BEFORE the tx is mined — which is what unblocks keyless strategy proposals\n * (#387). Works for any template (Moonwell, Aerodrome, Venice, Portfolio, …):\n * the mechanism is template-agnostic, only `initData` differs.\n */\nexport function encodeStrategyDeploy(args, chainId) {\n const template = getAddress(args.template);\n const vault = getAddress(args.vault);\n const proposer = getAddress(args.proposer);\n if (typeof args.initData !== \"string\" || !isHex(args.initData)) {\n throw usage(\"`initData` must be a 0x-prefixed hex string\");\n }\n if (template === ZERO_ADDRESS) {\n throw usage(\"`template` must be a non-zero address\");\n }\n if (proposer === ZERO_ADDRESS) {\n throw usage(\"`proposer` must be a non-zero address\");\n }\n const factory = args.factory\n ? getAddress(args.factory)\n : getDeployment(chainId).sherwood.strategyFactory;\n if (factory === ZERO_ADDRESS) {\n throw unavailable(`StrategyFactory is not yet deployed on chain ${chainId} — mirror its address into the SDK once it lands (issue #387), or pass an explicit \\`factory\\`.`);\n }\n // `salt` is what's passed in the calldata; the factory folds the vault in\n // (keccak256(abi.encode(vault, salt))) before CREATE2, so the prediction must\n // fold too — see `effectiveStrategySalt`.\n const salt = args.salt\n ? requireSalt(args.salt)\n : deriveStrategySalt(vault, proposer, template, args.initData);\n const clone = predictStrategyCloneAddress(factory, template, effectiveStrategySalt(vault, salt));\n const data = encodeFunctionData({\n abi: STRATEGY_FACTORY_ABI,\n functionName: \"cloneAndInitDeterministic\",\n args: [template, vault, proposer, args.initData, salt],\n });\n const tx = { to: factory, data, value: ZERO_VALUE, chainId };\n return {\n txs: [tx],\n preconditions: [],\n clone,\n salt,\n factory,\n description: `Deploy a strategy clone of ${template} for vault ${vault} (deterministic — clone at ${clone}).`,\n note: \"Broadcast this tx from `proposer` — the factory requires proposer == msg.sender, and msg.sender must be the vault owner or a registered agent. The vault must be registered on the SyndicateFactory and `template` must be on the factory's allowlist (the factory reverts otherwise). The clone address is fixed by (factory, template, vault, salt) — reference it as the proposal `strategy` and inside executeCalls/settlementCalls. The factory binds the salt to the vault, and `_authClone` lets only the vault's owner/agents deploy there, so the predicted address can't be front-run.\",\n };\n}\n","import { encodeFunctionData, getAddress } from \"viem\";\nimport { IDENTITY_REGISTRY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { unsupported, usage } from \"../errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ERC8004_TYPE = \"https://eips.ethereum.org/EIPS/eip-8004#registration-v1\";\nconst B64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n/**\n * Standard base64 of a UTF-8 string using only ES built-ins (no Buffer / btoa /\n * TextEncoder) so the SDK stays browser-safe and Node-types-free. Byte-identical\n * to `Buffer.from(str, \"utf8\").toString(\"base64\")` — pinned by the golden mint\n * test against the confirmed on-chain calldata.\n */\nfunction toBase64Utf8(str) {\n // UTF-8 bytes as a Latin1 (\"binary\") string via encodeURIComponent.\n const bin = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));\n let out = \"\";\n for (let i = 0; i < bin.length; i += 3) {\n const a = bin.charCodeAt(i);\n const hasB = i + 1 < bin.length;\n const hasC = i + 2 < bin.length;\n const b = hasB ? bin.charCodeAt(i + 1) : 0;\n const c = hasC ? bin.charCodeAt(i + 2) : 0;\n out += B64_ALPHABET[a >> 2];\n out += B64_ALPHABET[((a & 3) << 4) | (b >> 4)];\n out += hasB ? B64_ALPHABET[((b & 15) << 2) | (c >> 6)] : \"=\";\n out += hasC ? B64_ALPHABET[c & 63] : \"=\";\n }\n return out;\n}\n/**\n * Encode an ERC-8004 agent-identity mint as a single `register(agentURI, [])`\n * call against the IdentityRegistry — the same on-chain shape Agent0's\n * `registerOnChain()` produces, but built with viem only (no Agent0 SDK / IPFS).\n *\n * `agentURI` is a `data:application/json;base64,…` URI carrying the ERC-8004\n * registration JSON. The registry assigns the next token id and stores the URI;\n * the soft metadata fields don't affect the mint. The minted `chainId:tokenId`\n * is referenced cross-chain when creating/joining syndicates.\n *\n * ERC-8004 lives on Base only — throws UNSUPPORTED on other chains.\n */\nexport function encodeIdentityMint(args, chainId) {\n const registry = getDeployment(chainId).identityRegistry;\n if (registry === ZERO_ADDRESS) {\n throw unsupported(`ERC-8004 identity registry is not deployed on chain ${chainId} — mint on Base (8453).`);\n }\n if (!args.name)\n throw usage(\"`name` is required\");\n if (!args.description)\n throw usage(\"`description` is required\");\n // Key order is significant for byte-stable output — mirrors Agent0's\n // on-chain data-URI registration JSON: type, name, description, image?,\n // services, active, x402Support.\n const reg = {\n type: ERC8004_TYPE,\n name: args.name,\n description: args.description,\n };\n if (args.image)\n reg.image = args.image;\n reg.services = [];\n reg.active = args.active ?? true;\n reg.x402Support = args.x402Support ?? false;\n const json = JSON.stringify(reg);\n const dataUri = `data:application/json;base64,${toBase64Utf8(json)}`;\n return {\n txs: [\n {\n to: getAddress(registry),\n data: encodeFunctionData({\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"register\",\n args: [dataUri, []],\n }),\n value: \"0x0\",\n chainId,\n },\n ],\n preconditions: [],\n description: `Mint an ERC-8004 agent identity \"${args.name}\" on chain ${chainId}.`,\n note: \"ERC-8004 identity is minted on Base. Read the resulting token id from the mint receipt (chainId:tokenId); reference it when creating or joining syndicates.\",\n };\n}\n","import { encodeAbiParameters, encodeFunctionData, getAddress, parseAbiParameters, } from \"viem\";\nimport { EAS_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { encodeRegisterAgent } from \"./vault.js\";\nimport { unsupported } from \"../errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ZERO_BYTES32 = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\nconst JOIN_REQUEST_PARAMS = parseAbiParameters(\"uint256, uint256, address, string\");\nconst AGENT_APPROVED_PARAMS = parseAbiParameters(\"uint256, uint256, address\");\nconst toBig = (x) => (typeof x === \"bigint\" ? x : BigInt(x));\n// ── Message-prefix helpers (ported from cli/src/lib/eas.ts) ──\n//\n// Join-request messages carry CLI metadata as bracketed prefixes so a creator\n// querying Base EAS can recover the source chain + referrer. Order is\n// `[chain:<slug>] [ref:<id>] body` — chain outer, ref inner. Kept byte-identical\n// to the CLI so calldata-built join requests are indistinguishable from\n// CLI-signed ones in `sherwood syndicate requests`.\nfunction formatMessageWithRef(message, referrerAgentId) {\n if (referrerAgentId == null)\n return message;\n return `[ref:${referrerAgentId}] ${message}`;\n}\nfunction formatMessageWithChain(message, sourceSlug, easSlug) {\n if (sourceSlug === easSlug)\n return message;\n return `[chain:${sourceSlug}] ${message}`;\n}\n/** Build an EAS `attest` tx (revocable, no expiry, no refUID, zero value). */\nfunction buildAttestTx(easAddress, schema, recipient, data, chainId) {\n return {\n to: getAddress(easAddress),\n data: encodeFunctionData({\n abi: EAS_ABI,\n functionName: \"attest\",\n args: [\n {\n schema,\n data: {\n recipient,\n expirationTime: 0n,\n revocable: true,\n refUID: ZERO_BYTES32,\n data,\n value: 0n,\n },\n },\n ],\n }),\n value: \"0x0\",\n chainId,\n };\n}\n/**\n * Encode a SYNDICATE_JOIN_REQUEST EAS attestation (agent → creator).\n *\n * The attest tx ALWAYS lands on Base (where coordination attestations live),\n * even when the syndicate runs on another chain — a `[chain:<slug>]` prefix is\n * added to the message so the creator can recover the source chain. Throws\n * UNSUPPORTED on chains with no EAS path (Robinhood).\n */\nexport function encodeJoinRequest(args, chainId) {\n const dep = getDeployment(chainId);\n const eas = dep.eas;\n if (eas.address === ZERO_ADDRESS) {\n throw unsupported(`No EAS coordination path on chain ${chainId} — join requests require a chain whose attestations are pinned to Base.`);\n }\n const easSlug = getDeployment(eas.chainId).slug;\n const message = formatMessageWithChain(formatMessageWithRef(args.message, args.referrerAgentId), dep.slug, easSlug);\n const data = encodeAbiParameters(JOIN_REQUEST_PARAMS, [\n toBig(args.syndicateId),\n toBig(args.agentId),\n getAddress(args.vault),\n message,\n ]);\n return {\n txs: [\n buildAttestTx(eas.address, eas.schemas.joinRequest, getAddress(args.creator), data, eas.chainId),\n ],\n preconditions: [],\n description: `Request to join syndicate ${toBig(args.syndicateId).toString()} (vault ${getAddress(args.vault)}).`,\n note: \"EAS coordination attestation — always submitted on Base, even for syndicates on another chain. Revocable; the creator discovers it via the join-request schema.\",\n };\n}\n/**\n * Encode the two txs a creator submits to approve an agent:\n * 1. `vault.registerAgent(agentAddress, agentId)` on the syndicate's own chain\n * 2. AGENT_APPROVED EAS attestation on Base\n *\n * These land on two different chains — `txs[0].chainId` is the syndicate chain,\n * `txs[1].chainId` is Base.\n */\nexport function encodeApproveAgent(args, chainId) {\n const dep = getDeployment(chainId);\n const eas = dep.eas;\n if (eas.address === ZERO_ADDRESS) {\n throw unsupported(`No EAS coordination path on chain ${chainId} — approvals require a chain whose attestations are pinned to Base.`);\n }\n const registerTx = encodeRegisterAgent({\n vault: args.vault,\n agentAddress: args.agentAddress,\n agentId: toBig(args.agentId),\n }, chainId).txs[0];\n const data = encodeAbiParameters(AGENT_APPROVED_PARAMS, [\n toBig(args.syndicateId),\n toBig(args.agentId),\n getAddress(args.vault),\n ]);\n const attestTx = buildAttestTx(eas.address, eas.schemas.agentApproved, getAddress(args.agentAddress), data, eas.chainId);\n return {\n txs: [registerTx, attestTx],\n preconditions: [],\n description: `Approve agent ${toBig(args.agentId).toString()} for syndicate ${toBig(args.syndicateId).toString()}: register on the vault (chain ${chainId}) + AGENT_APPROVED attestation on Base.`,\n note: \"Vault owner only. Two txs on two chains: registerAgent runs on the syndicate's chain; the approval attestation runs on Base.\",\n };\n}\n","import { encodeFunctionData, getAddress } from \"viem\";\nimport { GUARDIAN_REGISTRY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { unsupported, usage } from \"../errors.js\";\nconst ZERO_VALUE = \"0x0\";\nfunction registryTx(chainId, data) {\n const registry = getDeployment(chainId).sherwood.guardianRegistry;\n if (registry === \"0x0000000000000000000000000000000000000000\") {\n throw unsupported(`Guardian registry is not deployed on chain ${chainId} yet`);\n }\n return { to: registry, data, value: ZERO_VALUE, chainId };\n}\nfunction parseUint(value, field) {\n if (typeof value === \"bigint\") {\n if (value < 0n)\n throw usage(`\\`${field}\\` must be a non-negative integer`);\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0) {\n throw usage(`\\`${field}\\` must be a non-negative integer`);\n }\n return BigInt(value);\n }\n if (!/^\\d+$/.test(value)) {\n throw usage(`\\`${field}\\` must be a non-negative integer string, got \"${value}\"`);\n }\n return BigInt(value);\n}\n// ── Guardian self-stake ───────────────────────────────────\nexport function encodeGuardianStake(args, chainId) {\n if (args.amount <= 0n)\n throw usage(\"`amount` must be > 0\");\n const agentId = parseUint(args.agentId, \"agentId\");\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"stakeAsGuardian\",\n args: [args.amount, agentId],\n });\n const registry = getDeployment(chainId).sherwood.guardianRegistry;\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [\n // Caller must have approved WOOD for the registry; agent should\n // check this client-side and prepend an ERC20.approve if needed.\n {\n type: \"allowance\",\n token: registry,\n spender: registry,\n min: args.amount.toString(),\n minDecimal: args.amount.toString(),\n },\n ],\n description: `Stake ${args.amount.toString()} WOOD as guardian (agent ${agentId.toString()}).`,\n note: \"Caller must have approved WOOD for the registry first. Stake locks the WOOD; use /prepare/guardian-unstake later to start the 7d unstake cooldown.\",\n };\n}\nconst GUARDIAN_UNSTAKE_FN = {\n request: \"requestUnstakeGuardian\",\n cancel: \"cancelUnstakeGuardian\",\n claim: \"claimUnstakeGuardian\",\n};\nexport function encodeGuardianUnstake(args, chainId) {\n const fn = GUARDIAN_UNSTAKE_FN[args.action];\n if (!fn) {\n throw usage(`\\`action\\` must be one of: ${Object.keys(GUARDIAN_UNSTAKE_FN).join(\", \")}`);\n }\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: fn,\n args: [],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Guardian unstake ${args.action}.`,\n note: args.action === \"request\"\n ? \"Starts a 7-day cooldown. After it elapses, call again with action=claim to withdraw.\"\n : args.action === \"claim\"\n ? \"Withdraws the unstake amount once the 7-day cooldown has elapsed.\"\n : \"Cancels a pending unstake request and re-activates the guardian.\",\n };\n}\n// ── Delegation ────────────────────────────────────────────\nexport function encodeGuardianDelegate(args, chainId) {\n if (args.amount <= 0n)\n throw usage(\"`amount` must be > 0\");\n const delegate = getAddress(args.delegate);\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"delegateStake\",\n args: [delegate, args.amount],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Delegate ${args.amount.toString()} WOOD to ${delegate}.`,\n note: \"Caller must have approved WOOD for the registry first. Delegation does NOT activate the delegate as a guardian — they must self-stake separately.\",\n };\n}\nconst DELEGATION_UNSTAKE_FN = {\n request: \"requestUnstakeDelegation\",\n cancel: \"cancelUnstakeDelegation\",\n claim: \"claimUnstakeDelegation\",\n};\nexport function encodeDelegationUnstake(args, chainId) {\n const fn = DELEGATION_UNSTAKE_FN[args.action];\n if (!fn) {\n throw usage(`\\`action\\` must be one of: ${Object.keys(DELEGATION_UNSTAKE_FN).join(\", \")}`);\n }\n const delegate = getAddress(args.delegate);\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: fn,\n args: [delegate],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Delegation unstake ${args.action} for delegate ${delegate}.`,\n note: args.action === \"request\"\n ? \"Starts a 7-day cooldown on the delegated amount.\"\n : args.action === \"claim\"\n ? \"Withdraws the delegated amount once the 7-day cooldown has elapsed.\"\n : \"Cancels a pending unstake of the delegation.\",\n };\n}\n// ── Commission ────────────────────────────────────────────\nexport function encodeSetCommission(args, chainId) {\n if (!Number.isInteger(args.bps) || args.bps < 0 || args.bps > 5000) {\n throw usage(\"`bps` must be an integer in [0, 5000] (0–50%)\");\n }\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"setCommission\",\n args: [args.bps],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Set DPoS commission to ${args.bps} bps.`,\n note: \"Raise-rate is capped at 500 bps above the epoch-start rate; first set on a delegate is exempt. Decreases are unbounded.\",\n };\n}\n// ── Reward claims ─────────────────────────────────────────\nexport function encodeClaimProposalReward(args, chainId) {\n const proposalId = parseUint(args.proposalId, \"proposalId\");\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"claimProposalReward\",\n args: [proposalId],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Claim guardian-fee reward for proposal ${proposalId.toString()}.`,\n note: \"Approver-side claim. Pulls the DPoS commission slice and seeds the delegator pool atomically.\",\n };\n}\nexport function encodeClaimDelegatorProposalReward(args, chainId) {\n const proposalId = parseUint(args.proposalId, \"proposalId\");\n const delegate = getAddress(args.delegate);\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"claimDelegatorProposalReward\",\n args: [delegate, proposalId],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Claim delegator-share reward from delegate ${delegate} for proposal ${proposalId.toString()}.`,\n note: \"Delegator-side claim. The approver must have claimed first to seed the delegator pool.\",\n };\n}\n","import { getAddress } from \"viem\";\nimport { SYNDICATE_FACTORY_ABI, SYNDICATE_VAULT_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { notFound, unavailable, usage } from \"../errors.js\";\nconst SECONDS_PER_DAY = 86400n;\nexport async function readActiveSyndicates(client, chainId, opts = {}) {\n const factory = getDeployment(chainId).sherwood.factory;\n let raw;\n try {\n raw = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"getAllActiveSyndicates\",\n }));\n }\n catch (err) {\n throw unavailable(`Failed to read getAllActiveSyndicates from chain ${chainId}`, err);\n }\n // Newest-first, then truncate to `limit`. Default 25, hard cap 100 — same\n // shape as /v1/proposals.\n const limit = Math.min(opts.limit ?? 25, 100);\n const sorted = [...raw].sort((a, b) => a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0);\n const page = sorted.slice(0, limit);\n if (page.length === 0)\n return [];\n // One round-trip per vault: totalAssets + getAgentCount + paused +\n // openDeposits. Use Promise.all rather than multicall3 because the SDK\n // doesn't ship the multicall3 ABI today (would add weight + a new dep).\n // Page is small (default 25) so the parallel-RPC fan-out is fine.\n const enriched = await Promise.all(page.map(async (s) => {\n const [totalAssets, agentCount, paused, openDeposits] = await Promise.all([\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"totalAssets\",\n })\n .catch(() => 0n),\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"getAgentCount\",\n })\n .catch(() => 0n),\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"paused\",\n })\n .catch(() => false),\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"openDeposits\",\n })\n .catch(() => false),\n ]);\n const nowSec = BigInt(Math.floor(Date.now() / 1000));\n const ageSec = nowSec > s.createdAt ? nowSec - s.createdAt : 0n;\n return {\n id: s.id.toString(),\n vault: s.vault,\n creator: s.creator,\n subdomain: s.subdomain,\n metadataURI: s.metadataURI,\n createdAt: s.createdAt.toString(),\n ageDays: Number(ageSec / SECONDS_PER_DAY),\n agentCount: Number(agentCount),\n totalAssets: totalAssets.toString(),\n paused,\n openDeposits,\n };\n }));\n return enriched;\n}\n/**\n * Resolve a syndicate's id (and canonical vault/creator/subdomain) from either\n * its vault address or its subdomain — the reliable path the issue's reporter\n * lacked. `vault.syndicateId()` does not exist; resolution goes through the\n * factory's `vaultToSyndicate` / `subdomainToSyndicate` → `syndicates(id)`.\n *\n * Throws USAGE when neither key is given, NOT_FOUND when nothing maps.\n */\nexport async function readSyndicateResolution(client, chainId, by) {\n const factory = getDeployment(chainId).sherwood.factory;\n let id;\n if (by.vault) {\n id = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"vaultToSyndicate\",\n args: [getAddress(by.vault)],\n }));\n }\n else if (by.subdomain) {\n id = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"subdomainToSyndicate\",\n args: [by.subdomain],\n }));\n }\n else {\n throw usage(\"Provide `vault` or `subdomain` to resolve a syndicate\");\n }\n if (id === 0n) {\n throw notFound(`No syndicate found for ${by.vault ? `vault ${by.vault}` : `subdomain ${by.subdomain}`} on chain ${chainId}`);\n }\n const s = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"syndicates\",\n args: [id],\n }));\n return {\n syndicateId: s[0].toString(),\n vault: s[1],\n creator: s[2],\n subdomain: s[6],\n };\n}\n","/**\n * MoonwellSupplyStrategy call builder.\n *\n * InitParams (Solidity): (address underlying, address mToken, uint256 supplyAmount, uint256 minRedeemAmount)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n underlying: Address,\n mToken: Address,\n supplyAmount: bigint,\n minRedeemAmount: bigint,\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"uint256\" },\n ],\n [underlying, mToken, supplyAmount, minRedeemAmount],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n underlying: Address,\n supplyAmount: bigint,\n): BatchCall[] {\n return [\n {\n target: underlying,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, supplyAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * VeniceInferenceStrategy call builder.\n *\n * InitParams (Solidity struct):\n * address asset, address weth, address vvv, address sVVV,\n * address aeroRouter, address aeroFactory, address agent,\n * uint256 assetAmount, uint256 minVVV, uint256 deadlineOffset, bool singleHop\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface VeniceInferenceInitParams {\n asset: Address;\n weth: Address;\n vvv: Address;\n sVVV: Address;\n aeroRouter: Address;\n aeroFactory: Address;\n agent: Address;\n assetAmount: bigint;\n minVVV: bigint;\n deadlineOffset: bigint;\n singleHop: boolean;\n}\n\nconst INIT_PARAMS_TYPES = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"asset\", type: \"address\" as const },\n { name: \"weth\", type: \"address\" as const },\n { name: \"vvv\", type: \"address\" as const },\n { name: \"sVVV\", type: \"address\" as const },\n { name: \"aeroRouter\", type: \"address\" as const },\n { name: \"aeroFactory\", type: \"address\" as const },\n { name: \"agent\", type: \"address\" as const },\n { name: \"assetAmount\", type: \"uint256\" as const },\n { name: \"minVVV\", type: \"uint256\" as const },\n { name: \"deadlineOffset\", type: \"uint256\" as const },\n { name: \"singleHop\", type: \"bool\" as const },\n ],\n },\n] as const;\n\nexport function buildInitData(params: VeniceInferenceInitParams): Hex {\n return encodeAbiParameters(INIT_PARAMS_TYPES, [params]);\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n assetAmount: bigint,\n): BatchCall[] {\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, assetAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * AerodromeLPStrategy call builder.\n *\n * InitParams (Solidity struct):\n * address tokenA, address tokenB, bool stable,\n * address factory, address router, address gauge, address lpToken,\n * uint256 amountADesired, uint256 amountBDesired,\n * uint256 amountAMin, uint256 amountBMin,\n * uint256 minAmountAOut, uint256 minAmountBOut\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface AerodromeLPInitParams {\n tokenA: Address;\n tokenB: Address;\n stable: boolean;\n factory: Address;\n router: Address;\n gauge: Address;\n lpToken: Address;\n amountADesired: bigint;\n amountBDesired: bigint;\n amountAMin: bigint;\n amountBMin: bigint;\n minAmountAOut: bigint;\n minAmountBOut: bigint;\n}\n\nconst INIT_PARAMS_TYPES = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"tokenA\", type: \"address\" as const },\n { name: \"tokenB\", type: \"address\" as const },\n { name: \"stable\", type: \"bool\" as const },\n { name: \"factory\", type: \"address\" as const },\n { name: \"router\", type: \"address\" as const },\n { name: \"gauge\", type: \"address\" as const },\n { name: \"lpToken\", type: \"address\" as const },\n { name: \"amountADesired\", type: \"uint256\" as const },\n { name: \"amountBDesired\", type: \"uint256\" as const },\n { name: \"amountAMin\", type: \"uint256\" as const },\n { name: \"amountBMin\", type: \"uint256\" as const },\n { name: \"minAmountAOut\", type: \"uint256\" as const },\n { name: \"minAmountBOut\", type: \"uint256\" as const },\n ],\n },\n] as const;\n\nexport function buildInitData(params: AerodromeLPInitParams): Hex {\n return encodeAbiParameters(INIT_PARAMS_TYPES, [params]);\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n tokenA: Address,\n amountA: bigint,\n tokenB: Address,\n amountB: bigint,\n): BatchCall[] {\n return [\n {\n target: tokenA,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, amountA],\n }),\n value: 0n,\n },\n {\n target: tokenB,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, amountB],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * WstETHMoonwellStrategy call builder.\n *\n * InitParams (Solidity struct):\n * address weth, address wsteth, address mwsteth,\n * address aeroRouter, address aeroFactory, address chainlinkWstethEthFeed,\n * uint256 supplyAmount, uint256 minWstethOutPerWeth, uint256 minWethOutPerWsteth, uint256 deadlineOffset\n * supplyAmount = 0 means use the vault's full WETH balance at execute time\n * min*PerX are 1e18-scaled per-unit rates so slippage protection scales with amountIn.\n * chainlinkWstethEthFeed is the Chainlink WSTETH/ETH price feed used by the\n * strategy's `_positionValue` for live NAV during an active proposal. Base\n * mainnet: 0x43a5C292A453A3bF3606fa856197f09D7B74251a (heartbeat 24h, 18 decimals).\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData, maxUint256 } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface WstETHMoonwellInitParams {\n weth: Address;\n wsteth: Address;\n mwsteth: Address;\n aeroRouter: Address;\n aeroFactory: Address;\n chainlinkWstethEthFeed: Address;\n supplyAmount: bigint;\n minWstethOutPerWeth: bigint;\n minWethOutPerWsteth: bigint;\n deadlineOffset: bigint;\n}\n\nconst INIT_PARAMS_TYPES = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"weth\", type: \"address\" as const },\n { name: \"wsteth\", type: \"address\" as const },\n { name: \"mwsteth\", type: \"address\" as const },\n { name: \"aeroRouter\", type: \"address\" as const },\n { name: \"aeroFactory\", type: \"address\" as const },\n { name: \"chainlinkWstethEthFeed\", type: \"address\" as const },\n { name: \"supplyAmount\", type: \"uint256\" as const },\n { name: \"minWstethOutPerWeth\", type: \"uint256\" as const },\n { name: \"minWethOutPerWsteth\", type: \"uint256\" as const },\n { name: \"deadlineOffset\", type: \"uint256\" as const },\n ],\n },\n] as const;\n\nexport function buildInitData(params: WstETHMoonwellInitParams): Hex {\n return encodeAbiParameters(INIT_PARAMS_TYPES, [params]);\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n weth: Address,\n supplyAmount: bigint,\n): BatchCall[] {\n // In dynamic-all mode (supplyAmount == 0) we can't know the exact amount\n // at proposal-build time, so approve maxUint256 then revoke to 0 after\n // execute() in the same batch. This bounds the residual allowance to a\n // single atomic tx — any leftover approval is cleared before control\n // returns to the governor.\n const approveAmount = supplyAmount === 0n ? maxUint256 : supplyAmount;\n\n return [\n {\n target: weth,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, approveAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n {\n target: weth,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, 0n],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * MamoYieldStrategy call builder.\n *\n * InitParams (Solidity): (address underlying, address mamoFactory, uint256 minRedeemAmount)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n underlying: Address,\n mamoFactory: Address,\n minRedeemAmount: bigint,\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"address\" },\n { type: \"uint256\" },\n ],\n [underlying, mamoFactory, minRedeemAmount],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n underlying: Address,\n amount: bigint,\n): BatchCall[] {\n return [\n {\n target: underlying,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, amount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}","/**\n * PortfolioStrategy call builder.\n *\n * InitParams (Solidity): (address asset, address swapAdapter, address chainlinkVerifier,\n * address[] tokens, uint256[] weightsBps, uint256 totalAmount, uint256 maxSlippageBps,\n * bytes[] swapExtraData, uint8[] priceDecimals)\n *\n * `priceDecimals[i]` declares the raw Chainlink Data Streams report scale for\n * allocation `i` (typically 8 for tokenized stocks, 18 for crypto pairs). It\n * is used by `_positionValue` to normalize live NAV into the vault asset's\n * decimals — see PortfolioStrategy `_positionValue` for the formula.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface BasketAllocation {\n token: Address;\n weightBps: number; // e.g. 4000 = 40%\n swapExtraData: Hex; // adapter-specific (fee tier, path, etc.)\n priceDecimals: number; // Chainlink Data Streams report decimals (8 or 18)\n}\n\nexport function buildInitData(\n asset: Address,\n swapAdapter: Address,\n chainlinkVerifier: Address,\n allocations: BasketAllocation[],\n totalAmount: bigint,\n maxSlippageBps: number,\n): Hex {\n const tokens = allocations.map((a) => a.token);\n const weightsBps = allocations.map((a) => BigInt(a.weightBps));\n const swapExtraData = allocations.map((a) => a.swapExtraData);\n const priceDecimals = allocations.map((a) => a.priceDecimals);\n\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"address\" },\n { type: \"address\" },\n { type: \"address[]\" },\n { type: \"uint256[]\" },\n { type: \"uint256\" },\n { type: \"uint256\" },\n { type: \"bytes[]\" },\n { type: \"uint8[]\" },\n ],\n [\n asset,\n swapAdapter,\n chainlinkVerifier,\n tokens,\n weightsBps,\n totalAmount,\n BigInt(maxSlippageBps),\n swapExtraData,\n priceDecimals,\n ],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n totalAmount: bigint,\n): BatchCall[] {\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, totalAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildUpdateParamsCalls(\n clone: Address,\n newWeightsBps: number[],\n newMaxSlippageBps: number,\n newSwapExtraData: Hex[],\n): BatchCall[] {\n const data = encodeAbiParameters(\n [{ type: \"uint256[]\" }, { type: \"uint256\" }, { type: \"bytes[]\" }],\n [\n newWeightsBps.map((w) => BigInt(w)),\n BigInt(newMaxSlippageBps),\n newSwapExtraData,\n ],\n );\n\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: [\n {\n type: \"function\",\n name: \"updateParams\",\n inputs: [{ type: \"bytes\", name: \"data\" }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n ],\n functionName: \"updateParams\",\n args: [data],\n }),\n value: 0n,\n },\n ];\n}\n\n// ── Rebalancing ──\n\nimport { PORTFOLIO_STRATEGY_ABI } from \"../lib/abis.js\";\n\n/**\n * Encode calldata for the simple `rebalance()` call.\n * This is called directly by the proposer (not via vault batch).\n */\nexport function encodeRebalanceCalldata(): Hex {\n return encodeFunctionData({\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"rebalance\",\n });\n}\n\n/**\n * Encode calldata for `updateParams()` to change weights before rebalancing.\n */\nexport function encodeUpdateWeightsCalldata(\n newWeightsBps: number[],\n newMaxSlippageBps: number,\n newSwapExtraData: Hex[],\n): Hex {\n const data = encodeAbiParameters(\n [{ type: \"uint256[]\" }, { type: \"uint256\" }, { type: \"bytes[]\" }],\n [\n newWeightsBps.map((w) => BigInt(w)),\n BigInt(newMaxSlippageBps),\n newSwapExtraData,\n ],\n );\n\n return encodeFunctionData({\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"updateParams\",\n args: [data],\n });\n}\n","/**\n * HyperliquidPerpStrategy call builder.\n *\n * InitParams (Solidity): (address asset, uint256 depositAmount, uint32 perpAssetIndex, uint32 leverage, uint256 maxPositionSize, uint32 maxTradesPerDay)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData, maxUint256 } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI, HYPERLIQUID_PERP_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n asset: Address,\n depositAmount: bigint,\n perpAssetIndex: number,\n leverage: number,\n maxPositionSize: bigint,\n maxTradesPerDay: number,\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n { type: \"uint32\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n ],\n [asset, depositAmount, perpAssetIndex, leverage, maxPositionSize, maxTradesPerDay],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n amount: bigint,\n): BatchCall[] {\n // In dynamic-all mode (amount == 0) we approve maxUint256 up front and\n // revoke to 0 after execute() in the same atomic batch — the residual\n // allowance never persists beyond the tx.\n const approveAmount = amount === 0n ? maxUint256 : amount;\n\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, approveAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, 0n],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n\n/** Phase 2: sweep USDC back to vault after async HyperCore transfer completes. */\nexport function buildSweepToVaultCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: HYPERLIQUID_PERP_STRATEGY_ABI,\n functionName: \"sweepToVault\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * HyperliquidGridStrategy call builder.\n *\n * InitParams (Solidity): (address asset, uint256 depositAmount, uint32 leverage, uint256 maxOrderSize, uint32 maxOrdersPerTick, uint32[] assetIndices)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData, maxUint256 } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n asset: Address,\n depositAmount: bigint,\n leverage: number,\n maxOrderSize: bigint,\n maxOrdersPerTick: number,\n assetIndices: number[],\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n { type: \"uint32[]\" },\n ],\n [asset, depositAmount, leverage, maxOrderSize, maxOrdersPerTick, assetIndices],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n amount: bigint,\n): BatchCall[] {\n const approveAmount = amount === 0n ? maxUint256 : amount;\n\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, approveAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, 0n],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * Subgraph query wrapper for syndicate discovery.\n *\n * Queries The Graph's hosted/studio subgraph for indexed\n * factory + vault events. Much faster than on-chain iteration.\n *\n * Requires SUBGRAPH_URL env var pointing to the subgraph's\n * query endpoint (from The Graph Studio).\n */\n\nexport interface SubgraphSyndicate {\n id: string;\n vault: string;\n creator: string;\n metadataURI: string;\n createdAt: string;\n active: boolean;\n totalDeposits: string;\n totalWithdrawals: string;\n}\n\nexport interface SubgraphAgent {\n id: string;\n agentAddress: string;\n active: boolean;\n registeredAt: string;\n totalBatches: string;\n totalAssetAmount: string;\n}\n\nexport interface SubgraphDeposit {\n id: string;\n sender: string;\n owner: string;\n assets: string;\n shares: string;\n timestamp: string;\n txHash: string;\n}\n\nexport interface SyndicateDetails extends SubgraphSyndicate {\n agents: SubgraphAgent[];\n deposits: SubgraphDeposit[];\n}\n\nfunction getSubgraphUrl(): string {\n const url = process.env.SUBGRAPH_URL;\n if (!url) {\n throw new Error(\n \"SUBGRAPH_URL env var is required. Set it to your The Graph Studio query endpoint.\",\n );\n }\n return url;\n}\n\nasync function query<T>(graphql: string, variables?: Record<string, unknown>): Promise<T> {\n const url = getSubgraphUrl();\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ query: graphql, variables }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Subgraph query failed (${response.status}): ${text}`);\n }\n\n const result = (await response.json()) as { data?: T; errors?: { message: string }[] };\n\n if (result.errors?.length) {\n throw new Error(`Subgraph query error: ${result.errors.map((e) => e.message).join(\", \")}`);\n }\n\n if (!result.data) {\n throw new Error(\"Subgraph returned no data\");\n }\n\n return result.data;\n}\n\n/**\n * Get all active syndicates, optionally filtered by creator.\n */\nexport async function getActiveSyndicates(\n creator?: string,\n): Promise<SubgraphSyndicate[]> {\n if (creator) {\n const data = await query<{ syndicates: SubgraphSyndicate[] }>(\n `query($creator: String!) {\n syndicates(where: { active: true, creator: $creator }, orderBy: createdAt, orderDirection: desc, first: 100) {\n id\n vault\n creator\n metadataURI\n createdAt\n active\n totalDeposits\n totalWithdrawals\n }\n }`,\n { creator: creator.toLowerCase() },\n );\n return data.syndicates;\n }\n\n const data = await query<{ syndicates: SubgraphSyndicate[] }>(`\n {\n syndicates(where: { active: true }, orderBy: createdAt, orderDirection: desc, first: 100) {\n id\n vault\n creator\n metadataURI\n createdAt\n active\n totalDeposits\n totalWithdrawals\n }\n }\n `);\n\n return data.syndicates;\n}\n\n/**\n * Get detailed syndicate info including agents, recent deposits, and batch executions.\n */\nexport async function getSyndicateDetails(\n syndicateId: string,\n): Promise<SyndicateDetails | null> {\n const data = await query<{ syndicate: SyndicateDetails | null }>(\n `query($id: ID!) {\n syndicate(id: $id) {\n id\n vault\n creator\n metadataURI\n createdAt\n active\n totalDeposits\n totalWithdrawals\n agents(first: 50) {\n id\n agentAddress\n active\n registeredAt\n totalBatches\n totalAssetAmount\n }\n deposits(first: 10, orderBy: timestamp, orderDirection: desc) {\n id\n sender\n owner\n assets\n shares\n timestamp\n txHash\n }\n }\n }`,\n { id: syndicateId },\n );\n\n return data.syndicate;\n}\n\n/**\n * Get deposit/withdrawal history for a specific depositor across all syndicates.\n */\nexport async function getDepositorHistory(\n depositorAddress: string,\n): Promise<{ deposits: SubgraphDeposit[]; withdrawals: SubgraphDeposit[] }> {\n const addr = depositorAddress.toLowerCase();\n\n const data = await query<{\n deposits: SubgraphDeposit[];\n withdrawals: SubgraphDeposit[];\n }>(\n `query($owner: String!) {\n deposits(where: { owner: $owner }, orderBy: timestamp, orderDirection: desc, first: 50) {\n id\n sender\n owner\n assets\n shares\n timestamp\n txHash\n }\n withdrawals: withdrawals(where: { owner: $owner }, orderBy: timestamp, orderDirection: desc, first: 50) {\n id\n sender\n owner\n assets\n shares\n timestamp\n txHash\n }\n }`,\n { owner: addr },\n );\n\n return { deposits: data.deposits, withdrawals: data.withdrawals };\n}\n","/**\n * Venice commands — sherwood venice <subcommand>\n *\n * Manages Venice private inference: provision API keys, check status,\n * list models, run inference.\n *\n * Venice funding uses the VeniceInferenceStrategy template via the\n * proposal flow (sherwood proposal create).\n */\n\nimport { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { formatUnits, isAddress, parseUnits } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getPublicClient, getAccount, writeContractWithRetry, waitForReceipt, formatContractError } from \"../lib/client.js\";\nimport { getChain } from \"../lib/network.js\";\nimport { VENICE } from \"../lib/addresses.js\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI, VENICE_STAKING_ABI } from \"../lib/abis.js\";\nimport { provisionApiKey, checkApiKeyValid, chatCompletion, listModels } from \"../lib/venice.js\";\nimport { getVeniceApiKey } from \"../lib/config.js\";\nimport { readFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline/promises\";\n\nexport function registerVeniceCommands(program: Command): void {\n const venice = program.command(\"venice\").description(\"Venice private inference — provision API keys, run inference\");\n\n // ── venice provision ──\n\n venice\n .command(\"provision\")\n .description(\"Self-provision a Venice API key (requires sVVV in wallet)\")\n .action(async () => {\n const account = getAccount();\n const client = getPublicClient();\n\n // Check sVVV balance\n const checkSpinner = ora(\"Checking sVVV balance...\").start();\n try {\n const sVvvBalance = await client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n if (sVvvBalance === 0n) {\n checkSpinner.fail(\"No sVVV found in wallet\");\n console.log(chalk.yellow(\" Your wallet must hold staked VVV (sVVV) to provision a Venice API key.\"));\n console.log(chalk.yellow(\" Use the VeniceInferenceStrategy via a proposal to distribute sVVV to agents.\"));\n process.exit(1);\n }\n\n checkSpinner.succeed(`sVVV balance: ${formatUnits(sVvvBalance, 18)}`);\n } catch (err) {\n checkSpinner.fail(\"Failed to check sVVV balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Provision API key\n const keySpinner = ora(\"Provisioning Venice API key...\").start();\n try {\n const apiKey = await provisionApiKey();\n keySpinner.succeed(\"Venice API key provisioned\");\n console.log(chalk.dim(` Key: ${apiKey.slice(0, 8)}...${apiKey.slice(-4)}`));\n console.log(chalk.dim(\" Saved to ~/.sherwood/config.json\"));\n\n // Create EAS attestation\n try {\n const { createVeniceProvisionAttestation, getEasScanUrl } = await import(\"../lib/eas.js\");\n const { uid } = await createVeniceProvisionAttestation(account.address);\n if (uid !== \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n console.log(chalk.dim(` Attested: ${getEasScanUrl(uid)}`));\n }\n } catch {\n // Attestation is best-effort\n }\n } catch (err) {\n keySpinner.fail(\"Failed to provision API key\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice stake ──\n\n venice\n .command(\"stake\")\n .description(\"Stake VVV tokens to receive sVVV (required for API key provisioning)\")\n .requiredOption(\"--amount <n>\", \"Amount of VVV to stake (human-readable, e.g. 13)\")\n .action(async (opts) => {\n const account = getAccount();\n const client = getPublicClient();\n const chain = getChain();\n const veniceAddrs = VENICE();\n const amount = parseUnits(opts.amount, 18);\n\n // Check VVV balance\n const balSpinner = ora(\"Checking VVV balance...\").start();\n try {\n const vvvBalance = await client.readContract({\n address: veniceAddrs.VVV,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n if (vvvBalance < amount) {\n balSpinner.fail(`Insufficient VVV: have ${formatUnits(vvvBalance, 18)}, need ${opts.amount}`);\n process.exit(1);\n }\n balSpinner.succeed(`VVV balance: ${formatUnits(vvvBalance, 18)}`);\n } catch (err) {\n balSpinner.fail(\"Failed to check VVV balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Approve VVV spend\n const approveSpinner = ora(\"Approving VVV for staking contract...\").start();\n try {\n const approveHash = await writeContractWithRetry({\n account,\n chain,\n address: veniceAddrs.VVV,\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [veniceAddrs.STAKING, amount],\n });\n await waitForReceipt(approveHash);\n approveSpinner.succeed(\"VVV approved\");\n } catch (err) {\n approveSpinner.fail(\"Approve failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Stake VVV → sVVV\n const stakeSpinner = ora(`Staking ${opts.amount} VVV...`).start();\n try {\n const stakeHash = await writeContractWithRetry({\n account,\n chain,\n address: veniceAddrs.STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"stake\",\n args: [account.address, amount],\n });\n await waitForReceipt(stakeHash);\n\n // Read new sVVV balance\n const sVvvBalance = await client.readContract({\n address: veniceAddrs.STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n stakeSpinner.succeed(`Staked ${opts.amount} VVV → ${formatUnits(sVvvBalance, 18)} sVVV`);\n console.log(chalk.dim(\" You can now run: sherwood venice provision\"));\n } catch (err) {\n stakeSpinner.fail(\"Stake failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice mint-diem ──\n\n venice\n .command(\"mint-diem\")\n .description(\"Lock sVVV to mint DIEM (Venice inference credits; ~1d cooldown)\")\n .requiredOption(\"--amount <n>\", \"Amount of sVVV to lock (human-readable, 18 decimals)\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (default 500 = 5%)\", \"500\")\n .option(\"--yes\", \"Skip the cooldown confirmation prompt\")\n .action(async (opts) => {\n const account = getAccount();\n const client = getPublicClient();\n const chain = getChain();\n const { STAKING, DIEM } = VENICE();\n\n const amount = parseUnits(opts.amount, 18);\n const slippageBps = BigInt(opts.slippage ?? \"500\");\n if (slippageBps < 0n || slippageBps > 10000n) {\n console.error(chalk.red(`Invalid slippage bps: ${opts.slippage} (must be 0–10000)`));\n process.exit(1);\n }\n\n // 1. Check sVVV balance\n const balSpinner = ora(\"Checking sVVV balance...\").start();\n let sVvvBalance: bigint;\n try {\n sVvvBalance = await client.readContract({\n address: STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n } catch (err) {\n balSpinner.fail(\"Failed to read sVVV balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n if (sVvvBalance < amount) {\n balSpinner.fail(\n `Insufficient sVVV: have ${formatUnits(sVvvBalance, 18)}, need ${opts.amount}`,\n );\n console.log(chalk.yellow(\" Stake VVV first (see VeniceInferenceStrategy proposal flow).\"));\n process.exit(1);\n }\n balSpinner.succeed(`sVVV balance: ${formatUnits(sVvvBalance, 18)}`);\n\n // 2. Quote DIEM out\n const quoteSpinner = ora(\"Quoting DIEM output...\").start();\n let expected: bigint;\n try {\n expected = await client.readContract({\n address: STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"getDiemAmountOut\",\n args: [amount],\n }) as bigint;\n } catch (err) {\n quoteSpinner.fail(\"Failed to quote DIEM output\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n if (expected === 0n) {\n quoteSpinner.fail(\"Quote returned 0 DIEM — refusing to mint\");\n process.exit(1);\n }\n const minOut = (expected * (10000n - slippageBps)) / 10000n;\n quoteSpinner.succeed(\n `Expected: ${formatUnits(expected, 18)} DIEM (minOut @ ${slippageBps}bps: ${formatUnits(minOut, 18)})`,\n );\n\n // 3. Spendability check — Venice requires >= 0.1 DIEM minimum before any\n // DIEM credit becomes spendable on inference calls. Warn the agent\n // upfront so they can size up sVVV (or switch to x402) before locking.\n const MIN_SPENDABLE_DIEM = parseUnits(\"0.1\", 18);\n let currentDiem = 0n;\n try {\n currentDiem = await client.readContract({\n address: DIEM,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n } catch {\n // best-effort\n }\n const projectedDiem = currentDiem + expected;\n if (projectedDiem < MIN_SPENDABLE_DIEM) {\n const shortfall = MIN_SPENDABLE_DIEM - projectedDiem;\n // Linear extrapolation: scale up amount by the ratio shortfall/expected\n const sVvvNeeded = (amount * shortfall + expected - 1n) / expected; // ceil-div\n console.log();\n console.log(chalk.red(\" ⚠ Venice requires ≥ 0.1 DIEM minimum before ANY DIEM credit\"));\n console.log(chalk.red(\" becomes spendable on inference calls.\"));\n console.log(chalk.red(` Projected DIEM after mint: ${formatUnits(projectedDiem, 18)} (short by ${formatUnits(shortfall, 18)})`));\n console.log(chalk.red(` Approx additional sVVV needed: ${formatUnits(sVvvNeeded, 18)}`));\n console.log(chalk.dim(\" Below threshold, this DIEM sits idle — consider acquiring\"));\n console.log(chalk.dim(\" more sVVV first, or use x402 USDC pay-per-request.\"));\n }\n\n // 4. Lockup warning + confirmation\n console.log();\n console.log(chalk.yellow(\" ⚠ Locked sVVV cannot be unstaked directly. To recover it you must\"));\n console.log(chalk.yellow(\" first call `staking.burnDiem(amount)` (burns DIEM, unlocks sVVV\"));\n console.log(chalk.yellow(\" at your average mint rate), then `initiateUnstake` + wait the\"));\n console.log(chalk.yellow(\" 7-day staking cooldown, then `finalizeUnstake`.\"));\n console.log(chalk.dim(\" x402 alternative (pay-per-request in USDC, no DIEM lock):\"));\n console.log(chalk.dim(\" https://docs.venice.ai/overview/guides/generating-api-key-agent#paying-for-inference\"));\n console.log();\n\n if (!opts.yes) {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = (await rl.question(` Lock ${opts.amount} sVVV for DIEM credits? [y/N] `)).trim().toLowerCase();\n if (answer !== \"y\" && answer !== \"yes\") {\n console.log(chalk.dim(\" Aborted.\"));\n process.exit(0);\n }\n } finally {\n rl.close();\n }\n }\n\n // 5. Mint DIEM (reuses `currentDiem` read in step 3 as the pre-balance)\n const diemBefore = currentDiem;\n const mintSpinner = ora(`Minting DIEM from ${opts.amount} sVVV...`).start();\n try {\n const hash = await writeContractWithRetry({\n account,\n chain,\n address: STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"mintDiem\",\n args: [amount, minOut],\n });\n await waitForReceipt(hash);\n\n const diemAfter = await client.readContract({\n address: DIEM,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n const delta = diemAfter - diemBefore;\n\n mintSpinner.succeed(\n `Minted ${formatUnits(delta > 0n ? delta : diemAfter, 18)} DIEM` +\n (delta > 0n ? ` (balance: ${formatUnits(diemAfter, 18)})` : \"\"),\n );\n console.log(chalk.dim(` Tx: ${hash}`));\n console.log(chalk.yellow(\" Note: Venice requires ≥ 0.1 DIEM to spend ANY DIEM credit, and\"));\n console.log(chalk.yellow(\" refreshes daily allocation at 00:00 UTC. Below threshold,\"));\n console.log(chalk.yellow(\" inference will continue to 402.\"));\n console.log(chalk.dim(\" Once over threshold: sherwood venice infer --model <id> --prompt \\\"...\\\"\"));\n } catch (err) {\n mintSpinner.fail(\"mintDiem failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice status ──\n\n venice\n .command(\"status\")\n .description(\"Show Venice inference status: sVVV balances, DIEM, API key\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .action(async (opts) => {\n const vaultAddress = opts.vault as Address;\n if (!isAddress(vaultAddress)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const client = getPublicClient();\n const account = getAccount();\n const spinner = ora(\"Loading Venice status...\").start();\n\n try {\n // Read vault state\n const [assetAddress, totalDeposited, agents] = await Promise.all([\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"asset\" }) as Promise<Address>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"totalDeposited\" }) as Promise<bigint>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"getAgentAddresses\" }) as Promise<Address[]>,\n ]);\n\n const [assetDecimals, assetSymbol, assetBalance] = await Promise.all([\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"balanceOf\", args: [vaultAddress] }) as Promise<bigint>,\n ]);\n\n // Read VVV balance on vault\n const vaultVvvBalance = await client.readContract({\n address: VENICE().VVV,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [vaultAddress],\n }) as bigint;\n\n // Read per-agent sVVV balances\n const agentBalances = await Promise.all(\n agents.map(async (agent) => {\n const bal = await client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [agent],\n }) as bigint;\n return { agent, balance: bal };\n })\n );\n\n // Check current agent's sVVV + pending rewards + DIEM\n const [mySvvv, myPending, myDiem] = await Promise.all([\n client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as Promise<bigint>,\n client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"pendingRewards\",\n args: [account.address],\n }) as Promise<bigint>,\n client.readContract({\n address: VENICE().DIEM,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as Promise<bigint>,\n ]);\n\n // Check API key\n const apiKeyValid = await checkApiKeyValid();\n const apiKey = getVeniceApiKey();\n\n spinner.stop();\n\n const profit = assetBalance > totalDeposited ? assetBalance - totalDeposited : 0n;\n\n console.log();\n console.log(chalk.bold(\"Venice Inference Status\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n\n console.log(chalk.bold(\"\\n Vault\"));\n console.log(` Profit available: ${formatUnits(profit, assetDecimals)} ${assetSymbol}`);\n console.log(` VVV (unstaked): ${formatUnits(vaultVvvBalance, 18)}`);\n\n console.log(chalk.bold(\"\\n Agent sVVV Balances\"));\n for (const { agent, balance } of agentBalances) {\n const isMe = agent.toLowerCase() === account.address.toLowerCase();\n const label = isMe ? chalk.green(`${agent} (you)`) : agent;\n console.log(` ${label}: ${formatUnits(balance, 18)} sVVV`);\n }\n\n console.log(chalk.bold(\"\\n Your Wallet\"));\n console.log(` sVVV: ${formatUnits(mySvvv, 18)}`);\n console.log(` Pending rewards: ${formatUnits(myPending, 18)} VVV`);\n console.log(` DIEM (credits): ${formatUnits(myDiem, 18)}`);\n console.log(chalk.dim(\" (mint via `sherwood venice mint-diem --amount <sVVV>`)\"));\n\n console.log(chalk.bold(\"\\n Venice API\"));\n console.log(` Key: ${apiKey ? `${apiKey.slice(0, 8)}...${apiKey.slice(-4)}` : chalk.dim(\"not provisioned\")}`);\n console.log(` Status: ${apiKeyValid ? chalk.green(\"valid\") : chalk.red(\"invalid/missing\")}`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load status\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice models ──\n\n venice\n .command(\"models\")\n .description(\"List available Venice inference models\")\n .action(async () => {\n const spinner = ora(\"Fetching Venice models...\").start();\n try {\n const models = await listModels();\n spinner.succeed(`${models.length} models available`);\n console.log();\n for (const model of models) {\n console.log(` ${model}`);\n }\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to list models\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice infer ──\n\n venice\n .command(\"infer\")\n .description(\"Run private inference via Venice chat completions\")\n .requiredOption(\"--prompt <text>\", \"User prompt\")\n .requiredOption(\"--model <id>\", \"Venice model ID (use 'venice models' to list)\")\n .option(\"--system <text>\", \"System prompt\")\n .option(\"--data <path>\", \"Path to data file — contents prepended to prompt as context\")\n .option(\"--web-search\", \"Enable Venice web search\", false)\n .option(\"--no-thinking\", \"Disable chain-of-thought reasoning\")\n .option(\"--temperature <n>\", \"Sampling temperature (0-2)\")\n .option(\"--max-tokens <n>\", \"Maximum completion tokens\")\n .option(\"--json\", \"Output raw JSON response\", false)\n .option(\"--vault <address>\", \"Vault address — attestation recipient (defaults to config vault)\")\n .action(async (opts) => {\n // Build messages\n const messages: { role: \"system\" | \"user\" | \"assistant\"; content: string }[] = [];\n\n if (opts.system) {\n messages.push({ role: \"system\", content: opts.system });\n }\n\n let userContent = opts.prompt;\n if (opts.data) {\n try {\n const data = readFileSync(opts.data, \"utf-8\");\n userContent = `Context data:\\n\\`\\`\\`\\n${data}\\n\\`\\`\\`\\n\\n${opts.prompt}`;\n } catch (err) {\n console.error(chalk.red(`Failed to read data file: ${opts.data}`));\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n }\n messages.push({ role: \"user\", content: userContent });\n\n const spinner = ora(`Running inference (${opts.model})...`).start();\n try {\n const result = await chatCompletion({\n model: opts.model,\n messages,\n temperature: opts.temperature !== undefined ? Number(opts.temperature) : undefined,\n maxTokens: opts.maxTokens !== undefined ? Number(opts.maxTokens) : undefined,\n enableWebSearch: opts.webSearch,\n disableThinking: opts.thinking === false,\n });\n\n spinner.succeed(\"Inference complete\");\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log();\n console.log(result.content);\n console.log();\n console.log(chalk.dim(`Model: ${result.model} | Tokens: ${result.usage.promptTokens} in, ${result.usage.completionTokens} out, ${result.usage.totalTokens} total`));\n }\n\n // Create EAS attestation (best-effort)\n try {\n const { createVeniceInferenceAttestation, getEasScanUrl } = await import(\"../lib/eas.js\");\n const { keccak256, toHex, isAddress: isAddr } = await import(\"viem\");\n const { getChainContracts } = await import(\"../lib/config.js\");\n const { getChain: getActiveChain } = await import(\"../lib/network.js\");\n const vaultRecipient = (opts.vault && isAddr(opts.vault)) ? opts.vault : getChainContracts(getActiveChain().id).vault;\n const promptHash = keccak256(toHex(userContent)).slice(0, 18); // short hash\n const { uid } = await createVeniceInferenceAttestation(\n result.model,\n result.usage.promptTokens,\n result.usage.completionTokens,\n promptHash,\n vaultRecipient as `0x${string}` | undefined,\n );\n if (uid !== \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n console.log(chalk.dim(`Attested: ${getEasScanUrl(uid)}`));\n }\n } catch {\n // Attestation is best-effort\n }\n } catch (err) {\n spinner.fail(\"Inference failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * Allowance commands — sherwood allowance <subcommand>\n *\n * Disburses vault profits as USDC to agent operator wallets for\n * operational expenses (gas, x402 API payments, etc.).\n */\n\nimport { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { parseUnits, formatUnits, isAddress } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getPublicClient, getAccount, formatContractError } from \"../lib/client.js\";\nimport { getExplorerUrl } from \"../lib/network.js\";\nimport { TOKENS } from \"../lib/addresses.js\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI } from \"../lib/abis.js\";\nimport { getQuote, getMultiHopQuote, encodeSwapPath, applySlippage } from \"../lib/quote.js\";\nimport { formatBatch } from \"../lib/batch.js\";\nimport { executeBatch } from \"../lib/vault.js\";\nimport { buildDisburseBatch, type AllowanceDisbursConfig } from \"../strategies/allowance-disburse.js\";\n\nconst VALID_FEES = [500, 3000, 10000] as const;\n\nexport function registerAllowanceCommands(program: Command): void {\n const allowance = program.command(\"allowance\").description(\"Disburse vault profits to agent wallets\");\n\n // ── allowance disburse ──\n\n allowance\n .command(\"disburse\")\n .description(\"Swap vault profits → USDC → distribute to all agent operator wallets\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .requiredOption(\"--amount <amount>\", \"Deposit token amount to convert & distribute (e.g. 500)\")\n .option(\"--fee <tier>\", \"Fee tier for asset → USDC swap (500, 3000, 10000)\", \"3000\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps\", \"100\")\n .option(\"--execute\", \"Execute on-chain (default: simulate only)\", false)\n .action(async (opts) => {\n const vaultAddress = opts.vault as Address;\n if (!isAddress(vaultAddress)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const fee = Number(opts.fee);\n if (!VALID_FEES.includes(fee as 500 | 3000 | 10000)) {\n console.error(chalk.red(`Invalid fee tier. Valid: ${VALID_FEES.join(\", \")}`));\n process.exit(1);\n }\n const slippageBps = Number(opts.slippage);\n\n const client = getPublicClient();\n\n // ── Read vault state ──\n\n const spinner = ora(\"Reading vault state...\").start();\n let assetAddress: Address;\n let assetDecimals: number;\n let assetSymbol: string;\n let totalDeposited: bigint;\n let assetBalance: bigint;\n let agents: Address[];\n\n try {\n [assetAddress, totalDeposited, agents] = await Promise.all([\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"asset\" }) as Promise<Address>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"totalDeposited\" }) as Promise<bigint>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"getAgentAddresses\" }) as Promise<Address[]>,\n ]);\n\n [assetDecimals, assetSymbol, assetBalance] = await Promise.all([\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"balanceOf\", args: [vaultAddress] }) as Promise<bigint>,\n ]);\n spinner.stop();\n } catch (err) {\n spinner.fail(\"Failed to read vault state\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n if (agents.length === 0) {\n console.error(chalk.red(\"No agents registered in vault. Register agents first.\"));\n process.exit(1);\n }\n\n const requestedAmount = parseUnits(opts.amount, assetDecimals);\n const profit = assetBalance > totalDeposited ? assetBalance - totalDeposited : 0n;\n\n // ── Display config ──\n\n const isUsdc = assetAddress.toLowerCase() === TOKENS().USDC.toLowerCase();\n const isWeth = assetAddress.toLowerCase() === TOKENS().WETH.toLowerCase();\n\n console.log();\n console.log(chalk.bold(\"Allowance Disburse\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Asset: ${assetSymbol} (${assetDecimals} decimals)`);\n console.log(` Amount: ${opts.amount} ${assetSymbol}`);\n console.log(` Vault balance: ${formatUnits(assetBalance, assetDecimals)} ${assetSymbol}`);\n console.log(` Deposited: ${formatUnits(totalDeposited, assetDecimals)} ${assetSymbol}`);\n console.log(` Profit: ${formatUnits(profit, assetDecimals)} ${assetSymbol}`);\n console.log(` Agents: ${agents.length} (USDC will be split equally)`);\n if (!isUsdc) {\n console.log(` Routing: ${isWeth ? `WETH → USDC (fee ${fee})` : `${assetSymbol} → WETH → USDC (fee ${fee})`}`);\n console.log(` Slippage: ${(slippageBps / 100).toFixed(2)}%`);\n }\n console.log(` Vault: ${vaultAddress}`);\n console.log();\n\n if (requestedAmount > profit) {\n console.warn(chalk.yellow(` Warning: amount (${opts.amount}) exceeds available profit (${formatUnits(profit, assetDecimals)})`));\n console.warn(chalk.yellow(\" This will use deposited capital, not just profits.\"));\n console.log();\n }\n\n // ── Get USDC amount (quote or direct) ──\n\n let minUsdc: bigint;\n let swapPath: `0x${string}` | null = null;\n\n if (isUsdc) {\n // No swap needed — distribute the asset directly\n minUsdc = requestedAmount;\n } else {\n const quoteSpinner = ora(\"Fetching Uniswap quote...\").start();\n try {\n let amountOut: bigint;\n\n if (isWeth) {\n // Single-hop: WETH → USDC\n const quote = await getQuote({\n tokenIn: TOKENS().WETH,\n tokenOut: TOKENS().USDC,\n amountIn: requestedAmount,\n fee,\n });\n amountOut = quote.amountOut;\n } else {\n // Multi-hop: asset → WETH → USDC\n swapPath = encodeSwapPath(\n [assetAddress, TOKENS().WETH, TOKENS().USDC],\n [fee, 500], // WETH→USDC typically uses 500 (0.05%) fee tier\n );\n const quote = await getMultiHopQuote({\n path: swapPath,\n amountIn: requestedAmount,\n });\n amountOut = quote.amountOut;\n }\n\n minUsdc = applySlippage(amountOut, slippageBps);\n\n quoteSpinner.succeed(\n `Quote: ${formatUnits(amountOut, 6)} USDC ` +\n `(min: ${formatUnits(minUsdc, 6)}, per agent: ${formatUnits(minUsdc / BigInt(agents.length), 6)})`\n );\n } catch (err) {\n quoteSpinner.fail(\"Failed to fetch quote\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n }\n\n // ── Per-agent display ──\n\n const perAgent = minUsdc / BigInt(agents.length);\n if (isUsdc) {\n console.log(chalk.dim(` Per agent: ${formatUnits(perAgent, 6)} USDC`));\n console.log();\n }\n\n // ── Build batch ──\n\n const config: AllowanceDisbursConfig = {\n amount: opts.amount,\n fee,\n slippageBps,\n };\n\n const calls = buildDisburseBatch(config, vaultAddress, agents, assetAddress, assetDecimals, minUsdc, swapPath);\n\n console.log();\n console.log(chalk.bold(`Batch calls (${calls.length}):`));\n console.log(formatBatch(calls));\n console.log();\n\n // ── Execute ──\n\n if (!opts.execute) {\n console.log();\n console.log(chalk.yellow(\"Dry run complete. Add --execute to submit on-chain.\"));\n return;\n }\n\n const execSpinner = ora(\"Executing batch via vault...\").start();\n try {\n const txHash = await executeBatch(calls);\n execSpinner.succeed(`Batch executed: ${txHash}`);\n console.log(chalk.dim(` ${getExplorerUrl(txHash)}`));\n } catch (err) {\n execSpinner.fail(\"Execution failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── allowance status ──\n\n allowance\n .command(\"status\")\n .description(\"Show vault profit and agent USDC balances\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .action(async (opts) => {\n const vaultAddress = opts.vault as Address;\n if (!isAddress(vaultAddress)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const client = getPublicClient();\n const spinner = ora(\"Loading allowance status...\").start();\n\n try {\n // Read vault state\n const [assetAddress, totalDeposited, agents] = await Promise.all([\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"asset\" }) as Promise<Address>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"totalDeposited\" }) as Promise<bigint>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"getAgentAddresses\" }) as Promise<Address[]>,\n ]);\n\n const [assetDecimals, assetSymbol, assetBalance] = await Promise.all([\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"balanceOf\", args: [vaultAddress] }) as Promise<bigint>,\n ]);\n\n // Read per-agent USDC balances\n const agentBalances = await Promise.all(\n agents.map(async (agent) => {\n const bal = await client.readContract({\n address: TOKENS().USDC,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [agent],\n }) as bigint;\n return { agent, balance: bal };\n })\n );\n\n spinner.stop();\n\n const profit = assetBalance > totalDeposited ? assetBalance - totalDeposited : 0n;\n const account = getAccount();\n\n console.log();\n console.log(chalk.bold(\"Allowance Status\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n\n console.log(chalk.bold(\"\\n Vault\"));\n console.log(` Asset: ${assetSymbol}`);\n console.log(` Balance: ${formatUnits(assetBalance, assetDecimals)} ${assetSymbol}`);\n console.log(` Deposited: ${formatUnits(totalDeposited, assetDecimals)} ${assetSymbol}`);\n console.log(` Profit: ${formatUnits(profit, assetDecimals)} ${assetSymbol}`);\n\n console.log(chalk.bold(\"\\n Agent USDC Balances\"));\n for (const { agent, balance } of agentBalances) {\n const isMe = agent.toLowerCase() === account.address.toLowerCase();\n const label = isMe ? chalk.green(`${agent} (you)`) : agent;\n console.log(` ${label}: ${formatUnits(balance, 6)} USDC`);\n }\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load status\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * Allowance Disburse Strategy — swap vault profits to USDC and distribute to agents.\n *\n * If the vault's deposit token is already USDC, transfers directly to each agent.\n * Otherwise, swaps asset → USDC via Uniswap V3 (single-hop or multi-hop via WETH),\n * then distributes USDC equally to each agent's operator wallet.\n *\n * Agents use USDC for operational expenses: gas, x402 API payments, etc.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseUnits } from \"viem\";\nimport type { BatchCall } from \"../lib/batch.js\";\nimport { TOKENS, UNISWAP } from \"../lib/addresses.js\";\nimport {\n ERC20_ABI,\n SWAP_ROUTER_EXACT_INPUT_SINGLE_ABI,\n SWAP_ROUTER_ABI as SWAP_ROUTER_EXACT_INPUT_ABI,\n} from \"../lib/abis.js\";\n\n// ── Strategy Config ──\n\nexport interface AllowanceDisbursConfig {\n /** Deposit token amount to convert & distribute (human-readable, e.g. \"500\") */\n amount: string;\n /** Fee tier for asset → USDC swap (ignored if asset = USDC) */\n fee: number;\n /** Max slippage in basis points (e.g. 100 = 1%) */\n slippageBps: number;\n}\n\n// ── Batch Builder ──\n\n/**\n * Build the allowance disburse batch.\n *\n * @param config - Strategy parameters\n * @param vaultAddress - Vault contract address (delegatecall identity)\n * @param agents - Agent operator EOA addresses to receive USDC\n * @param assetAddress - Vault's deposit token address\n * @param assetDecimals - Deposit token decimals\n * @param minUsdc - Minimum USDC output (post-slippage), or raw amount if asset IS USDC\n * @param swapPath - Encoded Uniswap V3 path for multi-hop (null if single-hop or no swap)\n */\nexport function buildDisburseBatch(\n config: AllowanceDisbursConfig,\n vaultAddress: Address,\n agents: Address[],\n assetAddress: Address,\n assetDecimals: number,\n minUsdc: bigint,\n swapPath: Hex | null,\n): BatchCall[] {\n const assetAmount = parseUnits(config.amount, assetDecimals);\n const isUsdc = assetAddress.toLowerCase() === TOKENS().USDC.toLowerCase();\n const isWeth = assetAddress.toLowerCase() === TOKENS().WETH.toLowerCase();\n const calls: BatchCall[] = [];\n\n if (!isUsdc) {\n // 1. Approve SwapRouter to spend vault asset\n calls.push({\n target: assetAddress,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [UNISWAP().SWAP_ROUTER, assetAmount],\n }),\n value: 0n,\n });\n\n // 2. Swap asset → USDC\n if (isWeth) {\n // Single-hop: WETH → USDC\n calls.push({\n target: UNISWAP().SWAP_ROUTER,\n data: encodeFunctionData({\n abi: SWAP_ROUTER_EXACT_INPUT_SINGLE_ABI,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: TOKENS().WETH,\n tokenOut: TOKENS().USDC,\n fee: config.fee,\n recipient: vaultAddress,\n amountIn: assetAmount,\n amountOutMinimum: minUsdc,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n value: 0n,\n });\n } else {\n // Multi-hop: asset → WETH → USDC\n calls.push({\n target: UNISWAP().SWAP_ROUTER,\n data: encodeFunctionData({\n abi: SWAP_ROUTER_EXACT_INPUT_ABI,\n functionName: \"exactInput\",\n args: [\n {\n path: swapPath!,\n recipient: vaultAddress,\n amountIn: assetAmount,\n amountOutMinimum: minUsdc,\n },\n ],\n }),\n value: 0n,\n });\n }\n }\n\n // 3. Transfer USDC to each agent equally\n const perAgent = minUsdc / BigInt(agents.length);\n for (const agent of agents) {\n calls.push({\n target: TOKENS().USDC,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"transfer\",\n args: [agent, perAgent],\n }),\n value: 0n,\n });\n }\n\n return calls;\n}\n","/**\n * Identity commands — sherwood identity <subcommand>\n *\n * Wraps the Agent0 SDK (@agent0-sdk) for ERC-8004 agent identity management.\n * Handles: mint (register), set metadata, check status, load existing agent.\n * Required before creating or joining syndicates.\n */\n\nimport { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { SDK } from \"agent0-sdk\";\nimport { getPublicClient, getAccount, formatContractError } from \"../lib/client.js\";\nimport { getExplorerUrl, getChain, getRpcUrl } from \"../lib/network.js\";\nimport { AGENT_REGISTRY } from \"../lib/addresses.js\";\nimport { setAgentId, getAgentId, loadConfig } from \"../lib/config.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeIdentityMint, type ChainId } from \"@sherwoodagent/sdk\";\n\n// ── ABI (minimal, for status reads without SDK) ──\n\nconst IDENTITY_REGISTRY_ABI = [\n {\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"ownerOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"tokenId\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n] as const;\n\n/**\n * Initialize the Agent0 SDK with the current network config.\n */\nfunction getAgent0SDK(): SDK {\n // Read key from config first, env var as fallback\n const config = loadConfig();\n const key = config.privateKey || process.env.PRIVATE_KEY;\n if (!key) {\n throw new Error(\n \"Private key not found. Run 'sherwood config set --private-key <key>' or set PRIVATE_KEY env var.\",\n );\n }\n\n return new SDK({\n chainId: getChain().id,\n rpcUrl: getRpcUrl(),\n privateKey: key.startsWith(\"0x\") ? key : `0x${key}`,\n });\n}\n\nexport function registerIdentityCommands(program: Command): void {\n const identity = program.command(\"identity\").description(\"Manage ERC-8004 agent identity (via Agent0 SDK)\");\n\n // ── identity mint ──\n\n identity\n .command(\"mint\")\n .description(\"Register a new ERC-8004 agent identity (required before creating/joining syndicates)\")\n .requiredOption(\"--name <name>\", \"Agent name (e.g. 'Alpha Seeker Agent')\")\n .option(\"--description <desc>\", \"Agent description\", \"Sherwood syndicate agent\")\n .option(\"--image <uri>\", \"Agent image URI (IPFS recommended)\")\n .action(async (opts) => {\n // --calldata-only: emit the unsigned ERC-8004 register() calldata and\n // stop. No Agent0 SDK init, no IPFS, no private key.\n if (isCalldataOnly()) {\n emitCalldata(\n encodeIdentityMint(\n {\n name: opts.name,\n description: opts.description,\n image: opts.image,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const account = getAccount();\n\n // Check if wallet already has an identity\n const existingId = getAgentId();\n if (existingId) {\n console.log(chalk.yellow(`You already have an agent identity saved: #${existingId}`));\n console.log(chalk.dim(\" Minting a new one anyway. The old ID is not affected.\"));\n console.log();\n }\n\n const spinner = ora(\"Initializing Agent0 SDK...\").start();\n try {\n const sdk = getAgent0SDK();\n\n // Create agent with metadata\n spinner.text = \"Creating agent profile...\";\n const agent = sdk.createAgent(opts.name, opts.description, opts.image);\n\n // Register on-chain (mints ERC-8004 NFT)\n spinner.text = \"Registering on-chain (minting ERC-8004 identity)...\";\n const txHandle = await agent.registerOnChain();\n\n spinner.text = \"Waiting for confirmation...\";\n await txHandle.waitMined();\n\n const agentId = agent.agentId;\n if (!agentId) {\n spinner.warn(\"Identity registered but could not read agentId\");\n console.log(chalk.dim(\" Check the transaction on the explorer.\"));\n return;\n }\n\n // Agent0 agentId format is \"chainId:tokenId\" — extract the token ID\n const tokenId = Number(agentId.includes(\":\") ? agentId.split(\":\")[1] : agentId);\n\n // Save to config\n setAgentId(tokenId);\n\n spinner.succeed(`Agent identity registered: #${tokenId}`);\n console.log(chalk.dim(` Agent0 ID: ${agentId}`));\n console.log(chalk.dim(` Name: ${opts.name}`));\n console.log(chalk.dim(` Owner: ${account.address}`));\n console.log(chalk.dim(` Saved to ~/.sherwood/config.json`));\n console.log();\n console.log(chalk.green(\"You can now create syndicates:\"));\n console.log(chalk.dim(` sherwood syndicate create --agent-id ${tokenId} --subdomain <name> --name <name>`));\n } catch (err) {\n spinner.fail(\"Failed to register identity\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── identity load ──\n\n identity\n .command(\"load\")\n .description(\"Load an existing ERC-8004 agent identity into your config\")\n .requiredOption(\"--id <tokenId>\", \"Agent token ID to load\")\n .action(async (opts) => {\n const account = getAccount();\n const client = getPublicClient();\n const registry = AGENT_REGISTRY().IDENTITY_REGISTRY;\n const tokenId = Number(opts.id);\n\n const spinner = ora(`Verifying ownership of agent #${tokenId}...`).start();\n try {\n const owner = await client.readContract({\n address: registry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"ownerOf\",\n args: [BigInt(tokenId)],\n }) as Address;\n\n if (owner.toLowerCase() !== account.address.toLowerCase()) {\n spinner.fail(`Agent #${tokenId} is owned by ${owner}, not your wallet`);\n process.exit(1);\n }\n\n setAgentId(tokenId);\n spinner.succeed(`Agent #${tokenId} loaded and saved to config`);\n console.log(chalk.dim(` Owner: ${account.address}`));\n console.log(chalk.dim(` Saved to ~/.sherwood/config.json`));\n } catch (err) {\n spinner.fail(\"Failed to load identity\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── identity find ──\n\n identity\n .command(\"find\")\n .description(\"Search ERC-8004 agents by wallet address or name (recover a lost agent ID)\")\n .option(\"--wallet <address>\", \"Filter by owner / wallet address\")\n .option(\"--name <text>\", \"Filter by agent name (exact or substring match, depending on registry)\")\n .option(\"--all-chains\", \"Search across all chains, not just the active one\")\n .action(async (opts) => {\n if (!opts.wallet && !opts.name) {\n console.error(chalk.red(\"Pass --wallet <address> or --name <text> (or both).\"));\n process.exit(1);\n }\n\n const spinner = ora(\"Searching ERC-8004 registry...\").start();\n try {\n const sdk = getAgent0SDK();\n const filters: Record<string, unknown> = {};\n if (opts.wallet) filters.walletAddress = opts.wallet;\n if (opts.name) filters.name = opts.name;\n // SearchFilters['chains']: explicit list per-chain or 'all'\n filters.chains = opts.allChains ? \"all\" : [getChain().id];\n\n const results = await sdk.searchAgents(filters);\n spinner.stop();\n\n if (results.length === 0) {\n console.log(chalk.dim(\"No agents found matching those filters.\"));\n console.log(chalk.dim(\"If you minted on a different chain, retry with --all-chains.\"));\n return;\n }\n\n console.log();\n console.log(chalk.bold(`Found ${results.length} agent${results.length === 1 ? \"\" : \"s\"}`));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (const a of results) {\n // Agent0 agentId format is \"chainId:tokenId\" — split for display\n const idStr = String(a.agentId);\n const tokenId = idStr.includes(\":\") ? idStr.split(\":\")[1] : idStr;\n console.log(` ${chalk.bold(`#${tokenId}`)} ${a.name || chalk.dim(\"(no name)\")}`);\n console.log(chalk.dim(` Chain: ${a.chainId}`));\n console.log(chalk.dim(` Full: ${idStr}`));\n if (a.owners?.length) {\n console.log(chalk.dim(` Owner: ${a.owners[0]}`));\n }\n if (a.walletAddress) {\n console.log(chalk.dim(` Wallet: ${a.walletAddress}`));\n }\n }\n console.log();\n console.log(chalk.green(\"To bind one of these to this machine:\"));\n console.log(chalk.dim(` sherwood identity load --id <tokenId>`));\n } catch (err) {\n spinner.fail(\"Search failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── identity status ──\n\n identity\n .command(\"status\")\n .description(\"Show your agent identity status\")\n .action(async () => {\n const account = getAccount();\n const registry = AGENT_REGISTRY().IDENTITY_REGISTRY;\n const client = getPublicClient();\n\n const spinner = ora(\"Checking identity...\").start();\n try {\n const balance = await client.readContract({\n address: registry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n spinner.stop();\n\n const savedId = getAgentId();\n\n console.log();\n console.log(chalk.bold(\"Agent Identity (ERC-8004)\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Wallet: ${account.address}`);\n console.log(` Registry: ${registry}`);\n console.log(` NFTs owned: ${balance.toString()}`);\n\n if (savedId) {\n // Verify the saved ID is still owned by this wallet\n try {\n const owner = await client.readContract({\n address: registry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"ownerOf\",\n args: [BigInt(savedId)],\n }) as Address;\n\n const isOwner = owner.toLowerCase() === account.address.toLowerCase();\n console.log(` Saved ID: #${savedId} ${isOwner ? chalk.green(\"(verified)\") : chalk.red(\"(owned by \" + owner + \")\")}`);\n\n // Load full agent details via SDK if verified\n if (isOwner) {\n try {\n const sdk = getAgent0SDK();\n const agent = await sdk.loadAgent(`${getChain().id}:${savedId}`);\n if (agent.name) console.log(` Name: ${agent.name}`);\n if (agent.description) console.log(` Desc: ${chalk.dim(agent.description)}`);\n if (agent.walletAddress) console.log(` Wallet: ${agent.walletAddress}`);\n } catch {\n // SDK load failed — not critical, basic info already shown\n }\n }\n } catch {\n console.log(` Saved ID: #${savedId} ${chalk.red(\"(token not found)\")}`);\n }\n console.log();\n } else if (balance > 0n) {\n // Wallet owns identities but none saved locally — fetch and surface\n // them so the user can pick one to bind. Closes the trap where a\n // fresh CLI install on a wallet with prior identities reports\n // \"Saved ID: none\" without explaining what's actually on-chain.\n console.log(` Saved ID: ${chalk.yellow(\"none (but this wallet owns NFTs — listing below)\")}`);\n console.log();\n\n const lookupSpinner = ora(\"Resolving owned token IDs via Agent0 SDK...\").start();\n try {\n const sdk = getAgent0SDK();\n const results = await sdk.searchAgents({\n walletAddress: account.address,\n chains: [getChain().id],\n });\n lookupSpinner.stop();\n\n if (results.length === 0) {\n console.log(chalk.dim(\" No agents resolved for this wallet on the active chain.\"));\n console.log(chalk.dim(\" If you minted on a different chain, try:\"));\n console.log(chalk.dim(\" sherwood identity find --wallet \" + account.address + \" --all-chains\"));\n } else {\n console.log(chalk.bold(` Owned identities on this chain (${results.length}):`));\n for (const a of results) {\n const idStr = String(a.agentId);\n const tokenId = idStr.includes(\":\") ? idStr.split(\":\")[1] : idStr;\n console.log(` ${chalk.bold(`#${tokenId}`)} ${a.name || chalk.dim(\"(no name)\")}`);\n }\n console.log();\n console.log(chalk.green(\" Bind one to this machine:\"));\n if (results.length === 1) {\n const idStr = String(results[0].agentId);\n const tokenId = idStr.includes(\":\") ? idStr.split(\":\")[1] : idStr;\n console.log(chalk.dim(` sherwood identity load --id ${tokenId}`));\n } else {\n console.log(chalk.dim(\" sherwood identity load --id <tokenId>\"));\n }\n }\n } catch (err) {\n lookupSpinner.warn(\"Could not resolve owned token IDs via Agent0 SDK\");\n console.log(chalk.dim(` ${(err as Error).message}`));\n console.log(chalk.dim(\" Try: sherwood identity find --wallet \" + account.address));\n }\n console.log();\n } else {\n console.log(` Saved ID: ${chalk.dim(\"none — run 'sherwood identity mint --name <name>'\")}`);\n console.log();\n }\n } catch (err) {\n spinner.fail(\"Failed to check identity\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * Proposal commands — sherwood proposal <subcommand>\n *\n * Manages the full proposal lifecycle: create, list, show, vote,\n * execute, settle, cancel, simulate.\n */\n\nimport { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { isAddress, encodeFunctionData } from \"viem\";\nimport { getVaultOwner, getAssetAddress } from \"../lib/vault.js\";\nimport { ERC20_ABI } from \"../lib/abis.js\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { readFileSync } from \"node:fs\";\nimport { getAccount, formatContractError } from \"../lib/client.js\";\nimport { getExplorerUrl, getNetwork, getChain } from \"../lib/network.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeVote, encodeExecute, encodeSettle, encodeCancel, encodeUnstick, encodeEmergencySettle, encodePropose, type ChainId } from \"@sherwoodagent/sdk\";\nimport { uploadMetadata } from \"../lib/ipfs.js\";\nimport type { SyndicateMetadata } from \"../lib/ipfs.js\";\nimport { fetchMetadata } from \"../lib/ipfs.js\";\nimport {\n getGovernorAddress,\n getGovernorParams,\n getProposal,\n getProposalState,\n proposalCount,\n propose,\n vote,\n executeProposal,\n settleProposal,\n emergencySettle,\n getExecuteCalls,\n getSettlementCalls,\n cancelProposal,\n emergencyCancel,\n getVoteWeight,\n hasVoted,\n getCapitalSnapshot,\n getActiveProposal,\n parseDuration,\n PROPOSAL_STATES,\n PROPOSAL_STATE,\n VOTE_TYPE,\n} from \"../lib/governor.js\";\nimport type { BatchCall } from \"../lib/governor.js\";\nimport { formatDurationShort as formatDuration, formatShares, formatUSDC, parseBigIntArg } from \"../lib/format.js\";\nimport { simulateBatchCalls, printSimulationResult, sendSimulationAlert } from \"../lib/simulate.js\";\nimport type { RiskContext } from \"../lib/simulate.js\";\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\nfunction formatTimestamp(ts: bigint): string {\n if (ts === 0n) return \"—\";\n return new Date(Number(ts) * 1000).toLocaleString();\n}\n\nfunction parseCallsFile(path: string): BatchCall[] {\n const raw = readFileSync(path, \"utf-8\");\n const parsed = JSON.parse(raw) as { target: string; data: string; value: string }[];\n return parsed.map((c) => ({\n target: c.target as Address,\n data: c.data as Hex,\n value: BigInt(c.value || \"0\"),\n }));\n}\n\nexport function registerProposalCommands(program: Command): void {\n const proposal = program.command(\"proposal\").description(\"Governance proposals — create, vote, execute, settle\");\n\n // ── proposal create ──\n\n proposal\n .command(\"create\")\n .description(\"Submit a strategy proposal\")\n .requiredOption(\"--vault <address>\", \"Vault address the proposal targets\")\n .requiredOption(\"--name <name>\", \"Strategy name\")\n .requiredOption(\"--description <text>\", \"Strategy rationale and risk summary\")\n .requiredOption(\"--performance-fee <bps>\", \"Agent fee in bps (e.g. 1500 = 15%)\")\n .requiredOption(\"--duration <duration>\", \"Strategy duration (e.g. 7d, 24h, 3600)\")\n .requiredOption(\"--execute-calls <path>\", \"Path to JSON file with execute Call[] array\")\n .requiredOption(\"--settle-calls <path>\", \"Path to JSON file with settlement Call[] array\")\n .option(\"--strategy <address>\", \"Live-NAV strategy clone address (default: none — queue-only)\")\n .option(\"--metadata-uri <uri>\", \"Override — skip IPFS upload and use this URI directly\")\n .option(\"--simulate\", \"Simulate calls via Tenderly before submitting\")\n .option(\"--force\", \"Submit even if simulation fails (requires --simulate)\")\n .action(async (opts) => {\n try {\n const vault = opts.vault as Address;\n if (!isAddress(vault)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const performanceFeeBps = parseBigIntArg(opts.performanceFee, \"performance-fee\");\n const strategyDuration = parseDuration(opts.duration);\n const executeCalls = parseCallsFile(opts.executeCalls);\n const settleCalls = parseCallsFile(opts.settleCalls);\n\n // Live-NAV strategy clone (optional). Zero address = queue-only. The\n // strategy-template `propose --write-calls` flow prints the clone\n // address to pass here for an external-signer submission.\n const ZERO_STRATEGY = \"0x0000000000000000000000000000000000000000\" as Address;\n let strategy: Address = ZERO_STRATEGY;\n if (opts.strategy) {\n if (!isAddress(opts.strategy)) {\n console.error(chalk.red(`Invalid strategy address: ${opts.strategy}`));\n process.exit(1);\n }\n strategy = opts.strategy as Address;\n }\n\n // --calldata-only: emit propose calldata. IPFS metadata upload needs a\n // signing wallet, so a metadata URI must be supplied explicitly here.\n if (isCalldataOnly()) {\n if (!opts.metadataUri) {\n console.error(\n chalk.red(\n \"--calldata-only requires --metadata-uri (IPFS metadata upload needs a signing wallet)\",\n ),\n );\n process.exit(1);\n }\n try {\n emitCalldata(\n encodePropose(\n {\n vault,\n strategy,\n metadataURI: opts.metadataUri,\n performanceFeeBps: Number(performanceFeeBps),\n strategyDuration,\n executeCalls,\n settlementCalls: settleCalls,\n },\n getChain().id as ChainId,\n ),\n );\n } catch (err) {\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n return;\n }\n\n // ── Pin metadata ──\n let metadataURI = opts.metadataUri || \"\";\n\n if (!metadataURI) {\n const spinner = ora({ text: W(\"Uploading metadata to IPFS...\"), color: \"green\" }).start();\n try {\n const account = getAccount();\n const metadata: SyndicateMetadata = {\n schema: \"sherwood/proposal/v1\",\n name: opts.name,\n description: opts.description,\n chain: getNetwork(),\n strategies: [],\n terms: {},\n links: {},\n };\n // Attach proposal-specific fields\n const proposalMeta = {\n ...metadata,\n proposer: account.address,\n vault,\n performanceFeeBps: Number(performanceFeeBps),\n strategyDuration: Number(strategyDuration),\n createdAt: Math.floor(Date.now() / 1000),\n };\n // Use the existing upload function — it accepts SyndicateMetadata shape\n metadataURI = await uploadMetadata(proposalMeta as unknown as SyndicateMetadata);\n spinner.succeed(G(`Metadata pinned: ${DIM(metadataURI)}`));\n } catch (err) {\n spinner.warn(chalk.yellow(\"IPFS upload failed — using inline metadata\"));\n const json = JSON.stringify({ name: opts.name, description: opts.description, vault });\n metadataURI = `data:application/json;base64,${Buffer.from(json).toString(\"base64\")}`;\n }\n }\n\n // ── Summary ──\n console.log();\n console.log(LABEL(\" ◆ Proposal Summary\"));\n SEP();\n console.log(W(` Name: ${BOLD(opts.name)}`));\n console.log(W(` Vault: ${G(vault)}`));\n console.log(W(` Performance Fee: ${Number(performanceFeeBps) / 100}%`));\n console.log(W(` Duration: ${formatDuration(strategyDuration)}`));\n console.log(W(` Calls: ${executeCalls.length} execute + ${settleCalls.length} settle`));\n console.log(W(` Metadata: ${DIM(metadataURI.length > 50 ? metadataURI.slice(0, 50) + \"...\" : metadataURI)}`));\n SEP();\n\n // ── Simulate (optional) ──\n if (opts.simulate) {\n // Build risk context from the proposal parameters\n let createRiskContext: RiskContext = { vault, performanceFeeBps, strategyDuration };\n try {\n const govParams = await getGovernorParams();\n createRiskContext = { ...createRiskContext, governorParams: govParams };\n } catch { /* non-fatal — skip parameter bounds checks */ }\n\n const simSpinner = ora({ text: W(\"Simulating execute calls...\"), color: \"green\" }).start();\n const execResult = await simulateBatchCalls(vault, executeCalls, \"execute\", createRiskContext);\n simSpinner.stop();\n printSimulationResult(execResult, \"execute\");\n\n if (settleCalls.length > 0) {\n const settleSpinner = ora({ text: W(\"Simulating settlement calls...\"), color: \"green\" }).start();\n const settleResult = await simulateBatchCalls(vault, settleCalls, \"settlement\", createRiskContext);\n settleSpinner.stop();\n printSimulationResult(settleResult, \"settlement\");\n\n if (!settleResult.success && !opts.force) {\n console.error(chalk.red(\"\\n ✖ Settlement simulation failed. Use --force to submit anyway.\"));\n process.exit(1);\n }\n }\n\n if (!execResult.success && !opts.force) {\n console.error(chalk.red(\"\\n ✖ Execution simulation failed. Use --force to submit anyway.\"));\n process.exit(1);\n }\n\n // Block on critical risks\n const hasCriticalRisks = execResult.risks.some((r) => r.level === \"critical\");\n if (hasCriticalRisks && !opts.force) {\n console.error(chalk.red(\"\\n ✖ Critical risks detected. Use --force to submit anyway.\"));\n process.exit(1);\n }\n }\n\n // ── Submit ──\n // Strategy address: zero for queue-only behavior, or the `--strategy`\n // clone for live NAV. The `strategy-template propose` command resolves\n // a freshly-cloned strategy address you can pass via `--strategy`.\n const spinner = ora({ text: W(\"Submitting proposal...\"), color: \"green\" }).start();\n const result = await propose(\n vault,\n strategy,\n metadataURI,\n performanceFeeBps,\n strategyDuration,\n executeCalls,\n settleCalls,\n );\n spinner.succeed(G(\"Proposal submitted\"));\n\n console.log();\n console.log(LABEL(\" ◆ Proposal Created\"));\n SEP();\n console.log(W(` Proposal ID: ${G(`#${result.proposalId}`)}`));\n console.log(W(` Tx: ${DIM(getExplorerUrl(result.hash))}`));\n SEP();\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal list ──\n\n proposal\n .command(\"list\")\n .description(\"List proposals\")\n .option(\"--vault <address>\", \"Filter by vault\")\n .option(\"--state <filter>\", \"Filter by state: draft, pending, approved, executed, settled, all\", \"all\")\n .action(async (opts) => {\n const spinner = ora(\"Loading proposals...\").start();\n try {\n const count = await proposalCount();\n if (count === 0n) {\n spinner.stop();\n console.log(DIM(\"\\n No proposals found.\\n\"));\n return;\n }\n\n const vaultFilter = opts.vault ? (opts.vault as string).toLowerCase() : null;\n const stateFilter = opts.state.toLowerCase();\n const stateIndex = PROPOSAL_STATES.findIndex((s) => s.toLowerCase() === stateFilter);\n\n // Fetch all proposals + computed states concurrently\n const ids = Array.from({ length: Number(count) }, (_, i) => BigInt(i + 1));\n const results = await Promise.all(\n ids.map(async (id) => {\n const [p, state] = await Promise.all([getProposal(id), getProposalState(id)]);\n return { ...p, computedState: state };\n }),\n );\n\n const proposals = results.filter((p) => {\n if (vaultFilter && p.vault.toLowerCase() !== vaultFilter) return false;\n if (stateFilter !== \"all\" && stateIndex >= 0 && p.computedState !== stateIndex) return false;\n return true;\n });\n\n spinner.stop();\n\n if (proposals.length === 0) {\n console.log(DIM(\"\\n No matching proposals.\\n\"));\n return;\n }\n\n console.log();\n console.log(BOLD(`Proposals (${proposals.length})`));\n console.log(DIM(\"─\".repeat(90)));\n console.log(\n DIM(\" ID \") +\n DIM(\"Agent\".padEnd(14)) +\n DIM(\"State\".padEnd(12)) +\n DIM(\"Votes (For/Against)\".padEnd(22)) +\n DIM(\"Fee\".padEnd(8)) +\n DIM(\"Duration\".padEnd(10)) +\n DIM(\"Created\"),\n );\n console.log(DIM(\"─\".repeat(90)));\n\n for (const p of proposals) {\n const state = PROPOSAL_STATES[p.computedState] || \"Unknown\";\n const created = p.snapshotTimestamp > 0n\n ? new Date(Number(p.snapshotTimestamp) * 1000).toLocaleDateString()\n : \"—\";\n const agent = `${p.proposer.slice(0, 6)}...${p.proposer.slice(-4)}`;\n const fee = `${Number(p.performanceFeeBps) / 100}%`;\n const dur = formatDuration(p.strategyDuration);\n const votes = `${formatShares(p.votesFor)}/${formatShares(p.votesAgainst)}`;\n\n console.log(\n ` ${String(p.id).padEnd(4)}` +\n `${agent.padEnd(14)}` +\n `${state.padEnd(12)}` +\n `${votes.padEnd(22)}` +\n `${fee.padEnd(8)}` +\n `${dur.padEnd(10)}` +\n `${created}`,\n );\n }\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load proposals\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── proposal show ──\n\n proposal\n .command(\"show\")\n .description(\"Show full proposal details\")\n .argument(\"<id>\", \"Proposal ID\")\n .action(async (idStr) => {\n const spinner = ora(\"Loading proposal...\").start();\n try {\n const id = parseBigIntArg(idStr, \"proposal ID\");\n const p = await getProposal(id);\n const state = await getProposalState(id);\n const params = await getGovernorParams();\n\n spinner.stop();\n\n const stateLabel = PROPOSAL_STATES[state] || \"Unknown\";\n const totalVotes = p.votesFor + p.votesAgainst;\n const quorumNeeded = totalVotes > 0n ? `${Number(params.vetoThresholdBps) / 100}%` : \"—\";\n\n console.log();\n console.log(LABEL(` ◆ Proposal #${p.id}`));\n SEP();\n\n // Try to resolve IPFS metadata\n if (p.metadataURI && p.metadataURI.startsWith(\"ipfs://\")) {\n try {\n const meta = await fetchMetadata(p.metadataURI);\n console.log(W(` Name: ${BOLD(meta.name)}`));\n console.log(W(` Description: ${DIM(meta.description)}`));\n } catch {\n console.log(W(` Metadata: ${DIM(p.metadataURI)}`));\n }\n } else if (p.metadataURI) {\n console.log(W(` Metadata: ${DIM(p.metadataURI)}`));\n }\n\n console.log(W(` State: ${BOLD(stateLabel)}`));\n console.log(W(` Proposer: ${G(p.proposer)}`));\n console.log(W(` Vault: ${G(p.vault)}`));\n console.log(W(` Performance Fee: ${Number(p.performanceFeeBps) / 100}%`));\n console.log(W(` Duration: ${formatDuration(p.strategyDuration)}`));\n\n console.log();\n console.log(LABEL(\" Timestamps\"));\n console.log(W(` Snapshot: ${formatTimestamp(p.snapshotTimestamp)}`));\n console.log(W(` Vote End: ${formatTimestamp(p.voteEnd)}`));\n console.log(W(` Execute By: ${formatTimestamp(p.executeBy)}`));\n console.log(W(` Executed At: ${formatTimestamp(p.executedAt)}`));\n\n console.log();\n console.log(LABEL(\" Votes\"));\n console.log(W(` For: ${formatShares(p.votesFor)}`));\n console.log(W(` Against: ${formatShares(p.votesAgainst)}`));\n console.log(W(` Abstain: ${formatShares(p.votesAbstain)}`));\n console.log(W(` Veto Threshold: ${quorumNeeded}`));\n\n if (state === PROPOSAL_STATE.Executed || state === PROPOSAL_STATE.Settled) {\n try {\n const cap = await getCapitalSnapshot(id);\n console.log();\n console.log(LABEL(\" Capital\"));\n // TODO: formatUSDC hardcodes 6 decimals — should use the vault's actual asset decimals\n console.log(W(` Snapshot: ${formatUSDC(cap)}`));\n } catch { /* no snapshot */ }\n }\n\n const execCalls = await getExecuteCalls(id);\n const settlCalls = await getSettlementCalls(id);\n\n console.log();\n console.log(LABEL(` Execute Calls (${execCalls.length})`));\n for (let i = 0; i < execCalls.length; i++) {\n console.log(DIM(` [${i}] target=${execCalls[i].target}`));\n console.log(DIM(` data=${execCalls[i].data.slice(0, 20)}... value=${execCalls[i].value}`));\n }\n console.log(LABEL(` Settlement Calls (${settlCalls.length})`));\n for (let i = 0; i < settlCalls.length; i++) {\n console.log(DIM(` [${i}] target=${settlCalls[i].target}`));\n console.log(DIM(` data=${settlCalls[i].data.slice(0, 20)}... value=${settlCalls[i].value}`));\n }\n\n SEP();\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load proposal\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── proposal vote ──\n\n proposal\n .command(\"vote\")\n .description(\"Cast a vote on a pending proposal\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .requiredOption(\"--support <for|against|abstain>\", \"Vote direction: for, against, or abstain\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n const supportRaw = String(opts.support).toLowerCase();\n const support = supportRaw === \"yes\" || supportRaw === \"for\"\n ? VOTE_TYPE.For\n : supportRaw === \"no\" || supportRaw === \"against\"\n ? VOTE_TYPE.Against\n : supportRaw === \"abstain\"\n ? VOTE_TYPE.Abstain\n : null;\n if (support === null) {\n console.error(chalk.red(`Invalid support value \"${opts.support}\". Use for|against|abstain.`));\n process.exit(1);\n }\n\n if (isCalldataOnly()) {\n const voteDir = support === VOTE_TYPE.For ? \"For\" : support === VOTE_TYPE.Against ? \"Against\" : \"Abstain\";\n emitCalldata(encodeVote({ proposalId, vote: voteDir }, getChain().id as ChainId));\n return;\n }\n\n const account = getAccount();\n\n const spinner = ora(\"Loading proposal...\").start();\n const p = await getProposal(proposalId);\n const state = await getProposalState(proposalId);\n\n if (state !== PROPOSAL_STATE.Pending) {\n spinner.fail(`Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"}, not Pending`);\n process.exit(1);\n }\n\n const alreadyVoted = await hasVoted(proposalId, account.address);\n if (alreadyVoted) {\n spinner.fail(\"You have already voted on this proposal\");\n process.exit(1);\n }\n\n const weight = await getVoteWeight(proposalId, account.address);\n spinner.stop();\n\n console.log();\n console.log(LABEL(\" ◆ Cast Vote\"));\n SEP();\n console.log(W(` Proposal: #${proposalId}`));\n console.log(W(` Vault: ${G(p.vault)}`));\n console.log(W(\n ` Support: ${\n support === VOTE_TYPE.For ? G(\"FOR\")\n : support === VOTE_TYPE.Against ? chalk.red(\"AGAINST\")\n : DIM(\"ABSTAIN\")\n }`,\n ));\n console.log(W(` Weight: ${formatShares(weight)} shares`));\n SEP();\n\n const voteSpinner = ora({ text: W(\"Submitting vote...\"), color: \"green\" }).start();\n const hash = await vote(proposalId, support);\n voteSpinner.succeed(G(\"Vote cast\"));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // NOTE: `proposal bind-adapter` was removed. The strategy address is now\n // a `propose()` parameter (`strategy` field on `StrategyProposal`), set\n // immutably at propose time — no separate bind step. `strategy propose`\n // resolves the freshly-cloned strategy address and passes it through.\n\n // ── proposal execute ──\n\n proposal\n .command(\"execute\")\n .description(\"Execute an approved proposal\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .option(\"--dry-run\", \"Simulate execution without sending a transaction\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n if (isCalldataOnly()) {\n emitCalldata(encodeExecute({ proposalId }, getChain().id as ChainId));\n return;\n }\n\n const spinner = ora(\"Loading proposal...\").start();\n const state = await getProposalState(proposalId);\n\n if (state !== PROPOSAL_STATE.Approved) {\n spinner.fail(`Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"}, not Approved`);\n process.exit(1);\n }\n\n // Dry run — simulate instead of executing\n if (opts.dryRun) {\n const p = await getProposal(proposalId);\n const execCalls = await getExecuteCalls(proposalId);\n const dryRunContext: RiskContext = {\n vault: p.vault,\n performanceFeeBps: p.performanceFeeBps,\n strategyDuration: p.strategyDuration,\n };\n spinner.text = W(\"Simulating execution...\");\n const result = await simulateBatchCalls(p.vault, execCalls, \"execute\", dryRunContext);\n spinner.stop();\n printSimulationResult(result, \"execute\");\n const hasCritical = result.risks.some((r) => r.level === \"critical\");\n process.exit(result.success && !hasCritical ? 0 : 1);\n }\n\n spinner.text = W(\"Executing proposal...\");\n const hash = await executeProposal(proposalId);\n spinner.succeed(G(\"Proposal executed\"));\n\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n\n try {\n const cap = await getCapitalSnapshot(proposalId);\n // TODO: formatUSDC hardcodes 6 decimals — should use the vault's actual asset decimals\n console.log(DIM(` Capital snapshot: ${formatUSDC(cap)}`));\n } catch { /* no snapshot yet */ }\n\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal settle ──\n\n proposal\n .command(\"settle\")\n .description(\"Settle an executed proposal (auto-routes settlement path)\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .option(\"--calls <path>\", \"Path to JSON file with settle Call[] (for agent/emergency settle)\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n if (isCalldataOnly()) {\n // With --calls this is an owner-opened emergency-settle review\n // (emergencySettleWithCalls); without, the standard settle path.\n if (opts.calls) {\n const calls = parseCallsFile(opts.calls);\n emitCalldata(\n encodeEmergencySettle({ proposalId, calls }, getChain().id as ChainId),\n );\n } else {\n emitCalldata(encodeSettle({ proposalId }, getChain().id as ChainId));\n }\n return;\n }\n\n const account = getAccount();\n\n const spinner = ora(\"Loading proposal...\").start();\n const p = await getProposal(proposalId);\n const state = await getProposalState(proposalId);\n\n if (state !== PROPOSAL_STATE.Executed) {\n spinner.fail(`Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"}, not Executed`);\n process.exit(1);\n }\n\n const isProposer = account.address.toLowerCase() === p.proposer.toLowerCase();\n const now = BigInt(Math.floor(Date.now() / 1000));\n const durationElapsed = p.executedAt > 0n && now >= p.executedAt + p.strategyDuration;\n\n let hash: Hex;\n\n if (isProposer && !durationElapsed) {\n // Proposer can settle anytime\n spinner.text = W(\"Settling (proposer)...\");\n hash = await settleProposal(proposalId);\n spinner.succeed(G(\"Settled by proposer\"));\n } else if (durationElapsed && !opts.calls) {\n // Permissionless settle after duration\n spinner.text = W(\"Settling (permissionless)...\");\n hash = await settleProposal(proposalId);\n spinner.succeed(G(\"Settled (permissionless)\"));\n } else if (durationElapsed && opts.calls) {\n // Emergency settle — owner with custom calls\n spinner.text = W(\"Emergency settling...\");\n const calls = parseCallsFile(opts.calls);\n hash = await emergencySettle(proposalId, calls);\n spinner.succeed(G(\"Emergency settled\"));\n } else {\n spinner.fail(\"Cannot settle: duration not elapsed and you are not the proposer.\");\n process.exit(1);\n }\n\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal unstick ──\n // Guardian-only recovery path. Hidden from `--help` on purpose: this is a\n // last-resort command used by the syndicate-owner skill when an Executed\n // proposal's pre-committed settlement calls revert, leaving the vault\n // locked (`redemptionsLocked() == true`, `getActiveProposal(vault) != 0`).\n //\n // It calls `emergencySettle(id, [noopCall])` where `noopCall` is a\n // harmless `asset.balanceOf(vault)` view-call on the vault's underlying\n // asset. The governor's `_tryPrecommittedThenFallback` catches the\n // pre-committed revert and runs this no-op fallback, causing\n // `_finishSettlement` to mark the proposal `Settled` and clear\n // `_activeProposal[vault]`. LPs can redeem afterwards.\n //\n // Docs: skill/skills/syndicate-owner/SKILL.md § \"Recovering a stuck proposal\"\n\n proposal\n .command(\"unstick\", { hidden: true })\n .description(\n \"Guardian-only: unstick a vault whose Executed proposal cannot settle (no funds moved)\",\n )\n .requiredOption(\"--id <proposalId>\", \"Proposal ID to unstick\")\n .option(\"--yes\", \"Skip the interactive confirmation\")\n .option(\n \"--dry-run\",\n \"Check preconditions and print the fallback call without broadcasting\",\n )\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n // --calldata-only: emit the V1.5 unstick(proposalId) call. The contract\n // enforces the owner / Executed / duration-elapsed preconditions, so we\n // skip the (account-requiring) pre-flight checks below.\n if (isCalldataOnly()) {\n emitCalldata(encodeUnstick({ proposalId }, getChain().id as ChainId));\n return;\n }\n\n const account = getAccount();\n\n const spinner = ora(\"Loading proposal...\").start();\n const p = await getProposal(proposalId);\n const state = await getProposalState(proposalId);\n\n // 1. State must be Executed\n if (state !== PROPOSAL_STATE.Executed) {\n spinner.fail(\n `Proposal ${proposalId} is ${PROPOSAL_STATES[state] || \"Unknown\"} — unstick only applies to Executed proposals.`,\n );\n console.error(\n DIM(\n \"\\n Other states have their own recovery path:\\n\" +\n \" Draft/Pending/GuardianReview/Approved → sherwood proposal cancel --id <id> (proposer)\\n\" +\n \" Draft/Pending (vault owner) → sherwood proposal cancel --id <id> --emergency\\n\" +\n \" Pending (vault owner) → sherwood proposal veto --id <id>\\n\" +\n \" Expired → vault is not locked, nothing to do\\n\" +\n \" Settled → already settled\\n\" +\n \" Cancelled → governor upgrade required (issue #177)\\n\",\n ),\n );\n process.exit(1);\n }\n\n // 2. Strategy duration must have elapsed (emergencySettle requires it)\n const now = BigInt(Math.floor(Date.now() / 1000));\n const expiresAt = p.executedAt + p.strategyDuration;\n if (p.executedAt === 0n || now < expiresAt) {\n spinner.fail(\"Strategy duration has not elapsed yet.\");\n const remaining = expiresAt - now;\n console.error(\n DIM(\n `\\n Can unstick after: ${new Date(Number(expiresAt) * 1000).toLocaleString()} (in ~${formatDuration(remaining)})\\n`,\n ),\n );\n process.exit(1);\n }\n\n // 3. Vault must actually be locked by this proposal\n const vault = p.vault as Address;\n const active = await getActiveProposal(vault);\n if (active !== proposalId) {\n spinner.fail(\n `Vault ${vault} active proposal is ${active}, not ${proposalId} — nothing to unstick for this proposal.`,\n );\n process.exit(1);\n }\n\n // 4. Caller must be vault owner\n const vaultOwner = await getVaultOwner(vault);\n if (account.address.toLowerCase() !== vaultOwner.toLowerCase()) {\n spinner.fail(\"Only the vault owner can unstick a proposal.\");\n console.error(\n DIM(`\\n Vault owner: ${vaultOwner}\\n Your wallet: ${account.address}\\n`),\n );\n process.exit(1);\n }\n\n // 5. Craft the no-op fallback call: asset.balanceOf(vault)\n // Cannot revert, costs ~2.5k gas, satisfies fallbackCalls.length > 0\n // requirement in _tryPrecommittedThenFallback.\n const asset = await getAssetAddress();\n const noopCalldata = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [vault],\n });\n const fallbackCalls: BatchCall[] = [\n { target: asset, data: noopCalldata, value: 0n },\n ];\n\n spinner.stop();\n\n // Print plan\n console.log();\n console.log(BOLD(\"Unstick plan\"));\n SEP();\n console.log(` Proposal: ${proposalId}`);\n console.log(` Vault: ${vault}`);\n console.log(` Asset: ${asset}`);\n console.log(` State: ${PROPOSAL_STATES[state]} (duration elapsed)`);\n console.log(` Caller: ${account.address} (vault owner ✓)`);\n console.log();\n console.log(LABEL(\" Fallback call (no-op, cannot revert):\"));\n console.log(DIM(` target: ${asset}`));\n console.log(DIM(` data: ${noopCalldata} // balanceOf(${vault})`));\n console.log(DIM(\" value: 0\"));\n console.log();\n console.log(\n DIM(\n \" This calls emergencySettle(id, [noop]). The governor catches any revert\\n\" +\n \" from the pre-committed settlement calls and runs the no-op instead. No\\n\" +\n \" funds move. The proposal transitions to Settled and the vault unlocks.\\n\" +\n \" LPs can then redeem via `sherwood vault redeem`.\",\n ),\n );\n console.log();\n\n if (opts.dryRun) {\n console.log(G(\" (dry-run) Preconditions OK — not broadcasting.\\n\"));\n return;\n }\n\n if (!opts.yes) {\n process.stdout.write(chalk.yellow(\" Proceed? [y/N] \"));\n const answer = await new Promise<string>((resolve) => {\n process.stdin.resume();\n process.stdin.setEncoding(\"utf-8\");\n process.stdin.once(\"data\", (d) => resolve(String(d).trim().toLowerCase()));\n });\n process.stdin.pause();\n if (answer !== \"y\" && answer !== \"yes\") {\n console.log(DIM(\" Cancelled.\\n\"));\n return;\n }\n }\n\n const send = ora(\"Broadcasting emergencySettle...\").start();\n const hash = await emergencySettle(proposalId, fallbackCalls);\n send.succeed(G(\"Vault unstuck — proposal Settled\"));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n\n // Verify unlock\n const stillActive = await getActiveProposal(vault);\n if (stillActive === 0n) {\n console.log(G(\" redemptionsLocked cleared ✓\"));\n } else {\n console.log(\n chalk.yellow(\n ` ⚠ getActiveProposal(vault) still returns ${stillActive} — check manually.`,\n ),\n );\n }\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal cancel ──\n\n proposal\n .command(\"cancel\")\n .description(\"Cancel a proposal (proposer or vault owner)\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .option(\"--emergency\", \"Emergency cancel (vault owner only, any non-settled state)\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n if (isCalldataOnly()) {\n emitCalldata(encodeCancel({ proposalId }, getChain().id as ChainId));\n return;\n }\n\n const spinner = ora(\"Loading proposal...\").start();\n const state = await getProposalState(proposalId);\n\n if (state === PROPOSAL_STATE.Settled || state === PROPOSAL_STATE.Cancelled) {\n spinner.fail(`Proposal is already ${PROPOSAL_STATES[state]}`);\n process.exit(1);\n }\n\n // Allowlists mirror SyndicateGovernor.cancelProposal (proposer path,\n // Draft / Pending / GuardianReview / Approved) and emergencyCancel\n // (vault-owner path, Draft / Pending only). Earlier versions of this\n // CLI rejected proposer-side cancels from GuardianReview / Approved\n // with the misleading hint \"use --emergency for non-pending/approved\"\n // — but emergencyCancel reverts on those states. Keep these in sync\n // with the contract; treating the on-chain revert as the only gate\n // gives a worse error than this pre-check does.\n const PROPOSER_CANCELLABLE: ReadonlySet<number> = new Set([\n PROPOSAL_STATE.Draft,\n PROPOSAL_STATE.Pending,\n PROPOSAL_STATE.GuardianReview,\n PROPOSAL_STATE.Approved,\n ]);\n const OWNER_EMERGENCY_CANCELLABLE: ReadonlySet<number> = new Set([\n PROPOSAL_STATE.Draft,\n PROPOSAL_STATE.Pending,\n ]);\n\n let hash: Hex;\n\n if (opts.emergency) {\n if (!OWNER_EMERGENCY_CANCELLABLE.has(state)) {\n spinner.fail(\n `Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"} — emergencyCancel only works in Draft or Pending. ` +\n `For GuardianReview / Approved, the proposer can run: sherwood proposal cancel --id ${proposalId}`,\n );\n process.exit(1);\n }\n spinner.text = W(\"Emergency cancelling...\");\n hash = await emergencyCancel(proposalId);\n spinner.succeed(G(\"Emergency cancelled\"));\n } else {\n if (!PROPOSER_CANCELLABLE.has(state)) {\n spinner.fail(\n `Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"} — not cancellable in this state. ` +\n `cancelProposal accepts Draft / Pending / GuardianReview / Approved (proposer only).`,\n );\n process.exit(1);\n }\n spinner.text = W(\"Cancelling proposal...\");\n hash = await cancelProposal(proposalId);\n spinner.succeed(G(\"Proposal cancelled\"));\n }\n\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal simulate ──\n\n proposal\n .command(\"simulate\")\n .description(\"Simulate proposal calls via Tenderly (or eth_call fallback)\")\n .option(\"--id <proposalId>\", \"Proposal ID to simulate\")\n .option(\"--vault <address>\", \"Vault address (required with --execute-calls)\")\n .option(\"--execute-calls <path>\", \"Path to JSON execute calls file\")\n .option(\"--settle-calls <path>\", \"Path to JSON settlement calls file\")\n .option(\"--notify <subdomain>\", \"Send results to syndicate XMTP chat\")\n .action(async (opts) => {\n try {\n let vault: Address;\n let executeCalls: BatchCall[];\n let settlementCalls: BatchCall[] = [];\n let riskContext: RiskContext = {};\n let proposalId: bigint | undefined;\n\n if (opts.id) {\n // By proposal ID — fetch calls and build full risk context\n proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n const spinner = ora(\"Loading proposal...\").start();\n\n const p = await getProposal(proposalId);\n vault = p.vault;\n executeCalls = await getExecuteCalls(proposalId);\n settlementCalls = await getSettlementCalls(proposalId);\n\n riskContext = {\n vault,\n performanceFeeBps: p.performanceFeeBps,\n strategyDuration: p.strategyDuration,\n };\n\n try {\n const govParams = await getGovernorParams();\n riskContext.governorParams = govParams;\n } catch { /* non-fatal */ }\n\n spinner.stop();\n console.log(DIM(`\\n Simulating proposal #${proposalId} on vault ${vault.slice(0, 10)}...`));\n } else if (opts.executeCalls) {\n // By call files — minimal risk context (no proposal params)\n if (!opts.vault || !isAddress(opts.vault)) {\n console.error(chalk.red(\"\\n ✖ --vault is required when using --execute-calls\"));\n process.exit(1);\n }\n vault = opts.vault as Address;\n executeCalls = parseCallsFile(opts.executeCalls);\n if (opts.settleCalls) {\n settlementCalls = parseCallsFile(opts.settleCalls);\n }\n riskContext = { vault };\n } else {\n console.error(chalk.red(\"\\n ✖ Provide --id <proposalId> or --execute-calls <path>\"));\n process.exit(1);\n }\n\n // Simulate execute calls\n const spinner = ora({ text: W(\"Simulating execute calls...\"), color: \"green\" }).start();\n const execResult = await simulateBatchCalls(vault, executeCalls, \"execute\", riskContext);\n spinner.stop();\n printSimulationResult(execResult, \"execute\");\n\n // Simulate settlement calls if present\n let settleResult;\n if (settlementCalls.length > 0) {\n const settleSpinner = ora({ text: W(\"Simulating settlement calls...\"), color: \"green\" }).start();\n settleResult = await simulateBatchCalls(vault, settlementCalls, \"settlement\", riskContext);\n settleSpinner.stop();\n printSimulationResult(settleResult, \"settlement\");\n }\n\n // Send XMTP notification if requested\n if (opts.notify && proposalId !== undefined) {\n const notifySpinner = ora({ text: W(\"Sending XMTP alert...\"), color: \"green\" }).start();\n await sendSimulationAlert(opts.notify, proposalId, vault, execResult, settleResult);\n notifySpinner.succeed(G(\"Risk report sent to chat\"));\n }\n\n // Exit with failure code if simulation or risks are critical\n const hasCritical = execResult.risks.some((r) => r.level === \"critical\")\n || (settleResult?.risks.some((r) => r.level === \"critical\") ?? false);\n\n if (!execResult.success || (settleResult && !settleResult.success) || hasCritical) {\n process.exit(1);\n }\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n });\n}\n","/**\n * Shared formatting helpers for CLI output.\n */\n\n/** Compact duration: \"3d\", \"2.5h\", \"15m\", \"30s\" */\nexport function formatDurationShort(seconds: bigint): string {\n const s = Number(seconds);\n if (s >= 86400) return `${(s / 86400).toFixed(s % 86400 === 0 ? 0 : 1)}d`;\n if (s >= 3600) return `${(s / 3600).toFixed(s % 3600 === 0 ? 0 : 1)}h`;\n if (s >= 60) return `${(s / 60).toFixed(0)}m`;\n return `${s}s`;\n}\n\n/** Verbose duration: \"3 days\", \"2.5 hours\", \"15 min\", \"30s\" */\nexport function formatDurationLong(seconds: bigint): string {\n const s = Number(seconds);\n if (s >= 86400) return `${(s / 86400).toFixed(s % 86400 === 0 ? 0 : 1)} day${s >= 172800 ? \"s\" : \"\"}`;\n if (s >= 3600) return `${(s / 3600).toFixed(s % 3600 === 0 ? 0 : 1)} hour${s >= 7200 ? \"s\" : \"\"}`;\n if (s >= 60) return `${(s / 60).toFixed(0)} min`;\n return `${s}s`;\n}\n\n/** Format raw share amounts to human-readable (e.g. 124000000000 → \"124,000\") */\nexport function formatShares(raw: bigint, decimals: number = 6): string {\n const num = Number(raw) / 10 ** decimals;\n return num.toLocaleString(\"en-US\", { minimumFractionDigits: 0, maximumFractionDigits: 2 });\n}\n\n/** Format USDC amount (6 decimals) to human-readable (e.g. 50000000000 → \"$50,000.00\") */\nexport function formatUSDC(raw: bigint): string {\n const num = Number(raw) / 1e6;\n return `$${num.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;\n}\n\n/** Validate string as BigInt, throw user-friendly error */\nexport function parseBigIntArg(value: string, name: string): bigint {\n if (!/^-?\\d+$/.test(value)) {\n throw new Error(`Invalid ${name}: \"${value}\" is not a valid integer`);\n }\n return BigInt(value);\n}\n","/**\n * Proposal simulation — Tenderly API client, eth_call fallback,\n * calldata decoder, and CLI output formatter.\n *\n * The Tenderly integration is proxied through the Sherwood app API\n * (/api/simulate) so credentials stay server-side.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { decodeFunctionData, encodeFunctionData } from \"viem\";\nimport chalk from \"chalk\";\nimport { getPublicClient } from \"./client.js\";\nimport { getChain } from \"./network.js\";\nimport { getGovernorAddress } from \"./governor.js\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI, SWAP_ROUTER_ABI } from \"./abis.js\";\nimport { TOKENS, MOONWELL, UNISWAP, SHERWOOD, AERODROME, VENICE, STRATEGY_TEMPLATES } from \"./addresses.js\";\nimport type { BatchCall } from \"./batch.js\";\n\n// ── Risk analyzer — canonical home is ./risk.ts ──────────\n// Re-exported from here so downstream files that imported these\n// from ./simulate.js keep working without changes.\nimport {\n analyzeRisk,\n truncAddr,\n type RiskContext,\n type RiskFlag,\n type RiskLevel,\n type KnownAddresses,\n} from \"./risk.js\";\n\nexport {\n analyzeRisk,\n verdictOf,\n buildLabelMapFromKnown,\n truncAddr,\n decodeCallArgs,\n type BatchCall,\n type RiskFlag,\n type RiskLevel,\n type RiskContext,\n type KnownAddresses,\n type Verdict,\n} from \"./risk.js\";\n\n// ── Styling (matches proposal.ts conventions) ────────────\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\n// ── Types ────────────────────────────────────────────────\n\nexport interface SimulationCallResult {\n index: number;\n target: Address;\n decodedFunction: string | null;\n selector: Hex;\n success: boolean;\n gasUsed: number;\n}\n\nexport interface SimulationResult {\n success: boolean;\n totalGasUsed: number;\n callResults: SimulationCallResult[];\n warnings: string[];\n risks: RiskFlag[];\n source: \"api\" | \"eth_call\";\n errorMessage?: string;\n}\n\n// ── Moonwell cToken ABI fragment (not in main abis.ts) ───\n\nconst MOONWELL_CTOKEN_ABI = [\n {\n name: \"mint\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"mintAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"redeem\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"redeemTokens\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"redeemUnderlying\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"redeemAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"borrow\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"borrowAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"repayBorrow\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"repayAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Moonwell Comptroller ABI fragment ────────────────────\n\nconst MOONWELL_COMPTROLLER_ABI = [\n {\n name: \"enterMarkets\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"mTokens\", type: \"address[]\" }],\n outputs: [{ name: \"\", type: \"uint256[]\" }],\n },\n {\n name: \"exitMarket\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"mToken\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Uniswap SwapRouter exactInputSingle ABI fragment ─────\n\nconst SWAP_ROUTER_SINGLE_ABI = [\n {\n name: \"exactInputSingle\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n {\n name: \"params\",\n type: \"tuple\",\n components: [\n { name: \"tokenIn\", type: \"address\" },\n { name: \"tokenOut\", type: \"address\" },\n { name: \"fee\", type: \"uint24\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"amountOutMinimum\", type: \"uint256\" },\n { name: \"sqrtPriceLimitX96\", type: \"uint160\" },\n ],\n },\n ],\n outputs: [{ name: \"amountOut\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Address label registry ───────────────────────────────\n\nfunction buildLabelMap(): Map<string, string> {\n const map = new Map<string, string>();\n const add = (addr: Address, label: string) => {\n if (addr !== \"0x0000000000000000000000000000000000000000\") {\n map.set(addr.toLowerCase(), label);\n }\n };\n\n try {\n const tokens = TOKENS();\n add(tokens.USDC, \"USDC\");\n add(tokens.WETH, \"WETH\");\n add(tokens.cbETH, \"cbETH\");\n add(tokens.wstETH, \"wstETH\");\n add(tokens.cbBTC, \"cbBTC\");\n add(tokens.DAI, \"DAI\");\n add(tokens.AERO, \"AERO\");\n\n const mw = MOONWELL();\n add(mw.COMPTROLLER, \"Moonwell Comptroller\");\n add(mw.mUSDC, \"mUSDC\");\n add(mw.mWETH, \"mWETH\");\n add(mw.mCbETH, \"mCbETH\");\n add(mw.mWstETH, \"mWstETH\");\n add(mw.mCbBTC, \"mCbBTC\");\n add(mw.mDAI, \"mDAI\");\n add(mw.mAERO, \"mAERO\");\n\n const uni = UNISWAP();\n add(uni.SWAP_ROUTER, \"SwapRouter\");\n add(uni.QUOTER_V2, \"QuoterV2\");\n\n const sw = SHERWOOD();\n add(sw.FACTORY, \"SyndicateFactory\");\n add(sw.GOVERNOR, \"SyndicateGovernor\");\n\n const aero = AERODROME();\n add(aero.ROUTER, \"Aerodrome Router\");\n add(aero.FACTORY, \"Aerodrome Factory\");\n\n const venice = VENICE();\n add(venice.VVV, \"VVV\");\n add(venice.STAKING, \"sVVV Staking\");\n add(venice.DIEM, \"DIEM\");\n\n const strats = STRATEGY_TEMPLATES();\n add(strats.MOONWELL_SUPPLY, \"MoonwellSupplyStrategy\");\n add(strats.AERODROME_LP, \"AerodromeLPStrategy\");\n add(strats.VENICE_INFERENCE, \"VeniceInferenceStrategy\");\n add(strats.WSTETH_MOONWELL, \"WstETHMoonwellStrategy\");\n } catch {\n // Network not set yet — return partial map\n }\n\n return map;\n}\n\n/** Known token decimals for human-readable formatting */\nfunction buildDecimalsMap(): Map<string, { decimals: number; symbol: string }> {\n const map = new Map<string, { decimals: number; symbol: string }>();\n try {\n const tokens = TOKENS();\n map.set(tokens.USDC.toLowerCase(), { decimals: 6, symbol: \"USDC\" });\n map.set(tokens.WETH.toLowerCase(), { decimals: 18, symbol: \"WETH\" });\n map.set(tokens.cbETH.toLowerCase(), { decimals: 18, symbol: \"cbETH\" });\n map.set(tokens.wstETH.toLowerCase(), { decimals: 18, symbol: \"wstETH\" });\n map.set(tokens.cbBTC.toLowerCase(), { decimals: 8, symbol: \"cbBTC\" });\n map.set(tokens.DAI.toLowerCase(), { decimals: 18, symbol: \"DAI\" });\n map.set(tokens.AERO.toLowerCase(), { decimals: 18, symbol: \"AERO\" });\n } catch {\n // Network not set\n }\n return map;\n}\n\n/** Moonwell mToken → underlying token address mapping */\nfunction buildMTokenToUnderlying(): Map<string, string> {\n const map = new Map<string, string>();\n try {\n const mw = MOONWELL();\n const tokens = TOKENS();\n map.set(mw.mUSDC.toLowerCase(), tokens.USDC.toLowerCase());\n map.set(mw.mWETH.toLowerCase(), tokens.WETH.toLowerCase());\n map.set(mw.mCbETH.toLowerCase(), tokens.cbETH.toLowerCase());\n map.set(mw.mWstETH.toLowerCase(), tokens.wstETH.toLowerCase());\n map.set(mw.mCbBTC.toLowerCase(), tokens.cbBTC.toLowerCase());\n map.set(mw.mDAI.toLowerCase(), tokens.DAI.toLowerCase());\n map.set(mw.mAERO.toLowerCase(), tokens.AERO.toLowerCase());\n } catch {\n // Network not set\n }\n return map;\n}\n\nexport function getAddressLabel(addr: Address): string | null {\n const labels = buildLabelMap();\n return labels.get(addr.toLowerCase()) ?? null;\n}\n\n// ── Human-readable formatting helpers ────────────────────\n\nfunction labeledAddr(addr: string): string {\n const label = buildLabelMap().get(addr.toLowerCase());\n const short = truncAddr(addr);\n return label ? `${short} (${label})` : short;\n}\n\nfunction formatTokenAmount(amount: bigint, target: string): string {\n const decimalsMap = buildDecimalsMap();\n\n // Direct match: target is a token\n const tokenInfo = decimalsMap.get(target.toLowerCase());\n if (tokenInfo) {\n return formatWithDecimals(amount, tokenInfo.decimals, tokenInfo.symbol);\n }\n\n // mToken: use underlying token's decimals\n const mTokenMap = buildMTokenToUnderlying();\n const underlying = mTokenMap.get(target.toLowerCase());\n if (underlying) {\n const underlyingInfo = decimalsMap.get(underlying);\n if (underlyingInfo) {\n return formatWithDecimals(amount, underlyingInfo.decimals, underlyingInfo.symbol);\n }\n }\n\n // Unknown — return raw\n return amount.toString();\n}\n\nfunction formatWithDecimals(amount: bigint, decimals: number, symbol: string): string {\n const num = Number(amount) / 10 ** decimals;\n const formatted = num.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: decimals <= 8 ? 2 : 4,\n });\n return `${formatted} ${symbol}`;\n}\n\n// ── Calldata decoder ─────────────────────────────────────\n\n/**\n * Decode calldata into a human-readable function call string.\n * Returns null for unknown selectors.\n */\nexport function decodeCallData(target: Address, data: Hex): string | null {\n if (data.length < 10) return null;\n\n const labels = buildLabelMap();\n const targetLower = target.toLowerCase();\n\n // Build a list of (abi, contextLabel) pairs to try, ordered by target match\n type AbiEntry = { abi: readonly unknown[]; context: string };\n const candidates: AbiEntry[] = [];\n\n // Moonwell mTokens\n const mw = safeCall(() => MOONWELL());\n if (mw) {\n const isMToken = [mw.mUSDC, mw.mWETH, mw.mCbETH, mw.mWstETH, mw.mCbBTC, mw.mDAI, mw.mAERO]\n .some((a) => a.toLowerCase() === targetLower);\n if (isMToken) {\n candidates.push({ abi: MOONWELL_CTOKEN_ABI, context: labels.get(targetLower) || \"mToken\" });\n }\n\n if (mw.COMPTROLLER.toLowerCase() === targetLower) {\n candidates.push({ abi: MOONWELL_COMPTROLLER_ABI, context: \"Comptroller\" });\n }\n }\n\n // Uniswap SwapRouter\n const uni = safeCall(() => UNISWAP());\n if (uni && uni.SWAP_ROUTER.toLowerCase() === targetLower) {\n candidates.push({ abi: SWAP_ROUTER_ABI, context: \"SwapRouter\" });\n candidates.push({ abi: SWAP_ROUTER_SINGLE_ABI, context: \"SwapRouter\" });\n }\n\n // ERC20 as generic fallback (always try last)\n candidates.push({ abi: ERC20_ABI, context: labels.get(targetLower) || \"ERC20\" });\n\n for (const { abi, context } of candidates) {\n try {\n const decoded = decodeFunctionData({\n abi: abi as readonly unknown[],\n data,\n });\n\n const args = formatArgs(decoded.args as readonly unknown[], decoded.functionName, target);\n return `${decoded.functionName}(${args})`;\n } catch {\n continue;\n }\n }\n\n return null;\n}\n\nfunction formatArgs(args: readonly unknown[], functionName: string, target: Address): string {\n if (!args || args.length === 0) return \"\";\n\n const parts: string[] = [];\n\n for (const arg of args) {\n if (typeof arg === \"bigint\") {\n parts.push(formatTokenAmount(arg, target));\n } else if (typeof arg === \"string\" && arg.startsWith(\"0x\") && arg.length === 42) {\n parts.push(labeledAddr(arg));\n } else if (typeof arg === \"object\" && arg !== null && !Array.isArray(arg)) {\n // Struct (e.g. exactInput params)\n const entries = Object.entries(arg as Record<string, unknown>);\n const structParts: string[] = [];\n for (const [key, val] of entries) {\n if (typeof val === \"bigint\") {\n structParts.push(`${key}: ${formatTokenAmount(val, target)}`);\n } else if (typeof val === \"string\" && val.startsWith(\"0x\") && val.length === 42) {\n structParts.push(`${key}: ${labeledAddr(val)}`);\n } else if (typeof val === \"string\" && val.startsWith(\"0x\") && key === \"path\") {\n structParts.push(`path: ${decodeUniswapPath(val)}`);\n } else {\n structParts.push(`${key}: ${String(val)}`);\n }\n }\n parts.push(`{${structParts.join(\", \")}}`);\n } else if (Array.isArray(arg)) {\n const arrParts = (arg as unknown[]).map((item) => {\n if (typeof item === \"string\" && item.startsWith(\"0x\") && item.length === 42) {\n return labeledAddr(item);\n }\n return String(item);\n });\n parts.push(`[${arrParts.join(\", \")}]`);\n } else {\n parts.push(String(arg));\n }\n }\n\n return parts.join(\", \");\n}\n\n/** Decode a Uniswap V3 packed path (address + fee + address + ...) */\nfunction decodeUniswapPath(pathHex: string): string {\n const labels = buildLabelMap();\n const path = pathHex.startsWith(\"0x\") ? pathHex.slice(2) : pathHex;\n const tokens: string[] = [];\n\n // Path format: 20 bytes address, 3 bytes fee, 20 bytes address, ...\n let offset = 0;\n while (offset + 40 <= path.length) {\n const addr = `0x${path.slice(offset, offset + 40)}`;\n const label = labels.get(addr.toLowerCase());\n tokens.push(label || truncAddr(addr));\n offset += 40;\n if (offset + 6 <= path.length) {\n offset += 6; // skip 3-byte fee\n } else {\n break;\n }\n }\n\n return tokens.join(\" → \");\n}\n\nfunction safeCall<T>(fn: () => T): T | null {\n try {\n return fn();\n } catch {\n return null;\n }\n}\n\n// ── API simulation ───────────────────────────────────────\n\nconst API_URLS: Record<string, string> = {\n \"base\": \"https://app.sherwood.sh\",\n \"base-sepolia\": \"https://testnet.app.sherwood.sh\",\n};\n\nfunction getApiBaseUrl(): string {\n // Allow override for local development\n if (process.env.SHERWOOD_API_URL) return process.env.SHERWOOD_API_URL;\n\n const chain = getChain();\n return API_URLS[chain.testnet ? \"base-sepolia\" : \"base\"] || API_URLS[\"base\"];\n}\n\nasync function simulateViaApi(\n vault: Address,\n calls: BatchCall[],\n): Promise<SimulationResult> {\n const baseUrl = getApiBaseUrl();\n const chainId = getChain().id;\n\n const response = await fetch(`${baseUrl}/api/simulate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n vault,\n chainId,\n calls: calls.map((c) => ({\n target: c.target,\n data: c.data,\n value: c.value.toString(),\n })),\n }),\n });\n\n if (!response.ok) {\n const body = await response.json().catch(() => ({ error: \"Unknown error\" })) as { error?: string; details?: string };\n throw new Error(body.error || `Simulation API returned ${response.status}`);\n }\n\n const result = await response.json() as {\n success: boolean;\n totalGasUsed: number;\n errorMessage: string | null;\n calls: Array<{\n index: number;\n target: string;\n success: boolean;\n gasUsed: number;\n returnData: string;\n }>;\n };\n\n const callResults: SimulationCallResult[] = result.calls.map((c, i) => ({\n index: c.index,\n target: (calls[i]?.target || c.target) as Address,\n decodedFunction: calls[i] ? decodeCallData(calls[i].target, calls[i].data) : null,\n selector: (calls[i]?.data.slice(0, 10) || \"0x\") as Hex,\n success: c.success,\n gasUsed: c.gasUsed,\n }));\n\n // Add decoded functions for any calls the API returned that weren't in our original list\n // (shouldn't happen, but defensive)\n for (const cr of callResults) {\n if (!cr.decodedFunction) {\n const matchingCall = calls[cr.index];\n if (matchingCall) {\n cr.decodedFunction = decodeCallData(matchingCall.target, matchingCall.data);\n }\n }\n }\n\n const warnings: string[] = [];\n for (const cr of callResults) {\n if (!cr.success) {\n warnings.push(`Call #${cr.index + 1} to ${labeledAddr(cr.target)} failed`);\n }\n }\n\n return {\n success: result.success,\n totalGasUsed: result.totalGasUsed,\n callResults,\n warnings,\n risks: [],\n source: \"api\",\n errorMessage: result.errorMessage ?? undefined,\n };\n}\n\n// ── eth_call fallback ────────────────────────────────────\n\nasync function simulateViaEthCall(\n vault: Address,\n calls: BatchCall[],\n): Promise<SimulationResult> {\n const governor = getGovernorAddress();\n const client = getPublicClient();\n\n const input = encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"executeGovernorBatch\",\n args: [calls.map((c) => ({ target: c.target, data: c.data, value: c.value }))],\n });\n\n // Decode calldata for display regardless of simulation result\n const callResults: SimulationCallResult[] = calls.map((c, i) => ({\n index: i,\n target: c.target,\n decodedFunction: decodeCallData(c.target, c.data),\n selector: c.data.slice(0, 10) as Hex,\n success: true, // will be set after simulation\n gasUsed: 0,\n }));\n\n try {\n await client.call({\n account: governor,\n to: vault,\n data: input,\n });\n\n return {\n success: true,\n totalGasUsed: 0,\n callResults,\n warnings: [],\n risks: [],\n source: \"eth_call\",\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n\n // Mark all calls as potentially failed (no per-call granularity)\n for (const cr of callResults) {\n cr.success = false;\n }\n\n return {\n success: false,\n totalGasUsed: 0,\n callResults,\n warnings: [`Batch reverted: ${message.slice(0, 200)}`],\n risks: [],\n source: \"eth_call\",\n errorMessage: message,\n };\n }\n}\n\n// ── Public API ───────────────────────────────────────────\n\nexport async function simulateBatchCalls(\n vault: Address,\n calls: BatchCall[],\n callType: \"execute\" | \"settlement\",\n riskContext?: RiskContext,\n): Promise<SimulationResult> {\n let result: SimulationResult;\n\n try {\n result = await simulateViaApi(vault, calls);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.log(DIM(` Simulation API unavailable (${message}), falling back to eth_call...`));\n\n result = await simulateViaEthCall(vault, calls);\n }\n\n // Run risk analysis on the results\n // Build a KnownAddresses dict from the CLI's chain-aware label map so\n // risk.ts stays decoupled from ./addresses.ts.\n const inlineLabels = buildLabelMap();\n const knownAddresses: KnownAddresses = {};\n for (const [addr, label] of inlineLabels) {\n knownAddresses[label] = addr as `0x${string}`;\n }\n const ctx: RiskContext = { vault, ...riskContext, knownAddresses };\n result.risks = analyzeRisk(calls, result.callResults, ctx);\n\n return result;\n}\n\n// ── Output formatter ─────────────────────────────────────\n\nexport function printSimulationResult(result: SimulationResult, callType: string): void {\n console.log();\n console.log(LABEL(` ◆ Simulation — ${callType} calls`));\n SEP();\n\n const sourceLabel = result.source === \"api\"\n ? \"Tenderly (via API)\"\n : `eth_call ${DIM(\"(configure Tenderly for detailed results)\")}`;\n console.log(W(` Source: ${sourceLabel}`));\n\n const statusIcon = result.success ? G(\"✓ PASS\") : chalk.red(\"✖ FAIL\");\n console.log(W(` Status: ${statusIcon}`));\n\n if (result.totalGasUsed > 0) {\n console.log(W(` Total Gas: ${result.totalGasUsed.toLocaleString()}`));\n }\n\n if (result.errorMessage && !result.success) {\n console.log(chalk.red(` Error: ${result.errorMessage.slice(0, 120)}`));\n }\n\n console.log();\n\n for (const cr of result.callResults) {\n const icon = cr.success ? G(\"✓\") : chalk.red(\"✖\");\n const funcName = cr.decodedFunction || `${cr.selector}... ${DIM(\"(unknown)\")}`;\n console.log(W(` [${cr.index + 1}] ${icon} ${funcName}`));\n\n const label = getAddressLabel(cr.target);\n const targetDisplay = label ? `${cr.target} (${label})` : cr.target;\n console.log(DIM(` Target: ${targetDisplay}`));\n\n if (cr.gasUsed > 0) {\n console.log(DIM(` Gas: ${cr.gasUsed.toLocaleString()}`));\n }\n\n console.log();\n }\n\n // ── Risk assessment ──\n if (result.risks.length > 0) {\n const criticals = result.risks.filter((r) => r.level === \"critical\");\n const warnings = result.risks.filter((r) => r.level === \"warning\");\n const infos = result.risks.filter((r) => r.level === \"info\");\n\n if (criticals.length > 0) {\n console.log(chalk.red.bold(` ✖ CRITICAL RISKS (${criticals.length})`));\n for (const r of criticals) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n console.log(chalk.red(` ✖${ref} ${r.code} — ${r.message}`));\n }\n console.log();\n }\n\n if (warnings.length > 0) {\n console.log(chalk.yellow.bold(` ⚠ WARNINGS (${warnings.length})`));\n for (const r of warnings) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n console.log(chalk.yellow(` ⚠${ref} ${r.code} — ${r.message}`));\n }\n console.log();\n }\n\n if (criticals.length === 0 && warnings.length === 0 && infos.length > 0) {\n console.log(G.bold(` ✓ RISK ASSESSMENT: CLEAN`));\n for (const r of infos) {\n console.log(G(` ✓ ${r.message}`));\n }\n console.log();\n }\n }\n\n if (result.warnings.length > 0) {\n console.log(chalk.yellow(` ⚠ Simulation Warnings`));\n for (const w of result.warnings) {\n console.log(chalk.yellow(` - ${w}`));\n }\n console.log();\n }\n\n SEP();\n}\n\n// ── XMTP escalation ─────────────────────────────────────\n\n/**\n * Send a simulation risk report to the syndicate's XMTP chat.\n * Uses RISK_ALERT message type for critical findings, POSITION_UPDATE otherwise.\n * Fails silently if XMTP is not configured.\n */\nexport async function sendSimulationAlert(\n subdomain: string,\n proposalId: bigint,\n vault: Address,\n execResult: SimulationResult,\n settleResult?: SimulationResult,\n): Promise<void> {\n try {\n const xmtp = await import(\"./xmtp.js\");\n const { getAccount } = await import(\"./client.js\");\n\n const group = await xmtp.getGroup(\"\", subdomain);\n\n // Collect all risks across both results\n const allRisks = [...execResult.risks, ...(settleResult?.risks ?? [])];\n const criticals = allRisks.filter((r) => r.level === \"critical\");\n const warnings = allRisks.filter((r) => r.level === \"warning\");\n\n const highestLevel: RiskLevel = criticals.length > 0 ? \"critical\" : warnings.length > 0 ? \"warning\" : \"info\";\n\n // Build markdown report\n const lines: string[] = [];\n const statusEmoji = highestLevel === \"critical\" ? \"🚨\" : highestLevel === \"warning\" ? \"⚠️\" : \"✅\";\n const statusText = highestLevel === \"critical\" ? \"RISKS DETECTED\" : highestLevel === \"warning\" ? \"WARNINGS\" : \"CLEAN\";\n\n lines.push(`## ${statusEmoji} Proposal #${proposalId} — Simulation Report`);\n lines.push(`**Vault**: \\`${truncAddr(vault)}\\``);\n lines.push(`**Status**: ${statusText}`);\n lines.push(`**Source**: ${execResult.source === \"api\" ? \"Tenderly\" : \"eth_call\"}`);\n lines.push(\"\");\n\n // Execute calls summary\n lines.push(`### Execute Calls ${execResult.success ? \"✓\" : \"✖\"}`);\n for (const cr of execResult.callResults) {\n const icon = cr.success ? \"✓\" : \"✖\";\n const fn = cr.decodedFunction || `${cr.selector}...`;\n const flag = allRisks.find((r) => r.callIndex === cr.index);\n const suffix = flag && flag.level === \"critical\" ? \" ← **\" + flag.code + \"**\" : \"\";\n lines.push(`${cr.index + 1}. ${icon} \\`${fn}\\`${suffix}`);\n }\n lines.push(\"\");\n\n // Settlement calls summary (if present)\n if (settleResult && settleResult.callResults.length > 0) {\n lines.push(`### Settlement Calls ${settleResult.success ? \"✓\" : \"✖\"}`);\n for (const cr of settleResult.callResults) {\n const icon = cr.success ? \"✓\" : \"✖\";\n const fn = cr.decodedFunction || `${cr.selector}...`;\n lines.push(`${cr.index + 1}. ${icon} \\`${fn}\\``);\n }\n lines.push(\"\");\n }\n\n // Risk flags\n if (criticals.length > 0) {\n lines.push(`### 🚨 Critical Risks`);\n for (const r of criticals) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n lines.push(`- **${r.code}**${ref}: ${r.message}`);\n }\n lines.push(\"\");\n }\n\n if (warnings.length > 0) {\n lines.push(`### ⚠️ Warnings`);\n for (const r of warnings) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n lines.push(`- **${r.code}**${ref}: ${r.message}`);\n }\n lines.push(\"\");\n }\n\n // Action recommendation\n if (highestLevel === \"critical\") {\n lines.push(`### Action Required`);\n lines.push(`Recommend **VETO** — critical risks detected.`);\n } else if (highestLevel === \"warning\") {\n lines.push(`### Review Required`);\n lines.push(`Warnings detected — manual review recommended before execution.`);\n } else {\n lines.push(`### ✅ No Risks Detected`);\n lines.push(`All call targets verified. All calldata decoded. Safe to proceed.`);\n }\n\n const markdown = lines.join(\"\\n\");\n const messageType = highestLevel === \"critical\" ? \"RISK_ALERT\" as const : \"POSITION_UPDATE\" as const;\n\n await xmtp.sendEnvelope(group, {\n type: messageType,\n from: getAccount().address,\n text: markdown,\n data: {\n format: \"markdown\",\n proposalId: Number(proposalId),\n vault,\n riskLevel: highestLevel,\n riskCodes: allRisks.filter((r) => r.level !== \"info\").map((r) => r.code),\n simulationSuccess: execResult.success && (settleResult?.success ?? true),\n },\n timestamp: Math.floor(Date.now() / 1000),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.log(chalk.yellow(` ⚠ Failed to send XMTP alert: ${message.slice(0, 100)}`));\n }\n}\n","// cli/src/lib/risk.ts\n// SPDX-License-Identifier: MIT\n//\n// Pure risk-code analyzer for proposal batch calls. Self-contained: also owns\n// the calldata decoder and its inline ABI fragments (ERC-20, Moonwell cToken /\n// comptroller, Uniswap SwapRouter single- and multi-hop) plus the verdict\n// helper. No coupling to ./addresses.ts — callers inject KnownAddresses, so the\n// module can be MIT-vendored as-is.\n// Extracted from simulate.ts so it can be vendored by the public\n// sherwood-guardian repo at https://github.com/sherwoodagent/sherwood-guardian.\n\nimport { decodeFunctionData, erc20Abi, type Abi, type Address, type Hex } from \"viem\";\n\n// ── Types ────────────────────────────────────────────────\n\nexport interface BatchCall {\n target: Address;\n data: Hex;\n value: bigint;\n}\n\nexport interface SimulationCallResult {\n index: number;\n target: Address;\n decodedFunction: string | null;\n selector: Hex;\n success: boolean;\n gasUsed: number;\n}\n\nexport type RiskLevel = \"critical\" | \"warning\" | \"info\";\n\nexport interface RiskFlag {\n level: RiskLevel;\n code: string;\n message: string;\n callIndex?: number;\n}\n\nexport interface KnownAddresses {\n [label: string]: Address | undefined;\n}\n\nexport interface GovernorParamsLike {\n maxPerformanceFeeBps?: bigint;\n}\n\nexport interface RiskContext {\n vault?: Address;\n knownAddresses?: KnownAddresses;\n performanceFeeBps?: bigint;\n strategyDuration?: bigint;\n governorParams?: GovernorParamsLike;\n}\n\ninterface DecodedCall {\n functionName: string;\n args: readonly unknown[];\n}\n\n// ── ABI fragments (decoder coverage) ─────────────────────\n\nconst MOONWELL_CTOKEN_ABI = [\n { name: \"mint\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"mintAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"redeem\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"redeemTokens\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"redeemUnderlying\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"redeemAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"borrow\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"borrowAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"repayBorrow\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"repayAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n] as const;\n\nconst MOONWELL_COMPTROLLER_ABI = [\n { name: \"enterMarkets\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"mTokens\", type: \"address[]\" }], outputs: [{ name: \"\", type: \"uint256[]\" }] },\n { name: \"exitMarket\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"mToken\", type: \"address\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n] as const;\n\nconst SWAP_ROUTER_SINGLE_ABI = [\n {\n name: \"exactInputSingle\", type: \"function\", stateMutability: \"nonpayable\",\n inputs: [{\n name: \"params\", type: \"tuple\",\n components: [\n { name: \"tokenIn\", type: \"address\" },\n { name: \"tokenOut\", type: \"address\" },\n { name: \"fee\", type: \"uint24\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"amountOutMinimum\", type: \"uint256\" },\n { name: \"sqrtPriceLimitX96\", type: \"uint160\" },\n ],\n }],\n outputs: [{ name: \"amountOut\", type: \"uint256\" }],\n },\n] as const;\n\nconst SWAP_ROUTER_MULTI_ABI = [\n {\n name: \"exactInput\", type: \"function\", stateMutability: \"nonpayable\",\n inputs: [{\n name: \"params\", type: \"tuple\",\n components: [\n { name: \"path\", type: \"bytes\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"amountOutMinimum\", type: \"uint256\" },\n ],\n }],\n outputs: [{ name: \"amountOut\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Address helpers ──────────────────────────────────────\n\nexport function buildLabelMapFromKnown(known: KnownAddresses): Map<string, string> {\n const map = new Map<string, string>();\n for (const [label, addr] of Object.entries(known)) {\n if (addr && addr !== \"0x0000000000000000000000000000000000000000\") {\n map.set(addr.toLowerCase(), label);\n }\n }\n return map;\n}\n\nexport function truncAddr(addr: string): string {\n return `${addr.slice(0, 6)}…${addr.slice(-4)}`;\n}\n\nfunction labeledAddr(addr: string, labels: Map<string, string>): string {\n const label = labels.get(addr.toLowerCase());\n return label ? `${label} (${truncAddr(addr)})` : truncAddr(addr);\n}\n\n// ── Calldata decoder ─────────────────────────────────────\n\nfunction tryDecode(abi: Abi, data: Hex): DecodedCall | null {\n try {\n const decoded = decodeFunctionData({ abi, data });\n return { functionName: decoded.functionName, args: (decoded.args ?? []) as readonly unknown[] };\n } catch {\n return null;\n }\n}\n\n// Candidate ABIs are tried in order; the first selector match wins. Correctness\n// depends on the 4-byte selectors being DISJOINT across every fragment below\n// (ERC-20 transfer/transferFrom/approve, Moonwell cToken mint/redeem/borrow/...,\n// comptroller enterMarkets/exitMarket, SwapRouter exactInputSingle, exactInput).\n// They are today; adding a fragment to any pile without re-checking selector\n// disjointness could silently mis-decode a call against the wrong ABI.\nexport function decodeCallArgs(data: Hex): DecodedCall | null {\n return (\n tryDecode(erc20Abi, data) ??\n tryDecode(MOONWELL_CTOKEN_ABI, data) ??\n tryDecode(MOONWELL_COMPTROLLER_ABI, data) ??\n tryDecode(SWAP_ROUTER_SINGLE_ABI, data) ?? // exactInputSingle (single-hop)\n tryDecode(SWAP_ROUTER_MULTI_ABI, data) // exactInput (multi-hop) — restored, was dropped in extraction\n );\n}\n\n// ── Risk analyzer ────────────────────────────────────────\n\nexport function analyzeRisk(\n calls: BatchCall[],\n callResults: SimulationCallResult[],\n context?: RiskContext,\n): RiskFlag[] {\n const risks: RiskFlag[] = [];\n const labels = buildLabelMapFromKnown(context?.knownAddresses ?? {});\n const vaultLower = context?.vault?.toLowerCase();\n\n const isKnown = (addr: string): boolean => {\n const lower = addr.toLowerCase();\n return labels.has(lower) || lower === vaultLower;\n };\n\n // A 0-call proposal (e.g. a performance-fee-only check) starts both false so it\n // doesn't emit vacuously-true ALL_TARGETS_VERIFIED / ALL_CALLS_DECODED info\n // flags. (Intentional change from the in-simulate.ts version, which started true.)\n let allTargetsVerified = calls.length > 0;\n let allCallsDecoded = calls.length > 0;\n\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const result = callResults[i];\n const callNum = i + 1;\n\n if (result && !result.success) {\n risks.push({ level: \"critical\", code: \"SIMULATION_FAILED\",\n message: `Call #${callNum} to ${labeledAddr(call.target, labels)} reverted during simulation`, callIndex: i });\n }\n\n const targetKnown = isKnown(call.target);\n if (!targetKnown) {\n allTargetsVerified = false;\n risks.push({ level: \"critical\", code: \"UNKNOWN_TARGET\",\n message: `Call #${callNum} targets ${labeledAddr(call.target, labels)} which is not in the known address registry`, callIndex: i });\n }\n\n const decoded = decodeCallArgs(call.data);\n if (!decoded) {\n allCallsDecoded = false;\n if (!targetKnown) {\n risks.push({ level: \"critical\", code: \"UNDECODED_CALLDATA\",\n message: `Call #${callNum} has unrecognized calldata (selector ${call.data.slice(0, 10)}) targeting unknown contract`, callIndex: i });\n }\n continue;\n }\n\n if (decoded.functionName === \"transfer\" && decoded.args.length >= 2) {\n const to = decoded.args[0] as string;\n if (typeof to === \"string\" && to.startsWith(\"0x\") && !isKnown(to)) {\n risks.push({ level: \"critical\", code: \"TRANSFER_TO_UNKNOWN\",\n message: `Call #${callNum} transfer() sends funds to ${truncAddr(to)} which is not a known protocol`, callIndex: i });\n }\n }\n if (decoded.functionName === \"transferFrom\" && decoded.args.length >= 3) {\n const to = decoded.args[1] as string;\n if (typeof to === \"string\" && to.startsWith(\"0x\") && !isKnown(to)) {\n risks.push({ level: \"critical\", code: \"TRANSFER_FROM_TO_UNKNOWN\",\n message: `Call #${callNum} transferFrom() sends funds to ${truncAddr(to)} which is not a known protocol`, callIndex: i });\n }\n }\n if (decoded.functionName === \"approve\" && decoded.args.length >= 2) {\n const spender = decoded.args[0] as string;\n if (typeof spender === \"string\" && spender.startsWith(\"0x\") && !isKnown(spender)) {\n risks.push({ level: \"critical\", code: \"APPROVE_TO_UNKNOWN\",\n message: `Call #${callNum} approve() grants allowance to ${truncAddr(spender)} which is not a known protocol`, callIndex: i });\n }\n }\n }\n\n if (context?.performanceFeeBps !== undefined) {\n const fee = context.performanceFeeBps;\n const maxFee = context.governorParams?.maxPerformanceFeeBps;\n if (maxFee !== undefined && fee > (maxFee * 80n) / 100n) {\n risks.push({ level: \"critical\", code: \"EXCESSIVE_PERFORMANCE_FEE\",\n message: `Performance fee ${Number(fee) / 100}% is within 20% of the hard cap (${Number(maxFee) / 100}%)` });\n } else if (fee > 2000n) {\n risks.push({ level: \"warning\", code: \"HIGH_PERFORMANCE_FEE\",\n message: `Performance fee ${Number(fee) / 100}% exceeds 20% threshold` });\n }\n }\n\n if (context?.strategyDuration !== undefined) {\n const dur = context.strategyDuration;\n if (dur < 3600n) {\n risks.push({ level: \"warning\", code: \"SHORT_STRATEGY_DURATION\",\n message: `Strategy duration ${Number(dur)}s is under 1 hour — flash-loan-style risk` });\n }\n if (dur > 2_592_000n) {\n risks.push({ level: \"warning\", code: \"LONG_STRATEGY_DURATION\",\n message: `Strategy duration ${Number(dur) / 86400} days exceeds 30-day threshold` });\n }\n }\n\n const hasCritical = risks.some((r) => r.level === \"critical\");\n const hasWarning = risks.some((r) => r.level === \"warning\");\n if (!hasCritical && !hasWarning) {\n if (allTargetsVerified) {\n risks.push({ level: \"info\", code: \"ALL_TARGETS_VERIFIED\", message: \"All call targets are verified protocol addresses\" });\n }\n if (allCallsDecoded) {\n risks.push({ level: \"info\", code: \"ALL_CALLS_DECODED\", message: \"All calldata successfully decoded\" });\n }\n }\n\n return risks;\n}\n\n// ── Verdict helper ───────────────────────────────────────\n\nexport type Verdict = \"CLEAN\" | \"WARNING\" | \"CRITICAL\";\n\nexport function verdictOf(risks: RiskFlag[]): Verdict {\n if (risks.some((r) => r.level === \"critical\")) return \"CRITICAL\";\n if (risks.some((r) => r.level === \"warning\")) return \"WARNING\";\n return \"CLEAN\";\n}\n","/**\n * Governor commands — sherwood governor <subcommand>\n *\n * View and manage SyndicateGovernor parameters (owner-only setters).\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getExplorerUrl, getChain } from \"../lib/network.js\";\nimport { formatContractError } from \"../lib/errors.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeGovernorParam, type ChainId, type GovernorParam } from \"@sherwoodagent/sdk\";\nimport {\n getGovernorAddress,\n getGovernorParams,\n getRegisteredVaults,\n setVotingPeriod,\n setExecutionWindow,\n setVetoThresholdBps,\n setProtocolFeeBps,\n setMaxPerformanceFeeBps,\n setMaxStrategyDuration,\n setCooldownPeriod,\n} from \"../lib/governor.js\";\nimport { formatDurationLong as formatDuration, parseBigIntArg } from \"../lib/format.js\";\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\n/**\n * Register one owner-only parameter setter. V1.5 setters are owner-instant\n * (no on-chain timelock — the owner multisig enforces its own delay), so the\n * success copy says \"updated\", not \"queued\". With `--calldata-only` it prints\n * the unsigned `setX(value)` calldata via the shared SDK encoder instead.\n */\nfunction registerParamSetter(\n governor: Command,\n spec: {\n command: string;\n description: string;\n flag: string;\n flagDescription: string;\n valueLabel: string;\n param: GovernorParam;\n setter: (value: bigint) => Promise<`0x${string}`>;\n spinnerText: string;\n succeed: (rawValue: string) => string;\n failText: string;\n },\n): void {\n governor\n .command(spec.command)\n .description(spec.description)\n .requiredOption(spec.flag, spec.flagDescription)\n .action(async (opts) => {\n // `valueLabel` (\"seconds\" | \"bps\") matches the camelCased option key.\n const rawValue = String(opts[spec.valueLabel]);\n\n if (isCalldataOnly()) {\n try {\n const value = parseBigIntArg(rawValue, spec.valueLabel);\n emitCalldata(\n encodeGovernorParam({ param: spec.param, value }, getChain().id as ChainId),\n );\n } catch (err) {\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n return;\n }\n\n const spinner = ora(spec.spinnerText).start();\n try {\n const hash = await spec.setter(parseBigIntArg(rawValue, spec.valueLabel));\n spinner.succeed(G(spec.succeed(rawValue)));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(spec.failText);\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n\nexport function registerGovernorCommands(program: Command): void {\n const governor = program.command(\"governor\").description(\"Governor parameters and vault management\");\n\n // ── governor info ──\n\n governor\n .command(\"info\")\n .description(\"Display current governor parameters and registered vaults\")\n .action(async () => {\n const spinner = ora(\"Loading governor info...\").start();\n try {\n const [params, vaults] = await Promise.all([\n getGovernorParams(),\n getRegisteredVaults(),\n ]);\n\n spinner.stop();\n\n console.log();\n console.log(LABEL(\" ◆ Governor Parameters\"));\n SEP();\n console.log(W(` Address: ${G(getGovernorAddress())}`));\n console.log(W(` Voting Period: ${BOLD(formatDuration(params.votingPeriod))}`));\n console.log(W(` Execution Window: ${BOLD(formatDuration(params.executionWindow))}`));\n console.log(W(` Veto Threshold: ${BOLD(`${Number(params.vetoThresholdBps) / 100}%`)}`));\n console.log(W(` Max Performance Fee: ${BOLD(`${Number(params.maxPerformanceFeeBps) / 100}%`)}`));\n console.log(W(` Max Strategy Duration:${BOLD(` ${formatDuration(params.maxStrategyDuration)}`)}`));\n console.log(W(` Cooldown Period: ${BOLD(formatDuration(params.cooldownPeriod))}`));\n\n console.log();\n console.log(LABEL(` Registered Vaults (${vaults.length})`));\n if (vaults.length === 0) {\n console.log(DIM(\" (none)\"));\n } else {\n for (const v of vaults) {\n console.log(W(` ${G(v)}`));\n }\n }\n\n SEP();\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load governor info\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── governor parameter setters (owner-only, owner-instant in V1.5) ──\n\n registerParamSetter(governor, {\n command: \"set-voting-period\",\n description: \"Set the voting period (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New voting period in seconds\",\n valueLabel: \"seconds\",\n param: \"votingPeriod\",\n setter: setVotingPeriod,\n spinnerText: \"Setting voting period...\",\n succeed: (v) => `Voting period updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set voting period\",\n });\n\n registerParamSetter(governor, {\n command: \"set-execution-window\",\n description: \"Set the execution window (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New execution window in seconds\",\n valueLabel: \"seconds\",\n param: \"executionWindow\",\n setter: setExecutionWindow,\n spinnerText: \"Setting execution window...\",\n succeed: (v) => `Execution window updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set execution window\",\n });\n\n registerParamSetter(governor, {\n command: \"set-veto-threshold\",\n description: \"Set the veto threshold in bps (owner only)\",\n flag: \"--bps <n>\",\n flagDescription: \"New veto threshold in bps (e.g. 4000 = 40%)\",\n valueLabel: \"bps\",\n param: \"vetoThresholdBps\",\n setter: setVetoThresholdBps,\n spinnerText: \"Setting veto threshold...\",\n succeed: (v) => `Veto threshold updated to ${Number(v) / 100}% (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set veto threshold\",\n });\n\n registerParamSetter(governor, {\n command: \"set-max-fee\",\n description: \"Set the max performance fee in bps (owner only)\",\n flag: \"--bps <n>\",\n flagDescription: \"New max fee in bps (e.g. 3000 = 30%)\",\n valueLabel: \"bps\",\n param: \"maxPerformanceFeeBps\",\n setter: setMaxPerformanceFeeBps,\n spinnerText: \"Setting max fee...\",\n succeed: (v) => `Max performance fee updated to ${Number(v) / 100}% (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set max fee\",\n });\n\n registerParamSetter(governor, {\n command: \"set-max-duration\",\n description: \"Set the max strategy duration in seconds (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New max duration in seconds\",\n valueLabel: \"seconds\",\n param: \"maxStrategyDuration\",\n setter: setMaxStrategyDuration,\n spinnerText: \"Setting max duration...\",\n succeed: (v) => `Max strategy duration updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set max duration\",\n });\n\n registerParamSetter(governor, {\n command: \"set-cooldown\",\n description: \"Set the cooldown period in seconds (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New cooldown in seconds\",\n valueLabel: \"seconds\",\n param: \"cooldownPeriod\",\n setter: setCooldownPeriod,\n spinnerText: \"Setting cooldown...\",\n succeed: (v) => `Cooldown period updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set cooldown\",\n });\n\n registerParamSetter(governor, {\n command: \"set-protocol-fee\",\n description: \"Set the protocol fee in bps (owner only)\",\n flag: \"--bps <n>\",\n flagDescription: \"New protocol fee in bps (e.g. 500 = 5%, max 1000 = 10%)\",\n valueLabel: \"bps\",\n param: \"protocolFeeBps\",\n setter: setProtocolFeeBps,\n spinnerText: \"Setting protocol fee...\",\n succeed: (v) => `Protocol fee updated to ${Number(v) / 100}% (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set protocol fee\",\n });\n}\n","/**\n * Guardian delegation commands — sherwood guardian <subcommand>\n *\n * V1.5: stake-pool delegation into GuardianRegistry, DPoS commission\n * configuration, and Merkl reward-claim navigation. Rewards claim itself\n * happens on merkl.xyz; this CLI prints a deep link + pending-reward\n * summary when the API key is configured.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport type { Address } from \"viem\";\nimport { formatUnits, isAddress, parseUnits } from \"viem\";\nimport { getPublicClient, getWalletClient } from \"../lib/client.js\";\nimport { getNetwork, getChain } from \"../lib/network.js\";\nimport { SHERWOOD } from \"../lib/addresses.js\";\nimport { formatContractError } from \"../lib/errors.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport {\n encodeGuardianStake,\n encodeGuardianUnstake,\n encodeGuardianDelegate,\n encodeDelegationUnstake,\n encodeSetCommission,\n encodeClaimProposalReward,\n encodeClaimDelegatorProposalReward,\n type ChainId,\n} from \"@sherwoodagent/sdk\";\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst WARN = chalk.yellow;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\n// Minimal ABI fragments — only what this command set touches.\nconst GUARDIAN_REGISTRY_ABI = [\n // Guardian stake\n { type: \"function\", name: \"stakeAsGuardian\", inputs: [{ type: \"uint256\" }, { type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"requestUnstakeGuardian\", inputs: [], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"cancelUnstakeGuardian\", inputs: [], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"claimUnstakeGuardian\", inputs: [], outputs: [], stateMutability: \"nonpayable\" },\n // Delegation\n { type: \"function\", name: \"delegateStake\", inputs: [{ type: \"address\" }, { type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"requestUnstakeDelegation\", inputs: [{ type: \"address\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"cancelUnstakeDelegation\", inputs: [{ type: \"address\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"claimUnstakeDelegation\", inputs: [{ type: \"address\" }], outputs: [], stateMutability: \"nonpayable\" },\n // Commission\n { type: \"function\", name: \"setCommission\", inputs: [{ type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n // Views\n { type: \"function\", name: \"guardianStake\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"isActiveGuardian\", inputs: [{ type: \"address\" }], outputs: [{ type: \"bool\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"commissionOf\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"delegationOf\", inputs: [{ type: \"address\" }, { type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"delegatedInbound\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n // Guardian-fee claim (vault asset)\n { type: \"function\", name: \"claimProposalReward\", inputs: [{ type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"claimDelegatorProposalReward\", inputs: [{ type: \"address\" }, { type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n] as const;\n\nconst ERC20_ABI = [\n { type: \"function\", name: \"approve\", inputs: [{ type: \"address\" }, { type: \"uint256\" }], outputs: [{ type: \"bool\" }], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"balanceOf\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"decimals\", inputs: [], outputs: [{ type: \"uint8\" }], stateMutability: \"view\" },\n] as const;\n\nfunction requireAddress(name: string, addr: Address): Address {\n if (addr === \"0x0000000000000000000000000000000000000000\") {\n console.error(chalk.red(`${name} is not deployed on ${getNetwork()}. Update cli/src/lib/addresses.ts after deploy.`));\n process.exit(1);\n }\n return addr;\n}\n\nfunction registry(): Address {\n return requireAddress(\"GUARDIAN_REGISTRY\", SHERWOOD().GUARDIAN_REGISTRY);\n}\n\nfunction wood(): Address {\n return requireAddress(\"WOOD_TOKEN\", SHERWOOD().WOOD_TOKEN);\n}\n\nasync function ensureWoodAllowance(amount: bigint): Promise<void> {\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const addr = wallet.account!.address;\n const current = (await pc.readContract({\n address: wood(),\n abi: [{ type: \"function\", name: \"allowance\", inputs: [{ type: \"address\" }, { type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" }] as const,\n functionName: \"allowance\",\n args: [addr, registry()],\n })) as bigint;\n if (current >= amount) return;\n const spinner = ora(\"Approving WOOD...\").start();\n try {\n const hash = await wallet.writeContract({\n address: wood(), abi: ERC20_ABI, functionName: \"approve\", args: [registry(), 2n ** 256n - 1n], chain: null, account: wallet.account!,\n });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(\"WOOD approval granted\");\n } catch (err) {\n spinner.fail(\"WOOD approval failed\");\n throw err;\n }\n}\n\nexport function registerGuardianCommands(program: Command): void {\n const guardian = program.command(\"guardian\").description(\"Guardian staking, delegation, and rewards (V1.5)\");\n\n // ── status ──\n\n guardian\n .command(\"status [address]\")\n .description(\"Show guardian stake + commission + active status for an address (default: caller)\")\n .action(async (addressArg?: string) => {\n const pc = getPublicClient();\n let target: Address;\n if (addressArg) {\n if (!isAddress(addressArg)) {\n console.error(chalk.red(\"Invalid address\"));\n process.exit(1);\n }\n target = addressArg;\n } else {\n const wallet = getWalletClient();\n target = wallet.account!.address;\n }\n\n const spinner = ora(\"Loading...\").start();\n try {\n const [stake, active, commission] = await Promise.all([\n pc.readContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"guardianStake\", args: [target] }) as Promise<bigint>,\n pc.readContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"isActiveGuardian\", args: [target] }) as Promise<boolean>,\n pc.readContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"commissionOf\", args: [target] }) as Promise<bigint>,\n ]);\n const delegatedIn = (await pc.readContract({\n address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"delegatedInbound\", args: [target],\n })) as bigint;\n spinner.stop();\n\n console.log();\n console.log(LABEL(\" ◆ Guardian Status\"));\n SEP();\n console.log(W(` Address: ${G(target)}`));\n console.log(W(` Active guardian: ${active ? G(\"yes\") : DIM(\"no\")}`));\n console.log(W(` Own stake: ${BOLD(formatUnits(stake, 18))} WOOD`));\n console.log(W(` Delegated inbound: ${BOLD(formatUnits(delegatedIn, 18))} WOOD`));\n console.log(W(` Commission: ${BOLD(`${Number(commission) / 100}%`)}`));\n SEP();\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── stake ──\n\n guardian\n .command(\"stake <amount>\")\n .description(\"Stake as a guardian. Amount in WOOD (min = registry.minGuardianStake).\")\n .option(\"--agent-id <id>\", \"ERC-8004 agent ID to associate (first-stake only)\", \"0\")\n .action(async (amountStr: string, opts: { agentId: string }) => {\n const amount = parseUnits(amountStr, 18);\n const agentId = BigInt(opts.agentId);\n if (isCalldataOnly()) {\n emitCalldata(encodeGuardianStake({ amount, agentId: opts.agentId }, getChain().id as ChainId));\n return;\n }\n await ensureWoodAllowance(amount);\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`Staking ${amountStr} WOOD...`).start();\n try {\n const hash = await wallet.writeContract({\n address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"stakeAsGuardian\", args: [amount, agentId], chain: null, account: wallet.account!,\n });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Staked. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Stake failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── unstake (request / cancel / claim) ──\n\n guardian\n .command(\"unstake <action>\")\n .description(\"Unstake flow: 'request' | 'cancel' | 'claim' (7d cooldown)\")\n .action(async (action: string) => {\n const fn = { request: \"requestUnstakeGuardian\", cancel: \"cancelUnstakeGuardian\", claim: \"claimUnstakeGuardian\" }[action];\n if (!fn) {\n console.error(chalk.red(`Unknown action '${action}'. Use request | cancel | claim.`));\n process.exit(1);\n }\n if (isCalldataOnly()) {\n emitCalldata(encodeGuardianUnstake({ action: action as \"request\" | \"cancel\" | \"claim\" }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`${action}...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: fn as any, args: [], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`${action} confirmed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(`${action} failed`);\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── delegate ──\n\n guardian\n .command(\"delegate <delegate> <amount>\")\n .description(\"Delegate WOOD stake to a guardian. Amount in WOOD.\")\n .action(async (delegate: string, amountStr: string) => {\n if (!isAddress(delegate)) {\n console.error(chalk.red(\"Invalid delegate address\"));\n process.exit(1);\n }\n const amount = parseUnits(amountStr, 18);\n if (isCalldataOnly()) {\n emitCalldata(encodeGuardianDelegate({ delegate, amount }, getChain().id as ChainId));\n return;\n }\n await ensureWoodAllowance(amount);\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`Delegating ${amountStr} WOOD to ${delegate}...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"delegateStake\", args: [delegate, amount], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Delegated. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Delegation failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n guardian\n .command(\"undelegate <delegate> <action>\")\n .description(\"Unstake-delegation flow: 'request' | 'cancel' | 'claim'\")\n .action(async (delegate: string, action: string) => {\n if (!isAddress(delegate)) {\n console.error(chalk.red(\"Invalid delegate address\"));\n process.exit(1);\n }\n const fn = { request: \"requestUnstakeDelegation\", cancel: \"cancelUnstakeDelegation\", claim: \"claimUnstakeDelegation\" }[action];\n if (!fn) {\n console.error(chalk.red(`Unknown action '${action}'. Use request | cancel | claim.`));\n process.exit(1);\n }\n if (isCalldataOnly()) {\n emitCalldata(encodeDelegationUnstake({ action: action as \"request\" | \"cancel\" | \"claim\", delegate }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`${action}...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: fn as any, args: [delegate], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`${action} confirmed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(`${action} failed`);\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── commission ──\n\n guardian\n .command(\"set-commission <bps>\")\n .description(\"Set your commission rate in bps (0-5000 = 0-50%). Raises capped cumulatively at 500 bps/epoch.\")\n .action(async (bpsStr: string) => {\n const bps = BigInt(bpsStr);\n if (bps > 5000n) {\n console.error(chalk.red(\"Commission cannot exceed 5000 bps (50%)\"));\n process.exit(1);\n }\n if (isCalldataOnly()) {\n emitCalldata(encodeSetCommission({ bps: Number(bps) }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`Setting commission to ${Number(bps) / 100}%...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"setCommission\", args: [bps], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Commission set. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"setCommission failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── reward claims ──\n\n guardian\n .command(\"claim-proposal <proposalId>\")\n .description(\"Claim guardian-fee commission for a settled proposal you voted Approve on (vault asset).\")\n .action(async (pidStr: string) => {\n const pid = BigInt(pidStr);\n if (isCalldataOnly()) {\n emitCalldata(encodeClaimProposalReward({ proposalId: pid }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(\"Claiming...\").start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"claimProposalReward\", args: [pid], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Claimed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Claim failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n guardian\n .command(\"claim-delegator <delegate> <proposalId>\")\n .description(\"Claim your delegator share of a delegate's guardian-fee pool for a specific proposal.\")\n .action(async (delegate: string, pidStr: string) => {\n if (!isAddress(delegate)) {\n console.error(chalk.red(\"Invalid delegate address\"));\n process.exit(1);\n }\n const pid = BigInt(pidStr);\n if (isCalldataOnly()) {\n emitCalldata(encodeClaimDelegatorProposalReward({ delegate, proposalId: pid }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(\"Claiming delegator share...\").start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"claimDelegatorProposalReward\", args: [delegate, pid], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Claimed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Claim failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── WOOD epoch rewards — Merkl ──\n\n guardian\n .command(\"claim-wood\")\n .description(\"Open merkl.xyz to claim WOOD epoch block-rewards (off-chain distribution).\")\n .action(async () => {\n const wallet = getWalletClient();\n const addr = wallet.account!.address;\n const url = `https://merkl.angle.money/user/${addr}`;\n console.log();\n console.log(LABEL(\" ◆ Merkl Reward Claim\"));\n SEP();\n console.log(W(\" WOOD epoch block-rewards are distributed off-chain via Merkl.\"));\n console.log(W(\" Open this URL in your browser to view + claim pending rewards:\"));\n console.log();\n console.log(G(` ${url}`));\n console.log();\n console.log(WARN(\" Note: guardian-fee rewards (vault assets) are claimed on-chain\"));\n console.log(WARN(\" via `sherwood guardian claim-proposal <pid>`.\"));\n SEP();\n console.log();\n });\n}\n","/**\n * Grid commands — sherwood grid start|status\n *\n * Runs the ATR-based grid trading strategy as a standalone loop,\n * parallel to the directional agent. Isolated capital and portfolio.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createInterface } from 'node:readline/promises';\nimport { GridLoop } from '../grid/loop.js';\nimport { GridPortfolio } from '../grid/portfolio.js';\nimport { GridHedgeManager } from '../grid/hedge.js';\nimport { OnchainGridExecutor } from '../grid/onchain-executor.js';\nimport { HyperliquidProvider } from '../providers/data/hyperliquid.js';\nimport { DEFAULT_GRID_CONFIG } from '../grid/config.js';\nimport { runBacktest } from '../grid/backtest.js';\nimport type { BacktestResult } from '../grid/backtest.js';\nimport type { GridConfig } from '../grid/config.js';\nimport { runSweep, type SweepResult, type SweepableField } from '../grid/sweep.js';\n\n/**\n * Default reason strings recorded on `state.pauseReason` when an operator\n * halts a grid. Stable strings so log-grep / dashboard filters can match\n * operator-initiated halts deterministically.\n */\nconst DEFAULT_PAUSE_REASON = 'Manually paused by operator';\nconst DEFAULT_FLATTEN_REASON = 'Manually flattened by operator';\n\n/** Seconds to wait at the y/N confirmation prompt before aborting. */\nconst CONFIRM_TIMEOUT_SECONDS = 60;\n\nconst DIM = chalk.gray;\nconst G = chalk.green;\nconst BOLD = chalk.white.bold;\nconst W = chalk.white;\nconst SEP = () => console.log(DIM('─'.repeat(60)));\n\nfunction printSummary(r: BacktestResult): void {\n const dd = r.drawdown;\n const days = r.window.days;\n const rtPerDay = (r.totals.roundTrips / Math.max(days, 1)).toFixed(1);\n const fillPerDay = (r.totals.fills / Math.max(days, 1)).toFixed(1);\n const pnlSign = r.capital.pnlUsd >= 0 ? '+' : '-';\n const pnlAbs = Math.abs(r.capital.pnlUsd).toFixed(2);\n const pnlPctStr = (r.capital.pnlPct * 100).toFixed(2);\n\n console.log();\n console.log(G.bold(` Grid Backtest — ${r.runId}`));\n console.log(DIM('─'.repeat(64)));\n console.log(W(` Window: ${r.window.fromIso.slice(0, 10)} → ${r.window.toIso.slice(0, 10)} (${days.toFixed(0)} days)`));\n console.log(W(` Capital: $${r.capital.initialUsd.toLocaleString()} → $${r.capital.finalUsd.toFixed(2)} (${pnlSign}$${pnlAbs}, ${pnlSign}${pnlPctStr}%)`));\n console.log(W(` Gross PnL: $${r.capital.grossPnlUsd.toFixed(2)} (before fees)`));\n console.log(W(` Fees (${r.fees.bps}bps): -$${r.fees.totalUsd.toFixed(2)} ($${r.fees.perFill.toFixed(4)}/fill)`));\n if (r.hedge.enabled) {\n const hedgeNet = r.hedge.realizedPnlUsd + r.hedge.unrealizedPnlUsd;\n const hedgeSign = hedgeNet >= 0 ? '+' : '-';\n const hedgeAbs = Math.abs(hedgeNet).toFixed(2);\n console.log(W(` Hedge: ${hedgeSign}$${hedgeAbs} (realized $${r.hedge.realizedPnlUsd.toFixed(2)} + unrealized $${r.hedge.unrealizedPnlUsd.toFixed(2)}, ${r.hedge.adjustments} adj)`));\n } else {\n console.log(W(` Hedge: disabled`));\n }\n console.log(W(` Round trips: ${r.totals.roundTrips} (${rtPerDay}/day)`));\n console.log(W(` Fills: ${r.totals.fills} (${fillPerDay}/day)`));\n console.log(W(` Rebuilds: ${r.totals.rebuilds}`));\n console.log(W(` Max drawdown: -$${dd.maxUsd.toFixed(2)} (-${(dd.maxPct * 100).toFixed(2)}%)`));\n console.log(W(` Paused: ${r.totals.pausedSteps} steps (${((r.totals.pausedSteps / Math.max(r.totals.totalSteps, 1)) * 100).toFixed(1)}%)`));\n console.log(W(` Skipped: ${r.totals.skippedSteps} steps`));\n console.log();\n console.log(BOLD(' Per token:'));\n for (const t of r.perToken) {\n const tokPnl = t.pnlUsd >= 0 ? G(`+$${t.pnlUsd.toFixed(2)}`) : chalk.red(`-$${Math.abs(t.pnlUsd).toFixed(2)}`);\n console.log(W(` ${t.token.padEnd(10)} $${t.allocation.initial.toFixed(0).padStart(6)} → $${t.allocation.final.toFixed(0).padStart(6)} ${tokPnl} RTs=${t.roundTrips} fills=${t.fills}`));\n }\n if (r.liquidations.events.length > 0) {\n console.log();\n console.log(BOLD(' Liquidations:'));\n for (const ev of r.liquidations.events) {\n const date = new Date(ev.timestamp).toISOString().slice(0, 10);\n console.log(W(` ${ev.token.padEnd(10)} ${date} unrealized=$${ev.unrealizedPnlAtLiquidation.toFixed(0)} threshold=$${ev.thresholdUsd.toFixed(0)}`));\n }\n if (r.liquidations.haltedAt !== null) {\n const haltDate = new Date(r.liquidations.haltedAt).toISOString().slice(0, 10);\n console.log(chalk.red.bold(` RUN HALTED on ${haltDate} — all tokens liquidated.`));\n }\n }\n console.log();\n console.log(W(` Wall time: ${(r.durationMs / 1000).toFixed(1)}s`));\n console.log(DIM('─'.repeat(64)));\n}\n\nfunction printSweepSummary(s: SweepResult): void {\n const days = s.window.days;\n console.log();\n console.log(G.bold(` Grid Sweep — ${s.sweepId}`));\n console.log(DIM('─'.repeat(96)));\n console.log(W(` Window: ${new Date(s.window.fromMs).toISOString().slice(0, 10)} → ${new Date(s.window.toMs).toISOString().slice(0, 10)} (${days.toFixed(0)} days)`));\n console.log(W(` Tokens: ${s.tokens.join(', ')}`));\n console.log(W(` Capital: $${s.capital.toLocaleString()}`));\n console.log(W(` Fees: ${s.feeBps} bps/fill`));\n console.log(W(` Runs: ${s.runs.length}`));\n console.log(W(` Wall: ${(s.durationMs / 1000).toFixed(1)}s`));\n console.log(DIM('─'.repeat(96)));\n console.log();\n console.log(BOLD(' Rank Surv Lev Levels ATR× Drift RTs NetPnL$ NetPnL% DD% Risk-Adj'));\n console.log(DIM(' ' + '─'.repeat(102)));\n for (let i = 0; i < s.runs.length; i++) {\n const r = s.runs[i]!;\n const rank = String(i + 1).padStart(4);\n const surv = r.survived ? G(' ✓ ') : chalk.red(' ✗ ');\n const lev = String(r.config.leverage ?? '').padStart(3);\n const lvls = String(r.config.levelsPerSide ?? '').padStart(6);\n const atr = String(r.config.atrMultiplier ?? '').padStart(4);\n const drift = String(r.config.rebalanceDriftPct ?? '').padStart(5);\n const rts = String(r.totals.roundTrips).padStart(5);\n const netPnl = `$${r.capital.pnlUsd.toFixed(0)}`.padStart(11);\n const netPct = `${(r.capital.pnlPct * 100).toFixed(1)}%`.padStart(8);\n const ddPct = `${(r.drawdown.maxPct * 100).toFixed(1)}%`.padStart(8);\n const ra = r.riskAdjusted.toFixed(2).padStart(8);\n const pnlColor = r.capital.pnlUsd >= 0 ? G : chalk.red;\n console.log(` ${rank} ${surv} ${lev} ${lvls} ${atr} ${drift} ${rts} ${pnlColor(netPnl)} ${pnlColor(netPct)} ${ddPct} ${ra}`);\n }\n console.log(DIM(' ' + '─'.repeat(102)));\n console.log();\n console.log(W(` Saved: ${s.sweepId}/sweep.json + per-run JSONs in ~/.sherwood/grid/sweeps/`));\n console.log();\n}\n\n/**\n * Parse `--asset-indices` flag value (e.g. `bitcoin=0,ethereum=1,solana=5`)\n * into `{ bitcoin: 0, ethereum: 1, solana: 5 }`. Validates that each value\n * is a non-negative integer so a typo doesn't quietly become `NaN` in the\n * encoded cancel/place tx.\n */\nfunction parseAssetIndices(raw: string): Record<string, number> {\n const indices: Record<string, number> = {};\n for (const pair of raw.split(',')) {\n const [tok, idx] = pair.split('=');\n if (!tok || !idx) {\n throw new Error(`Bad asset-indices pair: '${pair}' (expected token=index)`);\n }\n const n = Number(idx.trim());\n if (!Number.isInteger(n) || n < 0) {\n throw new Error(`Bad asset-indices value for '${tok}': '${idx}' (must be a non-negative integer)`);\n }\n indices[tok.trim()] = n;\n }\n return indices;\n}\n\nfunction parseTokenSplit(raw: string, tokens: string[]): Record<string, number> {\n const split: Record<string, number> = {};\n for (const pair of raw.split(',')) {\n const [tok, w] = pair.split('=');\n if (!tok || !w) throw new Error(`Bad token-split pair: '${pair}' (expected token=weight)`);\n const weight = Number(w.trim());\n if (!Number.isFinite(weight) || weight < 0) {\n throw new Error(`Bad token-split weight for '${tok}': '${w}'`);\n }\n split[tok.trim()] = weight;\n }\n for (const t of tokens) {\n if (!(t in split)) {\n throw new Error(`--token-split missing weight for '${t}'`);\n }\n }\n const sum = Object.values(split).reduce((a, b) => a + b, 0);\n if (Math.abs(sum - 1.0) > 1e-6) {\n throw new Error(`--token-split weights must sum to 1.0, got ${sum.toFixed(6)}`);\n }\n return split;\n}\n\nexport function registerGridCommand(program: Command): void {\n const grid = program\n .command('grid')\n .description('Grid trading strategy — ATR-based grid on BTC/ETH/SOL');\n\n // ── grid start ──\n grid\n .command('start')\n .description('Start the grid trading loop')\n .option('--capital <usd>', 'Starting capital in USD', '5000')\n .option('--cycle <seconds>', 'Cycle interval in seconds', '60')\n .option('--tokens <list>', 'Comma-separated token list', 'bitcoin,ethereum,solana')\n .option('--leverage <n>', 'Leverage multiplier', String(DEFAULT_GRID_CONFIG.leverage))\n .option('--levels <n>', 'Grid levels per side', String(DEFAULT_GRID_CONFIG.levelsPerSide))\n .option('--live', 'enable live execution (places real orders on Hyperliquid)')\n .option('--asset-indices <pairs>', 'comma-separated token=index pairs (mainnet: bitcoin=0,ethereum=1,solana=5)')\n .option('--strategy <address>', 'on-chain strategy contract address (enables on-chain executor)')\n .option('--token-split <pairs>', 'Comma-separated token=weight pairs (must sum to 1.0). Default: equal-weight.')\n .option('--state-dir <path>', 'Override directory for portfolio.json / hedge.json / cycles.jsonl / onchain-state.json. Defaults to ~/.sherwood/grid. Use a separate dir to run paper and live grids in parallel.')\n .action(async (opts) => {\n const capital = parseFloat(opts.capital);\n const cycleMs = parseInt(opts.cycle, 10) * 1000;\n const tokens = opts.tokens.split(',').map((t: string) => t.trim());\n const leverage = parseFloat(opts.leverage);\n const levels = parseInt(opts.levels, 10);\n const stateDir = opts.stateDir as string | undefined;\n\n const live = !!opts.live;\n let assetIndices: Record<string, number> | undefined;\n if (live) {\n if (!opts.assetIndices) {\n throw new Error('--asset-indices required when --live (mainnet: --asset-indices bitcoin=0,ethereum=1,solana=5)');\n }\n assetIndices = parseAssetIndices(opts.assetIndices as string);\n }\n\n const strategyAddress = opts.strategy as `0x${string}` | undefined;\n if (strategyAddress && !live) {\n throw new Error('--strategy requires --live');\n }\n\n // Build token split (explicit if provided, else equal-weight)\n let tokenSplit: Record<string, number>;\n if (opts.tokenSplit) {\n tokenSplit = parseTokenSplit(opts.tokenSplit as string, tokens);\n } else {\n const weight = 1 / tokens.length;\n tokenSplit = {};\n for (const t of tokens) {\n tokenSplit[t] = weight;\n }\n }\n\n console.log();\n console.log(G.bold(' Grid Strategy'));\n SEP();\n console.log(W(` Capital: $${capital.toLocaleString()}`));\n console.log(W(` Cycle: ${opts.cycle}s`));\n console.log(W(` Tokens: ${tokens.join(', ')}`));\n console.log(W(` Leverage: ${leverage}x`));\n console.log(W(` Levels: ${levels}/side`));\n SEP();\n\n const loop = new GridLoop({\n capital,\n cycle: cycleMs,\n live,\n assetIndices,\n strategyAddress,\n stateDir,\n config: {\n ...DEFAULT_GRID_CONFIG,\n tokens,\n leverage,\n levelsPerSide: levels,\n tokenSplit,\n },\n });\n\n await loop.start();\n });\n\n // ── grid status ──\n grid\n .command('status')\n .description('Show current grid portfolio status')\n .option('--state-dir <path>', 'Read state from a custom directory (defaults to ~/.sherwood/grid)')\n .action(async (opts) => {\n const portfolio = new GridPortfolio(opts.stateDir as string | undefined);\n const state = await portfolio.load();\n\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Run `sherwood grid start` first.\\n'));\n return;\n }\n\n // Reset daily stats if needed before display\n portfolio.resetDailyStats(state);\n const agg = portfolio.aggregateStats(state);\n\n console.log();\n console.log(G.bold(' Grid Portfolio'));\n SEP();\n console.log(W(` Allocation: $${state.totalAllocation.toLocaleString()}`));\n console.log(W(` Status: ${state.paused ? chalk.red('PAUSED — ' + state.pauseReason) : G('Active')}`));\n console.log(W(` Initialized: ${new Date(state.initializedAt).toLocaleString()}`));\n SEP();\n\n // Per-token table\n console.log();\n console.log(BOLD(' Token Alloc RTs PnL Today PnL Fills'));\n console.log(DIM(' ' + '─'.repeat(72)));\n\n for (const g of state.grids) {\n const name = g.token.padEnd(13);\n const alloc = `$${g.allocation.toFixed(0)}`.padStart(8);\n const rts = String(g.stats.totalRoundTrips).padStart(6);\n const pnl = `$${g.stats.totalPnlUsd.toFixed(2)}`.padStart(10);\n const todayPnl = `$${g.stats.todayPnlUsd.toFixed(2)}`.padStart(10);\n const fills = String(g.stats.totalFills).padStart(6);\n const pnlColor = g.stats.totalPnlUsd >= 0 ? G : chalk.red;\n const todayColor = g.stats.todayPnlUsd >= 0 ? G : chalk.red;\n\n console.log(` ${W(name)} ${alloc} ${rts} ${pnlColor(pnl)} ${todayColor(todayPnl)} ${fills}`);\n }\n\n console.log(DIM(' ' + '─'.repeat(72)));\n\n // Totals\n const totalPnlColor = agg.totalPnlUsd >= 0 ? G : chalk.red;\n const todayTotalColor = agg.todayPnlUsd >= 0 ? G : chalk.red;\n console.log(` ${BOLD('TOTAL'.padEnd(13))} ${`$${state.totalAllocation.toFixed(0)}`.padStart(8)} ${String(agg.totalRoundTrips).padStart(6)} ${totalPnlColor(`$${agg.totalPnlUsd.toFixed(2)}`.padStart(10))} ${todayTotalColor(`$${agg.todayPnlUsd.toFixed(2)}`.padStart(10))} ${String(agg.todayFills).padStart(6)}`);\n console.log();\n });\n\n // ── grid backtest ──\n grid\n .command('backtest')\n .description('Replay historical Hyperliquid prices through the grid strategy')\n .option('--from <iso>', 'Window start (ISO date). Default: 30d ago.')\n .option('--to <iso>', 'Window end (ISO date). Default: now.')\n .option('--capital <usd>', 'Starting capital in USD', '5000')\n .option('--tokens <list>', 'Comma-separated token list', 'bitcoin,ethereum,solana')\n .option('--leverage <n>', 'Override leverage')\n .option('--levels <n>', 'Override levels per side')\n .option('--atr-multiplier <n>', 'Override ATR multiplier')\n .option('--rebalance-drift <n>', 'Override rebalanceDriftPct')\n .option('--snapshot-every <min>', 'Equity-curve snapshot cadence (minutes)', '60')\n .option('--verbose', 'Print manager fill logs during replay')\n .option('--no-cache', 'Skip cache; always fetch fresh data')\n .option('--out <path>', 'Override output path')\n .option('--fee-bps <n>', 'Trading fee in basis points per fill (default 5 = 0.05%)', '5')\n .option('--no-hedge', 'Disable hedge simulation (hedge is ON by default to match live grid)')\n .option('--maintenance-pct <n>', 'Per-token maintenance margin fraction (default 0.02 = 2%, typical Hyperliquid)', '0.02')\n .option('--pause-threshold <n>', 'Pool drop fraction that triggers pause (default 0.40, may be too lenient post leverage-fix)')\n .option('--unpause-recovery <n>', 'Pool drop fraction below which paused grid resumes (default 0.10)')\n .option('--token-split <pairs>', 'Comma-separated token=weight pairs (must sum to 1.0). Default: equal-weight or 0.45/0.30/0.25 for BTC/ETH/SOL.')\n .option('--stop-loss <n>', 'Per-fill stop-loss fraction (default 0.10 = 10%, 0 disables)')\n .action(async (opts) => {\n const now = Date.now();\n const toMs = opts.to ? Date.parse(opts.to) : now;\n const fromMs = opts.from ? Date.parse(opts.from) : (now - 30 * 24 * 3600_000);\n if (Number.isNaN(toMs) || Number.isNaN(fromMs)) {\n throw new Error('--from / --to must be ISO dates (e.g. 2026-04-01)');\n }\n\n const tokens = (opts.tokens as string).split(',').map(t => t.trim());\n let tokenSplit: Record<string, number>;\n if (opts.tokenSplit) {\n tokenSplit = parseTokenSplit(opts.tokenSplit as string, tokens);\n } else {\n const weight = 1 / tokens.length;\n tokenSplit = {};\n for (const t of tokens) tokenSplit[t] = weight;\n }\n\n const config: GridConfig = {\n ...DEFAULT_GRID_CONFIG,\n tokens,\n tokenSplit,\n leverage: opts.leverage ? Number(opts.leverage) : DEFAULT_GRID_CONFIG.leverage,\n levelsPerSide: opts.levels ? Number(opts.levels) : DEFAULT_GRID_CONFIG.levelsPerSide,\n atrMultiplier: opts.atrMultiplier ? Number(opts.atrMultiplier) : DEFAULT_GRID_CONFIG.atrMultiplier,\n rebalanceDriftPct: opts.rebalanceDrift ? Number(opts.rebalanceDrift) : DEFAULT_GRID_CONFIG.rebalanceDriftPct,\n maintenanceMarginPct: opts.maintenancePct ? Number(opts.maintenancePct) : DEFAULT_GRID_CONFIG.maintenanceMarginPct,\n pauseThresholdPct: opts.pauseThreshold ? Number(opts.pauseThreshold) : DEFAULT_GRID_CONFIG.pauseThresholdPct,\n unpauseRecoveryPct: opts.unpauseRecovery ? Number(opts.unpauseRecovery) : DEFAULT_GRID_CONFIG.unpauseRecoveryPct,\n stopLossPct: opts.stopLoss !== undefined ? Number(opts.stopLoss) : DEFAULT_GRID_CONFIG.stopLossPct,\n };\n\n const capital = Number(opts.capital);\n const snapshotEveryMinutes = Number(opts.snapshotEvery);\n\n console.log();\n console.log(G.bold(' Grid Backtest'));\n SEP();\n console.log(W(` Window: ${new Date(fromMs).toISOString().slice(0, 10)} → ${new Date(toMs).toISOString().slice(0, 10)}`));\n console.log(W(` Capital: $${capital.toLocaleString()}`));\n console.log(W(` Tokens: ${tokens.join(', ')}`));\n console.log(W(` Leverage: ${config.leverage}x`));\n console.log(W(` Levels: ${config.levelsPerSide}/side`));\n SEP();\n\n const result = await runBacktest({\n fromMs,\n toMs,\n capital,\n config,\n snapshotEveryMinutes,\n verbose: !!opts.verbose,\n noCache: opts.cache === false,\n outPath: opts.out,\n feeBps: Number(opts.feeBps),\n hedge: opts.hedge !== false,\n });\n\n printSummary(result);\n });\n\n // ── grid sweep ──\n grid\n .command('sweep')\n .description('Run a parameter sweep over multiple grid configurations')\n .option('--from <iso>', 'Window start (ISO date). Default: 30d ago.')\n .option('--to <iso>', 'Window end (ISO date). Default: now.')\n .option('--capital <usd>', 'Starting capital in USD', '5000')\n .option('--tokens <list>', 'Comma-separated token list', 'bitcoin,ethereum,solana')\n .option('--leverage <list>', 'Comma-separated leverage values to sweep')\n .option('--levels <list>', 'Comma-separated levels-per-side values to sweep')\n .option('--atr-multiplier <list>', 'Comma-separated ATR multiplier values to sweep')\n .option('--rebalance-drift <list>', 'Comma-separated rebalance drift values to sweep')\n .option('--fee-bps <n>', 'Trading fee in basis points per fill (default 5)', '5')\n .option('--no-cache', 'Skip cache; always fetch fresh data')\n .option('--token-split <pairs>', 'Comma-separated token=weight pairs (must sum to 1.0). Default: equal-weight or 0.45/0.30/0.25 for BTC/ETH/SOL.')\n .action(async (opts) => {\n const now = Date.now();\n const toMs = opts.to ? Date.parse(opts.to) : now;\n const fromMs = opts.from ? Date.parse(opts.from) : (now - 30 * 24 * 3600_000);\n if (Number.isNaN(toMs) || Number.isNaN(fromMs)) {\n throw new Error('--from / --to must be ISO dates (e.g. 2026-04-01)');\n }\n const tokens = (opts.tokens as string).split(',').map(t => t.trim());\n\n const parseList = (s: string | undefined): number[] | undefined => {\n if (!s) return undefined;\n return s.split(',').map(v => Number(v.trim())).filter(n => Number.isFinite(n));\n };\n\n const sweep: Partial<Record<SweepableField, number[]>> = {\n leverage: parseList(opts.leverage),\n levelsPerSide: parseList(opts.levels),\n atrMultiplier: parseList(opts.atrMultiplier),\n rebalanceDriftPct: parseList(opts.rebalanceDrift),\n };\n\n const tokenSplit = opts.tokenSplit\n ? parseTokenSplit(opts.tokenSplit as string, tokens)\n : undefined;\n\n const result = await runSweep({\n fromMs,\n toMs,\n capital: Number(opts.capital),\n tokens,\n tokenSplit,\n sweep,\n feeBps: Number(opts.feeBps),\n noCache: opts.cache === false,\n });\n\n printSweepSummary(result);\n });\n\n // ── grid pause ──\n grid\n .command('pause')\n .description('Manually pause the live grid (sets state.paused=true)')\n .option('--reason <text>', 'Reason for the pause (shown in status output)', DEFAULT_PAUSE_REASON)\n .option('--state-dir <path>', 'Read/write state from a custom directory (defaults to ~/.sherwood/grid)')\n .action(async (opts) => {\n const portfolio = new GridPortfolio(opts.stateDir as string | undefined);\n const state = await portfolio.load();\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Nothing to pause.\\n'));\n return;\n }\n if (state.paused) {\n console.log(DIM(`\\n Grid already paused: ${state.pauseReason}\\n`));\n return;\n }\n state.paused = true;\n state.pauseReason = opts.reason as string;\n await portfolio.save(state);\n console.log();\n console.log(chalk.yellow(` Grid paused. Reason: ${state.pauseReason}`));\n console.log(DIM(' Next manager.tick will be a no-op until you run `sherwood grid resume`.'));\n console.log();\n });\n\n // ── grid resume ──\n grid\n .command('resume')\n .description('Resume a paused grid (clears state.paused)')\n .option('--state-dir <path>', 'Read/write state from a custom directory (defaults to ~/.sherwood/grid)')\n .action(async (opts) => {\n const portfolio = new GridPortfolio(opts.stateDir as string | undefined);\n const state = await portfolio.load();\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Nothing to resume.\\n'));\n return;\n }\n if (!state.paused) {\n console.log(DIM('\\n Grid is not paused. Nothing to do.\\n'));\n return;\n }\n const wasReason = state.pauseReason;\n const wasCircuitBroken = state.circuitBroken === true;\n state.paused = false;\n state.pauseReason = '';\n // Clear the hard circuit breaker if it was tripped — manual `resume`\n // is the documented way to re-engage trading after the deep-drawdown\n // halt. We do NOT auto-clear elsewhere.\n state.circuitBroken = false;\n state.circuitBrokenAt = 0;\n await portfolio.save(state);\n console.log();\n if (wasCircuitBroken) {\n console.log(chalk.yellow(` Hard circuit breaker cleared.`));\n }\n console.log(G(` Grid resumed. (was paused: ${wasReason || '<unknown>'})`));\n console.log();\n });\n\n // ── grid flatten ──\n // Wind a live grid down to no-orders + zero-hedge state, then pause it so\n // the next `start` won't re-enter. Pairs with stopping the systemd unit or\n // killing the loop process — this only cleans up state and (on-chain only)\n // cancels open CLOIDs via the strategy contract.\n grid\n .command('flatten')\n .description('Cancel all open grid orders on-chain, zero the hedge ledger, and pause the grid')\n .option('--state-dir <path>', 'Read/write state from a custom directory (defaults to ~/.sherwood/grid)')\n .option('--strategy <address>', 'Strategy contract address — required to cancel on-chain CLOIDs. Omit for hedge-only flatten.')\n .option('--asset-indices <pairs>', 'comma-separated token=index pairs (required with --strategy, e.g. bitcoin=3,ethereum=4,solana=5)')\n .option('--reason <text>', 'Reason recorded on the paused grid state', DEFAULT_FLATTEN_REASON)\n .option('--dry-run', 'Print intended actions and exit without touching state or chain')\n .option('--yes', 'Skip the confirmation prompt')\n .action(async (opts) => {\n const stateDir = opts.stateDir as string | undefined;\n const portfolio = new GridPortfolio(stateDir);\n const state = await portfolio.load();\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Nothing to flatten.\\n'));\n return;\n }\n\n // Summarize what we're about to touch — by-token open-fill counts come\n // from the in-memory portfolio rather than re-reading on-chain because\n // (a) the on-chain executor's placedCloids is the local truth, (b) HL\n // order state can lag a tick. The chain call below handles the actual\n // cancel encoding regardless.\n const openFills = state.grids.flatMap(g => g.openFills.filter(f => !f.closed));\n const hedgeMgr = new GridHedgeManager(stateDir);\n const hedgeState = await hedgeMgr.load();\n const openHedges = hedgeState.positions.filter(p => p.quantity > 0);\n\n let strategyAddress: `0x${string}` | undefined;\n let assetIndices: Record<string, number> | undefined;\n if (opts.strategy) {\n strategyAddress = opts.strategy as `0x${string}`;\n if (!opts.assetIndices) {\n throw new Error('--asset-indices required with --strategy (e.g. --asset-indices bitcoin=3,ethereum=4,solana=5)');\n }\n assetIndices = parseAssetIndices(opts.assetIndices as string);\n }\n\n console.log();\n console.log(BOLD(' Flatten plan'));\n SEP();\n console.log(W(` State dir: ${stateDir ?? '~/.sherwood/grid (default)'}`));\n console.log(W(` On-chain: ${strategyAddress ? strategyAddress : DIM('(skipped — no --strategy)')}`));\n console.log(W(` Open fills: ${openFills.length} (informational — on-chain CLOIDs cancelled per-token)`));\n console.log(W(` Hedge legs: ${openHedges.length}${openHedges.length > 0 ? ' (' + openHedges.map(h => h.token).join(', ') + ')' : ''}`));\n console.log(W(` Will pause: yes — reason: \"${opts.reason}\"`));\n SEP();\n\n if (opts.dryRun) {\n console.log(chalk.yellow(' --dry-run set — no state or chain mutation.'));\n console.log();\n return;\n }\n\n if (!opts.yes) {\n // Non-interactive cron / piped invocation must pass --yes; refuse to\n // touch live state without explicit consent so a stray invocation\n // can't quietly wipe a running strategy.\n if (!process.stdin.isTTY) {\n throw new Error('Refusing to flatten without --yes in a non-interactive context. Pass --yes to confirm.');\n }\n // readline gives line-buffered semantics that work even if stdin was\n // touched earlier in the process. AbortController guards against an\n // operator walking away from the prompt — auto-abort after the\n // CONFIRM_TIMEOUT_SECONDS window rather than hanging forever.\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), CONFIRM_TIMEOUT_SECONDS * 1000);\n let answer: string;\n try {\n answer = (await rl.question(chalk.yellow(' Proceed with flatten? [y/N] '), { signal: ac.signal })).trim().toLowerCase();\n } catch (e) {\n if ((e as { name?: string }).name === 'AbortError') {\n console.log(DIM(`\\n Timed out after ${CONFIRM_TIMEOUT_SECONDS}s. Aborted.\\n`));\n return;\n }\n throw e;\n } finally {\n clearTimeout(timer);\n rl.close();\n }\n if (answer !== 'y' && answer !== 'yes') {\n console.log(DIM(' Aborted.\\n'));\n return;\n }\n }\n\n // On-chain cancel — only when a strategy address is supplied. A\n // hedge-only flatten (no --strategy) is the right path for paper grids\n // or when the wallet has been emptied and there's nothing to cancel.\n if (strategyAddress && assetIndices) {\n const executor = new OnchainGridExecutor({ strategyAddress, assetIndices, stateDir });\n await executor.load();\n const res = await executor.flattenAll();\n if (res.cancelled.length > 0) {\n console.log(G(` Cancelled CLOIDs for: ${res.cancelled.join(', ')}`));\n for (const tx of res.txs) console.log(DIM(` tx ${tx}`));\n }\n if (res.skipped.length > 0) {\n console.log(DIM(` Skipped (no tracked CLOIDs): ${res.skipped.join(', ')}`));\n }\n if (res.errors.length > 0) {\n for (const err of res.errors) console.log(chalk.red(` Cancel error: ${err}`));\n }\n }\n\n // Zero the hedge ledger using current HL mark prices. If price-fetch\n // fails for a token we leave its position untouched and surface it —\n // operator can rerun with a working RPC or manually edit hedge.json.\n if (openHedges.length > 0) {\n const hl = new HyperliquidProvider();\n const prices: Record<string, number> = {};\n for (const pos of openHedges) {\n const data = await hl.getHyperliquidData(pos.token);\n if (data?.markPrice && data.markPrice > 0) prices[pos.token] = data.markPrice;\n }\n const hres = await hedgeMgr.flatten(prices);\n if (hres.closed.length > 0) {\n for (const c of hres.closed) {\n const sign = c.realizedPnl >= 0 ? '+' : '-';\n console.log(G(` Hedge closed ${c.token}: qty ${c.quantity.toFixed(6)} → 0 (${sign}$${Math.abs(c.realizedPnl).toFixed(2)} realized)`));\n }\n }\n if (hres.skipped.length > 0) {\n console.log(chalk.yellow(` Hedge skipped (no mark price): ${hres.skipped.join(', ')}`));\n }\n console.log(W(` Total hedge realized PnL: $${hres.totalRealizedPnl.toFixed(2)}`));\n } else {\n console.log(DIM(' No active hedge legs — ledger already flat.'));\n }\n\n // Pause the grid so a future `start` won't re-enter on the same state.\n if (!state.paused) {\n state.paused = true;\n state.pauseReason = opts.reason as string;\n await portfolio.save(state);\n console.log(chalk.yellow(` Grid paused. Reason: ${state.pauseReason}`));\n } else {\n console.log(DIM(` Grid was already paused: ${state.pauseReason}`));\n }\n\n console.log();\n console.log(G(' Flatten complete. Stop the loop process / systemd unit if still running.'));\n console.log();\n });\n}\n","/**\n * Standalone grid event loop — runs the grid strategy independently\n * from the directional agent loop on 1-minute cycles.\n *\n * Usage:\n * const loop = new GridLoop({ capital: 5000, cycle: 60_000 });\n * await loop.start();\n */\n\nimport chalk from 'chalk';\nimport { appendFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { GridManager } from './manager.js';\nimport { GridPortfolio } from './portfolio.js';\nimport { DEFAULT_GRID_CONFIG } from './config.js';\nimport type { GridConfig } from './config.js';\nimport { HyperliquidProvider } from '../providers/data/hyperliquid.js';\nimport { GridHedgeManager } from './hedge.js';\nimport { GridExecutor } from './executor.js';\nimport { OnchainGridExecutor } from './onchain-executor.js';\nimport { gridStateDir, gridStatePath } from './paths.js';\nimport type { Address } from 'viem';\n\nexport interface GridLoopConfig {\n /** Starting capital in USD. */\n capital: number;\n /** Cycle interval in milliseconds. */\n cycle: number;\n /** Optional overrides for the default grid config. */\n config?: Partial<GridConfig>;\n /** Live execution mode — when true, places real orders on Hyperliquid. */\n live?: boolean;\n /** HL asset indices per token (required when live=true). */\n assetIndices?: Record<string, number>;\n /** When set, use on-chain executor (calls strategy contract). */\n strategyAddress?: Address;\n /** Override directory for persisted state. Defaults to ~/.sherwood/grid. */\n stateDir?: string;\n}\n\nexport class GridLoop {\n private cfg: GridLoopConfig;\n private gridConfig: GridConfig;\n private manager: GridManager;\n private hedge: GridHedgeManager;\n private hl: HyperliquidProvider;\n private executor: GridExecutor | OnchainGridExecutor | null = null;\n private running = false;\n private cycleCount = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n private cyclesPath: string;\n\n constructor(cfg: GridLoopConfig) {\n this.cfg = cfg;\n this.gridConfig = { ...DEFAULT_GRID_CONFIG, ...cfg.config };\n this.cyclesPath = gridStatePath('cycles.jsonl', cfg.stateDir);\n this.manager = new GridManager(\n this.gridConfig,\n undefined,\n undefined,\n undefined,\n new GridPortfolio(cfg.stateDir),\n undefined,\n cfg.stateDir,\n );\n this.hedge = new GridHedgeManager(cfg.stateDir);\n this.hl = new HyperliquidProvider();\n\n if (cfg.live) {\n if (!cfg.assetIndices) {\n throw new Error('assetIndices required when live=true');\n }\n if (cfg.strategyAddress) {\n this.executor = new OnchainGridExecutor({\n strategyAddress: cfg.strategyAddress,\n assetIndices: cfg.assetIndices,\n stateDir: cfg.stateDir,\n });\n } else {\n this.executor = new GridExecutor({ assetIndices: cfg.assetIndices });\n }\n }\n }\n\n /** Start the grid loop. Resolves when shut down via SIGINT/SIGTERM. */\n async start(): Promise<void> {\n this.running = true;\n\n // Graceful shutdown\n const shutdown = () => {\n console.error(chalk.yellow('\\n [grid-loop] Shutting down…'));\n this.running = false;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n // Initialize grid if no state exists\n await this.manager.init(this.cfg.capital);\n\n if (this.executor instanceof OnchainGridExecutor) {\n await this.executor.load();\n }\n\n // Startup banner — include resolved state-dir so operators with multiple\n // grid processes can immediately see which one owns this PID.\n console.error(chalk.cyan(\n `\\n [grid-loop] Started — capital=$${this.cfg.capital.toFixed(0)} ` +\n `cycle=${(this.cfg.cycle / 1000).toFixed(0)}s ` +\n `tokens=[${this.gridConfig.tokens.join(', ')}] ` +\n `leverage=${this.gridConfig.leverage}x ` +\n `levels=${this.gridConfig.levelsPerSide}/side ` +\n `state-dir=${gridStateDir(this.cfg.stateDir)}\\n`\n ));\n\n // Main loop\n while (this.running) {\n try {\n await this.tick();\n } catch (err) {\n console.error(chalk.red(` [grid-loop] Tick error: ${(err as Error).message}`));\n }\n\n // Wait for next cycle (interruptible via shutdown)\n if (this.running) {\n await new Promise<void>(resolve => {\n this.timer = setTimeout(resolve, this.cfg.cycle);\n });\n }\n }\n\n // Cleanup listeners\n process.off('SIGINT', shutdown);\n process.off('SIGTERM', shutdown);\n console.error(chalk.yellow(' [grid-loop] Stopped.'));\n }\n\n /** Execute one grid cycle. */\n private async tick(): Promise<void> {\n this.cycleCount++;\n const start = Date.now();\n\n // Fetch mark prices from Hyperliquid\n const prices: Record<string, number> = {};\n for (const token of this.gridConfig.tokens) {\n const data = await this.hl.getHyperliquidData(token);\n if (data?.markPrice && data.markPrice > 0) {\n prices[token] = data.markPrice;\n }\n }\n\n if (Object.keys(prices).length === 0) {\n console.error(chalk.dim(` [grid-loop] #${this.cycleCount} — no prices, skipping`));\n return;\n }\n\n const result = await this.manager.tick(prices);\n const elapsed = Date.now() - start;\n\n // Live mode: submit real orders via executor\n if (this.executor) {\n const plan = this.manager.computeOrders(prices);\n if (plan.ordersToPlace.length > 0 || plan.assetsToCancel.length > 0) {\n const res = await this.executor.execute(plan);\n if (res.errors.length > 0) {\n console.error(chalk.yellow(` [grid-loop] Executor errors: ${res.errors.join('; ')}`));\n }\n if (res.placed > 0 || res.cancelled > 0) {\n console.error(chalk.cyan(` [grid-loop] Live: placed=${res.placed} cancelled=${res.cancelled}`));\n }\n }\n }\n\n // Log round trips when they happen\n if (result.roundTrips > 0) {\n console.error(chalk.green(\n ` [grid-loop] #${this.cycleCount} — ${result.roundTrips} RT(s), ` +\n `+$${result.pnlUsd.toFixed(2)} PnL, ${result.fills} fill(s) [${elapsed}ms]`\n ));\n }\n\n // Log fills (without round trips)\n if (result.fills > 0 && result.roundTrips === 0) {\n console.error(chalk.dim(\n ` [grid-loop] #${this.cycleCount} — ${result.fills} fill(s), 0 RTs [${elapsed}ms]`\n ));\n }\n\n // Delta hedge — adjust short positions to offset underwater grid longs.\n // Pass paused state so the hedge flattens (locks in PnL) when the grid\n // soft-pauses on a pool drawdown instead of letting unrealized erode on\n // mean reversion.\n const openExposure = this.manager.getOpenFillExposure();\n const marketTrend = this.manager.getMarketTrend();\n const hedgeResult = await this.hedge.tick(openExposure, prices, Date.now(), marketTrend, result.paused);\n if (hedgeResult.adjustments > 0) {\n console.error(chalk.magenta(\n ` [hedge] ${hedgeResult.adjustments} adjustment(s), ` +\n `unrealized: $${hedgeResult.unrealizedPnl.toFixed(2)}, ` +\n `total realized: $${hedgeResult.totalRealizedPnl.toFixed(2)}`\n ));\n }\n\n // Write cycle log for cron monitor\n const stats = this.manager.getStats();\n const cycleEntry = {\n cycleNumber: this.cycleCount,\n timestamp: Date.now(),\n gridFills: result.fills,\n gridRoundTrips: result.roundTrips,\n gridPnlUsd: result.pnlUsd,\n totalPnlUsd: stats?.totalPnlUsd ?? 0,\n todayPnlUsd: stats?.todayPnlUsd ?? 0,\n totalRoundTrips: stats?.totalRoundTrips ?? 0,\n allocation: stats?.allocation ?? 0,\n paused: stats?.paused ?? false,\n hedgeUnrealizedPnl: hedgeResult.unrealizedPnl,\n hedgeTotalRealizedPnl: hedgeResult.totalRealizedPnl,\n };\n try {\n await mkdir(dirname(this.cyclesPath), { recursive: true });\n await appendFile(this.cyclesPath, JSON.stringify(cycleEntry) + '\\n');\n } catch { /* non-critical */ }\n\n // Periodic status every ~60 cycles\n if (this.cycleCount % 60 === 0) {\n const stats = this.manager.getStats();\n if (stats) {\n const hedgeStatus = this.hedge.getStatus();\n const hedgeInfo = hedgeStatus && hedgeStatus.positions.length > 0\n ? ` hedge=$${hedgeResult.unrealizedPnl.toFixed(2)}unr/$${hedgeStatus.totalRealizedPnl.toFixed(2)}real`\n : '';\n console.error(chalk.cyan(\n ` [grid-loop] Status #${this.cycleCount} — ` +\n `totalPnL=$${stats.totalPnlUsd.toFixed(2)} ` +\n `todayPnL=$${stats.todayPnlUsd.toFixed(2)} ` +\n `RTs=${stats.totalRoundTrips} ` +\n `alloc=$${stats.allocation.toFixed(0)}` +\n `${hedgeInfo}` +\n `${stats.paused ? ' (PAUSED)' : ''}`\n ));\n }\n }\n }\n}\n","/**\n * Grid Manager — core engine for ATR-based grid trading.\n *\n * Builds grid levels from ATR, simulates fills against real prices each tick,\n * handles paired-order replacement and periodic rebalancing.\n */\n\nimport chalk from 'chalk';\nimport type {\n GridConfig,\n GridLevel,\n GridFill,\n GridTokenState,\n GridPortfolioState,\n} from './config.js';\nimport { GridPortfolio } from './portfolio.js';\nimport { HyperliquidProvider } from '../providers/data/hyperliquid.js';\nimport { getLatestSignals } from '../agent/technical.js';\n\n/** Decides if a level should fire at the current price.\n * Default checks against close; backtest checks against bar.low/high. */\nexport type FillDetector = (level: GridLevel, currentPrice: number) => boolean;\n\n/** Decides if an open fill's target has been reached.\n * Default checks against close; backtest checks against bar.high. */\nexport type CloseFillDetector = (openFill: GridFill, currentPrice: number) => boolean;\n\n/** Fetches OHLCV candles for ATR. Default delegates to HyperliquidProvider. */\nexport type CandleFetcher = (\n tokenId: string,\n interval: '1h' | '4h' | '1d',\n lookbackMs: number,\n) => Promise<Array<{ timestamp: number; open: number; high: number; low: number; close: number; volume: number }> | null>;\n\nconst defaultFillDetector: FillDetector = (level, currentPrice) =>\n level.side === 'buy' ? currentPrice <= level.price : currentPrice >= level.price;\n\nconst defaultCloseFillDetector: CloseFillDetector = (openFill, currentPrice) =>\n currentPrice >= openFill.targetSellPrice;\n\nexport class GridManager {\n private config: GridConfig;\n private portfolio: GridPortfolio;\n private hl: HyperliquidProvider;\n private candleFetcher: CandleFetcher;\n private fillDetector: FillDetector;\n private closeFillDetector: CloseFillDetector;\n private nowProvider: () => number;\n\n constructor(\n config: GridConfig,\n candleFetcher?: CandleFetcher,\n fillDetector?: FillDetector,\n closeFillDetector?: CloseFillDetector,\n portfolio?: GridPortfolio,\n nowProvider?: () => number,\n stateDir?: string,\n ) {\n this.config = config;\n // If no portfolio passed, build the default one against the resolved\n // stateDir so a caller that wants per-process isolation gets it without\n // having to wire a GridPortfolio themselves. Mirrors GridLoop's pattern.\n this.portfolio = portfolio ?? new GridPortfolio(stateDir);\n this.hl = new HyperliquidProvider();\n this.candleFetcher = candleFetcher ?? ((tokenId, interval, lookbackMs) =>\n this.hl.getCandles(tokenId, interval, lookbackMs));\n this.fillDetector = fillDetector ?? defaultFillDetector;\n this.closeFillDetector = closeFillDetector ?? defaultCloseFillDetector;\n this.nowProvider = nowProvider ?? (() => Date.now());\n }\n\n /** Load or initialize grid state.\n * Also syncs new tokens added to config after initial grid setup. */\n async init(totalPortfolioValue: number): Promise<void> {\n const existing = await this.portfolio.load();\n if (!existing) {\n await this.portfolio.initialize(totalPortfolioValue, this.config);\n return;\n }\n\n // Sync: add grids for tokens in config but not yet in state\n let addedAllocation = 0;\n for (const token of this.config.tokens) {\n if (!existing.grids.find(g => g.token === token)) {\n const split = this.config.tokenSplit[token] ?? (1 / this.config.tokens.length);\n const alloc = existing.totalAllocation * split;\n existing.grids.push({\n token,\n levels: [],\n openFills: [],\n allocation: alloc,\n stats: { totalRoundTrips: 0, totalPnlUsd: 0, todayPnlUsd: 0, totalFills: 0, todayFills: 0, lastDailyReset: 0, lastRebalanceAt: 0 },\n centerPrice: 0,\n atr: 0,\n trend: 0,\n lastTrendRefreshAt: 0,\n });\n addedAllocation += alloc;\n console.error(` [grid] Added new token grid: ${token} ($${alloc.toFixed(0)} allocation)`);\n }\n }\n if (addedAllocation > 0) {\n await this.portfolio.save(existing);\n }\n }\n\n /**\n * Run one grid tick — called every cycle from the agent loop.\n *\n * 1. Load state + reset daily counters\n * 2. For each token grid: fetch price, simulate fills, check rebalance\n * 3. Persist state\n *\n * Returns a summary for the cycle log.\n */\n async tick(prices: Record<string, number>, regime?: string): Promise<GridTickResult> {\n const state = await this.portfolio.load();\n if (!state || !this.config.enabled) {\n return { fills: 0, roundTrips: 0, pnlUsd: 0, paused: false };\n }\n\n // When paused, still run the pause/resume check — drawdown may have\n // recovered and the grid should auto-resume via unpauseRecoveryPct.\n if (state.paused) {\n const resumed = this.portfolio.checkPauseThreshold(state, this.config, prices);\n if (resumed) {\n await this.portfolio.save(state);\n }\n return { fills: 0, roundTrips: 0, pnlUsd: 0, paused: state.paused };\n }\n\n // Regime-aware grid control: only pause in high-volatility (dangerous swings).\n // Previously also paused buys in trending regimes, but the global regime\n // detector lags — BTC can be ranging $76-78k for a day while EMA(21,50)\n // still says \"trending-up\". The grid's own rebalance drift check is a\n // better signal: if price hasn't triggered a rebalance, it's range-bound\n // within the grid regardless of what the macro regime says.\n if (regime === 'high-volatility') {\n console.error(chalk.dim(` [grid] Paused: high-volatility regime — too risky for grid`));\n return { fills: 0, roundTrips: 0, pnlUsd: 0, paused: false };\n }\n\n // Reset daily counters at UTC boundary\n this.portfolio.resetDailyStats(state);\n\n let totalFills = 0;\n let totalRoundTrips = 0;\n let totalPnl = 0;\n\n for (const grid of state.grids) {\n const price = prices[grid.token];\n if (!price || price <= 0) continue;\n\n // Refresh trend at most once per hour. Lets the downtrend filter\n // respond to fast crashes between scheduled rebuilds (12h cadence).\n // No-op when buildGrid runs this same tick — it overwrites trend anyway.\n await this.maybeRefreshTrend(grid);\n\n // Build grid on first tick or after full rebuild interval\n if (grid.levels.length === 0 || this.needsFullRebuild(grid)) {\n await this.buildGrid(grid, price);\n }\n\n // Simulate fills — both buys and sells. The grid's own rebalance drift\n // handles directional moves (rebuilds when price drifts 40% toward edge).\n const { fills, roundTrips, pnlUsd } = this.simulateFills(grid, price);\n totalFills += fills;\n totalRoundTrips += roundTrips;\n totalPnl += pnlUsd;\n\n // Check rebalance (shift grid if price drifted)\n if (this.needsShift(grid, price)) {\n await this.shiftGrid(grid, price);\n }\n }\n\n // Check pause threshold (uses current prices for mark-to-market)\n this.portfolio.checkPauseThreshold(state, this.config, prices);\n\n // Persist\n await this.portfolio.save(state);\n\n // `checkPauseThreshold` above may have flipped `state.paused` to true on\n // this very bar. Return the mutated flag (not a hardcoded false) so the\n // live loop (loop.ts → hedge.tick) flattens the hedge on the same bar the\n // backtest does — backtest.ts already reads `stateAfter.paused` directly.\n return { fills: totalFills, roundTrips: totalRoundTrips, pnlUsd: totalPnl, paused: state.paused };\n }\n\n /** Hourly refresh of `grid.trend` from recent 4h candles. Called from\n * tick() so the downtrend filter sees fresh data between buildGrid runs. */\n private async maybeRefreshTrend(grid: GridTokenState): Promise<void> {\n const now = this.nowProvider();\n const ONE_HOUR = 60 * 60 * 1000;\n if (now - grid.lastTrendRefreshAt < ONE_HOUR) return;\n\n // 14 4h bars = 56h lookback (matches buildGrid window).\n const candles = await this.candleFetcher(grid.token, '4h', 14 * 4 * 60 * 60 * 1000);\n if (!candles || candles.length < 2) return;\n\n const TREND_LOOKBACK_BARS = 14;\n const sliceStart = Math.max(0, candles.length - TREND_LOOKBACK_BARS);\n const first = candles[sliceStart]!.close;\n const last = candles[candles.length - 1]!.close;\n if (first <= 0) return;\n\n grid.trend = (last - first) / first;\n grid.lastTrendRefreshAt = now;\n }\n\n /** Build a fresh grid centered on the current price using ATR. */\n private async buildGrid(grid: GridTokenState, currentPrice: number): Promise<void> {\n // Fetch ATR from HL candles\n const candles = await this.candleFetcher(grid.token, '4h', 14 * 24 * 60 * 60 * 1000);\n if (!candles || candles.length < this.config.atrPeriod) {\n console.error(chalk.dim(` [grid] Cannot build grid for ${grid.token}: insufficient candle data`));\n return;\n }\n\n const signals = getLatestSignals(candles);\n const atr = signals.atr;\n if (!Number.isFinite(atr) || atr <= 0) {\n console.error(chalk.dim(` [grid] Cannot build grid for ${grid.token}: invalid ATR (${atr})`));\n return;\n }\n\n // Trend signal: % change over the last 14 4h bars (~56 hours).\n // Using only the recent window so the trend captures local direction,\n // not all-time-vs-now (which would always be ~0 over multi-month\n // backtests where price ends near where it started).\n const TREND_LOOKBACK_BARS = 14;\n let trend = 0;\n if (candles.length >= 2) {\n const sliceStart = Math.max(0, candles.length - TREND_LOOKBACK_BARS);\n const first = candles[sliceStart]!.close;\n const last = candles[candles.length - 1]!.close;\n if (first > 0) {\n trend = (last - first) / first;\n }\n }\n\n const range = atr * this.config.atrMultiplier;\n const spacing = range / this.config.levelsPerSide;\n const effectiveCapital = grid.allocation * this.config.leverage;\n const quantity = effectiveCapital / (this.config.levelsPerSide * currentPrice);\n\n const levels: GridLevel[] = [];\n\n // Asymmetric grid in confirmed downtrend: skip most buy levels so the\n // grid stops adding exposure to a falling knife. Keep ONE buy level just\n // below current price so the grid can re-enter on a chop reversal once\n // trend recovers (otherwise we'd never re-engage). Sell levels still\n // place fully so existing inventory can exit on rallies.\n const inDowntrend = this.config.downtrendBlockPct > 0\n && trend < -this.config.downtrendBlockPct;\n const buyCount = inDowntrend ? 1 : this.config.levelsPerSide;\n\n for (let i = 1; i <= buyCount; i++) {\n levels.push({\n price: currentPrice - spacing * i,\n side: 'buy',\n quantity,\n filled: false,\n filledAt: 0,\n });\n }\n\n // Sell levels above current price\n for (let i = 1; i <= this.config.levelsPerSide; i++) {\n levels.push({\n price: currentPrice + spacing * i,\n side: 'sell',\n quantity,\n filled: false,\n filledAt: 0,\n });\n }\n\n grid.levels = levels;\n grid.centerPrice = currentPrice;\n grid.atr = atr;\n grid.trend = trend;\n grid.stats.lastRebalanceAt = Date.now();\n\n console.error(chalk.dim(\n ` [grid] Built ${grid.token} grid: center=$${currentPrice.toFixed(2)} ` +\n `ATR=$${atr.toFixed(2)} range=$${(currentPrice - range).toFixed(2)}-$${(currentPrice + range).toFixed(2)} ` +\n `spacing=$${spacing.toFixed(2)} qty=${quantity.toFixed(6)} trend=${(trend * 100).toFixed(1)}%` +\n `${inDowntrend ? ' [DOWNTREND: 1 buy / ' + this.config.levelsPerSide + ' sells]' : ''}`\n ));\n }\n\n /** Simulate order fills against the current price. */\n private simulateFills(\n grid: GridTokenState,\n currentPrice: number,\n ): { fills: number; roundTrips: number; pnlUsd: number } {\n let fills = 0;\n let roundTrips = 0;\n let pnlUsd = 0;\n const now = Date.now();\n const spacing = grid.atr > 0\n ? (grid.atr * this.config.atrMultiplier) / this.config.levelsPerSide\n : 0;\n\n if (spacing <= 0) return { fills: 0, roundTrips: 0, pnlUsd: 0 };\n\n // Max-exposure cap: stop placing new BUY fills when total open notional\n // exceeds the configured multiple of effective capital. Existing fills\n // can still close (sell levels and close-outs unaffected). Set\n // `maxOpenNotionalMultiple = Infinity` to disable.\n // Cap measures ENTRY notional (qty × buyPrice), not mark-to-market.\n // Mark-to-market shrinks as price falls, which would loosen the cap\n // exactly when we need it to bite (downtrends accumulating buys).\n const exposureCap = grid.allocation * this.config.leverage * this.config.maxOpenNotionalMultiple;\n const currentOpenNotional = grid.openFills\n .filter(f => !f.closed)\n .reduce((s, f) => s + f.quantity * f.buyPrice, 0);\n const buyExposureFull = currentOpenNotional >= exposureCap;\n\n // Downtrend filter: block new buy fills if the grid was built during a\n // sustained drop (trend < -downtrendBlockPct). Re-evaluated each rebuild\n // so buys resume when trend recovers. Set downtrendBlockPct=0 to disable.\n const inDowntrend = this.config.downtrendBlockPct > 0 && grid.trend < -this.config.downtrendBlockPct;\n\n // Step 1: Fill unfilled grid levels (buy when price drops, sell is just accounting)\n for (const level of grid.levels) {\n if (level.filled) continue;\n\n if (level.side === 'buy' && this.fillDetector(level, currentPrice)) {\n if (buyExposureFull) {\n continue; // skip — would exceed max open exposure\n }\n if (inDowntrend) {\n continue; // skip — sustained downtrend, don't buy into the knife\n }\n level.filled = true;\n level.filledAt = now;\n fills++;\n grid.stats.totalFills++;\n grid.stats.todayFills++;\n\n grid.openFills.push({\n token: grid.token,\n buyPrice: level.price,\n targetSellPrice: level.price + spacing,\n quantity: level.quantity,\n filledAt: now,\n closed: false,\n pnlUsd: 0,\n closedAt: 0,\n });\n\n console.error(chalk.dim(\n ` [grid] BUY fill ${grid.token} @ $${level.price.toFixed(2)} qty=${level.quantity.toFixed(6)}`\n ));\n }\n\n if (level.side === 'sell' && this.fillDetector(level, currentPrice)) {\n level.filled = true;\n level.filledAt = now;\n fills++;\n grid.stats.totalFills++;\n grid.stats.todayFills++;\n\n console.error(chalk.dim(\n ` [grid] SELL level ${grid.token} @ $${level.price.toFixed(2)} qty=${level.quantity.toFixed(6)}`\n ));\n }\n }\n\n // Step 2: Close open fills whose targetSellPrice has been reached.\n // This is decoupled from level fills — an open fill closes when\n // currentPrice >= its specific target, regardless of grid levels.\n // Bug fix: previously this only ran inside the sell-level loop, so\n // once a sell level was marked filled it was skipped on future ticks,\n // orphaning any open fill that wasn't matched at that exact moment.\n for (const openFill of grid.openFills) {\n if (openFill.closed) continue;\n if (this.closeFillDetector(openFill, currentPrice)) {\n // PnL = price_change × quantity. quantity is already the leveraged\n // contract size (effectiveCapital / (levels × price) at build), so\n // multiplying by leverage again would double-count. The realized\n // dollar PnL here is the same as a real futures position would book.\n const profit = (currentPrice - openFill.buyPrice) * openFill.quantity;\n if (profit >= this.config.minProfitPerFillUsd) {\n openFill.closed = true;\n openFill.pnlUsd = profit;\n openFill.closedAt = now;\n pnlUsd += profit;\n roundTrips++;\n grid.stats.totalRoundTrips++;\n grid.stats.totalPnlUsd += profit;\n grid.stats.todayPnlUsd += profit;\n grid.allocation += profit;\n\n console.error(chalk.green(\n ` [grid] ROUND-TRIP ${grid.token}: buy $${openFill.buyPrice.toFixed(2)} → sell $${currentPrice.toFixed(2)} = +$${profit.toFixed(2)}`\n ));\n }\n }\n }\n\n // Step 3: stop-loss — force-close any open buy whose unrealized loss\n // crosses the configured threshold. Acts as a per-position circuit\n // breaker. Without this, the grid can accumulate enough underwater\n // exposure across rebuilds to wipe the cross-margin pool even at\n // low leverage (issue #269). Disabled if stopLossPct = 0.\n if (this.config.stopLossPct > 0) {\n for (const openFill of grid.openFills) {\n if (openFill.closed) continue;\n const stopPrice = openFill.buyPrice * (1 - this.config.stopLossPct);\n if (currentPrice <= stopPrice) {\n const realizedLoss = (currentPrice - openFill.buyPrice) * openFill.quantity;\n openFill.closed = true;\n openFill.pnlUsd = realizedLoss;\n openFill.closedAt = now;\n pnlUsd += realizedLoss; // negative\n grid.stats.totalPnlUsd += realizedLoss;\n grid.stats.todayPnlUsd += realizedLoss;\n grid.allocation += realizedLoss; // pool shrinks; positive contributors do the same\n console.error(chalk.red(\n ` [grid] STOP-LOSS ${grid.token}: buy $${openFill.buyPrice.toFixed(2)} → close $${currentPrice.toFixed(2)} = $${realizedLoss.toFixed(2)}`\n ));\n }\n }\n }\n\n // Prune closed fills older than 24h to prevent unbounded growth\n const pruneThreshold = now - 24 * 60 * 60 * 1000;\n grid.openFills = grid.openFills.filter(f => !f.closed || f.closedAt > pruneThreshold);\n\n return { fills, roundTrips, pnlUsd };\n }\n\n /** Check if the grid needs a full rebuild. */\n private needsFullRebuild(grid: GridTokenState): boolean {\n if (grid.levels.length === 0) return true;\n const elapsed = Date.now() - grid.stats.lastRebalanceAt;\n return elapsed >= this.config.fullRebuildIntervalMs;\n }\n\n /** Check if price has drifted enough to warrant shifting the grid. */\n private needsShift(grid: GridTokenState, currentPrice: number): boolean {\n if (grid.centerPrice <= 0 || grid.atr <= 0) return false;\n const range = grid.atr * this.config.atrMultiplier;\n const distFromCenter = Math.abs(currentPrice - grid.centerPrice);\n return distFromCenter / range >= this.config.rebalanceDriftPct;\n }\n\n /** Shift the grid to re-center on the current price. */\n private async shiftGrid(grid: GridTokenState, currentPrice: number): Promise<void> {\n console.error(chalk.dim(\n ` [grid] Shifting ${grid.token} grid: center $${grid.centerPrice.toFixed(2)} → $${currentPrice.toFixed(2)}`\n ));\n // Full rebuild with the new center — keeps existing open fills\n await this.buildGrid(grid, currentPrice);\n }\n\n /** Recent market trend for hedge sizing — BTC's grid.trend (already\n * maintained at 56h cadence by the asymmetric-grid filter), falling back\n * to the median across tracked tokens if BTC is not in the universe.\n * Used by the trend-adaptive hedge ratio. Returns undefined if no signal\n * is yet available (cold start). */\n getMarketTrend(): number | undefined {\n const state = this.portfolio.getState();\n if (!state || state.grids.length === 0) return undefined;\n\n const btc = state.grids.find(g => g.token === 'bitcoin');\n if (btc && Number.isFinite(btc.trend) && btc.lastTrendRefreshAt > 0) return btc.trend;\n\n const trends = state.grids\n .filter(g => Number.isFinite(g.trend) && g.lastTrendRefreshAt > 0)\n .map(g => g.trend);\n if (trends.length === 0) return undefined;\n trends.sort((a, b) => a - b);\n return trends[Math.floor(trends.length / 2)];\n }\n\n /** Get open fill exposure per token — used by the hedge manager. */\n getOpenFillExposure(): Array<{ token: string; totalQuantity: number; totalNotional: number; avgEntryPrice: number; fillCount: number }> {\n const state = this.portfolio.getState();\n if (!state) return [];\n return state.grids.map(g => {\n const opens = g.openFills.filter(f => !f.closed);\n const totalQty = opens.reduce((s, f) => s + f.quantity, 0);\n const totalNotional = opens.reduce((s, f) => s + f.quantity * f.buyPrice, 0);\n return {\n token: g.token,\n totalQuantity: totalQty,\n totalNotional,\n avgEntryPrice: totalQty > 0 ? totalNotional / totalQty : 0,\n fillCount: opens.length,\n };\n }).filter(e => e.fillCount > 0);\n }\n\n /**\n * Compute the orders that should be placed for the current grid state,\n * without simulating fills. Used by the live executor.\n *\n * Returns:\n * - ordersToPlace: all current grid levels that haven't been filled\n * - assetsToCancel: tokens whose grid was rebalanced (need cancel-and-place)\n * - needsRebalance: whether any grid was rebuilt this tick\n */\n computeOrders(prices: Record<string, number>): GridOrderPlan {\n const state = this.portfolio.getState();\n if (!state || state.paused || !this.config.enabled) {\n return { ordersToPlace: [], assetsToCancel: [], needsRebalance: false };\n }\n\n const ordersToPlace: ComputedOrder[] = [];\n const assetsToCancel: string[] = [];\n let needsRebalance = false;\n\n for (const grid of state.grids) {\n const price = prices[grid.token];\n if (!price || price <= 0) continue;\n\n const wasEmpty = grid.levels.length === 0;\n const fullRebuild = wasEmpty || this.needsFullRebuild(grid);\n const shift = !fullRebuild && grid.centerPrice > 0 && this.needsShift(grid, price);\n\n if (fullRebuild || shift) {\n needsRebalance = true;\n if (!wasEmpty) assetsToCancel.push(grid.token);\n }\n\n for (const level of grid.levels) {\n if (level.filled) continue;\n ordersToPlace.push({\n token: grid.token,\n isBuy: level.side === 'buy',\n price: level.price,\n quantity: level.quantity,\n });\n }\n }\n\n return { ordersToPlace, assetsToCancel, needsRebalance };\n }\n\n /** Get aggregate stats for display. */\n getStats(): { totalPnlUsd: number; todayPnlUsd: number; todayFills: number; totalRoundTrips: number; allocation: number; paused: boolean } | null {\n const state = this.portfolio.getState();\n if (!state) return null;\n const agg = this.portfolio.aggregateStats(state);\n return {\n ...agg,\n allocation: state.totalAllocation,\n paused: state.paused,\n };\n }\n}\n\nexport interface GridTickResult {\n fills: number;\n roundTrips: number;\n pnlUsd: number;\n paused: boolean;\n}\n\nexport interface ComputedOrder {\n token: string;\n isBuy: boolean;\n price: number;\n quantity: number;\n}\n\nexport interface GridOrderPlan {\n ordersToPlace: ComputedOrder[];\n assetsToCancel: string[];\n needsRebalance: boolean;\n}\n","/**\n * Grid portfolio — isolated capital tracking and disk persistence.\n *\n * Separate from the directional portfolio.json. Grid profits compound\n * in the grid pool; directional never touches grid capital.\n */\n\nimport { readFile, writeFile, rename, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { gridStatePath } from './paths.js';\nimport type { GridPortfolioState, GridTokenState, GridStats, GridConfig } from './config.js';\n\nfunction emptyStats(): GridStats {\n return {\n totalRoundTrips: 0,\n totalPnlUsd: 0,\n todayPnlUsd: 0,\n totalFills: 0,\n todayFills: 0,\n lastDailyReset: 0,\n lastRebalanceAt: 0,\n };\n}\n\nexport class GridPortfolio {\n private state: GridPortfolioState | null = null;\n private statePath: string;\n\n constructor(stateDir?: string) {\n this.statePath = gridStatePath('portfolio.json', stateDir);\n }\n\n /** Load grid state from disk. Returns null if no grid initialized yet. */\n async load(): Promise<GridPortfolioState | null> {\n try {\n const raw = await readFile(this.statePath, 'utf-8');\n this.state = JSON.parse(raw) as GridPortfolioState;\n return this.state;\n } catch {\n return null;\n }\n }\n\n /** Save grid state to disk (atomic write). */\n async save(state: GridPortfolioState): Promise<void> {\n this.state = state;\n await mkdir(dirname(this.statePath), { recursive: true });\n const tmp = `${this.statePath}.tmp.${process.pid}`;\n await writeFile(tmp, JSON.stringify(state, null, 2), 'utf-8');\n await rename(tmp, this.statePath);\n }\n\n /**\n * Initialize the grid by carving capital from the directional portfolio.\n * Called once on first startup when grid-portfolio.json doesn't exist.\n *\n * Returns the USD amount carved out (caller must deduct from directional portfolio).\n */\n async initialize(capital: number, config: GridConfig): Promise<void> {\n const allocation = capital;\n\n const grids: GridTokenState[] = config.tokens.map(token => ({\n token,\n levels: [],\n openFills: [],\n allocation: allocation * (config.tokenSplit[token] ?? 1 / config.tokens.length),\n stats: emptyStats(),\n centerPrice: 0,\n atr: 0,\n trend: 0,\n lastTrendRefreshAt: 0,\n }));\n\n const state: GridPortfolioState = {\n totalAllocation: allocation,\n grids,\n paused: false,\n pauseReason: '',\n initializedAt: Date.now(),\n };\n\n await this.save(state);\n this.state = state;\n }\n\n /** Get current state (must load() first). */\n getState(): GridPortfolioState | null {\n return this.state;\n }\n\n /** Reset daily counters if UTC day boundary crossed. `now` is injectable\n * so the backtester can drive resets off backtest time, not wall-clock. */\n resetDailyStats(state: GridPortfolioState, now: number = Date.now()): boolean {\n const todayMidnight = new Date(now);\n todayMidnight.setUTCHours(0, 0, 0, 0);\n const todayMs = todayMidnight.getTime();\n\n let changed = false;\n for (const grid of state.grids) {\n if (!grid.stats.lastDailyReset || grid.stats.lastDailyReset < todayMs) {\n grid.stats.todayPnlUsd = 0;\n grid.stats.todayFills = 0;\n grid.stats.lastDailyReset = now;\n changed = true;\n }\n }\n return changed;\n }\n\n /** Check if grid should be paused or resumed (pool equity dropped/recovered).\n * `prices` is required to mark open buys to market. Hysteresis: pause at\n * `pauseThresholdPct` drop, resume only when drop recovers below\n * `unpauseRecoveryPct`. Returns true iff state.paused was changed. */\n checkPauseThreshold(\n state: GridPortfolioState,\n config: GridConfig,\n prices: Record<string, number>,\n ): boolean {\n const currentValue = state.grids.reduce((sum, g) => {\n const price = prices[g.token];\n // quantity already leveraged at build time — see manager.simulateFills.\n const unrealized = (price && price > 0)\n ? g.openFills\n .filter(f => !f.closed)\n .reduce((s, f) => s + (price - f.buyPrice) * f.quantity, 0)\n : 0;\n return sum + g.allocation + unrealized;\n }, 0);\n\n const dropPct = 1 - (currentValue / state.totalAllocation);\n\n // Hard circuit breaker — checked first because it overrides hysteresis.\n // Once tripped, only manual `sherwood grid resume` can clear it.\n if (!state.circuitBroken && dropPct >= config.circuitBreakerThresholdPct) {\n state.circuitBroken = true;\n state.circuitBrokenAt = Date.now();\n state.paused = true;\n state.pauseReason =\n `Hard circuit breaker tripped — pool dropped ${(dropPct * 100).toFixed(1)}% ` +\n `(>= ${(config.circuitBreakerThresholdPct * 100).toFixed(0)}%). ` +\n `Manual resume required: \\`sherwood grid resume\\`.`;\n return true;\n }\n\n // Soft pause (hysteresis path) — only relevant when circuit not tripped.\n if (!state.circuitBroken && !state.paused && dropPct >= config.pauseThresholdPct) {\n state.paused = true;\n state.pauseReason = `Grid pool dropped ${(dropPct * 100).toFixed(1)}% (pause threshold: ${(config.pauseThresholdPct * 100).toFixed(0)}%, resume when ≤ ${(config.unpauseRecoveryPct * 100).toFixed(0)}%)`;\n return true;\n }\n\n // Auto-resume — gated on circuitBroken to prevent re-engaging mid-crash.\n if (!state.circuitBroken && state.paused && dropPct <= config.unpauseRecoveryPct) {\n state.paused = false;\n state.pauseReason = '';\n return true;\n }\n\n return false;\n }\n\n /** Aggregate stats across all token grids. */\n aggregateStats(state: GridPortfolioState): {\n totalPnlUsd: number;\n todayPnlUsd: number;\n todayFills: number;\n totalRoundTrips: number;\n } {\n return {\n totalPnlUsd: state.grids.reduce((s, g) => s + g.stats.totalPnlUsd, 0),\n todayPnlUsd: state.grids.reduce((s, g) => s + g.stats.todayPnlUsd, 0),\n todayFills: state.grids.reduce((s, g) => s + g.stats.todayFills, 0),\n totalRoundTrips: state.grids.reduce((s, g) => s + g.stats.totalRoundTrips, 0),\n };\n }\n}\n","import { join, resolve } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport const DEFAULT_GRID_STATE_DIR = join(homedir(), '.sherwood', 'grid');\n\n/**\n * Resolve the grid state directory, with optional caller override.\n * Relative paths are resolved against the current working directory at the\n * moment of resolution — important for systemd / cron jobs that may set their\n * own CWD. Empty/whitespace overrides fall back to the default.\n *\n * Note: scope is intentionally narrow — only runtime mutable state\n * (`portfolio.json`, `hedge.json`, `cycles.jsonl`, `onchain-state.json`).\n * Backtest cache, sweep results, and historical-data downloads continue to\n * use `~/.sherwood/grid/` because they are not per-loop state.\n */\nexport function gridStateDir(override?: string): string {\n if (!override || override.trim().length === 0) return DEFAULT_GRID_STATE_DIR;\n return resolve(override);\n}\n\nexport function gridStatePath(file: string, override?: string): string {\n return join(gridStateDir(override), file);\n}\n","/**\n * Grid trading strategy — types and configuration.\n *\n * ATR-based grid that profits from ranging-market volatility on BTC + ETH.\n * Runs as a parallel mode alongside the directional signal-based strategy\n * with isolated capital allocation.\n */\n\n// ── Types ──\n\nexport interface GridLevel {\n /** Price at which this order fills. */\n price: number;\n /** 'buy' below current price, 'sell' above. */\n side: 'buy' | 'sell';\n /** Quantity per fill (in token units, e.g. 0.0124 BTC). */\n quantity: number;\n /** True if this level has been filled and is waiting for its paired order. */\n filled: boolean;\n /** Timestamp of fill (0 if unfilled). */\n filledAt: number;\n}\n\nexport interface GridFill {\n /** Token ID (e.g. 'bitcoin'). */\n token: string;\n /** Price at which we bought. */\n buyPrice: number;\n /** Price at which the paired sell should execute. */\n targetSellPrice: number;\n /** Quantity in token units. */\n quantity: number;\n /** Timestamp of buy fill. */\n filledAt: number;\n /** If this fill has been closed by its paired sell. */\n closed: boolean;\n /** PnL when closed (before leverage). */\n pnlUsd: number;\n /** Timestamp of close. */\n closedAt: number;\n}\n\nexport interface GridStats {\n /** Completed buy→sell round-trips. */\n totalRoundTrips: number;\n /** Cumulative grid profit in USD (after leverage). */\n totalPnlUsd: number;\n /** Today's grid profit (resets UTC midnight). */\n todayPnlUsd: number;\n /** Total fills (buy + sell) since inception. */\n totalFills: number;\n /** Today's fills. */\n todayFills: number;\n /** Last daily reset timestamp. */\n lastDailyReset: number;\n /** Last full grid rebuild timestamp. */\n lastRebalanceAt: number;\n}\n\nexport interface GridTokenState {\n /** CoinGecko token ID. */\n token: string;\n /** Current active grid levels. */\n levels: GridLevel[];\n /** Open fills waiting for their paired sell/buy. */\n openFills: GridFill[];\n /** USD allocated to this token's grid. */\n allocation: number;\n /** Cumulative stats for this token's grid. */\n stats: GridStats;\n /** Price at center when grid was last built/rebalanced. */\n centerPrice: number;\n /** ATR at last build. */\n atr: number;\n /** Trend at last grid build: (latest_4h_close - lookback_first_4h_close) / lookback_first_4h_close. */\n trend: number;\n /** Last time grid.trend was refreshed mid-tick (separate from buildGrid). */\n lastTrendRefreshAt: number;\n}\n\nexport interface GridPortfolioState {\n /** Total USD carved out for the grid strategy. */\n totalAllocation: number;\n /** Per-token grid state. */\n grids: GridTokenState[];\n /** Whether grid is paused (pool dropped below threshold). */\n paused: boolean;\n /** Reason for pause (empty if active). */\n pauseReason: string;\n /** Timestamp of initial allocation. */\n initializedAt: number;\n /** Hard circuit breaker tripped — pool drawdown exceeded\n * `circuitBreakerThresholdPct`. Auto-resume is BLOCKED while this is set;\n * only an explicit `sherwood grid resume` clears it. Persists in\n * portfolio.json so a process restart does not silently re-engage. */\n circuitBroken?: boolean;\n /** Timestamp when the circuit breaker was tripped (0 / undefined = never). */\n circuitBrokenAt?: number;\n}\n\n// ── Configuration ──\n\nexport interface GridConfig {\n /** Enable/disable the grid strategy. */\n enabled: boolean;\n /** Tokens to run grids on. */\n tokens: string[];\n /** Fraction of total portfolio to allocate to grid (0.35 = 35%). */\n allocationPct: number;\n /** Leverage multiplier on grid capital. */\n leverage: number;\n /** Number of buy levels below price (same number of sell levels above). */\n levelsPerSide: number;\n /** Grid range = price ± (atrMultiplier × ATR). */\n atrMultiplier: number;\n /** ATR lookback period. */\n atrPeriod: number;\n /** Shift grid when price drifts past this fraction of the range toward one edge. */\n rebalanceDriftPct: number;\n /** Full grid rebuild interval in ms. */\n fullRebuildIntervalMs: number;\n /** Per-token allocation split (must sum to 1.0). */\n tokenSplit: Record<string, number>;\n /** Skip fills where profit per round-trip < this (fee floor). */\n minProfitPerFillUsd: number;\n /** Pause grid if pool drops this fraction from initial allocation. */\n pauseThresholdPct: number;\n /** Resume paused grid when drawdown recovers below this fraction (hysteresis). */\n unpauseRecoveryPct: number;\n /** Hard circuit-breaker drawdown threshold. When pool MtM drop hits this,\n * the grid is permanently paused (auto-resume disabled) until an operator\n * runs `sherwood grid resume`. Distinct from `pauseThresholdPct` — the\n * soft pause has hysteresis and can re-engage on its own; the circuit\n * breaker requires manual review. Default 0.30 (30% drawdown). */\n circuitBreakerThresholdPct: number;\n /** Per-token maintenance margin fraction. Backtester uses this to model\n * exchange liquidation. Default 0.02 = 2% (typical Hyperliquid). */\n maintenanceMarginPct: number;\n /** Max open notional per token as a multiple of (allocation × leverage).\n * When exceeded, new buy fills are refused (existing fills can still\n * close as sells). Caps unbounded accumulation across rebuilds in\n * downtrends. Default 2.0 (allows up to 2 grid generations). */\n maxOpenNotionalMultiple: number;\n /** Block new buy fills when trend over the ATR lookback is below this\n * threshold. Default 0.10 (10% drop in 56h = clear downtrend → don't\n * buy into the falling knife). Set to 0 to disable filter. */\n downtrendBlockPct: number;\n /** Force-close any open buy if currentPrice drops this fraction below\n * buyPrice. Per-position stop-loss: limits how much any single fill can\n * contribute to the cross-margin pool's drawdown. Default 0.10 (10%\n * adverse from entry — empirical Nov–May: 10% saves the strategy at -4%,\n * 30% lets liquidations through at -37%). 0 = disabled. */\n stopLossPct: number;\n}\n\nexport const DEFAULT_GRID_CONFIG: GridConfig = {\n enabled: true,\n tokens: ['bitcoin', 'ethereum', 'solana'],\n allocationPct: 0.50,\n leverage: 5, // was 4 — +25% profit per RT\n levelsPerSide: 12, // disjoint-window winner — lowest MaxDD (18% vs 21-22%) at modest avg PnL trade-off\n atrMultiplier: 3, // ATR×3 dominates ATR×2 across all tested windows (lower fee burn)\n atrPeriod: 14,\n rebalanceDriftPct: 0.40, // was 0.55 — rebalance faster, keep levels near price\n fullRebuildIntervalMs: 12 * 60 * 60 * 1000, // 12h\n tokenSplit: { bitcoin: 0.55, ethereum: 0.25, solana: 0.20 }, // BTC-tilt — 30d backtest 2026-04-18..05-18 vs prior 0.45/0.30/0.25: net +$464 (+9.28%) vs +$422 (+8.44%) and max DD -$546 vs -$598\n minProfitPerFillUsd: 0.50,\n pauseThresholdPct: 0.20, // post leverage-fix calibration: fires at ~4% adverse move on 5x (real dollar terms); old 0.40 required ~8% which essentially never fired before liquidation\n unpauseRecoveryPct: 0.05, // hysteresis: resume when pool recovers to within 5% of initial (half of pause threshold to avoid ping-pong)\n circuitBreakerThresholdPct: 0.30, // hard halt at 30% drawdown — manual resume required. Bear-sweep: BEAR-60d went from -20% to -53% in second month; halting at -30% saves the rest.\n maintenanceMarginPct: 0.02,\n maxOpenNotionalMultiple: 2.0,\n downtrendBlockPct: 0.10,\n stopLossPct: 0.10, // empirical Nov-May: 10% saves the strategy (-4%); 30% lets liquidations through (-37%)\n};\n","/**\n * Grid Delta Hedge — maintains a partial short to offset underwater long fills.\n *\n * When the grid accumulates open buy fills (price dropped through buy levels),\n * the hedge opens a short position sized at HEDGE_RATIO of the total long exposure.\n * This limits drawdown during directional drops while preserving most grid profit\n * during ranging markets.\n *\n * Mechanics:\n * - Each tick: compute total long exposure from open fills\n * - Desired short = exposure × HEDGE_RATIO\n * - If current hedge size differs by >10%, adjust\n * - Track hedge PnL separately from grid PnL\n * - Close hedge when open fills drop below threshold (price recovered)\n *\n * Cost analysis (30% hedge on $6,400 exposure):\n * - Ranging drag: ~$8/day (5.6% of grid profit)\n * - Funding income: ~$2/day (shorts earn when rate positive)\n * - Net cost: ~$6/day — pays for itself on any >1.3% drop\n */\n\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { gridStatePath } from './paths.js';\nimport chalk from 'chalk';\n\n/** Default fraction of grid long exposure to hedge with a short.\n * Used as the chop/neutral baseline when no `marketTrend` is supplied or\n * trend is in the [-0.10, +0.10] range. See `hedgeRatioFor()` for the\n * trend-adaptive table. Override default via HEDGE_RATIO env var. */\nconst HEDGE_RATIO_DEFAULT = Number.isFinite(Number(process.env.HEDGE_RATIO))\n ? Number(process.env.HEDGE_RATIO)\n : 0.30;\n\n/**\n * Trend-adaptive hedge ratio.\n *\n * `marketTrend` is the recent BTC % move (negative = bearish), computed by\n * the manager over the same 56h / 14-bar window the asymmetric-grid filter\n * uses. Because that window is short, the magnitudes are small even in\n * sustained bears — empirically: BTC dropping ~1% / day prints a 56h\n * trend of −2-3%; the worst 56h slices in BEAR-30d-jan26 hit roughly −7%.\n * The thresholds below are calibrated to that scale, NOT to multi-week\n * cumulative drawdown.\n *\n * Bear-window backtest sweep (Oct '25 – Feb '26 BTC drawdowns):\n * - 50% hedge in bear cuts loss by ~25 ret pts vs 30%\n * - 10% hedge in bull saves ~7 ret pts vs 30% drag in chop\n *\n * Setting HEDGE_RATIO env var bypasses the table — useful for sweeps.\n */\nexport function hedgeRatioFor(marketTrend: number | undefined): number {\n if (process.env.HEDGE_RATIO !== undefined && Number.isFinite(Number(process.env.HEDGE_RATIO))) {\n return Number(process.env.HEDGE_RATIO);\n }\n if (marketTrend === undefined || !Number.isFinite(marketTrend)) {\n return HEDGE_RATIO_DEFAULT;\n }\n if (marketTrend <= -0.05) return 0.70; // strong bear (~ -1%/day sustained)\n if (marketTrend <= -0.025) return 0.50; // confirmed bear\n if (marketTrend >= 0.025) return 0.10; // strong bull — minimize drag\n return HEDGE_RATIO_DEFAULT; // chop / neutral\n}\n\n/** Minimum number of open buy fills before hedge activates. */\nconst MIN_FILLS_TO_HEDGE = 3;\n\n/** Don't adjust hedge unless size differs by more than this fraction. */\nconst ADJUSTMENT_THRESHOLD = 0.10;\n\nexport interface HedgePosition {\n token: string;\n /** Short entry price (average, updates on adjustments). */\n entryPrice: number;\n /** Short quantity in token units. */\n quantity: number;\n /** Timestamp of last adjustment. */\n lastAdjustedAt: number;\n /** Cumulative realized PnL from hedge adjustments. */\n realizedPnl: number;\n}\n\nexport interface HedgeState {\n positions: HedgePosition[];\n /** Total realized PnL across all hedge positions (including closed). */\n totalRealizedPnl: number;\n /** Today's realized PnL (resets daily). */\n todayRealizedPnl: number;\n lastDailyReset: number;\n}\n\nexport interface OpenFillExposure {\n token: string;\n totalQuantity: number;\n totalNotional: number;\n avgEntryPrice: number;\n fillCount: number;\n}\n\nexport interface HedgeTickResult {\n /** Number of hedge adjustments made this tick. */\n adjustments: number;\n /** Unrealized PnL across all active hedge positions. */\n unrealizedPnl: number;\n /** Total realized PnL (cumulative). */\n totalRealizedPnl: number;\n}\n\nexport class GridHedgeManager {\n private state: HedgeState | null = null;\n private statePath: string;\n\n constructor(stateDir?: string) {\n this.statePath = gridStatePath('hedge.json', stateDir);\n }\n\n async load(now: number = Date.now()): Promise<HedgeState> {\n if (this.state) return this.state;\n try {\n const raw = await readFile(this.statePath, 'utf-8');\n this.state = JSON.parse(raw) as HedgeState;\n } catch {\n this.state = {\n positions: [],\n totalRealizedPnl: 0,\n todayRealizedPnl: 0,\n lastDailyReset: now,\n };\n }\n\n // Reset daily PnL at UTC midnight (uses `now` so backtester can drive it)\n const todayMidnight = new Date(now);\n todayMidnight.setUTCHours(0, 0, 0, 0);\n if (this.state.lastDailyReset < todayMidnight.getTime()) {\n this.state.todayRealizedPnl = 0;\n this.state.lastDailyReset = now;\n }\n\n return this.state;\n }\n\n async save(): Promise<void> {\n if (!this.state) return;\n await mkdir(dirname(this.statePath), { recursive: true });\n const tmp = `${this.statePath}.tmp.${process.pid}`;\n await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf-8');\n const { rename } = await import('node:fs/promises');\n await rename(tmp, this.statePath);\n }\n\n /**\n * Run one hedge tick. Call after grid tick with current prices and open fill data.\n *\n * @param openFills - Per-token open fill exposure from the grid portfolio\n * @param prices - Current mark prices per token\n * @param now - injected clock (backtester drives this)\n * @param marketTrend - recent market trend (e.g. BTC's 56h trend) used by\n * `hedgeRatioFor()` to scale hedge size by regime. Pass\n * undefined to use the static default.\n * @param paused - when true, force desired hedge to zero for all tokens so\n * the close-path realizes any unrealized PnL into the\n * ledger. The loop passes `state.paused` so a soft-pause\n * grid doesn't hold paper-gain on the hedge that erodes\n * when the underlying mean-reverts toward the resume\n * threshold.\n */\n async tick(\n openFills: OpenFillExposure[],\n prices: Record<string, number>,\n now: number = Date.now(),\n marketTrend?: number,\n paused: boolean = false,\n ): Promise<HedgeTickResult> {\n const state = await this.load(now);\n let adjustments = 0;\n let unrealizedPnl = 0;\n\n // Resolve the active hedge ratio once per tick so all per-token sizing\n // and event logging use the same value.\n const activeRatio = hedgeRatioFor(marketTrend);\n\n for (const fill of openFills) {\n const price = prices[fill.token];\n if (!price || price <= 0) continue;\n\n // When the grid is soft-paused, force zero target. The existing close\n // branch below crystallizes unrealized PnL into the ledger — preserving\n // the protection value the hedge accrued during the drawdown instead\n // of giving it back when the underlying recovers toward unpause.\n const desiredShortQty = paused\n ? 0\n : fill.fillCount >= MIN_FILLS_TO_HEDGE\n ? fill.totalQuantity * activeRatio\n : 0;\n\n const existing = state.positions.find(p => p.token === fill.token);\n\n if (desiredShortQty <= 0) {\n // Close hedge if one exists\n if (existing && existing.quantity > 0) {\n const closePnl = (existing.entryPrice - price) * existing.quantity;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n existing.realizedPnl += closePnl;\n console.error(chalk.yellow(\n ` [hedge] CLOSE ${fill.token} short ${existing.quantity.toFixed(6)} @ $${price.toFixed(2)} ` +\n `PnL: $${closePnl.toFixed(2)}`\n ));\n existing.quantity = 0;\n existing.entryPrice = 0;\n adjustments++;\n }\n continue;\n }\n\n if (!existing) {\n // Open new hedge\n state.positions.push({\n token: fill.token,\n entryPrice: price,\n quantity: desiredShortQty,\n lastAdjustedAt: Date.now(),\n realizedPnl: 0,\n });\n console.error(chalk.magenta(\n ` [hedge] OPEN ${fill.token} short ${desiredShortQty.toFixed(6)} @ $${price.toFixed(2)} ` +\n `(${(activeRatio * 100).toFixed(0)}% of ${fill.fillCount} open fills)`\n ));\n adjustments++;\n } else if (existing.quantity > 0) {\n // Check if adjustment needed\n const diff = Math.abs(desiredShortQty - existing.quantity) / existing.quantity;\n if (diff > ADJUSTMENT_THRESHOLD) {\n if (desiredShortQty > existing.quantity) {\n // Increase hedge — add to short\n const addQty = desiredShortQty - existing.quantity;\n const newAvgEntry = (existing.entryPrice * existing.quantity + price * addQty) / desiredShortQty;\n existing.entryPrice = newAvgEntry;\n existing.quantity = desiredShortQty;\n existing.lastAdjustedAt = Date.now();\n console.error(chalk.magenta(\n ` [hedge] INCREASE ${fill.token} short to ${desiredShortQty.toFixed(6)} @ avg $${newAvgEntry.toFixed(2)}`\n ));\n adjustments++;\n } else {\n // Decrease hedge — partially close short\n const closeQty = existing.quantity - desiredShortQty;\n const closePnl = (existing.entryPrice - price) * closeQty;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n existing.realizedPnl += closePnl;\n existing.quantity = desiredShortQty;\n existing.lastAdjustedAt = Date.now();\n console.error(chalk.magenta(\n ` [hedge] DECREASE ${fill.token} short to ${desiredShortQty.toFixed(6)}, ` +\n `closed ${closeQty.toFixed(6)} PnL: $${closePnl.toFixed(2)}`\n ));\n adjustments++;\n }\n }\n\n // Compute unrealized PnL on current hedge\n const uPnl = (existing.entryPrice - price) * existing.quantity;\n unrealizedPnl += uPnl;\n } else {\n // Hedge was closed but fills are back — reopen\n existing.entryPrice = price;\n existing.quantity = desiredShortQty;\n existing.lastAdjustedAt = Date.now();\n console.error(chalk.magenta(\n ` [hedge] REOPEN ${fill.token} short ${desiredShortQty.toFixed(6)} @ $${price.toFixed(2)}`\n ));\n adjustments++;\n }\n }\n\n // Close hedges for tokens no longer in the fill list\n for (const pos of state.positions) {\n if (pos.quantity <= 0) continue;\n if (!openFills.find(f => f.token === pos.token)) {\n const price = prices[pos.token];\n if (price) {\n const closePnl = (pos.entryPrice - price) * pos.quantity;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n pos.realizedPnl += closePnl;\n console.error(chalk.yellow(\n ` [hedge] CLOSE orphaned ${pos.token} short, PnL: $${closePnl.toFixed(2)}`\n ));\n pos.quantity = 0;\n adjustments++;\n }\n }\n }\n\n await this.save();\n\n return {\n adjustments,\n unrealizedPnl,\n totalRealizedPnl: state.totalRealizedPnl,\n };\n }\n\n /**\n * Close every active hedge position in the ledger at the provided mark\n * prices, accumulating realized PnL using the same `(entry - price) * qty`\n * formula `tick()` uses on its auto-close path. Positions whose token is\n * missing from `prices` are left untouched and reported in `skipped`.\n *\n * Bookkeeping-only — this manager does not place perp orders; the actual\n * HL position (if any) must be closed externally. Use this to zero the\n * ledger as part of `sherwood grid flatten`.\n */\n async flatten(prices: Record<string, number>, now: number = Date.now()): Promise<{\n closed: Array<{ token: string; quantity: number; realizedPnl: number }>;\n skipped: string[];\n totalRealizedPnl: number;\n }> {\n const state = await this.load(now);\n const closed: Array<{ token: string; quantity: number; realizedPnl: number }> = [];\n const skipped: string[] = [];\n\n for (const pos of state.positions) {\n if (pos.quantity <= 0) continue;\n const price = prices[pos.token];\n if (!price || price <= 0) {\n skipped.push(pos.token);\n continue;\n }\n const closePnl = (pos.entryPrice - price) * pos.quantity;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n pos.realizedPnl += closePnl;\n closed.push({ token: pos.token, quantity: pos.quantity, realizedPnl: closePnl });\n pos.quantity = 0;\n pos.entryPrice = 0;\n pos.lastAdjustedAt = now;\n }\n\n await this.save();\n return { closed, skipped, totalRealizedPnl: state.totalRealizedPnl };\n }\n\n /** Get current hedge status for display. */\n getStatus(): { positions: HedgePosition[]; totalRealizedPnl: number; todayRealizedPnl: number } | null {\n if (!this.state) return null;\n return {\n positions: this.state.positions.filter(p => p.quantity > 0),\n totalRealizedPnl: this.state.totalRealizedPnl,\n todayRealizedPnl: this.state.todayRealizedPnl,\n };\n }\n}\n","/**\n * GridExecutor — bridges GridManager output to real Hyperliquid orders.\n *\n * The strategy contract owns USDC on HyperCore margin. The keeper (proposer EOA)\n * calls strategy.updateParams() with batch order data each tick. The CLI uses\n * the HL SDK directly via hlPlaceLimitOrder / hlCancelAllOrders for the simpler\n * deployment path (off-chain orders against the keeper's HyperCore account).\n */\n\nimport chalk from 'chalk';\nimport { hlPlaceLimitOrder, hlCancelAllOrders, resolveHLCoin } from '../lib/hyperliquid-executor.js';\nimport type { GridOrderPlan } from './manager.js';\n\nexport interface GridExecutorConfig {\n /** Hyperliquid asset index per token (e.g. bitcoin → 3). */\n assetIndices: Record<string, number>;\n}\n\nexport class GridExecutor {\n private cfg: GridExecutorConfig;\n\n constructor(cfg: GridExecutorConfig) {\n this.cfg = cfg;\n }\n\n /**\n * Execute the order plan against Hyperliquid.\n * Cancels stale orders for rebalanced tokens, then places new orders.\n */\n async execute(plan: GridOrderPlan): Promise<{ placed: number; cancelled: number; errors: string[] }> {\n const errors: string[] = [];\n let cancelled = 0;\n let placed = 0;\n\n for (const token of plan.assetsToCancel) {\n const coin = resolveHLCoin(token);\n if (!coin) {\n errors.push(`No HL ticker for ${token}`);\n continue;\n }\n try {\n await hlCancelAllOrders(coin);\n cancelled++;\n console.error(chalk.dim(` [grid-exec] Cancelled all orders for ${coin}`));\n } catch (e) {\n errors.push(`Cancel ${coin} failed: ${(e as Error).message}`);\n }\n }\n\n for (const order of plan.ordersToPlace) {\n const coin = resolveHLCoin(order.token);\n if (!coin) {\n errors.push(`No HL ticker for ${order.token}`);\n continue;\n }\n try {\n const res = await hlPlaceLimitOrder(coin, order.isBuy, order.quantity, order.price);\n if (res.success) {\n placed++;\n } else {\n errors.push(`Place ${coin} ${order.isBuy ? 'buy' : 'sell'} @${order.price}: ${res.error}`);\n }\n } catch (e) {\n errors.push(`Place ${coin} threw: ${(e as Error).message}`);\n }\n }\n\n return { placed, cancelled, errors };\n }\n}\n","/**\n * OnchainGridExecutor — calls HyperliquidGridStrategy.updateParams() on\n * HyperEVM via viem so grid orders execute against the strategy contract's\n * HyperCore account (which holds vault USDC).\n *\n * Persists per-token nonces + placed-CLOID tracking to disk so a restart\n * can correctly cancel the orders left on-chain by the prior process.\n */\n\nimport chalk from 'chalk';\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { encodeAbiParameters, parseUnits, type Address, type Hex } from 'viem';\nimport { getPublicClient, writeContractWithRetry } from '../lib/client.js';\nimport { hlGetMeta, resolveHLCoin, type HLAssetMeta } from '../lib/hyperliquid-executor.js';\nimport { gridCloid } from './cloid.js';\nimport { gridStatePath } from './paths.js';\nimport { HYPERLIQUID_GRID_STRATEGY_ABI } from './strategy-abi.js';\nimport type { GridOrderPlan } from './manager.js';\n\nconst UINT64_MAX = 18446744073709551615n;\n\nexport interface OnchainGridExecutorConfig {\n strategyAddress: Address;\n /** Hyperliquid asset index per token (e.g. bitcoin → 3). */\n assetIndices: Record<string, number>;\n /** Override directory for persisted state. Defaults to ~/.sherwood/grid. */\n stateDir?: string;\n}\n\ninterface PersistedState {\n /** Per-token nonce — increments on cancel/rebuild. */\n nonces: Record<string, number>;\n /** Per-token CLOIDs of the orders currently live on HyperCore. Stored as decimal strings (BigInt). */\n placedCloids: Record<string, string[]>;\n}\n\ninterface EncodedOrder {\n assetIndex: number;\n isBuy: boolean;\n limitPx: bigint;\n sz: bigint;\n cloid: bigint;\n}\n\nconst ACTION_PLACE_GRID = 1;\nconst ACTION_CANCEL_ALL = 2;\nconst ACTION_CANCEL_AND_PLACE = 3;\n\nfunction chunkArray<T>(arr: T[], size: number): T[][] {\n if (size <= 0) throw new Error(`chunk size must be > 0 (got ${size})`);\n if (arr.length === 0) return [];\n const out: T[][] = [];\n for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));\n return out;\n}\n\nconst GRID_ORDER_COMPONENTS = [\n { name: 'assetIndex', type: 'uint32' },\n { name: 'isBuy', type: 'bool' },\n { name: 'limitPx', type: 'uint64' },\n { name: 'sz', type: 'uint64' },\n { name: 'cloid', type: 'uint128' },\n] as const;\n\nexport class OnchainGridExecutor {\n private cfg: OnchainGridExecutorConfig;\n private nonces: Map<string, number> = new Map();\n private placedCloids: Map<string, bigint[]> = new Map();\n private meta: Map<string, HLAssetMeta> | null = null;\n private busy = false;\n /** On-chain `maxOrdersPerTick`; cached at load(). Used to chunk batches so\n * the strategy never reverts with TooManyOrders(actual, max). */\n private maxOrdersPerTick: number | null = null;\n private statePath: string;\n\n constructor(cfg: OnchainGridExecutorConfig) {\n this.cfg = cfg;\n this.statePath = gridStatePath('onchain-state.json', cfg.stateDir);\n }\n\n /** Read the strategy's per-call order cap and cache it. */\n private async fetchMaxOrdersPerTick(): Promise<number> {\n if (this.maxOrdersPerTick !== null) return this.maxOrdersPerTick;\n const pub = getPublicClient();\n const value = await pub.readContract({\n address: this.cfg.strategyAddress,\n abi: HYPERLIQUID_GRID_STRATEGY_ABI,\n functionName: 'maxOrdersPerTick',\n });\n this.maxOrdersPerTick = Number(value);\n return this.maxOrdersPerTick;\n }\n\n /**\n * Read persisted state from disk — does NOT touch the network. Use this\n * when you only need `nonces` + `placedCloids` (e.g. for `flattenAll`'s\n * cancel-only path). Idempotent: callers may invoke it repeatedly; each\n * call re-reads the file and clobbers in-memory maps with disk state.\n */\n private async loadFromDisk(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, 'utf-8');\n const state = JSON.parse(raw) as PersistedState;\n this.nonces.clear();\n this.placedCloids.clear();\n for (const [tok, n] of Object.entries(state.nonces)) this.nonces.set(tok, n);\n for (const [tok, cloids] of Object.entries(state.placedCloids)) {\n this.placedCloids.set(tok, cloids.map((s) => BigInt(s)));\n }\n console.error(chalk.dim(` [grid-onchain] Loaded state: ${this.nonces.size} tokens`));\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n // First run — fine\n } else {\n // Corrupt JSON or other read error — start fresh. On-chain state is the\n // source of truth; at worst we orphan one cycle of orders until HL\n // expires them via TIF.\n console.error(\n chalk.yellow(\n ` [grid-onchain] Failed to load state (${(e as Error).message}) — starting fresh. Existing on-chain orders may be orphaned.`,\n ),\n );\n }\n }\n }\n\n /** Load persisted state + chain meta. Call once before the first execute(). */\n async load(): Promise<void> {\n await this.loadFromDisk();\n if (!this.meta) this.meta = await hlGetMeta();\n await this.fetchMaxOrdersPerTick();\n }\n\n /**\n * Atomic save: write to .tmp, then POSIX-rename. A crash mid-write leaves\n * either the old file intact or the new file fully written — never a\n * partial JSON that would crash load() on restart.\n */\n private async save(): Promise<void> {\n const state: PersistedState = {\n nonces: Object.fromEntries(this.nonces),\n placedCloids: Object.fromEntries(\n [...this.placedCloids].map(([tok, cloids]) => [tok, cloids.map((c) => c.toString())]),\n ),\n };\n await mkdir(dirname(this.statePath), { recursive: true });\n const tmp = this.statePath + '.tmp';\n await writeFile(tmp, JSON.stringify(state, null, 2));\n await rename(tmp, this.statePath);\n }\n\n /**\n * Execute the order plan: cancel stale orders for rebalanced tokens, then\n * place new orders. Each (token) is one tx. Persists state after each tx\n * so a crash mid-execution still leaves a recoverable on-disk record.\n *\n * Concurrency-guarded: a second concurrent call returns immediately rather\n * than racing tx submission against another in-flight execute().\n */\n async execute(plan: GridOrderPlan): Promise<{ placed: number; cancelled: number; txs: Hex[]; errors: string[] }> {\n if (this.busy) {\n return { placed: 0, cancelled: 0, txs: [], errors: ['execute() already in flight — skipping'] };\n }\n this.busy = true;\n try {\n if (!this.meta) await this.load();\n\n const errors: string[] = [];\n const txs: Hex[] = [];\n let placed = 0;\n let cancelled = 0;\n\n const ordersByToken = new Map<string, GridOrderPlan['ordersToPlace']>();\n for (const o of plan.ordersToPlace) {\n if (!ordersByToken.has(o.token)) ordersByToken.set(o.token, []);\n ordersByToken.get(o.token)!.push(o);\n }\n const cancelSet = new Set(plan.assetsToCancel);\n const allTokens = new Set([...ordersByToken.keys(), ...cancelSet]);\n\n for (const token of allTokens) {\n const assetIndex = this.cfg.assetIndices[token];\n if (assetIndex === undefined) {\n errors.push(`No asset index for ${token}`);\n continue;\n }\n const coin = resolveHLCoin(token);\n if (!coin) {\n errors.push(`No HL ticker for ${token}`);\n continue;\n }\n const meta = this.meta!.get(coin);\n if (!meta) {\n errors.push(`No HL meta for ${coin} (run \\`sherwood grid status\\` to refresh)`);\n continue;\n }\n\n const wantCancel = cancelSet.has(token);\n const orders = ordersByToken.get(token) ?? [];\n const wantPlace = orders.length > 0;\n\n try {\n if (wantCancel && wantPlace) {\n const txArr = await this.cancelAndPlace(token, assetIndex, orders, meta);\n txs.push(...txArr);\n cancelled += 1;\n placed += orders.length;\n } else if (wantCancel) {\n const tx = await this.cancelAll(token, assetIndex);\n txs.push(tx);\n cancelled += 1;\n } else if (wantPlace) {\n const txArr = await this.placeGrid(token, assetIndex, orders, meta);\n txs.push(...txArr);\n placed += orders.length;\n }\n await this.save();\n } catch (e) {\n errors.push(`${token}: ${(e as Error).message}`);\n }\n }\n\n return { placed, cancelled, txs, errors };\n } finally {\n this.busy = false;\n }\n }\n\n private currentNonce(token: string): number {\n return this.nonces.get(token) ?? 0;\n }\n\n private bumpNonce(token: string): number {\n const next = this.currentNonce(token) + 1;\n this.nonces.set(token, next);\n return next;\n }\n\n /**\n * Pure encoding — does NOT mutate placedCloids. Caller commits CLOIDs\n * only after the on-chain tx confirms successfully.\n *\n * Uses viem's `parseUnits` for decimal scaling instead of float math so\n * high-szDecimals tokens (BTC=5, ETH=4) keep full precision on small sizes.\n */\n private encodeOrders(\n assetIndex: number,\n orders: GridOrderPlan['ordersToPlace'],\n meta: HLAssetMeta,\n nonce: number,\n ): { encoded: EncodedOrder[]; cloids: bigint[] } {\n const cloids: bigint[] = [];\n const encoded = orders.map((o, i) => {\n const cloid = gridCloid(this.cfg.strategyAddress, assetIndex, o.isBuy, i, nonce);\n cloids.push(cloid);\n // parseUnits uses string scaling — no float-rounding precision loss.\n const limitPx = parseUnits(o.price.toFixed(meta.pxDecimals), meta.pxDecimals);\n const sz = parseUnits(o.quantity.toFixed(meta.szDecimals), meta.szDecimals);\n // Defensive uint64 bound check — parseUnits returns uint256 but the\n // strategy contract reads uint64.\n if (limitPx > UINT64_MAX || sz > UINT64_MAX) {\n throw new Error(\n `Order exceeds uint64: token=${o.token} px=${limitPx} sz=${sz}`,\n );\n }\n return { assetIndex, isBuy: o.isBuy, limitPx, sz, cloid };\n });\n return { encoded, cloids };\n }\n\n /**\n * Place orders, chunking into batches of ≤ maxOrdersPerTick per tx.\n * Each chunk uses its own nonce so CLOIDs stay unique across chunks.\n * placedCloids is committed once after the last chunk lands; if any\n * chunk reverts, the partial cloids stay tracked via the per-chunk save.\n */\n private async placeGrid(\n token: string,\n assetIndex: number,\n orders: GridOrderPlan['ordersToPlace'],\n meta: HLAssetMeta,\n ): Promise<Hex[]> {\n const max = await this.fetchMaxOrdersPerTick();\n const chunks = chunkArray(orders, max);\n const txs: Hex[] = [];\n const allCloids: bigint[] = [...(this.placedCloids.get(token) ?? [])];\n for (const chunk of chunks) {\n const nonce = this.bumpNonce(token);\n const { encoded, cloids } = this.encodeOrders(assetIndex, chunk, meta, nonce);\n const data = encodeAbiParameters(\n [{ type: 'uint8' }, { type: 'tuple[]', components: [...GRID_ORDER_COMPONENTS] }],\n [ACTION_PLACE_GRID, encoded],\n );\n const tx = await this.send(data); // throws if reverts\n txs.push(tx);\n allCloids.push(...cloids);\n this.placedCloids.set(token, allCloids); // commit incrementally so cancel-on-restart sees what landed\n await this.save();\n }\n return txs;\n }\n\n private async cancelAll(token: string, assetIndex: number): Promise<Hex> {\n const cloids = this.placedCloids.get(token) ?? [];\n if (cloids.length === 0) {\n // Nothing tracked — nothing to cancel. Still bump nonce for consistency.\n this.bumpNonce(token);\n return '0x' as Hex;\n }\n const data = encodeAbiParameters(\n [{ type: 'uint8' }, { type: 'uint32' }, { type: 'uint128[]' }],\n [ACTION_CANCEL_ALL, assetIndex, cloids],\n );\n const tx = await this.send(data); // throws if reverts\n this.placedCloids.set(token, []); // commit only on success\n this.bumpNonce(token);\n return tx;\n }\n\n /**\n * Atomic cancel-old + place-new on rebalance. When `orders` exceeds\n * maxOrdersPerTick, the first chunk uses ACTION_CANCEL_AND_PLACE (so the\n * old orders are cleared in the same tx as the first wave of new orders);\n * subsequent chunks use ACTION_PLACE_GRID. Atomicity holds for chunk #1;\n * after that there's a brief window where some new orders are live before\n * the rest are placed — acceptable for a 60s rebuild cycle.\n */\n private async cancelAndPlace(\n token: string,\n assetIndex: number,\n orders: GridOrderPlan['ordersToPlace'],\n meta: HLAssetMeta,\n ): Promise<Hex[]> {\n const max = await this.fetchMaxOrdersPerTick();\n const chunks = chunkArray(orders, max);\n const oldCloids = this.placedCloids.get(token) ?? [];\n const txs: Hex[] = [];\n const allNewCloids: bigint[] = [];\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i]!;\n const newNonce = this.bumpNonce(token);\n const { encoded, cloids } = this.encodeOrders(assetIndex, chunk, meta, newNonce);\n let data: Hex;\n if (i === 0) {\n // First chunk swaps old → new in one tx.\n data = encodeAbiParameters(\n [\n { type: 'uint8' },\n { type: 'uint32' },\n { type: 'uint128[]' },\n { type: 'tuple[]', components: [...GRID_ORDER_COMPONENTS] },\n ],\n [ACTION_CANCEL_AND_PLACE, assetIndex, oldCloids, encoded],\n );\n } else {\n data = encodeAbiParameters(\n [{ type: 'uint8' }, { type: 'tuple[]', components: [...GRID_ORDER_COMPONENTS] }],\n [ACTION_PLACE_GRID, encoded],\n );\n }\n const tx = await this.send(data); // throws if reverts\n txs.push(tx);\n allNewCloids.push(...cloids);\n // After chunk #0 the old cloids are already cancelled on-chain — record\n // only the new cloids that have landed so far.\n this.placedCloids.set(token, [...allNewCloids]);\n await this.save();\n }\n return txs;\n }\n\n /**\n * Cancel every tracked CLOID across all configured tokens. Used by\n * `sherwood grid flatten` to wind the strategy down to a no-orders state\n * without placing anything new.\n *\n * Per-token errors are captured and returned rather than thrown — partial\n * progress is the expected outcome when one token reverts (e.g. nonce\n * desync after a manual on-chain action). Each successful cancel saves\n * before moving on, so a crash mid-flatten leaves a consistent on-disk\n * record of which tokens still hold cloids.\n */\n async flattenAll(): Promise<{ txs: Hex[]; cancelled: string[]; skipped: string[]; errors: string[] }> {\n if (this.busy) {\n return { txs: [], cancelled: [], skipped: [], errors: ['flattenAll() called while another execute()/flattenAll() is in flight'] };\n }\n this.busy = true;\n try {\n // Disk-only load — flatten must succeed even when chain meta / RPC are\n // unhealthy. The actual send() call below still needs RPC, but the init\n // path no longer aborts on a flaky HL HTTP endpoint or strategy read.\n await this.loadFromDisk();\n\n const txs: Hex[] = [];\n const cancelled: string[] = [];\n const skipped: string[] = [];\n const errors: string[] = [];\n\n // cancelAll is the single source of truth for the empty-cloid path:\n // it returns '0x' (no tx) and bumps nonce when there's nothing to\n // cancel. We use that return value to drive the skip set rather than\n // pre-filtering — keeps both call sites consistent.\n for (const [token, assetIndex] of Object.entries(this.cfg.assetIndices)) {\n try {\n const tx = await this.cancelAll(token, assetIndex);\n if (tx === '0x') {\n skipped.push(token);\n } else {\n txs.push(tx);\n cancelled.push(token);\n }\n await this.save();\n } catch (e) {\n errors.push(`${token}: ${(e as Error).message}`);\n }\n }\n\n return { txs, cancelled, skipped, errors };\n } finally {\n this.busy = false;\n }\n }\n\n /**\n * Submit and wait for receipt. Throwing here surfaces to the per-token\n * try/catch in execute(), recording the error and skipping the save() so\n * placedCloids never reflects orders that didn't land.\n */\n private async send(data: Hex): Promise<Hex> {\n const tx = await writeContractWithRetry({\n address: this.cfg.strategyAddress,\n abi: HYPERLIQUID_GRID_STRATEGY_ABI,\n functionName: 'updateParams',\n args: [data],\n });\n const pub = getPublicClient();\n const receipt = await pub.waitForTransactionReceipt({ hash: tx, timeout: 30_000 });\n if (receipt.status !== 'success') {\n throw new Error(`Tx ${tx} reverted on-chain`);\n }\n console.error(chalk.dim(` [grid-onchain] tx ${tx.slice(0, 10)}... confirmed`));\n return tx;\n }\n}\n","/**\n * Deterministic CLOID generator for grid orders.\n *\n * CLOID = uint128 = keccak256(strategy, assetIndex, isBuy, levelIndex, nonce)[0:16]\n *\n * Including the strategy address namespaces CLOIDs per-deployment so two\n * grid strategies running on the same HL account can't collide.\n *\n * The nonce is per-grid-rebuild — increments when a token's grid is\n * rebuilt/shifted, making prior CLOIDs stale (so `cancel-all` for a token\n * uses the OLD nonce's CLOIDs).\n */\n\nimport { keccak256, encodeAbiParameters, type Address } from 'viem';\n\nexport function gridCloid(\n strategy: Address,\n assetIndex: number,\n isBuy: boolean,\n levelIndex: number,\n nonce: number,\n): bigint {\n const hash = keccak256(\n encodeAbiParameters(\n [\n { type: 'address' },\n { type: 'uint32' },\n { type: 'bool' },\n { type: 'uint32' },\n { type: 'uint32' },\n ],\n [strategy, assetIndex, isBuy, levelIndex, nonce],\n ),\n );\n // Take the high 16 bytes as uint128.\n // keccak256 already returns `0x${string}` — no cast needed.\n const top16 = hash.slice(0, 2 + 32); // '0x' + 32 hex chars = 16 bytes\n return BigInt(top16);\n}\n","/**\n * Grid backtester — replays historical Hyperliquid 1-minute bars through\n * the existing GridManager and reports PnL, fills, drawdown.\n *\n * Uses Approach 2 from the design spec: a separate orchestrator that\n * reuses GridManager via injected dependencies (candle fetcher, fill\n * detectors, in-memory portfolio). Live mode is untouched.\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { homedir } from 'node:os';\nimport { createHash } from 'node:crypto';\nimport { GridManager, type CandleFetcher } from './manager.js';\nimport { BacktestPortfolio } from './backtest-portfolio.js';\nimport { HistoricalDataLoader, type Bar1m, type AtrPoint } from './historical-data-loader.js';\nimport { type GridConfig } from './config.js';\nimport { BacktestHedgeManager } from './backtest-hedge.js';\n\nconst DEFAULT_OUT_DIR = join(homedir(), '.sherwood', 'grid', 'backtests');\n\nexport interface BacktestOpts {\n fromMs: number;\n toMs: number;\n capital: number;\n config: GridConfig;\n /** Equity-curve snapshot cadence in simulated minutes. Default 60. */\n snapshotEveryMinutes?: number;\n /** When true, re-enables the manager's chalk console.error logs. */\n verbose?: boolean;\n /** When true, skips cache for fetch. */\n noCache?: boolean;\n /** Override the default JSON output path. */\n outPath?: string;\n /** Inject for tests — defaults to a real HistoricalDataLoader. */\n loader?: HistoricalDataLoader;\n /** Trading fee in basis points per fill. Default 5 (typical maker). */\n feeBps?: number;\n /** Simulate the GridHedgeManager. Default true (matches live grid). */\n hedge?: boolean;\n}\n\nexport interface EquityPoint {\n t: number;\n totalAllocation: number;\n totalPnl: number;\n totalRoundTrips: number;\n openFillCount: number;\n paused: boolean;\n}\n\nexport interface BacktestResult {\n runId: string;\n startedAt: number;\n finishedAt: number;\n durationMs: number;\n window: {\n fromMs: number;\n toMs: number;\n fromIso: string;\n toIso: string;\n days: number;\n };\n config: GridConfig;\n capital: {\n initialUsd: number;\n finalUsd: number;\n pnlUsd: number; // NET of fees\n pnlPct: number; // NET of fees\n grossPnlUsd: number; // before fees (= old pnlUsd value)\n };\n fees: {\n bps: number;\n totalUsd: number;\n perFill: number; // avg fee per fill in USD (across tokens, weighted)\n };\n hedge: {\n enabled: boolean;\n realizedPnlUsd: number;\n unrealizedPnlUsd: number; // at end of run\n adjustments: number; // total hedge adjustments across the run\n finalOpenPositions: number; // count of open shorts at end\n };\n liquidations: {\n /** Per-token liquidation events. */\n events: Array<{\n token: string;\n timestamp: number;\n tokenAllocation: number;\n unrealizedPnlAtLiquidation: number;\n thresholdUsd: number;\n }>;\n /** When all configured tokens are liquidated, the run terminates here. Null if not all liquidated. */\n haltedAt: number | null;\n };\n totals: {\n roundTrips: number;\n fills: number;\n rebuilds: number;\n pausedSteps: number;\n skippedSteps: number;\n totalSteps: number;\n };\n perToken: Array<{\n token: string;\n allocation: { initial: number; final: number };\n roundTrips: number;\n fills: number;\n pnlUsd: number;\n rebuilds: number;\n }>;\n drawdown: {\n maxUsd: number;\n maxPct: number;\n peakAt: number;\n troughAt: number;\n };\n equityCurve: EquityPoint[];\n}\n\n/** Compute a deterministic 8-char hash from window+config for run ID. */\nexport function shortHash(input: { fromMs: number; toMs: number; config: GridConfig }): string {\n const h = createHash('sha256').update(JSON.stringify(input)).digest('hex');\n return h.slice(0, 8);\n}\n\n/** Compute peak-to-trough drawdown from an equity curve. */\nexport function computeDrawdown(curve: EquityPoint[]): BacktestResult['drawdown'] {\n if (curve.length === 0) {\n return { maxUsd: 0, maxPct: 0, peakAt: 0, troughAt: 0 };\n }\n const equityAt = (p: EquityPoint) => p.totalAllocation + p.totalPnl;\n let peak = equityAt(curve[0]!);\n let peakAt = curve[0]!.t;\n let maxDrop = 0;\n let dropPeakAt = peakAt;\n let dropTroughAt = peakAt;\n for (const point of curve) {\n const eq = equityAt(point);\n if (eq > peak) {\n peak = eq;\n peakAt = point.t;\n }\n const drop = peak - eq;\n if (drop > maxDrop) {\n maxDrop = drop;\n dropPeakAt = peakAt;\n dropTroughAt = point.t;\n }\n }\n const peakPoint = curve.find(p => p.t === dropPeakAt);\n const peakValue = peakPoint ? equityAt(peakPoint) : 0;\n return {\n maxUsd: maxDrop,\n maxPct: peakValue > 0 ? maxDrop / peakValue : 0,\n peakAt: dropPeakAt,\n troughAt: dropTroughAt,\n };\n}\n\nfunction isoToYmdHms(ms: number): string {\n const d = new Date(ms);\n const pad = (n: number) => n.toString().padStart(2, '0');\n return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}-${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`;\n}\n\nexport function makeRunId(fromMs: number, toMs: number, config: GridConfig): string {\n return `bt-${isoToYmdHms(Date.now())}-${shortHash({ fromMs, toMs, config })}`;\n}\n\n/**\n * Run a backtest. Returns the structured result; also writes JSON to disk\n * unless outPath is the empty string ''.\n */\nexport async function runBacktest(opts: BacktestOpts): Promise<BacktestResult> {\n const startedAt = Date.now();\n\n // Validation\n if (opts.fromMs >= opts.toMs) throw new Error('--from must be before --to');\n const FIFTY_SIX_HOURS = 56 * 60 * 60 * 1000;\n if (opts.toMs - opts.fromMs < FIFTY_SIX_HOURS) {\n throw new Error('window too short — need ≥ 56h for ATR(14) warmup');\n }\n const splitSum = Object.values(opts.config.tokenSplit).reduce((a, b) => a + b, 0);\n if (Math.abs(splitSum - 1.0) > 1e-6) {\n throw new Error(`tokenSplit must sum to 1.0, got ${splitSum.toFixed(6)}`);\n }\n\n const loader = opts.loader ?? new HistoricalDataLoader({ noCache: opts.noCache });\n const snapshotEvery = opts.snapshotEveryMinutes ?? 60;\n\n // Load all token series in parallel\n const seriesByToken: Record<string, { minutes: Bar1m[]; fourHour: Bar1m[]; atrSeries: AtrPoint[] }> = {};\n await Promise.all(opts.config.tokens.map(async token => {\n seriesByToken[token] = await loader.load(token, opts.fromMs, opts.toMs);\n }));\n\n // Build unified timeline: minutes present in ALL token series\n const minuteSets = opts.config.tokens.map(t => new Set(seriesByToken[t]!.minutes.map(b => b.t)));\n const masterMinutes = seriesByToken[opts.config.tokens[0]!]!.minutes;\n const sharedTimestamps: number[] = [];\n let skippedSteps = 0;\n for (const bar of masterMinutes) {\n if (bar.t < opts.fromMs || bar.t >= opts.toMs) continue;\n if (minuteSets.every(s => s.has(bar.t))) {\n sharedTimestamps.push(bar.t);\n } else {\n skippedSteps++;\n }\n }\n\n if (sharedTimestamps.length === 0) {\n throw new Error('no overlapping bars across requested tokens');\n }\n\n // Index lookup: token → timestamp → bar\n const barIndex: Record<string, Map<number, Bar1m>> = {};\n for (const token of opts.config.tokens) {\n const m = new Map<number, Bar1m>();\n for (const bar of seriesByToken[token]!.minutes) m.set(bar.t, bar);\n barIndex[token] = m;\n }\n\n // Backtest clock injection\n let currentT = sharedTimestamps[0]!;\n const nowProvider = () => currentT;\n\n // Candle fetcher: returns 4h bars whose close ts ≤ currentT (point-in-time correct)\n const candleFetcher: CandleFetcher = async (tokenId, interval, lookbackMs) => {\n if (interval !== '4h') return null;\n const series = seriesByToken[tokenId];\n if (!series) return null;\n const cutoff = currentT - lookbackMs;\n return series.fourHour\n .filter(b => b.t <= currentT && b.t >= cutoff)\n .map(b => ({\n timestamp: b.t,\n open: b.o,\n high: b.h,\n low: b.l,\n close: b.c,\n volume: b.v,\n }));\n };\n\n // Construct manager with default close-only detectors. HLC fills are\n // implemented via TWO-PASS TICK: each step calls manager.tick twice\n // — once with bar.low (triggers buys), once with bar.high (triggers\n // sells + closes opens). Default close-only detector then fires at\n // the right times. No per-token detector context required.\n const portfolio = new BacktestPortfolio(nowProvider);\n const manager = new GridManager(opts.config, candleFetcher, undefined, undefined, portfolio, nowProvider);\n\n // Initialize portfolio with starting capital\n await manager.init(opts.capital);\n\n // Snapshot initial per-token allocation. Used only for fee notional\n // approximation (notionalPerFillByToken). Allocation compounding is now\n // live — grid.allocation += profit each step, matching live-mode behavior.\n // (Fee approx slightly understates fees as allocation compounds upward;\n // acceptable for v1 and can be refined later.)\n const initialAllocations: Record<string, number> = {};\n {\n const initState = portfolio.getState();\n if (initState) {\n for (const grid of initState.grids) {\n initialAllocations[grid.token] = grid.allocation;\n }\n }\n }\n\n // Pre-compute per-token notional-per-fill (used for running fee accrual)\n const feeBps = opts.feeBps ?? 5;\n const notionalPerFillByToken: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n const tokenInitial = initialAllocations[token] ?? 0;\n notionalPerFillByToken[token] = (tokenInitial * opts.config.leverage) / opts.config.levelsPerSide;\n }\n\n // Running fee accumulators (kept in sync with equity curve)\n const feesByToken: Record<string, number> = {};\n for (const token of opts.config.tokens) feesByToken[token] = 0;\n const lastSeenFills: Record<string, number> = {};\n for (const token of opts.config.tokens) lastSeenFills[token] = 0;\n\n const hedgeEnabled = opts.hedge ?? true;\n const hedge = new BacktestHedgeManager(nowProvider);\n let hedgeAdjustments = 0;\n let hedgeRealized = 0;\n let hedgeUnrealized = 0;\n\n // Track rebuild count via portfolio state (manager updates grid.stats.lastRebalanceAt)\n let totalRebuilds = 0;\n const lastRebalanceAt: Record<string, number> = {};\n for (const t of opts.config.tokens) lastRebalanceAt[t] = 0;\n\n // Liquidation tracking. A token is liquidated when its unrealized PnL\n // exceeds the calibrated maintenance threshold; once liquidated, the\n // token's grid is frozen (existing opens cleared as realized losses, no\n // new fills allowed). When all tokens are liquidated the run halts.\n const liquidatedTokens = new Set<string>();\n const liquidationEvents: BacktestResult['liquidations']['events'] = [];\n let haltedAt: number | null = null;\n\n // Equity curve\n const equityCurve: EquityPoint[] = [];\n let pausedSteps = 0;\n\n // Silence manager's chalk logs unless verbose\n const originalConsoleError = console.error;\n if (!opts.verbose) {\n console.error = () => {};\n }\n\n try {\n let cycleCount = 0;\n const totalSteps = sharedTimestamps.length;\n const decileSize = Math.max(1, Math.floor(totalSteps / 10));\n\n for (const t of sharedTimestamps) {\n currentT = t;\n\n // Per-token pass order inferred from bar color (option B):\n // green (close >= open): price went low → high → buy fills (Pass 1=low),\n // then close-outs may fire on the way up (Pass 2=high) — same-bar\n // round trip is realistic.\n // red (close < open): price went high → low → close-outs fire first\n // (Pass 1=high) on pre-existing opens. New buys from Pass 2=low can't\n // close this bar because low < target — no same-bar round trip.\n // Doji (close == open) treated as green.\n const passAPrices: Record<string, number> = {};\n const passBPrices: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n const bar = barIndex[token]!.get(t)!;\n const isGreen = bar.c >= bar.o;\n passAPrices[token] = isGreen ? bar.l : bar.h;\n passBPrices[token] = isGreen ? bar.h : bar.l;\n }\n\n const r1 = await manager.tick(passAPrices);\n const r2 = await manager.tick(passBPrices);\n\n // Detect rebuilds — manager updates grid.stats.lastRebalanceAt\n const stateAfter = portfolio.getState();\n if (stateAfter) {\n for (const grid of stateAfter.grids) {\n if (grid.stats.lastRebalanceAt > lastRebalanceAt[grid.token]!) {\n totalRebuilds++;\n lastRebalanceAt[grid.token] = grid.stats.lastRebalanceAt;\n }\n }\n }\n\n if (r1.paused || r2.paused) pausedSteps++;\n\n // Hedge tick: uses bar.close prices and the manager's open-fill exposure.\n if (hedgeEnabled) {\n const hedgePrices: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n const bar = barIndex[token]!.get(t)!;\n hedgePrices[token] = bar.c;\n }\n const exposure = manager.getOpenFillExposure();\n const marketTrend = manager.getMarketTrend();\n const hedgeResult = await hedge.tick(exposure, hedgePrices, t, marketTrend, stateAfter?.paused ?? false);\n hedgeAdjustments += hedgeResult.adjustments;\n hedgeRealized = hedgeResult.totalRealizedPnl;\n hedgeUnrealized = hedgeResult.unrealizedPnl;\n }\n\n // Accrue per-step fees: any new fills this step pay notionalPerFill × bps / 10_000\n if (stateAfter) {\n for (const grid of stateAfter.grids) {\n const newFills = grid.stats.totalFills - lastSeenFills[grid.token]!;\n if (newFills > 0) {\n feesByToken[grid.token]! += newFills * (notionalPerFillByToken[grid.token] ?? 0) * feeBps / 10_000;\n lastSeenFills[grid.token] = grid.stats.totalFills;\n }\n }\n }\n\n // Liquidation check: per token, sum unrealized PnL on its open fills\n // and compare against the calibrated threshold.\n // Threshold is in the backtester's overstated unrealized-PnL units (see\n // the leverage double-count caveat).\n const stateLiq = portfolio.getState();\n if (stateLiq && haltedAt === null) {\n const lev = opts.config.leverage;\n const maint = opts.config.maintenanceMarginPct;\n // Now that the manager's PnL formula no longer double-counts leverage,\n // unrealized in this loop is the REAL dollar PnL. Threshold drops\n // by a factor of leverage vs. the previous (overstated) calibration:\n // real-world liquidation at (1/lev - maint) adverse move →\n // unrealized loss = allocation - allocation × lev × maint\n // = allocation × (1 - lev × maint).\n const liquidationCoefficient = 1 - lev * maint;\n for (const grid of stateLiq.grids) {\n if (liquidatedTokens.has(grid.token)) continue;\n const close = barIndex[grid.token]?.get(t)?.c;\n if (close === undefined) continue;\n let unrealized = 0;\n for (const f of grid.openFills) {\n if (f.closed) continue;\n unrealized += (close - f.buyPrice) * f.quantity;\n }\n const tokenAlloc = initialAllocations[grid.token] ?? 0;\n const threshold = -tokenAlloc * liquidationCoefficient;\n if (tokenAlloc > 0 && unrealized <= threshold) {\n // Realize the loss and freeze the grid for this token.\n grid.stats.totalPnlUsd += unrealized;\n grid.stats.todayPnlUsd += unrealized;\n grid.allocation += unrealized; // bookkeeping; allocation now near-zero\n for (const f of grid.openFills) {\n if (!f.closed) {\n f.closed = true;\n f.closedAt = t;\n f.pnlUsd = (close - f.buyPrice) * f.quantity;\n }\n }\n // Drop the level grid so manager doesn't fire new fills\n grid.levels = [];\n liquidatedTokens.add(grid.token);\n liquidationEvents.push({\n token: grid.token,\n timestamp: t,\n tokenAllocation: tokenAlloc,\n unrealizedPnlAtLiquidation: unrealized,\n thresholdUsd: threshold,\n });\n // Stderr notice (always, not gated on verbose — this is a serious event)\n process.stderr.write(\n ` [backtest] LIQUIDATED ${grid.token} at t=${new Date(t).toISOString()}: unrealized=$${unrealized.toFixed(0)} (threshold=$${threshold.toFixed(0)})\\n`\n );\n }\n }\n // If all configured tokens are liquidated, halt the run\n if (liquidatedTokens.size === opts.config.tokens.length) {\n haltedAt = t;\n process.stderr.write(` [backtest] All tokens liquidated; halting run at t=${new Date(t).toISOString()}\\n`);\n }\n }\n\n if (haltedAt !== null) {\n // Capture a final snapshot at halt, then break\n const sFinal = portfolio.getState();\n if (sFinal) {\n const aggFinal = portfolio.aggregateStats(sFinal);\n const ofcFinal = sFinal.grids.reduce((sum, g) => sum + g.openFills.filter(f => !f.closed).length, 0);\n const runningFeesFinal = Object.values(feesByToken).reduce((a, b) => a + b, 0);\n equityCurve.push({\n t,\n totalAllocation: sFinal.totalAllocation,\n totalPnl: aggFinal.totalPnlUsd - runningFeesFinal + hedgeRealized + hedgeUnrealized,\n totalRoundTrips: aggFinal.totalRoundTrips,\n openFillCount: ofcFinal,\n paused: sFinal.paused,\n });\n }\n break;\n }\n\n // Snapshot\n cycleCount++;\n if (cycleCount % snapshotEvery === 0 || cycleCount === totalSteps) {\n const s = portfolio.getState();\n if (s) {\n const agg = portfolio.aggregateStats(s);\n const openFillCount = s.grids.reduce(\n (sum, g) => sum + g.openFills.filter(f => !f.closed).length,\n 0,\n );\n // Mark open positions to market at the current bar's close.\n // Without this, drawdown is always 0 because the grid only books\n // realized PnL on profitable closes — open underwater buys never\n // show up in equity.\n let unrealizedPnl = 0;\n for (const grid of s.grids) {\n const close = barIndex[grid.token]?.get(t)?.c;\n if (close === undefined) continue;\n for (const f of grid.openFills) {\n if (f.closed) continue;\n // quantity already leveraged — see manager.simulateFills note.\n unrealizedPnl += (close - f.buyPrice) * f.quantity;\n }\n }\n const runningFees = Object.values(feesByToken).reduce((a, b) => a + b, 0);\n equityCurve.push({\n t,\n totalAllocation: s.totalAllocation,\n totalPnl: agg.totalPnlUsd + unrealizedPnl - runningFees + hedgeRealized + hedgeUnrealized,\n totalRoundTrips: agg.totalRoundTrips,\n openFillCount,\n paused: s.paused,\n });\n }\n }\n\n // Progress (10% increments)\n if (cycleCount % decileSize === 0) {\n if (opts.verbose) {\n originalConsoleError(` [backtest] ${Math.round((cycleCount / totalSteps) * 100)}% step ${cycleCount}/${totalSteps}`);\n } else {\n process.stderr.write(` [backtest] ${Math.round((cycleCount / totalSteps) * 100)}% step ${cycleCount}/${totalSteps}\\n`);\n }\n }\n }\n } finally {\n console.error = originalConsoleError;\n }\n\n // Build result\n const finalState = portfolio.getState()!;\n const agg = portfolio.aggregateStats(finalState);\n\n const finishedAt = Date.now();\n const runId = makeRunId(opts.fromMs, opts.toMs, opts.config);\n\n const initialPerToken: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n initialPerToken[token] = opts.capital * (opts.config.tokenSplit[token] ?? 0);\n }\n\n // Fee totals from running accumulators (co-evolves with equity curve)\n const totalFeesUsd = Object.values(feesByToken).reduce((a, b) => a + b, 0);\n const totalFills = finalState.grids.reduce((s, g) => s + g.stats.totalFills, 0);\n const avgFeePerFill = totalFills > 0 ? totalFeesUsd / totalFills : 0;\n\n const grossPnl = agg.totalPnlUsd;\n const netPnl = grossPnl - totalFeesUsd;\n\n const hedgeStatus = hedgeEnabled ? hedge.getStatus() : null;\n const hedgePnl = hedgeRealized + hedgeUnrealized;\n const finalNetPnl = netPnl + hedgePnl;\n\n // Per-token rebuild count not preserved separately; total in totals.rebuilds.\n const perToken = finalState.grids.map(g => ({\n token: g.token,\n allocation: { initial: initialPerToken[g.token] ?? 0, final: g.allocation },\n roundTrips: g.stats.totalRoundTrips,\n fills: g.stats.totalFills,\n pnlUsd: g.stats.totalPnlUsd,\n rebuilds: 0,\n }));\n\n const result: BacktestResult = {\n runId,\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n window: {\n fromMs: opts.fromMs,\n toMs: opts.toMs,\n fromIso: new Date(opts.fromMs).toISOString(),\n toIso: new Date(opts.toMs).toISOString(),\n days: (opts.toMs - opts.fromMs) / (24 * 60 * 60 * 1000),\n },\n config: opts.config,\n capital: {\n initialUsd: opts.capital,\n finalUsd: opts.capital + finalNetPnl,\n pnlUsd: finalNetPnl,\n pnlPct: finalNetPnl / opts.capital,\n grossPnlUsd: grossPnl,\n },\n fees: {\n bps: feeBps,\n totalUsd: totalFeesUsd,\n perFill: avgFeePerFill,\n },\n hedge: {\n enabled: hedgeEnabled,\n realizedPnlUsd: hedgeRealized,\n unrealizedPnlUsd: hedgeUnrealized,\n adjustments: hedgeAdjustments,\n finalOpenPositions: hedgeStatus ? hedgeStatus.positions.length : 0,\n },\n liquidations: {\n events: liquidationEvents,\n haltedAt,\n },\n totals: {\n roundTrips: agg.totalRoundTrips,\n fills: finalState.grids.reduce((s, g) => s + g.stats.totalFills, 0),\n rebuilds: totalRebuilds,\n pausedSteps,\n skippedSteps,\n totalSteps: sharedTimestamps.length,\n },\n perToken,\n drawdown: computeDrawdown(equityCurve),\n equityCurve,\n };\n\n // Write JSON output (skip if outPath is empty string)\n if (opts.outPath !== '') {\n const outPath = opts.outPath ?? join(DEFAULT_OUT_DIR, `${runId}.json`);\n await mkdir(dirname(outPath), { recursive: true });\n await writeFile(outPath, JSON.stringify(result, null, 2), 'utf-8');\n }\n\n return result;\n}\n","/**\n * In-memory portfolio for backtest replays.\n *\n * Subclasses GridPortfolio to inherit the live state-shape semantics\n * (initialize, getState, checkPauseThreshold, aggregateStats) while\n * overriding load/save to skip disk I/O and resetDailyStats to use a\n * backtest clock instead of Date.now().\n */\n\nimport { GridPortfolio } from './portfolio.js';\nimport type { GridPortfolioState } from './config.js';\n\nexport class BacktestPortfolio extends GridPortfolio {\n private nowProvider: () => number;\n private inMemoryState: GridPortfolioState | null = null;\n\n constructor(nowProvider: () => number) {\n super();\n this.nowProvider = nowProvider;\n }\n\n /** Override: never read from disk. Returns the in-memory state. */\n override async load(): Promise<GridPortfolioState | null> {\n return this.inMemoryState;\n }\n\n /** Override: never write to disk. Stores the state in memory. */\n override async save(state: GridPortfolioState): Promise<void> {\n this.inMemoryState = state;\n }\n\n /** Override: read in-memory state instead of parent's private field. */\n override getState(): GridPortfolioState | null {\n return this.inMemoryState;\n }\n\n /** Override: use the injected clock instead of Date.now(). */\n override resetDailyStats(state: GridPortfolioState): boolean {\n return super.resetDailyStats(state, this.nowProvider());\n }\n}\n","/**\n * Historical data loader for the grid backtester.\n *\n * Fetches and caches 1-minute and 4-hour candles from Binance's /api/v3/klines\n * endpoint. Pre-computes ATR(14) for the 4-hour series.\n * Cache lives at ~/.sherwood/grid/backtest-cache/.\n */\n\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { TOKEN_TO_COIN } from '../providers/data/hyperliquid.js';\nimport { calculateATR } from '../agent/technical.js';\n\nconst BINANCE_BASE = 'https://api.binance.com/api/v3/klines';\nconst DEFAULT_CACHE_DIR = join(homedir(), '.sherwood', 'grid', 'backtest-cache');\n\nexport interface Bar1m {\n t: number; // open timestamp ms\n o: number;\n h: number;\n l: number;\n c: number;\n v: number;\n}\n\nexport interface AtrPoint {\n ts: number; // 4h bar close timestamp\n atr: number;\n}\n\nexport interface LoadedSeries {\n minutes: Bar1m[];\n fourHour: Bar1m[];\n atrSeries: AtrPoint[];\n}\n\nexport interface HistoricalDataLoaderOpts {\n cacheDir?: string;\n noCache?: boolean;\n /** Injectable for tests. Default: global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nconst FOUR_HOURS_MS = 4 * 60 * 60 * 1000;\nconst ONE_MIN_MS = 60 * 1000;\nconst ATR_PERIOD = 14;\nconst ATR_WARMUP_MS = ATR_PERIOD * FOUR_HOURS_MS;\nconst MAX_BARS_PER_REQUEST = 1000;\n\n/** Maps HL coin symbol → Binance USDT-spot symbol. */\nconst COIN_TO_BINANCE_SYMBOL: Record<string, string> = {\n BTC: 'BTCUSDT',\n ETH: 'ETHUSDT',\n SOL: 'SOLUSDT',\n ARB: 'ARBUSDT',\n LINK: 'LINKUSDT',\n AAVE: 'AAVEUSDT',\n UNI: 'UNIUSDT',\n DOGE: 'DOGEUSDT',\n};\n\nexport class HistoricalDataLoader {\n private cacheDir: string;\n private noCache: boolean;\n private fetchImpl: typeof fetch;\n\n constructor(opts: HistoricalDataLoaderOpts = {}) {\n this.cacheDir = opts.cacheDir ?? DEFAULT_CACHE_DIR;\n this.noCache = opts.noCache ?? false;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n /**\n * Load 1-minute bars and an aligned ATR(14) series for `coinTokenId`\n * (CoinGecko ID; resolved internally to HL coin symbol).\n *\n * The 4-hour series is fetched with ATR_WARMUP_MS extra prefix so ATR\n * is well-defined at fromMs.\n */\n async load(coinTokenId: string, fromMs: number, toMs: number): Promise<LoadedSeries> {\n const coin = TOKEN_TO_COIN[coinTokenId];\n if (!coin) throw new Error(`Unknown token: ${coinTokenId}`);\n\n const minutes = await this.loadInterval(coin, '1m', fromMs, toMs);\n if (minutes.length === 0) {\n throw new Error(`no data for ${coinTokenId} in window — check symbol mapping or date range`);\n }\n\n const fourHour = await this.loadInterval(coin, '4h', fromMs - ATR_WARMUP_MS, toMs);\n const atrSeries = computeAtrSeries(fourHour);\n\n return { minutes, fourHour, atrSeries };\n }\n\n /** Fetch + cache one interval. Public for unit testing. */\n async loadInterval(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n ): Promise<Bar1m[]> {\n if (!this.noCache) {\n const cached = await this.tryReadCache(coin, interval, fromMs, toMs);\n if (cached) return cached;\n }\n\n const fresh = await this.fetchPaginated(coin, interval, fromMs, toMs);\n if (!this.noCache && fresh.length > 0) {\n await this.writeCache(coin, interval, fromMs, toMs, fresh);\n }\n return fresh;\n }\n\n private async tryReadCache(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n ): Promise<Bar1m[] | null> {\n const path = this.cachePath(coin, interval, fromMs, toMs);\n try {\n const raw = await readFile(path, 'utf-8');\n const parsed = JSON.parse(raw) as { bars: Bar1m[] };\n if (!Array.isArray(parsed.bars)) return null;\n return parsed.bars;\n } catch {\n return null;\n }\n }\n\n private async writeCache(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n bars: Bar1m[],\n ): Promise<void> {\n await mkdir(this.cacheDir, { recursive: true });\n const path = this.cachePath(coin, interval, fromMs, toMs);\n const body = JSON.stringify({\n coin,\n interval,\n fetchedAt: Date.now(),\n bars,\n });\n await writeFile(path, body, 'utf-8');\n }\n\n private cachePath(coin: string, interval: '1m' | '4h', fromMs: number, toMs: number): string {\n return join(this.cacheDir, `${coin}-${interval}-${fromMs}-${toMs}.json`);\n }\n\n /** Paginate Binance klines until we cover [fromMs, toMs]. Dedup on merge. */\n private async fetchPaginated(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n ): Promise<Bar1m[]> {\n const intervalMs = interval === '1m' ? ONE_MIN_MS : FOUR_HOURS_MS;\n const pageSpanMs = MAX_BARS_PER_REQUEST * intervalMs;\n const seen = new Set<number>();\n const all: Bar1m[] = [];\n\n let cursor = fromMs;\n while (cursor < toMs) {\n const pageEnd = Math.min(cursor + pageSpanMs, toMs);\n const page = await this.fetchPageWithRetry(coin, interval, cursor, pageEnd);\n if (page.length === 0) break;\n\n for (const bar of page) {\n if (!seen.has(bar.t)) {\n seen.add(bar.t);\n all.push(bar);\n }\n }\n // Advance cursor to one interval past the last bar to avoid re-fetching\n const last = page[page.length - 1]!;\n const next = last.t + intervalMs;\n if (next <= cursor) break; // safety: HL returned older bars than requested\n cursor = next;\n }\n\n all.sort((a, b) => a.t - b.t);\n return all;\n }\n\n private async fetchPageWithRetry(\n coin: string,\n interval: '1m' | '4h',\n startTime: number,\n endTime: number,\n ): Promise<Bar1m[]> {\n const delays = [1000, 2000, 4000];\n let lastErr: Error | null = null;\n for (let attempt = 0; attempt < delays.length + 1; attempt++) {\n try {\n return await this.fetchPage(coin, interval, startTime, endTime);\n } catch (err) {\n lastErr = err as Error;\n if (attempt < delays.length) {\n await sleep(delays[attempt]!);\n }\n }\n }\n throw lastErr ?? new Error('fetchPage failed');\n }\n\n private async fetchPage(\n coin: string,\n interval: '1m' | '4h',\n startTime: number,\n endTime: number,\n ): Promise<Bar1m[]> {\n const symbol = COIN_TO_BINANCE_SYMBOL[coin];\n if (!symbol) throw new Error(`No Binance symbol for coin: ${coin}`);\n\n const url = `${BINANCE_BASE}?symbol=${symbol}&interval=${interval}` +\n `&startTime=${startTime}&endTime=${endTime}&limit=${MAX_BARS_PER_REQUEST}`;\n const res = await this.fetchImpl(url);\n if (!res.ok) throw new Error(`Binance ${res.status}: ${await res.text()}`);\n\n const raw = await res.json() as Array<[\n number, string, string, string, string, string, ...unknown[]\n ]>;\n if (!Array.isArray(raw)) return [];\n\n return raw.map(c => ({\n t: c[0],\n o: Number(c[1]),\n h: Number(c[2]),\n l: Number(c[3]),\n c: Number(c[4]),\n v: Number(c[5]),\n })).filter(b =>\n Number.isFinite(b.o) && Number.isFinite(b.h) && Number.isFinite(b.l) && Number.isFinite(b.c)\n );\n }\n}\n\nfunction computeAtrSeries(fourHourBars: Bar1m[]): AtrPoint[] {\n if (fourHourBars.length < ATR_PERIOD) return [];\n\n const candles = fourHourBars.map(b => ({\n timestamp: b.t,\n open: b.o,\n high: b.h,\n low: b.l,\n close: b.c,\n volume: b.v,\n }));\n\n const atrArr = calculateATR(candles, ATR_PERIOD);\n const out: AtrPoint[] = [];\n for (let i = 0; i < atrArr.length; i++) {\n if (Number.isFinite(atrArr[i]!)) {\n out.push({ ts: fourHourBars[i]!.t, atr: atrArr[i]! });\n }\n }\n return out;\n}\n\n/** Lookup ATR at backtest time `t`. Binary-search; returns last value with ts ≤ t.\n * Returns null if t is before the first available ATR (warmup not satisfied). */\nexport function lookupAtr(series: AtrPoint[], t: number): number | null {\n if (series.length === 0 || t < series[0]!.ts) return null;\n let lo = 0, hi = series.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (series[mid]!.ts <= t) lo = mid; else hi = mid - 1;\n }\n return series[lo]!.atr;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","/**\n * In-memory hedge manager for backtest replays.\n *\n * Subclasses GridHedgeManager so the live tick() logic is reused verbatim;\n * only state I/O and the clock are redirected — load() returns an in-memory\n * state initialized with a backtest-driven `lastDailyReset`, and save() is\n * a no-op.\n */\n\nimport { GridHedgeManager, type HedgeState } from './hedge.js';\n\nexport class BacktestHedgeManager extends GridHedgeManager {\n private nowProvider: () => number;\n private inMemoryState: HedgeState | null = null;\n\n constructor(nowProvider: () => number) {\n super();\n this.nowProvider = nowProvider;\n }\n\n override async load(_now?: number): Promise<HedgeState> {\n if (this.inMemoryState) {\n // Manual daily-reset using injected clock\n const now = this.nowProvider();\n const todayMidnight = new Date(now);\n todayMidnight.setUTCHours(0, 0, 0, 0);\n if (this.inMemoryState.lastDailyReset < todayMidnight.getTime()) {\n this.inMemoryState.todayRealizedPnl = 0;\n this.inMemoryState.lastDailyReset = now;\n }\n // Keep parent's `state` field in sync so getStatus() works.\n (this as unknown as { state: HedgeState | null }).state = this.inMemoryState;\n return this.inMemoryState;\n }\n const now = this.nowProvider();\n this.inMemoryState = {\n positions: [],\n totalRealizedPnl: 0,\n todayRealizedPnl: 0,\n lastDailyReset: now,\n };\n (this as unknown as { state: HedgeState | null }).state = this.inMemoryState;\n return this.inMemoryState;\n }\n\n override async save(): Promise<void> {\n // no-op: state stays in memory\n }\n}\n","/**\n * Parameter sweep for the grid backtester.\n *\n * Runs runBacktest over a Cartesian product of parameter values, sharing\n * one HistoricalDataLoader so the data is fetched once. Useful for\n * comparing leverage / level count / ATR multiplier / drift trade-offs\n * over the same window.\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { createHash } from 'node:crypto';\nimport { runBacktest, type BacktestResult } from './backtest.js';\nimport { HistoricalDataLoader } from './historical-data-loader.js';\nimport { DEFAULT_GRID_CONFIG, type GridConfig } from './config.js';\n\nconst DEFAULT_SWEEP_DIR = join(homedir(), '.sherwood', 'grid', 'sweeps');\n\nexport type SweepableField = 'leverage' | 'levelsPerSide' | 'atrMultiplier' | 'rebalanceDriftPct';\n\nexport interface SweepOpts {\n fromMs: number;\n toMs: number;\n capital: number;\n tokens: string[];\n /** Optional explicit token weights (must sum to 1.0). Defaults to equal weight. */\n tokenSplit?: Record<string, number>;\n /** Base config; sweep params override per run. tokenSplit auto-computed. */\n baseConfig?: Partial<GridConfig>;\n /** Map of sweepable field name → list of values to try. Empty list means use base value. */\n sweep: Partial<Record<SweepableField, number[]>>;\n /** Trading fee bps. Default 5. */\n feeBps?: number;\n /** Output dir for sweep result + per-run files. */\n outDir?: string;\n /** Skip cache for HL fetches. */\n noCache?: boolean;\n /** Print progress per run. Default true. */\n verbose?: boolean;\n}\n\nexport interface SweepRunSummary {\n index: number;\n config: Partial<Record<SweepableField, number>>;\n runId: string;\n resultPath: string;\n capital: { initialUsd: number; finalUsd: number; pnlUsd: number; pnlPct: number; grossPnlUsd: number };\n fees: { bps: number; totalUsd: number };\n totals: { roundTrips: number; fills: number; pausedSteps: number };\n drawdown: { maxUsd: number; maxPct: number };\n /** Net PnL pct divided by max(abs(drawdown pct), 1). Higher = better risk-adjusted. */\n riskAdjusted: number;\n /** True if no full liquidation halt occurred. Per-token liquidations still count as survived if not all tokens died. */\n survived: boolean;\n durationMs: number;\n}\n\nexport interface SweepResult {\n sweepId: string;\n startedAt: number;\n finishedAt: number;\n durationMs: number;\n window: { fromMs: number; toMs: number; days: number };\n tokens: string[];\n capital: number;\n feeBps: number;\n /** Cartesian-product run summaries, sorted by riskAdjusted desc. */\n runs: SweepRunSummary[];\n}\n\n/** Build the Cartesian product of parameter combinations. */\nexport function expandSweep(\n sweep: Partial<Record<SweepableField, number[]>>,\n base: Pick<GridConfig, 'leverage' | 'levelsPerSide' | 'atrMultiplier' | 'rebalanceDriftPct'>,\n): Array<Record<SweepableField, number>> {\n const fields: SweepableField[] = ['leverage', 'levelsPerSide', 'atrMultiplier', 'rebalanceDriftPct'];\n const valueLists: Record<SweepableField, number[]> = {\n leverage: sweep.leverage && sweep.leverage.length > 0 ? sweep.leverage : [base.leverage],\n levelsPerSide: sweep.levelsPerSide && sweep.levelsPerSide.length > 0 ? sweep.levelsPerSide : [base.levelsPerSide],\n atrMultiplier: sweep.atrMultiplier && sweep.atrMultiplier.length > 0 ? sweep.atrMultiplier : [base.atrMultiplier],\n rebalanceDriftPct: sweep.rebalanceDriftPct && sweep.rebalanceDriftPct.length > 0 ? sweep.rebalanceDriftPct : [base.rebalanceDriftPct],\n };\n let combos: Array<Record<SweepableField, number>> = [{} as Record<SweepableField, number>];\n for (const field of fields) {\n const next: Array<Record<SweepableField, number>> = [];\n for (const combo of combos) {\n for (const value of valueLists[field]) {\n next.push({ ...combo, [field]: value });\n }\n }\n combos = next;\n }\n return combos;\n}\n\nfunction makeSweepId(opts: SweepOpts): string {\n const d = new Date();\n const pad = (n: number) => n.toString().padStart(2, '0');\n const stamp = `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}-${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`;\n const hash = createHash('sha256').update(JSON.stringify({\n fromMs: opts.fromMs, toMs: opts.toMs, sweep: opts.sweep, tokens: opts.tokens,\n })).digest('hex').slice(0, 8);\n return `sw-${stamp}-${hash}`;\n}\n\nexport async function runSweep(opts: SweepOpts): Promise<SweepResult> {\n const startedAt = Date.now();\n const sweepId = makeSweepId(opts);\n const outDir = opts.outDir ?? DEFAULT_SWEEP_DIR;\n const sweepDir = join(outDir, sweepId);\n\n // Build tokenSplit (explicit or equal-weight)\n let tokenSplit: Record<string, number>;\n if (opts.tokenSplit) {\n tokenSplit = opts.tokenSplit;\n } else {\n const weight = 1 / opts.tokens.length;\n tokenSplit = {};\n for (const t of opts.tokens) tokenSplit[t] = weight;\n }\n\n // Base config\n const base: GridConfig = {\n ...DEFAULT_GRID_CONFIG,\n ...opts.baseConfig,\n tokens: opts.tokens,\n tokenSplit,\n };\n\n const combos = expandSweep(opts.sweep, base);\n if (combos.length === 0) throw new Error('sweep produced no combinations');\n\n // Share one loader (shared cache)\n const loader = new HistoricalDataLoader({ noCache: opts.noCache });\n\n if (opts.verbose !== false) {\n process.stderr.write(` [sweep] ${sweepId}: running ${combos.length} backtests…\\n`);\n }\n\n await mkdir(sweepDir, { recursive: true });\n\n const runs: SweepRunSummary[] = [];\n for (let i = 0; i < combos.length; i++) {\n const combo = combos[i]!;\n const config: GridConfig = { ...base, ...combo };\n const runOutPath = join(sweepDir, `run-${i.toString().padStart(3, '0')}.json`);\n\n if (opts.verbose !== false) {\n process.stderr.write(` [sweep] [${i + 1}/${combos.length}] ${JSON.stringify(combo)}\\n`);\n }\n\n const result: BacktestResult = await runBacktest({\n fromMs: opts.fromMs,\n toMs: opts.toMs,\n capital: opts.capital,\n config,\n loader,\n noCache: opts.noCache,\n feeBps: opts.feeBps,\n outPath: runOutPath,\n });\n\n const ddPct = Math.abs(result.drawdown.maxPct * 100);\n const pnlPct = result.capital.pnlPct * 100;\n const riskAdjusted = pnlPct / Math.max(ddPct, 1);\n const survived = result.liquidations.haltedAt === null;\n\n runs.push({\n index: i,\n config: combo,\n runId: result.runId,\n resultPath: runOutPath,\n capital: result.capital,\n fees: { bps: result.fees.bps, totalUsd: result.fees.totalUsd },\n totals: {\n roundTrips: result.totals.roundTrips,\n fills: result.totals.fills,\n pausedSteps: result.totals.pausedSteps,\n },\n drawdown: result.drawdown,\n riskAdjusted,\n survived,\n durationMs: result.durationMs,\n });\n }\n\n runs.sort((a, b) => {\n // Survivors first\n if (a.survived !== b.survived) return a.survived ? -1 : 1;\n // Then by risk-adjusted desc\n return b.riskAdjusted - a.riskAdjusted;\n });\n\n const finishedAt = Date.now();\n const sweep: SweepResult = {\n sweepId,\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n window: {\n fromMs: opts.fromMs,\n toMs: opts.toMs,\n days: (opts.toMs - opts.fromMs) / (24 * 60 * 60 * 1000),\n },\n tokens: opts.tokens,\n capital: opts.capital,\n feeBps: opts.feeBps ?? 5,\n runs,\n };\n\n const sweepJsonPath = join(sweepDir, 'sweep.json');\n await writeFile(sweepJsonPath, JSON.stringify(sweep, null, 2), 'utf-8');\n\n return sweep;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,UAAU,kBAAkB;AAErC,SAAS,qBAAqB;AAQ9B,SAAS,SAAS,cAAc;AAChC,SAAS,cAAAA,aAAY,eAAAC,cAAa,aAAAC,kBAAiB;AAEnD,OAAOC,aAAW;AAClB,OAAOC,UAAS;AAChB,SAAS,OAAO,SAAS,cAAc;;;ACbvC,SAAS,MAAM,mBAAmB;AAI3B,IAAM,mBAAN,MAAkD;AAAA,EACvD,OAAqB;AACnB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,MAAM;AAAA,MACN,cAAc;AAAA,QACZ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,iBAAiB,CAAC,MAAM,WAAW;AAAA,IACrC;AAAA,EACF;AAAA,EAEA,MAAM,kBAAkB,QAA0C;AAEhE,UAAM,IAAI,MAAM,4CAAuC;AAAA,EACzD;AAAA,EAEA,MAAM,OAAO,QAAyC;AACpD,UAAM,IAAI,MAAM,iBAAiB;AAAA,EACnC;AAAA,EAEA,MAAM,MAAM,QAAwC;AAClD,UAAM,IA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E;AACrE,UAAQ,IAAI,iBAAiB,UAAU,SAASA,QAAM,IAAI,SAAS,CAAC,EAAE;AACtE,UAAQ,IAAI,iBAAiB,iBAAiB,IAAIA,QAAM,MAAM,oBAAoB,IAAIA,QAAM,IAAI,SAAS,CAAC,EAAE;AAC5G,UAAQ,IAAI,iBAAiB,gBAAgB,IAAIA,QAAM,MAAM,oBAAoB,IAAIA,QAAM,IAAI,SAAS,CAAC,EAAE;AAG3G,QAAM,eAAe,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC;AAChF,MAAI,aAAa,SAAS,GAAG;AAC3B,YAAQ,IAAI;AACZ,YAAQ,IAAIA,QAAM,KAAK,eAAe,CAAC;AACvC,eAAW,CAAC,KAAK,GAAG,KAAK,cAAc;AACrC,cAAQ,IAAI,OAAO,GAAG,KAAKA,QAAM,KAAK,GAAG,CAAC,EAAE;AAAA,IAC9C;AAAA,EACF;AAEA,UAAQ,IAAI;AACZ,UAAQ,IAAIA,QAAM,IAAI,wCAAwC,CAAC;AAC/D,UAAQ,IAAI;AACd,CAAC;AAEH,QAAQ,MAAM;","names":["parseUnits","formatUnits","isAddress","chalk","ora","formatUnits","isAddress","encodeAbiParameters","SYNDICATE_VAULT_ABI","ERC20_ABI","ERC20_ABI","SYNDICATE_VAULT_ABI","SYNDICATE_VAULT_ABI","SYNDICATE_VAULT_ABI","encodeFunctionData","getAddress","ZERO_VALUE","encodeFunctionData","ZERO_ADDRESS","getAddress","strategy","encodeFunctionData","encodeFunctionData","getAddress","ZERO_VALUE","getAddress","encodeFunctionData","encodeFunctionData","getAddress","ZERO_ADDRESS","ZERO_VALUE","getAddress","encodeFunctionData","encodeFunctionData","getAddress","ZERO_ADDRESS","registry","getAddress","encodeFunctionData","encodeAbiParameters","encodeFunctionData","getAddress","ZERO_ADDRESS","ZERO_BYTES32","getAddress","encodeFunctionData","encodeAbiParameters","encodeFunctionData","getAddress","ZERO_VALUE","registry","encodeFunctionData","getAddress","getAddress","encodeAbiParameters","encodeFunctionData","encodeAbiParameters","encodeFunctionData","encodeAbiParameters","encodeFunctionData","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","INIT_PARAMS_TYPES","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","maxUint256","INIT_PARAMS_TYPES","buildInitData","encodeAbiParameters","buildExecuteCalls","maxUint256","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","maxUint256","buildInitData","encodeAbiParameters","buildExecuteCalls","maxUint256","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","maxUint256","buildInitData","encodeAbiParameters","buildExecuteCalls","maxUint256","encodeFunctionData","buildSettleCalls","concat","encodeAbiParameters","encoded","buildInitData","isAddress","buildExecuteCalls","buildSettleCalls","strategy","unavailable","performanceFeeBps","formatUnits","parseDuration","strategyDuration","executeCalls","settleCalls","propose","getActiveSyndicates","data","formatUnits","isAddress","parseUnits","chalk","ora","program","ora","chalk","formatUnits","getEasScanUrl","parseUnits","isAddress","keccak256","getChainContracts","parseUnits","formatUnits","isAddress","chalk","ora","encodeFunctionData","parseUnits","parseUnits","encodeFunctionData","program","isAddress","chalk","ora","parseUnits","formatUnits","chalk","ora","IDENTITY_REGISTRY_ABI","program","chalk","ora","registry","isAddress","encodeFunctionData","chalk","ora","readFileSync","decodeFunctionData","encodeFunctionData","chalk","erc20Abi","chalk","MOONWELL_CTOKEN_ABI","MOONWELL_COMPTROLLER_ABI","SWAP_ROUTER_SINGLE_ABI","labeledAddr","decodeFunctionData","input","encodeFunctionData","getAccount","G","chalk","W","DIM","BOLD","LABEL","SEP","readFileSync","program","isAddress","strategy","spinner","ora","encodeFunctionData","resolve","chalk","ora","G","chalk","W","DIM","BOLD","LABEL","SEP","ora","program","chalk","ora","formatUnits","isAddress","parseUnits","G","chalk","W","DIM","BOLD","LABEL","SEP","GUARDIAN_REGISTRY_ABI","ERC20_ABI","ora","program","isAddress","formatUnits","parseUnits","chalk","createInterface","chalk","mkdir","dirname","chalk","resolve","chalk","readFile","writeFile","mkdir","dirname","chalk","readFile","mkdir","dirname","writeFile","rename","chalk","chalk","chalk","mkdir","readFile","rename","writeFile","dirname","encodeAbiParameters","parseUnits","keccak256","encodeAbiParameters","strategy","size","readFile","chalk","mkdir","dirname","writeFile","rename","parseUnits","encodeAbiParameters","chalk","resolve","mkdir","dirname","stats","writeFile","mkdir","join","dirname","homedir","readFile","writeFile","mkdir","join","homedir","join","homedir","readFile","mkdir","writeFile","resolve","now","join","homedir","input","agg","mkdir","dirname","writeFile","writeFile","mkdir","join","homedir","createHash","join","homedir","base","createHash","mkdir","writeFile","DIM","chalk","G","BOLD","W","SEP","program","createInterface","require","G","chalk","W","DIM","BOLD","LABEL","SEP","isAddress","spinner","ora","chainId","refParam","getActiveSyndicates","AGENT_REGISTRY","registry","syndicate","referrerAgentId","parseUnits","formatUnits"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/providers/moonwell.ts","../src/commands/strategy-template.ts","../src/lib/clone.ts","../src/lib/tokens.ts","../src/grid/strategy-abi.ts","../src/lib/batch.ts","../src/lib/calldata.ts","../../sdk/dist/types.js","../../sdk/dist/errors.js","../../sdk/dist/abis.js","../../sdk/dist/addresses.js","../../sdk/dist/encoders/vault.js","../../sdk/dist/encoders/governor.js","../../sdk/dist/encoders/factory.js","../../sdk/dist/encoders/strategy.js","../../sdk/dist/encoders/identity.js","../../sdk/dist/encoders/eas.js","../../sdk/dist/encoders/guardian.js","../../sdk/dist/reads/syndicates.js","../src/strategies/moonwell-supply-template.ts","../src/strategies/venice-inference-template.ts","../src/strategies/aerodrome-lp-template.ts","../src/strategies/wsteth-moonwell-template.ts","../src/strategies/mamo-yield-template.ts","../src/strategies/portfolio-template.ts","../src/strategies/hyperliquid-perp-template.ts","../src/strategies/hyperliquid-grid-template.ts","../src/lib/subgraph.ts","../src/commands/venice.ts","../src/commands/allowance.ts","../src/strategies/allowance-disburse.ts","../src/commands/identity.ts","../src/commands/proposal.ts","../src/lib/format.ts","../src/lib/simulate.ts","../src/lib/risk.ts","../src/commands/governor.ts","../src/commands/guardian-delegate.ts","../src/commands/grid.ts","../src/grid/loop.ts","../src/grid/manager.ts","../src/grid/portfolio.ts","../src/grid/paths.ts","../src/grid/config.ts","../src/grid/hedge.ts","../src/grid/executor.ts","../src/grid/onchain-executor.ts","../src/grid/cloid.ts","../src/grid/backtest.ts","../src/grid/backtest-portfolio.ts","../src/grid/historical-data-loader.ts","../src/grid/backtest-hedge.ts","../src/grid/sweep.ts"],"sourcesContent":["#!/usr/bin/env node\n// Load .env if present (dev convenience — production uses ~/.sherwood/config.json)\nimport { config as loadDotenv } from \"dotenv\";\ntry { loadDotenv(); } catch {};\nimport { createRequire } from \"node:module\";\nconst require = createRequire(import.meta.url);\n// `CLI_VERSION_BUILD` is injected by tsup at build time (see tsup.config.ts) so\n// the bundled/standalone binary never reads ../package.json at runtime — that\n// path is unresolvable inside bun's compiled virtual filesystem and crashes the\n// binary on startup. The require fallback keeps `tsx src/index.ts` (dev) working.\nconst CLI_VERSION: string =\n process.env.CLI_VERSION_BUILD || require(\"../package.json\").version;\nimport { Command, Option } from \"commander\";\nimport { parseUnits, formatUnits, isAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { input, confirm, select } from \"@inquirer/prompts\";\nimport { setNetwork, getNetwork, VALID_NETWORKS, withNetwork } from \"./lib/network.js\";\nimport { getExplorerUrl, getChain } from \"./lib/network.js\";\nimport type { Network } from \"./lib/network.js\";\nimport { TOKENS } from \"./lib/addresses.js\";\nimport { getPublicClient, getAccount, formatContractError } from \"./lib/client.js\";\nimport { ERC20_ABI } from \"./lib/abis.js\";\nimport { MoonwellProvider } from \"./providers/moonwell.js\";\nimport { UniswapProvider } from \"./providers/uniswap.js\";\nimport { registerStrategyTemplateCommands } from \"./commands/strategy-template.js\";\nimport * as vaultLib from \"./lib/vault.js\";\nimport * as factoryLib from \"./lib/factory.js\";\nimport * as subgraphLib from \"./lib/subgraph.js\";\n// registryLib removed — strategy registry is deprecated, replaced by template commands\nimport { uploadMetadata } from \"./lib/ipfs.js\";\nimport type { SyndicateMetadata } from \"./lib/ipfs.js\";\nimport { registerVeniceCommands } from \"./commands/venice.js\";\nimport { registerAllowanceCommands } from \"./commands/allowance.js\";\nimport { registerIdentityCommands } from \"./commands/identity.js\";\nimport { registerProposalCommands } from \"./commands/proposal.js\";\nimport { registerGovernorCommands } from \"./commands/governor.js\";\nimport { registerGuardianCommands } from \"./commands/guardian-delegate.js\";\nimport { setTextRecord, getTextRecord, resolveVaultSyndicate, resolveSyndicate, searchSyndicateAcrossChains } from \"./lib/ens.js\";\nimport * as easLib from \"./lib/eas.js\";\nimport { EAS_SCHEMAS } from \"./lib/addresses.js\";\nimport {\n setCalldataOnly,\n isCalldataOnly,\n emitCalldata,\n} from \"./lib/calldata.js\";\nimport {\n encodeIdentityMint,\n encodeJoinRequest,\n encodeApproveAgent,\n encodeDeposit,\n encodeRedeem,\n encodeCreateSyndicate,\n encodeApproveDepositor,\n encodeRegisterAgent,\n type ChainId,\n} from \"@sherwoodagent/sdk\";\n\n// XMTP shells out to @xmtp/cli binary — lazy-load to avoid breaking\n// non-chat commands if the CLI is not installed.\nasync function loadXmtp() {\n return import(\"./lib/xmtp.js\");\n}\n// Lazy-load cron module (only needed for openclaw agents)\nasync function loadCron() {\n return import(\"./lib/cron.js\");\n}\nimport { cacheGroupId, getCachedGroupId, setChainContract, getChainContracts, loadConfig, setPrivateKey, getAgentId, setConfigRpcUrl, getNotifyTo, setNotifyTo, setUniswapApiKey, getUniswapApiKey, setVeniceApiKey, getVeniceApiKey, setAnthropicApiKey, addSyndicate, getSyndicates, setPrimarySyndicate, getPrimarySyndicate } from \"./lib/config.js\";\nimport { isTestnet } from \"./lib/network.js\";\n\n// ── Theme ──\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\nfunction validateAddress(value: string, name: string): Address {\n if (!isAddress(value)) {\n console.error(chalk.red(`Invalid ${name} address: ${value}`));\n process.exit(1);\n }\n return value as Address;\n}\n\n/** Set vault address from --vault flag or fall back to config. */\nfunction resolveVault(opts: { vault?: string }) {\n if (opts.vault) {\n vaultLib.setVaultAddress(validateAddress(opts.vault, \"vault\"));\n }\n // If no --vault flag, getVaultAddress() in vault.ts reads from config\n}\n\nconst program = new Command();\n\nprogram\n .name(\"sherwood\")\n .description(\"CLI for agent-managed investment syndicates\")\n .version(CLI_VERSION)\n .addOption(\n new Option(\"--chain <network>\", \"Target network\")\n .choices(VALID_NETWORKS)\n .default(\"base\"),\n )\n .option(\"--testnet\", \"Alias for --chain base-sepolia (deprecated)\", false)\n .option(\n \"--calldata-only\",\n \"Print unsigned EIP-5792 calldata as JSON instead of signing/sending (for external signers — no private key required)\",\n false,\n )\n .hook(\"preAction\", (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n setCalldataOnly(Boolean(opts.calldataOnly));\n let network: string = opts.chain;\n if (opts.testnet) {\n process.env.ENABLE_TESTNET = \"true\";\n if (network !== \"base\") {\n console.warn(\n chalk.yellow(\"[warn] --testnet ignored, --chain takes precedence\"),\n );\n } else {\n network = \"base-sepolia\";\n }\n }\n setNetwork(network as Network);\n if (getNetwork() !== \"base\") {\n console.log(chalk.yellow(`[${getNetwork()}]`));\n }\n });\n\n// ── Syndicate commands ──\nconst syndicate = program.command(\"syndicate\");\n\nsyndicate\n .command(\"create\")\n .description(\"Create a new syndicate via the factory (interactive)\")\n .option(\"--subdomain <name>\", \"ENS subdomain (skip prompt)\")\n .option(\"--name <name>\", \"Syndicate name (skip prompt)\")\n .option(\"--agent-id <id>\", \"ERC-8004 agent identity token ID (skip prompt)\")\n .option(\"--asset <symbol-or-address>\", \"Vault asset: USDC, WETH, or a token address\")\n .option(\"--description <text>\", \"Short description\")\n .option(\"--metadata-uri <uri>\", \"Override metadata URI (skip IPFS upload)\")\n .option(\"--open-deposits\", \"Allow anyone to deposit (default: whitelist only)\")\n .option(\"--public-chat\", \"Enable dashboard spectator mode\", false)\n .option(\"-y, --yes\", \"Skip confirmation prompt (non-interactive mode)\", false)\n .action(async (opts) => {\n try {\n // ── Header ──\n console.log();\n console.log(LABEL(\" ◆ Create Syndicate\"));\n SEP();\n\n // --calldata-only has no wallet to display (no private key); show network only.\n if (!isCalldataOnly()) {\n const wallet = getAccount();\n console.log(DIM(` Wallet: ${wallet.address}`));\n }\n console.log(DIM(` Network: ${getChain().name}`));\n SEP();\n\n // ── Gather inputs (prompt if not provided via flags) ──\n\n const savedAgentId = getAgentId();\n\n const nonInteractive = opts.yes;\n\n const name = opts.name || (nonInteractive\n ? (() => { throw new Error(\"--name is required in non-interactive mode (-y)\"); })()\n : await input({\n message: G(\"Syndicate name\"),\n validate: (v: string) => v.length > 0 || \"Name is required\",\n }));\n\n const subdomain = opts.subdomain || (nonInteractive\n ? name.toLowerCase().replace(/\\s+/g, \"-\").replace(/[^a-z0-9-]/g, \"\")\n : await input({\n message: G(\"ENS subdomain\"),\n default: name.toLowerCase().replace(/\\s+/g, \"-\").replace(/[^a-z0-9-]/g, \"\"),\n validate: (v: string) => v.length >= 3 || \"Must be at least 3 characters\",\n }));\n\n const description = opts.description || (nonInteractive\n ? `${name} — a Sherwood syndicate`\n : await input({\n message: G(\"Description\"),\n default: `${name} — a Sherwood syndicate`,\n }));\n\n const agentIdStr = opts.agentId || (savedAgentId\n ? (nonInteractive\n ? String(savedAgentId)\n : await input({ message: G(\"Agent ID (ERC-8004)\"), default: String(savedAgentId) }))\n : (nonInteractive\n ? \"0\"\n : await input({ message: G(\"Agent ID (ERC-8004)\"), validate: (v: string) => /^\\d+$/.test(v) || \"Must be a number\" }))\n );\n\n const openDeposits = opts.openDeposits !== undefined ? opts.openDeposits : (nonInteractive\n ? false\n : await confirm({\n message: G(\"Open deposits? (anyone can deposit, no whitelist)\"),\n default: false,\n }));\n\n // ── Resolve asset ──\n // Supported symbols (testnet + mainnet). Will expand on mainnet launch.\n const ASSET_SYMBOLS: Record<string, Address> = {\n USDC: TOKENS().USDC,\n WETH: TOKENS().WETH,\n };\n\n let asset: Address;\n if (opts.asset) {\n const upper = opts.asset.toUpperCase();\n if (ASSET_SYMBOLS[upper]) {\n asset = ASSET_SYMBOLS[upper];\n } else if (opts.asset.startsWith(\"0x\") && opts.asset.length === 42) {\n asset = opts.asset as Address;\n } else {\n const supported = Object.keys(ASSET_SYMBOLS).join(\", \");\n console.error(chalk.red(` Unknown asset \"${opts.asset}\". Use a symbol (${supported}) or a 0x address.`));\n process.exit(1);\n }\n } else if (nonInteractive) {\n // Default to WETH on chains without USDC, otherwise USDC\n asset = TOKENS().USDC !== \"0x0000000000000000000000000000000000000000\"\n ? ASSET_SYMBOLS.USDC\n : ASSET_SYMBOLS.WETH;\n } else {\n // Interactive prompt\n const assetChoice = await select({\n message: G(\"Vault asset (what token do depositors provide?)\"),\n choices: [\n { name: \"USDC\", value: \"USDC\", description: \"USD Coin (6 decimals)\" },\n { name: \"WETH\", value: \"WETH\", description: \"Wrapped Ether (18 decimals)\" },\n ],\n });\n asset = ASSET_SYMBOLS[assetChoice];\n }\n\n const publicClient = getPublicClient();\n const [decimals, assetSymbol] = await Promise.all([\n publicClient.readContract({ address: asset, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n publicClient.readContract({ address: asset, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n ]);\n const symbol = `sw${assetSymbol}`;\n\n // ── Confirmation ──\n console.log();\n console.log(LABEL(\" ◆ Review\"));\n SEP();\n console.log(W(` Name: ${BOLD(name)}`));\n console.log(W(` ENS: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Description: ${DIM(description)}`));\n console.log(W(` Agent ID: #${agentIdStr}`));\n console.log(W(` Asset: ${assetSymbol} (${asset.slice(0, 10)}...)`));\n console.log(W(` Share token: ${symbol}`));\n console.log(W(` Open deposits: ${openDeposits ? chalk.yellow(\"yes (anyone can deposit)\") : G(\"no (whitelist)\")}`));\n SEP();\n\n if (!nonInteractive) {\n const go = await confirm({ message: G(\"Deploy syndicate?\"), default: true });\n if (!go) {\n console.log(DIM(\" Cancelled.\"));\n return;\n }\n }\n\n // ── Upload metadata to IPFS ──\n let metadataURI = opts.metadataUri || \"\";\n\n if (!metadataURI) {\n const spinner = ora({ text: W(\"Uploading metadata to IPFS...\"), color: \"green\" }).start();\n try {\n const metadata: SyndicateMetadata = {\n schema: \"sherwood/syndicate/v1\",\n name,\n description,\n chain: getChain().name,\n strategies: [],\n terms: {\n feeModel: \"none\",\n },\n links: {},\n };\n metadataURI = await uploadMetadata(metadata);\n spinner.succeed(G(`Metadata pinned: ${DIM(metadataURI)}`));\n } catch (err) {\n spinner.warn(chalk.yellow(`IPFS upload failed — using inline metadata`));\n const json = JSON.stringify({ name, description, subdomain, asset: assetSymbol, openDeposits, createdBy: \"@sherwoodagent/cli\" });\n metadataURI = `data:application/json;base64,${Buffer.from(json).toString(\"base64\")}`;\n }\n }\n\n // --calldata-only: emit the unsigned createSyndicate calldata and stop,\n // before the subdomain idempotency check (which reads getAccount()).\n // Owner-stake bonding (guardianRegistry.prepareOwnerStake) is a separate\n // prerequisite — see the action note.\n if (isCalldataOnly()) {\n emitCalldata(\n encodeCreateSyndicate(\n {\n creatorAgentId: agentIdStr,\n metadataURI,\n asset,\n name,\n symbol,\n openDeposits,\n subdomain,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n // ── Idempotent check: resume if subdomain already exists ──\n const existingId = await factoryLib.subdomainExists(subdomain);\n if (existingId !== null) {\n const existingInfo = await factoryLib.getSyndicate(existingId);\n const callerAddress = getAccount().address.toLowerCase();\n\n if (existingInfo.creator.toLowerCase() !== callerAddress) {\n console.error(chalk.red(`\\n ✖ Subdomain '${subdomain}' is already taken by another syndicate.\\n`));\n process.exit(1);\n }\n\n // Partial completion — creator already deployed, resume post-deploy steps\n console.log(chalk.yellow(`\\n ⚠ Syndicate '${subdomain}' already exists — resuming setup...\\n`));\n\n const spinner = ora({ text: W(\"Resuming setup...\"), color: \"green\" }).start();\n\n // Save to config\n const chainId = getChain().id;\n setChainContract(chainId, \"vault\", existingInfo.vault);\n addSyndicate(chainId, { subdomain, vault: existingInfo.vault, role: \"creator\" });\n setPrimarySyndicate(chainId, subdomain);\n\n // Register creator as agent (if not already)\n spinner.text = W(\"Checking agent registration...\");\n try {\n vaultLib.setVaultAddress(existingInfo.vault);\n const isAlreadyAgent = await vaultLib.isAgent(getAccount().address);\n if (!isAlreadyAgent) {\n spinner.text = W(\"Registering creator as agent...\");\n await vaultLib.registerAgent(BigInt(agentIdStr), getAccount().address);\n }\n } catch { /* non-fatal */ }\n\n // Create XMTP group (if not already)\n spinner.text = W(\"Checking chat group...\");\n try {\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n try {\n await xmtp.getGroup(xmtpClient, subdomain);\n // Group exists, skip\n } catch {\n // No group — create one\n spinner.text = W(\"Creating chat group...\");\n const groupId = await xmtp.createSyndicateGroup(xmtpClient, subdomain, opts.publicChat);\n await setTextRecord(subdomain, \"xmtpGroupId\", groupId, existingInfo.vault as Address);\n cacheGroupId(subdomain, groupId);\n }\n } catch {\n console.warn(chalk.yellow(\"\\n ⚠ Could not set up XMTP chat group\"));\n }\n\n // Register crons\n try {\n const cron = await loadCron();\n cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n } catch { /* non-fatal */ }\n\n spinner.stop();\n console.log();\n console.log(LABEL(\" ◆ Syndicate Setup Resumed\"));\n SEP();\n console.log(W(` ID: ${G(`#${existingId}`)}`));\n console.log(W(` Vault: ${G(existingInfo.vault)}`));\n console.log(W(` ENS: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Chat: ${DIM(`sherwood chat ${subdomain}`)}`));\n const refParam = getAgentId() ? `?ref=${getAgentId()}` : \"\";\n console.log(W(` Share: ${G(`https://sherwood.sh/syndicate/${subdomain}${refParam}`)}`));\n SEP();\n console.log(G(\" ✓ Syndicate saved to ~/.sherwood/config.json (set as primary)\"));\n console.log();\n return;\n }\n\n // ── Deploy (fresh syndicate) ──\n const spinner = ora({ text: W(\"Deploying vault via factory...\"), color: \"green\" }).start();\n\n const result = await factoryLib.createSyndicate({\n creatorAgentId: BigInt(agentIdStr),\n metadataURI,\n asset,\n name,\n symbol,\n openDeposits,\n subdomain,\n });\n\n // Auto-save vault address + syndicate membership to config\n const chainId = getChain().id;\n setChainContract(chainId, \"vault\", result.vault);\n addSyndicate(chainId, { subdomain, vault: result.vault, role: \"creator\" });\n setPrimarySyndicate(chainId, subdomain);\n\n // ── Register creator as agent on the vault ──\n // Brief delay to let the RPC node sync its nonce after createSyndicate tx\n await new Promise((r) => setTimeout(r, 2000));\n spinner.text = W(\"Registering creator as agent...\");\n try {\n vaultLib.setVaultAddress(result.vault);\n const creatorAddress = getAccount().address;\n await vaultLib.registerAgent(\n BigInt(agentIdStr),\n creatorAddress, // agentAddress = creator EOA (direct execution)\n );\n } catch (regErr) {\n // Non-fatal — creator can register later via `syndicate add`\n console.warn(chalk.yellow(\"\\n ⚠ Could not auto-register creator as agent — register manually with `syndicate add`\"));\n }\n\n spinner.text = W(\"Setting up chat...\");\n\n // Create XMTP group for syndicate chat\n try {\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n const groupId = await xmtp.createSyndicateGroup(xmtpClient, subdomain, opts.publicChat);\n cacheGroupId(subdomain, groupId);\n try {\n await setTextRecord(subdomain, \"xmtpGroupId\", groupId, result.vault as Address);\n } catch { /* ENS not available on all chains */ }\n } catch {\n console.warn(chalk.yellow(\"\\n ⚠ Could not create XMTP chat group\"));\n console.warn(chalk.dim(` Recover later with: sherwood chat ${subdomain} init`));\n }\n\n // ── Auto-register participation crons ──\n try {\n const cron = await loadCron();\n const cronResult = cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n if (cronResult.isOpenClaw && cronResult.registered) {\n console.log(G(\" ✓ Participation crons registered (15m check + hourly summary)\"));\n } else if (!cronResult.isOpenClaw) {\n console.log(DIM(\" Tip: Set up a scheduled process to run `sherwood session check \" + subdomain + \"` periodically\"));\n }\n } catch { /* non-fatal */ }\n\n spinner.stop();\n\n // ── Success ──\n console.log();\n console.log(LABEL(\" ◆ Syndicate Created\"));\n SEP();\n console.log(W(` ID: ${G(`#${result.syndicateId}`)}`));\n console.log(W(` Vault: ${G(result.vault)}`));\n console.log(W(` ENS: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Metadata: ${DIM(metadataURI.length > 50 ? metadataURI.slice(0, 50) + \"...\" : metadataURI)}`));\n console.log(W(` Explorer: ${DIM(getExplorerUrl(result.hash))}`));\n console.log(W(` Chat: ${DIM(`sherwood chat ${subdomain}`)}`));\n const refParam = getAgentId() ? `?ref=${getAgentId()}` : \"\";\n console.log(W(` Share: ${G(`https://sherwood.sh/syndicate/${subdomain}${refParam}`)}`));\n SEP();\n console.log(G(\" ✓ Syndicate saved to ~/.sherwood/config.json (set as primary)\"));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"list\")\n .description(\"List active syndicates (queries subgraph, falls back to on-chain)\")\n .option(\"--creator <address>\", \"Filter by creator address\")\n .option(\"--all-chains\", \"Aggregate active syndicates across all supported chains (on-chain only)\")\n .action(async (opts) => {\n const spinner = ora(\"Loading syndicates...\").start();\n try {\n // Each row carries an optional `chain` so the --all-chains output can\n // tell users which network a syndicate lives on.\n type Row = {\n id: string | bigint;\n vault: string;\n creator: string;\n metadataURI: string;\n createdAt: string | bigint;\n totalDeposits?: string;\n totalWithdrawals?: string;\n subdomain?: string;\n chain?: Network;\n };\n let syndicates: Row[] = [];\n\n if (opts.allChains) {\n // Subgraph is single-chain; on-chain only when iterating networks.\n const includeTestnets = process.env.ENABLE_TESTNET === \"true\";\n const targets = VALID_NETWORKS.filter((n) => includeTestnets || ![\"base-sepolia\", \"robinhood-testnet\", \"hyperevm-testnet\"].includes(n));\n for (const net of targets) {\n spinner.text = `Loading from ${net}...`;\n try {\n const rows = await withNetwork(net, () => factoryLib.getActiveSyndicates());\n for (const s of rows) {\n syndicates.push({\n id: s.id.toString(),\n vault: s.vault,\n creator: s.creator,\n metadataURI: s.metadataURI,\n createdAt: s.createdAt.toString(),\n subdomain: s.subdomain,\n chain: net,\n });\n }\n } catch {\n // Skip flaky chain RPCs rather than failing the whole listing.\n }\n }\n if (opts.creator) {\n const c = String(opts.creator).toLowerCase();\n syndicates = syndicates.filter((s) => s.creator.toLowerCase() === c);\n }\n } else if (process.env.SUBGRAPH_URL) {\n const result = await subgraphLib.getActiveSyndicates(opts.creator);\n syndicates = result;\n } else {\n const result = await factoryLib.getActiveSyndicates();\n syndicates = result.map((s) => ({\n id: s.id.toString(),\n vault: s.vault,\n creator: s.creator,\n metadataURI: s.metadataURI,\n createdAt: s.createdAt.toString(),\n subdomain: s.subdomain,\n }));\n }\n\n spinner.stop();\n\n if (syndicates.length === 0) {\n console.log(chalk.dim(\"No active syndicates found.\"));\n return;\n }\n\n console.log();\n console.log(chalk.bold(`Active Syndicates (${syndicates.length})`));\n if (!process.env.SUBGRAPH_URL && !opts.allChains) {\n console.log(chalk.dim(\" (Set SUBGRAPH_URL for faster indexed queries)\"));\n }\n if (opts.allChains) {\n console.log(chalk.dim(\" (Aggregated across chains via on-chain factory calls; SUBGRAPH_URL is single-chain only)\"));\n }\n console.log(chalk.dim(\"─\".repeat(70)));\n\n for (const s of syndicates) {\n const ts = typeof s.createdAt === \"string\" ? Number(s.createdAt) : Number(s.createdAt);\n const date = new Date(ts * 1000).toLocaleDateString();\n const ensName = s.subdomain ? `${s.subdomain}.sherwoodagent.eth` : \"\";\n const chainTag = s.chain ? chalk.dim(`[${s.chain}] `) : \"\";\n console.log(` ${chainTag}#${s.id} ${chalk.bold(ensName || String(s.vault))}`);\n if (ensName) console.log(` Vault: ${chalk.cyan(String(s.vault))}`);\n console.log(` Creator: ${s.creator}`);\n console.log(` Created: ${date}`);\n if (s.totalDeposits) {\n console.log(` Deposits: ${s.totalDeposits} USDC`);\n }\n if (s.metadataURI) {\n console.log(` Metadata: ${chalk.dim(s.metadataURI)}`);\n }\n console.log();\n }\n } catch (err) {\n spinner.fail(\"Failed to load syndicates\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"info\")\n .description(\"Display syndicate details by ID or subdomain\")\n .argument(\"<id>\", \"Syndicate ID or subdomain name\")\n .action(async (idStr) => {\n const spinner = ora(\"Loading syndicate info...\").start();\n try {\n let id: bigint;\n let crossChainHint: { network: Network; others: Network[] } | null = null;\n let infoOverride: factoryLib.SyndicateInfo | null = null;\n\n if (/^\\d+$/.test(idStr)) {\n id = BigInt(idStr);\n } else {\n // Try active chain first; on miss, scan all enabled chains so users\n // who default to base can still inspect a HyperEVM syndicate.\n try {\n const resolved = await resolveSyndicate(idStr);\n id = resolved.id;\n } catch {\n spinner.text = `Searching across chains...`;\n const hits = await searchSyndicateAcrossChains(idStr);\n if (hits.length === 0) {\n spinner.fail(`Syndicate \"${idStr}\" not found on any supported chain`);\n process.exit(1);\n }\n // Prefer active chain hit, else first hit.\n const active = getNetwork();\n const primary = hits.find((h) => h.network === active) ?? hits[0];\n id = primary.result.id;\n // Read the syndicate from the chain it actually lives on (NOT the\n // active chain) so vault stats etc. don't blow up trying to read a\n // non-existent vault on the active chain.\n infoOverride = await withNetwork(primary.network, () =>\n factoryLib.getSyndicate(primary.result.id),\n );\n crossChainHint = {\n network: primary.network,\n others: hits.filter((h) => h.network !== primary.network).map((h) => h.network),\n };\n }\n }\n const info = infoOverride ?? (await factoryLib.getSyndicate(id));\n spinner.stop();\n if (crossChainHint) {\n const others = crossChainHint.others.length > 0\n ? ` (also on: ${crossChainHint.others.join(\", \")})`\n : \"\";\n console.log(chalk.yellow(` Found on chain: ${chalk.bold(crossChainHint.network)}${others}`));\n console.log(chalk.dim(` Re-run with --chain ${crossChainHint.network} to interact with this syndicate.`));\n console.log();\n }\n\n if (!info.vault || info.vault === \"0x0000000000000000000000000000000000000000\") {\n console.log(chalk.red(`Syndicate #${id} not found.`));\n process.exit(1);\n }\n\n const date = new Date(Number(info.createdAt) * 1000).toLocaleDateString();\n console.log();\n console.log(chalk.bold(`Syndicate #${info.id}`));\n console.log(chalk.dim(\"─\".repeat(40)));\n if (info.subdomain) {\n console.log(` ENS: ${chalk.bold(`${info.subdomain}.sherwoodagent.eth`)}`);\n }\n console.log(` Vault: ${chalk.cyan(info.vault)}`);\n console.log(` Creator: ${info.creator}`);\n console.log(` Created: ${date}`);\n console.log(` Active: ${info.active ? chalk.green(\"yes\") : chalk.red(\"no\")}`);\n if (info.metadataURI) {\n console.log(` Metadata: ${chalk.dim(info.metadataURI)}`);\n }\n\n // Show XMTP group ID if cached\n if (info.subdomain) {\n const xmtpGroupId = getCachedGroupId(info.subdomain);\n if (xmtpGroupId) {\n console.log(` XMTP Group: ${chalk.cyan(xmtpGroupId)}`);\n }\n }\n\n // Also show vault info — when the syndicate lives on a different\n // chain than the active one, read the vault on its actual chain.\n vaultLib.setVaultAddress(info.vault);\n const vaultInfo = crossChainHint\n ? await withNetwork(crossChainHint.network, () => vaultLib.getVaultInfo())\n : await vaultLib.getVaultInfo();\n console.log();\n console.log(chalk.bold(\" Vault Stats\"));\n console.log(` Total Assets: ${vaultInfo.totalAssets}`);\n console.log(` Agent Count: ${vaultInfo.agentCount}`);\n console.log(` Redemptions Locked: ${vaultInfo.redemptionsLocked}`);\n console.log(` Management Fee: ${Number(vaultInfo.managementFeeBps) / 100}%`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load syndicate info\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"update-metadata\")\n .description(\"Update syndicate metadata (creator only)\")\n .requiredOption(\"--id <id>\", \"Syndicate ID\")\n .option(\"--name <name>\", \"Syndicate name\")\n .option(\"--description <text>\", \"Short description\")\n .option(\"--uri <uri>\", \"Direct metadata URI (skips IPFS upload)\")\n .action(async (opts) => {\n const spinner = ora({ text: W(\"Loading syndicate...\"), color: \"green\" }).start();\n try {\n const syndicateId = BigInt(opts.id);\n let metadataURI = opts.uri;\n\n if (!metadataURI) {\n const info = await factoryLib.getSyndicate(syndicateId);\n if (!info.vault || info.vault === \"0x0000000000000000000000000000000000000000\") {\n spinner.fail(`Syndicate #${opts.id} not found.`);\n process.exit(1);\n }\n\n const name = opts.name || info.subdomain;\n const description = opts.description || `${name} — a Sherwood syndicate on ${info.subdomain}.sherwoodagent.eth`;\n\n spinner.text = W(\"Uploading metadata to IPFS...\");\n const metadata: SyndicateMetadata = {\n schema: \"sherwood/syndicate/v1\",\n name,\n description,\n chain: getChain().name,\n strategies: [],\n terms: {},\n links: {},\n };\n metadataURI = await uploadMetadata(metadata);\n spinner.text = W(\"Updating on-chain metadata...\");\n }\n\n const hash = await factoryLib.updateMetadata(syndicateId, metadataURI);\n spinner.succeed(G(`Metadata updated`));\n console.log(DIM(` IPFS: ${metadataURI}`));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Metadata update failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"approve-depositor\")\n .description(\"Approve an address to deposit (owner only)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .requiredOption(\"--depositor <address>\", \"Address to approve\")\n .action(async (opts) => {\n resolveVault(opts);\n const depositor = validateAddress(opts.depositor, \"depositor\");\n if (isCalldataOnly()) {\n emitCalldata(\n encodeApproveDepositor(\n { vault: vaultLib.getVaultAddress(), depositor },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n const spinner = ora(\"Approving depositor...\").start();\n try {\n const hash = await vaultLib.approveDepositor(depositor);\n spinner.succeed(`Depositor approved: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Approval failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"remove-depositor\")\n .description(\"Remove an address from the depositor whitelist (owner only)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .requiredOption(\"--depositor <address>\", \"Address to remove\")\n .action(async (opts) => {\n resolveVault(opts);\n const spinner = ora(\"Removing depositor...\").start();\n try {\n const depositor = validateAddress(opts.depositor, \"depositor\");\n const hash = await vaultLib.removeDepositor(depositor);\n spinner.succeed(`Depositor removed: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Removal failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"add\")\n .description(\"Register an agent on a syndicate vault (creator only)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--agent-id <id>\", \"Agent's ERC-8004 identity token ID (resolved from wallet if omitted)\")\n .requiredOption(\"--wallet <address>\", \"Agent wallet address\")\n .action(async (opts) => {\n // --calldata-only: emit registerAgent calldata. Requires --agent-id (the\n // wallet-based auto-lookup is skipped in calldata mode) and runs before any\n // signer-dependent path.\n if (isCalldataOnly()) {\n resolveVault(opts);\n const agentWallet = validateAddress(opts.wallet, \"wallet\");\n if (!opts.agentId) {\n console.error(\n chalk.red(\n \"--calldata-only requires --agent-id (auto-lookup from wallet is skipped in calldata mode)\",\n ),\n );\n process.exit(1);\n }\n emitCalldata(\n encodeRegisterAgent(\n {\n vault: vaultLib.getVaultAddress(),\n agentAddress: agentWallet,\n agentId: BigInt(opts.agentId),\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const spinner = ora(\"Verifying creator...\").start();\n try {\n // Resolve vault address from --vault flag or config\n resolveVault(opts);\n const vaultAddress = vaultLib.getVaultAddress();\n\n // Verify caller is the syndicate creator\n const { creator, subdomain } = await resolveVaultSyndicate(vaultAddress);\n const callerAddress = getAccount().address.toLowerCase();\n if (creator.toLowerCase() !== callerAddress) {\n spinner.fail(\"Only the syndicate creator can add agents\");\n process.exit(1);\n }\n\n const agentWallet = validateAddress(opts.wallet, \"wallet\");\n\n // Resolve agent ID: use --agent-id if provided, otherwise look up from wallet\n let agentId: bigint;\n if (opts.agentId) {\n agentId = BigInt(opts.agentId);\n } else {\n const { AGENT_REGISTRY } = await import(\"./lib/addresses.js\");\n const registry = AGENT_REGISTRY().IDENTITY_REGISTRY;\n\n // Chains without ERC-8004 (e.g. HyperEVM) — contract skips identity check\n if (registry === \"0x0000000000000000000000000000000000000000\") {\n agentId = 0n;\n } else {\n spinner.text = \"Looking up ERC-8004 identity from wallet...\";\n const client = getPublicClient();\n\n const balance = await client.readContract({\n address: registry,\n abi: [{\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n }] as const,\n functionName: \"balanceOf\",\n args: [agentWallet],\n }) as bigint;\n\n if (balance === 0n) {\n spinner.fail(\"Agent wallet does not own an ERC-8004 identity NFT\");\n console.error(chalk.dim(\" Mint one first: sherwood identity mint --name <name>\"));\n process.exit(1);\n }\n\n const tokenId = await client.readContract({\n address: registry,\n abi: [{\n name: \"tokenOfOwnerByIndex\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }, { name: \"index\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n }] as const,\n functionName: \"tokenOfOwnerByIndex\",\n args: [agentWallet, 0n],\n }) as bigint;\n\n agentId = tokenId;\n console.log(chalk.dim(` Resolved agent ID: #${agentId}`));\n }\n }\n\n spinner.text = \"Registering agent...\";\n const hash = await vaultLib.registerAgent(agentId, agentWallet);\n spinner.succeed(`Agent registered: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n\n // Auto-add agent to XMTP chat group\n try {\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n const group = await xmtp.getGroup(xmtpClient, subdomain);\n await xmtp.addMember(group, opts.wallet);\n await xmtp.sendEnvelope(group, {\n type: \"AGENT_REGISTERED\",\n agent: { erc8004Id: Number(agentId), address: opts.wallet },\n syndicate: subdomain,\n timestamp: Math.floor(Date.now() / 1000),\n });\n console.log(chalk.dim(` Added to chat: ${subdomain}`));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not add agent to chat group\"));\n console.warn(chalk.dim(` If no group exists, run: sherwood chat ${subdomain} init`));\n }\n } catch (err) {\n spinner.fail(\"Registration failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"share\")\n .description(\"Print the shareable dashboard URL for your syndicate\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain (default: primary)\")\n .action(async (opts) => {\n try {\n const subdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (!subdomain) {\n console.error(chalk.red(\" No syndicate configured. Pass --subdomain <name> or run 'syndicate create/join' first.\"));\n process.exit(1);\n }\n\n // Verify syndicate exists on-chain\n const syndicateInfo = await resolveSyndicate(subdomain);\n\n const agentId = getAgentId();\n const refParam = agentId ? `?ref=${agentId}` : \"\";\n const dashboardUrl = `https://sherwood.sh/syndicate/${subdomain}${refParam}`;\n\n console.log();\n console.log(LABEL(\" ◆ Share Your Syndicate\"));\n SEP();\n console.log(W(` Dashboard: ${G(dashboardUrl)}`));\n console.log(W(` ENS: ${DIM(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Vault: ${DIM(syndicateInfo.vault)}`));\n console.log(W(` Join CLI: ${DIM(`sherwood syndicate join --subdomain ${subdomain}`)}`));\n SEP();\n\n // Try to copy to clipboard (optional — uses pbcopy/xclip if available)\n try {\n const { exec } = await import(\"node:child_process\");\n const platform = (await import(\"node:os\")).platform();\n const cmd = platform === \"darwin\" ? \"pbcopy\" : \"xclip -selection clipboard\";\n const proc = exec(cmd);\n proc.stdin?.write(dashboardUrl);\n proc.stdin?.end();\n console.log(G(\" ✓ Dashboard URL copied to clipboard\"));\n } catch {\n // clipboard not available — no problem\n }\n console.log();\n } catch (err) {\n console.error(chalk.red(` ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n// ── EAS Join Request / Approval Commands ──\n\nsyndicate\n .command(\"join\")\n .description(\"Request to join a syndicate (creates an EAS attestation)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain to join\")\n .option(\"--ref <agentId>\", \"Referrer agent ID (from invite link)\")\n .option(\"--message <text>\", \"Message to the creator\", \"Requesting to join your syndicate\")\n .action(async (opts) => {\n const spinner = ora(\"Resolving syndicate...\").start();\n try {\n const subdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (!subdomain) {\n spinner.fail(\"No syndicate configured. Pass --subdomain <name> or run 'syndicate create' first.\");\n process.exit(1);\n }\n\n const agentId = getAgentId();\n if (!agentId) {\n spinner.fail(\"No agent identity found. Run 'sherwood identity mint' first.\");\n process.exit(1);\n }\n\n let syndicate: Awaited<ReturnType<typeof resolveSyndicate>>;\n try {\n syndicate = await resolveSyndicate(subdomain);\n } catch {\n // Active chain doesn't have it — see if it lives elsewhere.\n spinner.text = \"Searching across chains...\";\n const hits = await searchSyndicateAcrossChains(subdomain);\n spinner.fail(`Syndicate \"${subdomain}\" not found on ${getNetwork()}`);\n if (hits.length === 0) {\n console.error(chalk.red(` Not found on any supported chain.`));\n } else if (hits.length === 1) {\n console.error(chalk.yellow(` Found on chain: ${chalk.bold(hits[0].network)}`));\n console.error(chalk.dim(` Re-run: sherwood --chain ${hits[0].network} syndicate join --subdomain ${subdomain}`));\n } else {\n const chains = hits.map((h) => h.network).join(\", \");\n console.error(chalk.yellow(` Found on chains: ${chalk.bold(chains)}`));\n console.error(chalk.dim(` Specify which chain to join with --chain <network>.`));\n }\n process.exit(1);\n }\n\n // --calldata-only: emit the unsigned join-request attestation and stop\n // before any signer-dependent path (membership checks read getAccount()).\n if (isCalldataOnly()) {\n const referrerAgentId = opts.ref ? parseInt(opts.ref, 10) : undefined;\n spinner.stop();\n emitCalldata(\n encodeJoinRequest(\n {\n syndicateId: syndicate.id,\n agentId: BigInt(agentId),\n vault: syndicate.vault,\n creator: syndicate.creator,\n message: opts.message,\n referrerAgentId,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const callerAddress = getAccount().address;\n\n // Check if already registered as an agent on this vault\n spinner.text = \"Checking membership...\";\n vaultLib.setVaultAddress(syndicate.vault);\n const alreadyAgent = await vaultLib.isAgent(callerAddress);\n if (alreadyAgent) {\n spinner.succeed(\"You are already a registered agent on this syndicate\");\n // Still ensure XMTP identity is ready\n try {\n const xmtp = await loadXmtp();\n await xmtp.getXmtpClient();\n console.log(chalk.dim(\" XMTP identity ready\"));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not initialize XMTP identity\"));\n }\n // Auto-register participation crons (idempotent)\n try {\n const cron = await loadCron();\n const cronResult = cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n if (cronResult.isOpenClaw && cronResult.registered) {\n console.log(chalk.green(\" ✓ Participation crons registered\"));\n } else if (!cronResult.isOpenClaw) {\n console.log(chalk.dim(\" Tip: Set up a scheduled process to run `sherwood session check \" + subdomain + \"` periodically\"));\n }\n } catch { /* non-fatal */ }\n return;\n }\n\n // Check for existing pending join request\n spinner.text = \"Checking pending requests...\";\n const pendingRequests = await easLib.queryJoinRequests(syndicate.creator);\n const existingRequest = pendingRequests.find(\n (r) => r.attester.toLowerCase() === callerAddress.toLowerCase()\n && r.decoded.vault.toLowerCase() === syndicate.vault.toLowerCase(),\n );\n if (existingRequest) {\n spinner.succeed(\"You already have a pending join request for this syndicate\");\n console.log(chalk.dim(` Attestation: ${existingRequest.uid}`));\n console.log(chalk.dim(` Submitted: ${new Date(existingRequest.time * 1000).toLocaleString()}`));\n // Still ensure XMTP identity is ready\n try {\n const xmtp = await loadXmtp();\n await xmtp.getXmtpClient();\n console.log(chalk.dim(\" XMTP identity ready\"));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not initialize XMTP identity\"));\n }\n return;\n }\n\n spinner.text = \"Creating join request attestation...\";\n const referrerAgentId = opts.ref ? parseInt(opts.ref, 10) : undefined;\n const { uid, hash } = await easLib.createJoinRequest(\n syndicate.id,\n BigInt(agentId),\n syndicate.vault,\n syndicate.creator,\n opts.message,\n referrerAgentId,\n );\n\n // Pre-register XMTP identity so the creator can add us to the group on approval\n try {\n spinner.text = \"Registering XMTP identity...\";\n const xmtp = await loadXmtp();\n await xmtp.getXmtpClient();\n spinner.succeed(\"Join request created (XMTP identity ready)\");\n } catch {\n spinner.succeed(\"Join request created\");\n console.warn(chalk.yellow(\" ⚠ Could not initialize XMTP identity — creator may not be able to auto-add you to chat\"));\n }\n\n // Save syndicate membership + set as primary\n addSyndicate(getChain().id, { subdomain, vault: syndicate.vault, role: \"agent\" });\n setPrimarySyndicate(getChain().id, subdomain);\n\n // Auto-register participation crons (will HEARTBEAT_OK until approved)\n try {\n const cron = await loadCron();\n const cronResult = cron.registerSyndicateCrons(subdomain, isTestnet(), getNotifyTo());\n if (cronResult.isOpenClaw && cronResult.registered) {\n console.log(G(\" ✓ Participation crons registered (will activate after approval)\"));\n } else if (!cronResult.isOpenClaw) {\n console.log(DIM(\" Tip: Set up a scheduled process to run `sherwood session check \" + subdomain + \"` periodically\"));\n }\n } catch { /* non-fatal */ }\n\n console.log();\n console.log(LABEL(\" ◆ Join Request Submitted\"));\n SEP();\n console.log(W(` Syndicate: ${G(`${subdomain}.sherwoodagent.eth`)}`));\n console.log(W(` Agent ID: #${agentId}`));\n console.log(W(` Creator: ${DIM(syndicate.creator)}`));\n console.log(W(` Attestation: ${DIM(uid)}`));\n console.log(W(` EAS Scan: ${DIM(easLib.getEasScanUrl(uid))}`));\n // EAS tx ran on Base (Base-Sepolia for testnet) regardless of --chain.\n console.log(W(` Explorer: ${DIM(easLib.getEasExplorerUrl(hash))}`));\n SEP();\n console.log(G(\" ✓ Syndicate saved to ~/.sherwood/config.json (set as primary)\"));\n console.log(G(\" ✓ The creator can review with:\"));\n console.log(DIM(` sherwood syndicate requests --subdomain ${subdomain}`));\n console.log();\n } catch (err) {\n spinner.fail(\"Join request failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"requests\")\n .description(\"View pending join requests for a syndicate (creator only)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .action(async (opts) => {\n const spinner = ora(\"Loading join requests...\").start();\n try {\n let creatorAddress: Address;\n let subdomain: string;\n let syndicateVault: Address;\n\n // Resolve syndicate: --subdomain > primary syndicate > --vault > config vault\n const resolvedSubdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (resolvedSubdomain) {\n const syndicateInfo = await resolveSyndicate(resolvedSubdomain);\n creatorAddress = syndicateInfo.creator;\n subdomain = resolvedSubdomain;\n syndicateVault = syndicateInfo.vault as Address;\n } else {\n resolveVault(opts);\n syndicateVault = vaultLib.getVaultAddress();\n const syndicateInfo = await resolveVaultSyndicate(syndicateVault);\n creatorAddress = syndicateInfo.creator;\n subdomain = syndicateInfo.subdomain;\n }\n\n // Verify caller is creator\n const callerAddress = getAccount().address.toLowerCase();\n if (creatorAddress.toLowerCase() !== callerAddress) {\n spinner.fail(\"Only the syndicate creator can view join requests\");\n process.exit(1);\n }\n\n spinner.text = \"Querying EAS attestations...\";\n const [allRequests, approvals] = await Promise.all([\n easLib.queryJoinRequests(creatorAddress),\n easLib.queryApprovals(creatorAddress),\n ]);\n\n // Filter out agents that have already been approved for the same vault\n const approvedKeys = new Set(\n approvals\n .filter((a) => a.decoded.vault.toLowerCase() === syndicateVault.toLowerCase())\n .map((a) => a.decoded.agentId.toString()),\n );\n const requests = allRequests.filter(\n (r) => !approvedKeys.has(r.decoded.agentId.toString())\n && r.decoded.vault.toLowerCase() === syndicateVault.toLowerCase(),\n );\n\n spinner.stop();\n\n if (requests.length === 0) {\n console.log(DIM(\"\\n No pending join requests.\\n\"));\n return;\n }\n\n console.log();\n console.log(LABEL(` ◆ Pending Join Requests (${requests.length})`));\n SEP();\n\n for (let i = 0; i < requests.length; i++) {\n const req = requests[i];\n const date = new Date(req.time * 1000).toLocaleString();\n const referrer = easLib.parseReferrer(req.decoded.message);\n const cleanMessage = easLib.stripReferrerPrefix(req.decoded.message);\n console.log(W(` ${i + 1}. Agent #${req.decoded.agentId} ${DIM(`(${req.attester})`)}`));\n console.log(DIM(` Message: \"${cleanMessage}\"`));\n if (referrer !== null) {\n console.log(G(` Referred by: Agent #${referrer}`));\n }\n console.log(DIM(` Requested: ${date}`));\n console.log(DIM(` Attestation: ${req.uid}`));\n console.log();\n }\n\n console.log(G(\" To approve:\"));\n console.log(DIM(` sherwood syndicate approve --agent-id <id> --wallet <addr>`));\n console.log(G(\" To reject:\"));\n console.log(DIM(` sherwood syndicate reject --attestation <uid>`));\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load requests\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"approve\")\n .description(\"Approve an agent join request (registers agent + creates EAS approval)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain (alternative to --vault)\")\n .requiredOption(\"--agent-id <id>\", \"Agent's ERC-8004 identity token ID\")\n .requiredOption(\"--wallet <address>\", \"Agent wallet address\")\n .action(async (opts) => {\n const spinner = ora(\"Verifying creator...\").start();\n try {\n // Resolve vault: --subdomain > primary syndicate > --vault > config vault\n const approveSubdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (approveSubdomain && !opts.vault) {\n const syndicateInfo = await resolveSyndicate(approveSubdomain);\n vaultLib.setVaultAddress(syndicateInfo.vault);\n } else {\n resolveVault(opts);\n }\n const vaultAddress = vaultLib.getVaultAddress();\n\n const agentWallet = validateAddress(opts.wallet, \"wallet\");\n\n // Verify caller is creator\n const { creator, subdomain, id: syndicateId } = await resolveVaultSyndicate(vaultAddress);\n\n // --calldata-only: emit registerAgent (syndicate chain) + AGENT_APPROVED\n // attest (Base) before any signer-dependent path.\n if (isCalldataOnly()) {\n spinner.stop();\n emitCalldata(\n encodeApproveAgent(\n {\n syndicateId,\n agentId: BigInt(opts.agentId),\n vault: vaultAddress,\n agentAddress: agentWallet,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const callerAddress = getAccount().address.toLowerCase();\n if (creator.toLowerCase() !== callerAddress) {\n spinner.fail(\"Only the syndicate creator can approve agents\");\n process.exit(1);\n }\n\n // 1. Register agent on-chain (same as syndicate add)\n spinner.text = \"Registering agent on vault...\";\n let agentWasRegistered = false;\n try {\n const regHash = await vaultLib.registerAgent(\n BigInt(opts.agentId),\n agentWallet,\n );\n agentWasRegistered = true;\n console.log(DIM(` Agent registered: ${getExplorerUrl(regHash)}`));\n } catch (regErr) {\n const msg = regErr instanceof Error ? regErr.message : String(regErr);\n if (msg.includes(\"0xe098d3ee\") || msg.includes(\"AgentAlreadyRegistered\")) {\n console.log(DIM(\" Agent already registered on vault — skipping\"));\n } else {\n throw regErr;\n }\n }\n\n // Brief delay after on-chain registration to let the RPC node sync its nonce\n if (agentWasRegistered) {\n await new Promise((r) => setTimeout(r, 2000));\n }\n\n // 2. Create AGENT_APPROVED attestation (skip if one already exists)\n spinner.text = \"Checking for existing approval...\";\n const existingApprovals = await easLib.queryApprovals(getAccount().address);\n const alreadyApproved = existingApprovals.find(\n (a) => a.decoded.agentId === BigInt(opts.agentId) && a.decoded.vault.toLowerCase() === vaultAddress.toLowerCase(),\n );\n\n let approvalUid: `0x${string}`;\n if (alreadyApproved) {\n approvalUid = alreadyApproved.uid;\n console.log(DIM(` Approval attestation already exists — skipping`));\n } else {\n spinner.text = \"Creating approval attestation...\";\n const result = await easLib.createApproval(\n syndicateId,\n BigInt(opts.agentId),\n vaultAddress,\n agentWallet,\n );\n approvalUid = result.uid;\n }\n\n // 3. Auto-add agent to XMTP chat group\n try {\n spinner.text = \"Adding to chat...\";\n const xmtp = await loadXmtp();\n const xmtpClient = await xmtp.getXmtpClient();\n const group = await xmtp.getGroup(xmtpClient, subdomain);\n await xmtp.addMember(group, opts.wallet);\n await xmtp.sendEnvelope(group, {\n type: \"AGENT_REGISTERED\",\n agent: { erc8004Id: Number(opts.agentId), address: opts.wallet },\n syndicate: subdomain,\n timestamp: Math.floor(Date.now() / 1000),\n });\n console.log(DIM(` Added to chat: ${subdomain}`));\n } catch {\n console.warn(chalk.yellow(\" ⚠ Could not add agent to chat group\"));\n console.warn(chalk.dim(` If no group exists, run: sherwood chat ${subdomain} init`));\n }\n\n spinner.succeed(\"Agent approved and registered\");\n console.log();\n console.log(LABEL(\" ◆ Agent Approved\"));\n SEP();\n console.log(W(` Agent ID: #${opts.agentId}`));\n console.log(W(` Wallet: ${G(opts.wallet)}`));\n console.log(W(` Approval: ${DIM(approvalUid)}`));\n console.log(W(` EAS Scan: ${DIM(easLib.getEasScanUrl(approvalUid))}`));\n SEP();\n } catch (err) {\n spinner.fail(\"Approval failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"reject\")\n .description(\"Reject a join request by revoking its attestation\")\n .requiredOption(\"--attestation <uid>\", \"Join request attestation UID to revoke\")\n .action(async (opts) => {\n const spinner = ora(\"Revoking attestation...\").start();\n try {\n // Revoke on Base / Base-Sepolia regardless of --chain — syndicate\n // join attestations always live on the EAS chain, not the syndicate's\n // chain.\n const hash = await easLib.revokeJoinRequest(opts.attestation as `0x${string}`);\n spinner.succeed(\"Join request rejected\");\n console.log(DIM(` ${easLib.getEasExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Rejection failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"leave\")\n .description(\"Leave a syndicate — removes participation crons and session state\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain to leave\")\n .action(async (opts) => {\n const subdomain = opts.subdomain || getPrimarySyndicate(getChain().id)?.subdomain;\n if (!subdomain) {\n console.error(chalk.red(\" No syndicate configured. Pass --subdomain <name>.\"));\n process.exit(1);\n }\n const spinner = ora(\"Cleaning up...\").start();\n try {\n // 1. Remove participation crons (if OpenClaw)\n let cronsRemoved = false;\n try {\n const cron = await loadCron();\n const result = cron.unregisterSyndicateCrons(subdomain, isTestnet());\n cronsRemoved = result.removed;\n } catch { /* non-fatal */ }\n\n // 2. Reset session state\n const { resetSession } = await import(\"./lib/session.js\");\n resetSession(subdomain);\n\n spinner.succeed(\"Left syndicate\");\n if (cronsRemoved) {\n console.log(G(\" ✓ Participation crons removed\"));\n }\n console.log(G(\" ✓ Session state cleared\"));\n console.log();\n console.log(chalk.dim(\" Note: This does not remove you on-chain. To exit your position:\"));\n console.log(chalk.dim(\" sherwood vault balance — check your LP share balance\"));\n console.log(chalk.dim(\" Redeem shares via the vault contract or dashboard\"));\n console.log();\n } catch (err) {\n spinner.fail(\"Leave failed\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n });\n\nsyndicate\n .command(\"set-primary\")\n .description(\"Set the active syndicate for CLI commands (auto-used when --subdomain is omitted)\")\n .option(\"--subdomain <name>\", \"Syndicate subdomain\")\n .option(\"--vault <address>\", \"Vault address\")\n .action(async (opts) => {\n try {\n const chainId = getChain().id;\n const memberships = getSyndicates(chainId);\n\n if (!opts.subdomain && !opts.vault) {\n // List syndicates and show which is primary\n const primary = getPrimarySyndicate(chainId);\n if (memberships.length === 0) {\n console.log(DIM(\"\\n No syndicates saved. Create or join one first.\\n\"));\n return;\n }\n console.log();\n console.log(LABEL(\" ◆ Your Syndicates\"));\n SEP();\n for (const m of memberships) {\n const isPrimary = primary?.subdomain === m.subdomain;\n const marker = isPrimary ? G(\" ★\") : \"\";\n console.log(W(` ${m.subdomain}.sherwoodagent.eth${marker} ${DIM(`(${m.role})`)}`));\n console.log(DIM(` vault: ${m.vault}`));\n }\n SEP();\n if (memberships.length > 1) {\n console.log(DIM(\" Switch with: sherwood syndicate set-primary --subdomain <name>\"));\n }\n console.log();\n return;\n }\n\n let target: string | undefined;\n\n if (opts.subdomain) {\n // Verify it's in our list\n const found = memberships.find((m) => m.subdomain === opts.subdomain);\n if (!found) {\n // Resolve on-chain to verify it exists, then add it\n const syndicateInfo = await resolveSyndicate(opts.subdomain);\n addSyndicate(chainId, { subdomain: opts.subdomain, vault: syndicateInfo.vault, role: \"agent\" });\n }\n target = opts.subdomain;\n } else if (opts.vault) {\n // Find by vault address\n const found = memberships.find(\n (m) => m.vault.toLowerCase() === opts.vault.toLowerCase(),\n );\n if (found) {\n target = found.subdomain;\n } else {\n // Resolve on-chain\n const syndicateInfo = await resolveVaultSyndicate(validateAddress(opts.vault, \"vault\"));\n addSyndicate(chainId, { subdomain: syndicateInfo.subdomain, vault: opts.vault, role: \"agent\" });\n target = syndicateInfo.subdomain;\n }\n }\n\n if (!target) {\n console.error(chalk.red(\" Could not resolve syndicate. Pass --subdomain or --vault.\"));\n process.exit(1);\n }\n\n setPrimarySyndicate(chainId, target);\n console.log(G(`\\n ✓ Primary syndicate set to ${target}.sherwoodagent.eth\\n`));\n } catch (err) {\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n// ── Vault commands ──\nconst vaultCmd = program.command(\"vault\");\n\nvaultCmd\n .command(\"deposit\")\n .description(\"Deposit into a vault\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .requiredOption(\"--amount <amount>\", \"Amount to deposit (in asset units)\")\n .option(\"--use-eth\", \"Auto-wrap ETH → WETH before depositing (for WETH vaults)\")\n .option(\"--receiver <address>\", \"Depositor / share receiver (required with --calldata-only)\")\n .action(async (opts) => {\n resolveVault(opts);\n const decimals = await vaultLib.getAssetDecimals();\n const amount = parseUnits(opts.amount, decimals);\n\n // --calldata-only: emit (optional wrap) + approve + deposit calldata. Needs\n // an explicit --receiver (no wallet to infer it from). With --use-eth on a\n // WETH vault, a WETH.deposit{value:shortfall}() wrap leg is prepended; the\n // shortfall is computed from the receiver's current WETH balance.\n if (isCalldataOnly()) {\n if (!opts.receiver) {\n console.error(\n chalk.red(\n \"--calldata-only requires --receiver <address> (the depositor / share receiver)\",\n ),\n );\n process.exit(1);\n }\n const receiver = validateAddress(opts.receiver, \"receiver\");\n const asset = await vaultLib.getAssetAddress();\n const assetSymbol = (await getPublicClient().readContract({\n address: asset,\n abi: ERC20_ABI,\n functionName: \"symbol\",\n })) as string;\n let currentWethBalance: bigint | undefined;\n if (opts.useEth) {\n currentWethBalance = (await getPublicClient().readContract({\n address: asset,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [receiver],\n })) as bigint;\n }\n try {\n emitCalldata(\n encodeDeposit(\n {\n vault: vaultLib.getVaultAddress(),\n receiver,\n asset,\n assetSymbol,\n assetDecimals: decimals,\n assets: amount,\n wrapEth: Boolean(opts.useEth),\n currentWethBalance,\n },\n getChain().id as ChainId,\n ),\n );\n } catch (err) {\n // e.g. --use-eth on a non-WETH vault — the encoder rejects it.\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n return;\n }\n\n // Pre-flight checks — catch issues before submitting transactions\n try {\n if (!opts.useEth) {\n await vaultLib.preflightDeposit(amount);\n }\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}\\n`));\n process.exit(1);\n }\n\n const spinner = ora(`Depositing ${opts.amount}...`).start();\n try {\n let hash;\n if (opts.useEth) {\n spinner.text = `Wrapping ETH + depositing ${opts.amount}...`;\n hash = await vaultLib.depositWithEthWrap(amount);\n } else {\n hash = await vaultLib.deposit(amount);\n }\n spinner.succeed(`Deposited: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(\"Deposit failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nvaultCmd\n .command(\"info\")\n .description(\"Display vault state\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .action(async (opts) => {\n resolveVault(opts);\n const spinner = ora(\"Loading vault info...\").start();\n try {\n const info = await vaultLib.getVaultInfo();\n spinner.stop();\n console.log();\n console.log(chalk.bold(\"Vault Info\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Address: ${info.address}`);\n console.log(` Total Assets: ${info.totalAssets}`);\n console.log(` Agent Count: ${info.agentCount}`);\n console.log(` Redemptions Locked: ${info.redemptionsLocked}`);\n console.log(` Management Fee: ${Number(info.managementFeeBps) / 100}%`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load vault info\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nvaultCmd\n .command(\"balance\")\n .description(\"Show LP share balance and asset value\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--address <address>\", \"Address to check (default: your wallet)\")\n .action(async (opts) => {\n resolveVault(opts);\n const spinner = ora(\"Loading balance...\").start();\n try {\n const balance = await vaultLib.getBalance(opts.address as Address | undefined);\n spinner.stop();\n console.log();\n console.log(chalk.bold(\"LP Position\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Shares: ${balance.shares.toString()}`);\n console.log(` Asset Value: ${balance.assetsValue}`);\n console.log(` % of Vault: ${balance.percentOfVault}`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\nvaultCmd\n .command(\"redeem\")\n .description(\"Redeem vault shares for the underlying asset (ERC-4626)\")\n .option(\"--vault <address>\", \"Vault address (default: from config)\")\n .option(\"--shares <amount>\", \"Shares to redeem in whole-share units (default: all)\")\n .option(\"--receiver <address>\", \"Receiver of the underlying asset (default: your wallet)\")\n .option(\"--owner <address>\", \"Share owner whose shares burn (required with --calldata-only)\")\n .action(async (opts) => {\n resolveVault(opts);\n\n // Vault shares use (assetDecimals + _decimalsOffset) where offset = assetDecimals.\n // For USDC (6) this is 12. Treat --shares as whole-share units and scale by decimals * 2.\n const assetDecimals = await vaultLib.getAssetDecimals();\n const shareDecimals = assetDecimals * 2;\n\n // --calldata-only: emit redeem calldata. Needs explicit --shares (auto-\"all\"\n // reads your on-chain balance) and --owner (the share holder).\n if (isCalldataOnly()) {\n if (!opts.shares) {\n console.error(\n chalk.red(\n \"--calldata-only requires --shares (auto-'all' needs your on-chain share balance)\",\n ),\n );\n process.exit(1);\n }\n if (!opts.owner) {\n console.error(\n chalk.red(\n \"--calldata-only requires --owner <address> (the share holder whose shares burn)\",\n ),\n );\n process.exit(1);\n }\n const owner = validateAddress(opts.owner, \"owner\");\n const receiver = opts.receiver\n ? validateAddress(opts.receiver, \"receiver\")\n : owner;\n emitCalldata(\n encodeRedeem(\n {\n vault: vaultLib.getVaultAddress(),\n receiver,\n owner,\n shares: parseUnits(opts.shares, shareDecimals),\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n let shares: bigint;\n try {\n if (opts.shares) {\n shares = parseUnits(opts.shares, shareDecimals);\n } else {\n shares = await vaultLib.getShareBalance();\n if (shares === 0n) {\n console.error(chalk.red(\"\\n ✖ No shares to redeem.\\n\"));\n process.exit(1);\n }\n }\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}\\n`));\n process.exit(1);\n }\n\n if (opts.receiver && !isAddress(opts.receiver)) {\n console.error(chalk.red(`\\n ✖ Invalid receiver address: ${opts.receiver}\\n`));\n process.exit(1);\n }\n\n try {\n await vaultLib.preflightRedeem(shares);\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}\\n`));\n process.exit(1);\n }\n\n const sharesDisplay = formatUnits(shares, shareDecimals);\n const spinner = ora(`Redeeming ${sharesDisplay} shares...`).start();\n try {\n const { hash, assetsOut } = await vaultLib.redeem(\n shares,\n opts.receiver as Address | undefined,\n );\n spinner.succeed(`Redeemed: ${hash}`);\n console.log(chalk.dim(` ${getExplorerUrl(hash)}`));\n console.log(` Assets received: ${formatUnits(assetsOut, assetDecimals)}`);\n } catch (err) {\n spinner.fail(\"Redeem failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n// ── Strategy commands ──\nconst strategy = program.command(\"strategy\").description(\"Strategy templates — list, clone, propose\");\nregisterStrategyTemplateCommands(strategy);\n\n// ── Provider info ──\nprogram\n .command(\"providers\")\n .description(\"List available DeFi providers\")\n .action(async () => {\n const { MessariProvider, NansenProvider } = await import(\"./providers/research/index.js\");\n const providers = [new MoonwellProvider(), new UniswapProvider(), new MessariProvider(), new NansenProvider()];\n for (const p of providers) {\n const info = p.info();\n console.log(`\\n${info.name} (${info.type})`);\n console.log(` Capabilities: ${info.capabilities.join(\", \")}`);\n console.log(` Chains: ${info.supportedChains.map((c) => c.name).join(\", \")}`);\n }\n });\n\n// ── Chat commands (lazy-loaded — requires @xmtp/cli binary) ──\ntry {\n const { registerChatCommands } = await import(\"./commands/chat.js\");\n registerChatCommands(program);\n} catch {\n program\n .command(\"chat <name> [action] [actionArgs...]\")\n .description(\"Syndicate chat (XMTP) — requires @xmtp/cli\")\n .action(() => {\n console.error(chalk.red(\"XMTP CLI not available.\"));\n console.error(chalk.dim(\"Install with: npm install -g @xmtp/cli\"));\n console.error(chalk.dim(\"Or reinstall: npm i -g @sherwoodagent/cli\"));\n process.exit(1);\n });\n}\n\n// ── Session commands ──\nconst { registerSessionCommands } = await import(\"./commands/session.js\");\nregisterSessionCommands(program);\n\n// ── Venice commands ──\nregisterVeniceCommands(program);\n\n// ── Allowance commands ──\nregisterAllowanceCommands(program);\n\n// ── Identity commands ──\nregisterIdentityCommands(program);\n\n// ── Proposal commands ──\nregisterProposalCommands(program);\n\n// ── Governor commands ──\nregisterGovernorCommands(program);\n\n// ── Guardian delegation commands (V1.5) ──\nregisterGuardianCommands(program);\n\n// ── Research commands ──\nconst { registerResearchCommands } = await import(\"./commands/research.js\");\nregisterResearchCommands(program);\n\n// ── Agent commands ──\nconst { registerAgentCommands } = await import(\"./commands/agent.js\");\nregisterAgentCommands(program);\n\n// ── Trade commands ──\nconst { registerTradeCommands } = await import(\"./commands/trade.js\");\nregisterTradeCommands(program);\n\n// ── Grid commands ──\nimport { registerGridCommand } from './commands/grid.js';\nregisterGridCommand(program);\n\n// ── Config commands ──\nconst configCmd = program.command(\"config\");\n\nconfigCmd\n .command(\"set\")\n .description(\"Save settings to ~/.sherwood/config.json (persists across sessions)\")\n .option(\"--private-key <key>\", \"Wallet private key (0x-prefixed)\")\n .option(\"--vault <address>\", \"Default SyndicateVault address\")\n .option(\"--rpc <url>\", \"Custom RPC URL for the active --chain network\")\n .option(\"--notify-to <id>\", \"Destination for cron summaries (Telegram chat ID, phone, etc.)\")\n .option(\"--uniswap-api-key <key>\", \"Uniswap Trading API key (from developers.uniswap.org)\")\n .option(\"--venice-api-key <key>\", \"Venice AI inference API key\")\n .option(\"--anthropic-api-key <key>\", \"Anthropic Claude API key (for LLM judge)\")\n .option(\"--xmtp-group <subdomain:groupId>\", \"Cache an XMTP group ID for a syndicate (e.g. my-fund:abc123)\")\n .action((opts) => {\n let saved = false;\n\n if (opts.privateKey) {\n setPrivateKey(opts.privateKey);\n const account = getAccount();\n console.log(chalk.green(\"Private key saved to ~/.sherwood/config.json\"));\n console.log(chalk.dim(` Wallet: ${account.address}`));\n saved = true;\n }\n\n if (opts.vault) {\n const chainId = getChain().id;\n setChainContract(chainId, \"vault\", opts.vault);\n console.log(chalk.green(`Vault saved to ~/.sherwood/config.json (chain ${chainId})`));\n console.log(chalk.dim(` Vault: ${opts.vault}`));\n saved = true;\n }\n\n if (opts.rpc) {\n const network = getNetwork();\n setConfigRpcUrl(network, opts.rpc);\n console.log(chalk.green(`RPC URL saved for ${network}`));\n console.log(chalk.dim(` RPC: ${opts.rpc}`));\n saved = true;\n }\n\n if (opts.notifyTo) {\n setNotifyTo(opts.notifyTo);\n console.log(chalk.green(\"Notify destination saved to ~/.sherwood/config.json\"));\n console.log(chalk.dim(` Notify to: ${opts.notifyTo}`));\n saved = true;\n }\n\n if (opts.uniswapApiKey) {\n setUniswapApiKey(opts.uniswapApiKey);\n console.log(chalk.green(\"Uniswap API key saved to ~/.sherwood/config.json\"));\n saved = true;\n }\n\n if (opts.veniceApiKey) {\n setVeniceApiKey(opts.veniceApiKey);\n console.log(chalk.green(\"Venice API key saved to ~/.sherwood/config.json\"));\n saved = true;\n }\n\n if (opts.anthropicApiKey) {\n setAnthropicApiKey(opts.anthropicApiKey);\n console.log(chalk.green(\"Anthropic API key saved to ~/.sherwood/config.json\"));\n saved = true;\n }\n\n if (opts.xmtpGroup) {\n const parts = opts.xmtpGroup.split(\":\");\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n console.log(chalk.red(\"Format: --xmtp-group <subdomain>:<groupId>\"));\n process.exit(1);\n }\n cacheGroupId(parts[0], parts[1]);\n console.log(chalk.green(`XMTP group ID cached for ${parts[0]}`));\n console.log(chalk.dim(` Group ID: ${parts[1]}`));\n saved = true;\n }\n\n if (!saved) {\n console.log(chalk.red(\"Provide at least one of: --private-key, --vault, --rpc, --notify-to, --uniswap-api-key, --venice-api-key, --anthropic-api-key, --xmtp-group\"));\n process.exit(1);\n }\n });\n\nconfigCmd\n .command(\"show\")\n .description(\"Display current config for the active network\")\n .action(() => {\n const network = getNetwork();\n const chainId = getChain().id;\n const contracts = getChainContracts(chainId);\n const config = loadConfig();\n const customRpc = config.rpc?.[network];\n\n console.log();\n console.log(chalk.bold(`Sherwood Config`));\n console.log(chalk.dim(\"─\".repeat(50)));\n console.log(` Network: ${chalk.cyan(network)} (chain ${chainId})`);\n console.log(` RPC: ${customRpc ? chalk.green(customRpc) : chalk.dim(\"default\")}`);\n console.log(` Wallet: ${config.privateKey ? chalk.green(\"configured\") : chalk.dim(\"not set\")}`);\n console.log(` Agent ID: ${config.agentId ?? chalk.dim(\"not set\")}`);\n console.log(` Vault: ${contracts.vault ?? chalk.dim(\"not set\")}`);\n console.log(` Uniswap: ${getUniswapApiKey() ? chalk.green(\"API key configured\") : chalk.dim(\"not set\")}`);\n console.log(` Venice: ${getVeniceApiKey() ? chalk.green(\"API key configured\") : chalk.dim(\"not set\")}`);\n\n // Show XMTP group IDs\n const groupEntries = Object.entries(config.groupCache || {}).filter(([, v]) => v);\n if (groupEntries.length > 0) {\n console.log();\n console.log(chalk.bold(\" XMTP Groups\"));\n for (const [sub, gid] of groupEntries) {\n console.log(` ${sub}: ${chalk.cyan(gid)}`);\n }\n }\n\n console.log();\n console.log(chalk.dim(\" Config file: ~/.sherwood/config.json\"));\n console.log();\n });\n\nprogram.parse();\n","// TODO: Not yet implemented. All methods throw \"Not implemented\".\n// This provider is registered but non-functional.\n\nimport type { Address, Chain } from \"viem\";\nimport { base, baseSepolia } from \"viem/chains\";\nimport type { LendingProvider, ProviderInfo, DepositParams, BorrowParams, RepayParams, WithdrawParams, TxResult, LendingPosition } from \"../types.js\";\nimport { MOONWELL as getMoonwell } from \"../lib/addresses.js\";\n\nexport class MoonwellProvider implements LendingProvider {\n info(): ProviderInfo {\n return {\n name: \"moonwell\",\n type: \"lending\",\n capabilities: [\n \"lend.deposit\",\n \"lend.borrow\",\n \"lend.repay\",\n \"lend.withdraw\",\n \"lend.positions\",\n ],\n supportedChains: [base, baseSepolia],\n };\n }\n\n async depositCollateral(params: DepositParams): Promise<TxResult> {\n // TODO: Build and send tx via viem\n throw new Error(\"Not implemented — wire up viem client\");\n }\n\n async borrow(params: BorrowParams): Promise<TxResult> {\n throw new Error(\"Not implemented\");\n }\n\n async repay(params: RepayParams): Promise<TxResult> {\n throw new Error(\"Not implemented\");\n }\n\n async withdrawCollateral(params: WithdrawParams): Promise<TxResult> {\n throw new Error(\"Not implemented\");\n }\n\n async getPosition(account: Address): Promise<LendingPosition> {\n throw new Error(\"Not implemented\");\n }\n}\n","/**\n * Strategy template commands — clone, build calls, propose, rebalance, status.\n *\n * Replaces the old strategy registry commands with template-based workflow:\n * sherwood strategy list — show available templates\n * sherwood strategy clone — clone + initialize a template\n * sherwood strategy propose — clone + init + build calls + submit proposal (all-in-one)\n * sherwood strategy status — read portfolio allocations + state\n * sherwood strategy rebalance — sell-all/re-buy at current target weights (Portfolio only)\n */\n\nimport type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { parseUnits, formatUnits, isAddress, erc20Abi, encodeAbiParameters, decodeAbiParameters } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { writeFileSync, mkdirSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nimport { getPublicClient, getAccount, writeContractWithRetry, waitForReceipt, formatContractError } from \"../lib/client.js\";\nimport { getChain, getExplorerUrl, getNetwork, CHAIN_REGISTRY } from \"../lib/network.js\";\nimport { getCachedSwapRoute, cacheSwapRoute, type SwapRoute } from \"../lib/config.js\";\nimport { TOKENS, MOONWELL, VENICE, AERODROME, UNISWAP, STRATEGY_TEMPLATES, SYNTHRA, CHAINLINK } from \"../lib/addresses.js\";\nimport { BASE_STRATEGY_ABI, PORTFOLIO_STRATEGY_ABI, SYNDICATE_VAULT_ABI, HYPERLIQUID_PERP_STRATEGY_ABI } from \"../lib/abis.js\";\nimport { cloneTemplate } from \"../lib/clone.js\";\nimport { resolveTokenInput } from \"../lib/tokens.js\";\nimport { HYPERLIQUID_GRID_STRATEGY_ABI } from \"../grid/strategy-abi.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\nimport { formatBatch } from \"../lib/batch.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeStrategyDeploy, encodePropose, type ChainId } from \"@sherwoodagent/sdk\";\n\nimport * as moonwellBuilder from \"../strategies/moonwell-supply-template.js\";\nimport * as veniceBuilder from \"../strategies/venice-inference-template.js\";\nimport * as aerodromeBuilder from \"../strategies/aerodrome-lp-template.js\";\nimport * as wstethBuilder from \"../strategies/wsteth-moonwell-template.js\";\nimport * as mamoBuilder from \"../strategies/mamo-yield-template.js\";\nimport * as portfolioBuilder from \"../strategies/portfolio-template.js\";\nimport * as hyperliquidPerpBuilder from \"../strategies/hyperliquid-perp-template.js\";\nimport * as hyperliquidGridBuilder from \"../strategies/hyperliquid-grid-template.js\";\n\nimport { concat, numberToHex, size } from \"viem\";\n\nconst ZERO: Address = \"0x0000000000000000000000000000000000000000\";\n\n// ── Uniswap V3 swap routing helpers ──\n\n/**\n * Encode Uniswap V3 packed path: token (20 bytes) + fee (3 bytes) + token (20 bytes) [+ fee + token ...]\n */\nfunction encodeV3Path(tokens: Address[], fees: number[]): Hex {\n if (tokens.length !== fees.length + 1) throw new Error(\"tokens.length must be fees.length + 1\");\n const parts: Hex[] = [];\n for (let i = 0; i < tokens.length; i++) {\n parts.push(tokens[i].toLowerCase() as Hex);\n if (i < fees.length) {\n // fee as 3 bytes (uint24)\n parts.push(numberToHex(fees[i], { size: 3 }));\n }\n }\n return concat(parts);\n}\n\n/**\n * Build swapExtraData for the UniswapSwapAdapter.\n *\n * Mode 0 — single-hop: 0x00 + abi.encode(uint24 fee)\n * Mode 1 — multi-hop: 0x01 + abi.encode(bytes path)\n *\n * For Synthra (Robinhood), extraData is just abi.encode(uint24 fee) with no mode prefix.\n */\nfunction buildSwapExtraData(\n network: string,\n tokenIn: Address,\n tokenOut: Address,\n feeTier: number,\n hop?: { via: Address; feeIn: number; feeOut: number },\n): Hex {\n if (network === \"robinhood-testnet\") {\n // SynthraDirectAdapter: plain abi.encode(uint24 fee)\n return encodeAbiParameters([{ type: \"uint24\" }], [feeTier]);\n }\n\n if (hop) {\n // Multi-hop: tokenIn → hop.via → tokenOut\n const path = encodeV3Path([tokenIn, hop.via, tokenOut], [hop.feeIn, hop.feeOut]);\n const encoded = encodeAbiParameters([{ type: \"bytes\" }], [path]);\n return `0x01${encoded.slice(2)}` as Hex;\n }\n\n // Single-hop: mode 0\n const encoded = encodeAbiParameters([{ type: \"uint24\" }], [feeTier]);\n return `0x00${encoded.slice(2)}` as Hex;\n}\n\n/**\n * Auto-detect swap route for a token pair on Uniswap V3.\n * Returns { direct: true, feeTier } or { direct: false, hop } or null if no route found.\n */\nasync function detectSwapRoute(\n asset: Address,\n token: Address,\n preferredFeeTier: number,\n): Promise<{ extraData: Hex; routeDesc: string } | null> {\n const network = getNetwork();\n if (network === \"robinhood-testnet\") {\n return {\n extraData: buildSwapExtraData(network, asset, token, preferredFeeTier),\n routeDesc: `direct (fee ${preferredFeeTier})`,\n };\n }\n\n const chainId = CHAIN_REGISTRY[network].chain.id;\n\n // Check config cache first\n const cached = getCachedSwapRoute(chainId, asset, token);\n if (cached) {\n const extraData = cached.hop\n ? buildSwapExtraData(network, asset, token, 0, {\n via: cached.hop.via as Address,\n feeIn: cached.hop.feeIn,\n feeOut: cached.hop.feeOut,\n })\n : buildSwapExtraData(network, asset, token, cached.feeTier);\n const desc = cached.hop\n ? `cached multi-hop: ${cached.hop.feeIn}→WETH→${cached.hop.feeOut}`\n : `cached direct (fee ${cached.feeTier})`;\n return { extraData, routeDesc: desc };\n }\n\n const publicClient = getPublicClient();\n const quoterAddr = UNISWAP().QUOTER_V2;\n const quoterAbi = [{\n type: \"function\",\n name: \"quoteExactInputSingle\",\n inputs: [{ type: \"tuple\", components: [\n { type: \"address\", name: \"tokenIn\" },\n { type: \"address\", name: \"tokenOut\" },\n { type: \"uint256\", name: \"amountIn\" },\n { type: \"uint24\", name: \"fee\" },\n { type: \"uint160\", name: \"sqrtPriceLimitX96\" },\n ]}],\n outputs: [\n { type: \"uint256\" }, { type: \"uint160\" }, { type: \"uint32\" }, { type: \"uint256\" },\n ],\n stateMutability: \"nonpayable\",\n }] as const;\n\n // 1. Try direct at preferred fee tier\n const testAmount = asset.toLowerCase() === TOKENS().USDC.toLowerCase() ? 1_000_000n : 1_000_000_000_000_000n; // 1 USDC or 0.001 WETH\n const feeTiers = [preferredFeeTier, 10000, 3000, 500].filter((v, i, a) => a.indexOf(v) === i);\n\n for (const fee of feeTiers) {\n try {\n await publicClient.simulateContract({\n address: quoterAddr,\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [{ tokenIn: asset, tokenOut: token, amountIn: testAmount, fee, sqrtPriceLimitX96: 0n }],\n });\n cacheSwapRoute(chainId, asset, token, { mode: \"direct\", feeTier: fee, detectedAt: Math.floor(Date.now() / 1000) });\n return {\n extraData: buildSwapExtraData(network, asset, token, fee),\n routeDesc: `direct (fee ${fee})`,\n };\n } catch {\n // No pool at this fee tier\n }\n }\n\n // 2. Try multi-hop via WETH\n const weth = TOKENS().WETH;\n if (asset.toLowerCase() === weth.toLowerCase()) return null; // Already tried direct with WETH\n\n // Find best USDC→WETH fee\n let bestAssetToWethFee: number | null = null;\n for (const fee of [500, 3000, 10000]) {\n try {\n await publicClient.simulateContract({\n address: quoterAddr,\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [{ tokenIn: asset, tokenOut: weth, amountIn: testAmount, fee, sqrtPriceLimitX96: 0n }],\n });\n bestAssetToWethFee = fee;\n break; // 500 is cheapest, prefer it\n } catch {}\n }\n if (!bestAssetToWethFee) return null;\n\n // Find best WETH→token fee\n const wethTestAmount = 1_000_000_000_000_000n; // 0.001 WETH\n for (const fee of feeTiers) {\n try {\n await publicClient.simulateContract({\n address: quoterAddr,\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [{ tokenIn: weth, tokenOut: token, amountIn: wethTestAmount, fee, sqrtPriceLimitX96: 0n }],\n });\n const hop = { via: weth, feeIn: bestAssetToWethFee, feeOut: fee };\n cacheSwapRoute(chainId, asset, token, { mode: \"multi-hop\", feeTier: 0, hop, detectedAt: Math.floor(Date.now() / 1000) });\n return {\n extraData: buildSwapExtraData(network, asset, token, 0, hop),\n routeDesc: `multi-hop: ${bestAssetToWethFee}→WETH→${fee}`,\n };\n } catch {}\n }\n\n return null; // No route found\n}\n\n// ── Template definitions ──\n\ninterface TemplateDef {\n name: string;\n key: string;\n description: string;\n addressKey: keyof ReturnType<typeof STRATEGY_TEMPLATES>;\n}\n\nconst TEMPLATES: TemplateDef[] = [\n {\n name: \"Moonwell Supply\",\n key: \"moonwell-supply\",\n description: \"Supply tokens to Moonwell lending market, earn yield\",\n addressKey: \"MOONWELL_SUPPLY\",\n },\n {\n name: \"Aerodrome LP\",\n key: \"aerodrome-lp\",\n description: \"Provide liquidity on Aerodrome DEX + optional gauge staking\",\n addressKey: \"AERODROME_LP\",\n },\n {\n name: \"Venice Inference\",\n key: \"venice-inference\",\n description: \"Stake VVV for sVVV — Venice private AI inference\",\n addressKey: \"VENICE_INFERENCE\",\n },\n {\n name: \"wstETH Moonwell Yield\",\n key: \"wsteth-moonwell\",\n description: \"WETH → wstETH → Moonwell — stack Lido + lending yield\",\n addressKey: \"WSTETH_MOONWELL\",\n },\n {\n name: \"Mamo Yield\",\n key: \"mamo-yield\",\n description: \"Deposit into Mamo for optimized yield across Moonwell + Morpho vaults\",\n addressKey: \"MAMO_YIELD\",\n },\n {\n name: \"Portfolio\",\n key: \"portfolio\",\n description: \"Weighted portfolio of tokens (stock tokens, crypto) with rebalancing\",\n addressKey: \"PORTFOLIO\",\n },\n {\n name: \"Hyperliquid Perp\",\n key: \"hyperliquid-perp\",\n description: \"Leveraged perp trading on Hyperliquid via HyperEVM precompiles\",\n addressKey: \"HYPERLIQUID_PERP\",\n },\n {\n name: \"Hyperliquid Grid\",\n key: \"hyperliquid-grid\",\n description: \"ATR-based grid trading on Hyperliquid via HyperEVM precompiles\",\n addressKey: \"HYPERLIQUID_GRID\",\n },\n];\n\nfunction resolveTemplate(key: string): { def: TemplateDef; address: Address } {\n const def = TEMPLATES.find((t) => t.key === key);\n if (!def) {\n console.error(chalk.red(`Unknown template: ${key}`));\n console.error(chalk.dim(`Available: ${TEMPLATES.map((t) => t.key).join(\", \")}`));\n process.exit(1);\n }\n const address = STRATEGY_TEMPLATES()[def.addressKey];\n if (address === ZERO) {\n console.error(chalk.red(`Template \"${def.name}\" not deployed on this network.`));\n process.exit(1);\n }\n return { def, address };\n}\n\n// ── Helpers for building init data per template ──\n\n/**\n * Pure (no-RPC) derivation of the assets a propose call will pull from the\n * vault. Mirrors the asset/amount slice of `buildInitDataForTemplate` so the\n * propose preflight can balance-check the vault BEFORE clone + init burns\n * any gas. Returns one entry per token the vault has to fund — single\n * entry for most templates, two for aerodrome-lp (tokenA + tokenB).\n *\n * Templates whose amount is `0n` (hyperliquid-perp / -grid in dynamic-all\n * mode, wsteth-moonwell without --amount) intentionally return entries\n * with `amount === 0n`; the caller short-circuits on those.\n *\n * Keep in sync with `buildInitDataForTemplate` per-branch logic. Diverging\n * here only weakens the preflight guard — the real values still come from\n * `buildInitDataForTemplate`, so we'd just miss a warning, never produce\n * an inconsistent on-chain call.\n */\nfunction computeProposalAssetChecks(\n templateKey: string,\n opts: Record<string, string | boolean | undefined>,\n): { asset: Address; amount: bigint; label: string }[] {\n if (templateKey === \"moonwell-supply\" || templateKey === \"mamo-yield\") {\n if (!opts.amount) return [];\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: token.toUpperCase() }];\n }\n\n if (templateKey === \"venice-inference\") {\n if (!opts.amount) return [];\n const assetSymbol = (opts.asset as string) || \"USDC\";\n const asset = resolveToken(assetSymbol);\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: assetSymbol.toUpperCase() }];\n }\n\n if (templateKey === \"aerodrome-lp\") {\n // Aerodrome needs both legs of the pair funded. We can't compute the\n // per-leg parseUnits without a decimals() RPC, so we fall back to a\n // raw-units balance check (vault must hold at least `amountA` raw of\n // tokenA AND `amountB` raw of tokenB). Worst case: a stricter check\n // than needed, never permissive.\n if (!opts.tokenA || !opts.tokenB || !opts.amountA || !opts.amountB) return [];\n // amountA/amountB are human strings — without decimals we can't normalize.\n // Skip the precise check for aerodrome and let buildInitDataForTemplate\n // handle errors. (Other templates cover the common --amount footgun.)\n return [];\n }\n\n if (templateKey === \"wsteth-moonwell\") {\n if (!opts.amount) return []; // dynamic-all mode\n return [{\n asset: TOKENS().WETH,\n amount: parseUnits(opts.amount as string, 18),\n label: \"WETH\",\n }];\n }\n\n if (templateKey === \"portfolio\") {\n if (!opts.amount) return [];\n const defaultAsset = getNetwork() === \"robinhood-testnet\" ? \"WETH\" : \"USDC\";\n const assetSymbol = (opts.asset as string) || defaultAsset;\n const asset = resolveToken(assetSymbol);\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: assetSymbol.toUpperCase() }];\n }\n\n if (templateKey === \"hyperliquid-perp\" || templateKey === \"hyperliquid-grid\") {\n if (!opts.amount) return []; // dynamic-all mode — skip check\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n return [{ asset, amount: parseUnits(opts.amount as string, decimals), label: token.toUpperCase() }];\n }\n\n return [];\n}\n\nasync function buildInitDataForTemplate(\n templateKey: string,\n opts: Record<string, string | boolean | undefined>,\n vault: Address,\n): Promise<{ initData: Hex; asset: Address; assetAmount: bigint; extraApprovals?: { token: Address; amount: bigint }[] }> {\n if (templateKey === \"moonwell-supply\") {\n if (!opts.amount) {\n console.error(chalk.red(\"--amount is required for moonwell-supply template\"));\n process.exit(1);\n }\n const token = (opts.token as string) || \"USDC\";\n const underlying = resolveToken(token);\n const mToken = resolveMToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n const supplyAmount = parseUnits(opts.amount as string, decimals);\n const minRedeem = parseUnits((opts.minRedeem as string) || opts.amount as string, decimals);\n\n return {\n initData: moonwellBuilder.buildInitData(underlying, mToken, supplyAmount, minRedeem),\n asset: underlying,\n assetAmount: supplyAmount,\n };\n }\n\n if (templateKey === \"venice-inference\") {\n if (!opts.amount) {\n console.error(chalk.red(\"--amount is required for venice-inference template\"));\n process.exit(1);\n }\n const assetSymbol = (opts.asset as string) || \"USDC\";\n const asset = resolveToken(assetSymbol);\n const vvv = VENICE().VVV;\n const isDirect = asset.toLowerCase() === vvv.toLowerCase();\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n const assetAmount = parseUnits(opts.amount as string, decimals);\n const agent = (opts.agent as Address) || getAccount().address;\n const isSingleHop = !!opts.singleHop;\n\n // Auto-quote minVVV if not specified (non-direct paths only)\n let minVVV = 0n;\n if (!isDirect) {\n if (opts.minVvv) {\n minVVV = parseUnits(opts.minVvv as string, 18);\n } else {\n // Quote expected VVV out and apply 5% slippage\n const publicClient = getPublicClient();\n const aeroRouterAbi = [{\n name: \"getAmountsOut\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"routes\", type: \"tuple[]\", components: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"stable\", type: \"bool\" },\n { name: \"factory\", type: \"address\" },\n ]},\n ],\n outputs: [{ name: \"amounts\", type: \"uint256[]\" }],\n }] as const;\n\n const routes = isSingleHop\n ? [{ from: asset, to: vvv, stable: false, factory: AERODROME().FACTORY }]\n : [\n { from: asset, to: TOKENS().WETH, stable: false, factory: AERODROME().FACTORY },\n { from: TOKENS().WETH, to: vvv, stable: false, factory: AERODROME().FACTORY },\n ];\n\n try {\n const amounts = await publicClient.readContract({\n address: AERODROME().ROUTER,\n abi: aeroRouterAbi,\n functionName: \"getAmountsOut\",\n args: [assetAmount, routes],\n });\n const expectedVVV = amounts[amounts.length - 1];\n // 5% slippage: minVVV = expectedVVV * 95 / 100\n minVVV = (expectedVVV * 95n) / 100n;\n console.log(chalk.dim(` Auto-quoted minVVV: ${(Number(minVVV) / 1e18).toFixed(4)} VVV (5% slippage on ~${(Number(expectedVVV) / 1e18).toFixed(4)} VVV)`));\n } catch {\n console.error(chalk.red(\"Could not quote USDC→VVV price. Pass --min-vvv <amount> manually.\"));\n process.exit(1);\n }\n }\n }\n\n const params: veniceBuilder.VeniceInferenceInitParams = {\n asset,\n weth: isDirect ? ZERO : TOKENS().WETH,\n vvv,\n sVVV: VENICE().STAKING,\n aeroRouter: isDirect ? ZERO : AERODROME().ROUTER,\n aeroFactory: isDirect ? ZERO : AERODROME().FACTORY,\n agent,\n assetAmount,\n minVVV,\n deadlineOffset: 300n,\n singleHop: isSingleHop,\n };\n\n return {\n initData: veniceBuilder.buildInitData(params),\n asset,\n assetAmount,\n };\n }\n\n if (templateKey === \"aerodrome-lp\") {\n for (const flag of [\"tokenA\", \"tokenB\", \"amountA\", \"amountB\", \"lpToken\"]) {\n if (!opts[flag]) {\n console.error(chalk.red(`--${flag.replace(/([A-Z])/g, \"-$1\").toLowerCase()} is required for aerodrome-lp template`));\n process.exit(1);\n }\n }\n const tokenA = opts.tokenA as Address;\n const tokenB = opts.tokenB as Address;\n const publicClient = getPublicClient();\n const [decimalsA, decimalsB] = await Promise.all([\n publicClient.readContract({ address: tokenA, abi: erc20Abi, functionName: \"decimals\" }),\n publicClient.readContract({ address: tokenB, abi: erc20Abi, functionName: \"decimals\" }),\n ]);\n const amountA = parseUnits(opts.amountA as string, decimalsA);\n const amountB = parseUnits(opts.amountB as string, decimalsB);\n const minAOut = parseUnits((opts.minAOut as string) || \"0\", decimalsA);\n const minBOut = parseUnits((opts.minBOut as string) || \"0\", decimalsB);\n\n const params: aerodromeBuilder.AerodromeLPInitParams = {\n tokenA,\n tokenB,\n stable: !!opts.stable,\n factory: AERODROME().FACTORY,\n router: AERODROME().ROUTER,\n gauge: (opts.gauge as Address) || ZERO,\n lpToken: opts.lpToken as Address,\n amountADesired: amountA,\n amountBDesired: amountB,\n amountAMin: amountA, // use desired as min for now\n amountBMin: amountB,\n minAmountAOut: minAOut,\n minAmountBOut: minBOut,\n };\n\n return {\n initData: aerodromeBuilder.buildInitData(params),\n asset: tokenA,\n assetAmount: amountA,\n extraApprovals: [{ token: tokenB, amount: amountB }],\n };\n }\n\n if (templateKey === \"wsteth-moonwell\") {\n const supplyAmount = opts.amount ? parseUnits(opts.amount as string, 18) : 0n; // WETH = 18 decimals; 0 => use full vault balance at execute time\n const slippageBps = BigInt((opts.slippage as string) || \"500\"); // default 5% slippage\n // Per-unit rates (1e18-scaled) — Aerodrome wstETH/WETH stable pool trades\n // near 1:1, so default the expected rate to 1e18. Slippage cuts from that.\n // Rates scale with amountIn at execute time → dynamic-all mode is safe.\n const ONE = 10n ** 18n;\n const minWstethOutPerWeth = (ONE * (10000n - slippageBps)) / 10000n;\n const minWethOutPerWsteth = (ONE * (10000n - slippageBps)) / 10000n;\n\n const params: wstethBuilder.WstETHMoonwellInitParams = {\n weth: TOKENS().WETH,\n wsteth: TOKENS().wstETH,\n mwsteth: MOONWELL().mWstETH,\n aeroRouter: AERODROME().ROUTER,\n aeroFactory: AERODROME().FACTORY,\n chainlinkWstethEthFeed: CHAINLINK().WSTETH_ETH_FEED,\n supplyAmount,\n minWstethOutPerWeth,\n minWethOutPerWsteth,\n deadlineOffset: 300n,\n };\n\n return {\n initData: wstethBuilder.buildInitData(params),\n asset: TOKENS().WETH,\n assetAmount: supplyAmount,\n };\n }\n\n if (templateKey === \"mamo-yield\") {\n if (!opts.amount) {\n console.error(chalk.red(\"--amount is required for mamo-yield template\"));\n process.exit(1);\n }\n if (!opts.mamoFactory) {\n console.error(chalk.red(\"--mamo-factory is required for mamo-yield template\"));\n process.exit(1);\n }\n const token = (opts.token as string) || \"USDC\";\n const underlying = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n const amount = parseUnits(opts.amount as string, decimals);\n const minRedeemAmount = parseUnits((opts.minRedeem as string) || opts.amount as string, decimals);\n\n return {\n initData: mamoBuilder.buildInitData(underlying, opts.mamoFactory as Address, minRedeemAmount),\n asset: underlying,\n assetAmount: amount,\n };\n }\n\n if (templateKey === \"portfolio\") {\n if (!opts.amount) { console.error(chalk.red(\"--amount is required for portfolio template\")); process.exit(1); }\n if (!opts.tokens || !opts.weights) {\n console.error(chalk.red(\"--tokens and --weights are required for portfolio template\"));\n console.error(chalk.dim(\" --tokens: comma-separated token addresses or symbols\"));\n console.error(chalk.dim(\" --weights: comma-separated bps (must sum to 10000)\"));\n process.exit(1);\n }\n const tokens = TOKENS();\n const defaultAsset = getNetwork() === \"robinhood-testnet\" ? \"WETH\" : \"USDC\";\n const assetSymbol = (opts.asset as string) || defaultAsset;\n const asset = resolveToken(assetSymbol);\n const decimals = assetSymbol.toUpperCase() === \"USDC\" ? 6 : 18;\n const totalAmount = parseUnits(opts.amount as string, decimals);\n const maxSlippageBps = Number((opts.maxSlippage as string) || \"500\");\n const feeTier = (opts.feeTier as string) || \"3000\";\n\n const tokenAddrs = (opts.tokens as string).split(\",\").map((t) => {\n try {\n return resolveTokenInput(t, tokens as Record<string, Address>);\n } catch (err) {\n console.error(chalk.red(err instanceof Error ? err.message : String(err))); process.exit(1);\n }\n });\n const weightsBps = (opts.weights as string).split(\",\").map((w) => Number(w.trim()));\n if (tokenAddrs.length !== weightsBps.length) { console.error(chalk.red(\"--tokens and --weights must have same length\")); process.exit(1); }\n if (weightsBps.reduce((a, b) => a + b, 0) !== 10000) { console.error(chalk.red(`Weights must sum to 10000`)); process.exit(1); }\n\n const swapAdapter = (opts.swapAdapter as Address) || resolveSwapAdapter();\n const chainlinkVerifier = CHAINLINK().VERIFIER_PROXY;\n\n // Auto-detect swap routes for each token\n console.log(chalk.dim(\" Detecting swap routes...\"));\n const allocations: portfolioBuilder.BasketAllocation[] = [];\n for (let i = 0; i < tokenAddrs.length; i++) {\n const token = tokenAddrs[i];\n const route = await detectSwapRoute(asset, token, Number(feeTier));\n if (!route) {\n console.error(chalk.red(`No swap route found for ${token}. No Uniswap V3 pool (direct or via WETH).`));\n process.exit(1);\n }\n console.log(chalk.dim(` ${token.slice(0, 10)}... → ${route.routeDesc}`));\n allocations.push({\n token, weightBps: weightsBps[i],\n swapExtraData: route.extraData,\n // Default Chainlink Data Streams report decimals: 18 for crypto pairs,\n // 8 for tokenized stocks. Tokenized-stock baskets should override\n // explicitly via the CLI flag once exposed; 18 keeps current crypto\n // baskets (TSLA/AMZN/NFLX on Robinhood Chain are 18-dec) correct.\n priceDecimals: 18,\n });\n }\n return {\n initData: portfolioBuilder.buildInitData(asset, swapAdapter, chainlinkVerifier, allocations, totalAmount, maxSlippageBps),\n asset, assetAmount: totalAmount,\n };\n }\n\n if (templateKey === \"hyperliquid-perp\") {\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n // Omit --amount to use the vault's full asset balance at execute time (dynamic-all mode).\n const depositAmount = opts.amount ? parseUnits(opts.amount as string, decimals) : 0n;\n const leverage = Number((opts.leverage as string) || \"10\");\n const assetIndex = Number((opts.assetIndex as string) || \"0\");\n const maxPosition = parseUnits((opts.maxPosition as string) || \"100000\", decimals);\n const maxTradesDay = Number((opts.maxTradesPerDay as string) || \"50\");\n return {\n initData: hyperliquidPerpBuilder.buildInitData(asset, depositAmount, assetIndex, leverage, maxPosition, maxTradesDay),\n asset, assetAmount: depositAmount,\n };\n }\n\n if (templateKey === \"hyperliquid-grid\") {\n const token = (opts.token as string) || \"USDC\";\n const asset = resolveToken(token);\n const decimals = token.toUpperCase() === \"USDC\" ? 6 : 18;\n const depositAmount = opts.amount ? parseUnits(opts.amount as string, decimals) : 0n;\n const leverage = Number((opts.leverage as string) || \"5\");\n const maxOrderSize = parseUnits((opts.maxOrderSize as string) || \"10000\", decimals);\n const maxOrdersPerTick = Number((opts.maxOrdersPerTick as string) || \"20\");\n const assetIndices = ((opts.assetIndices as string) || \"0\")\n .split(\",\")\n .map((s) => Number(s.trim()))\n .filter((n) => !Number.isNaN(n));\n return {\n initData: hyperliquidGridBuilder.buildInitData(asset, depositAmount, leverage, maxOrderSize, maxOrdersPerTick, assetIndices),\n asset, assetAmount: depositAmount,\n };\n }\n\n throw new Error(`No init builder for template: ${templateKey}`);\n}\n\nfunction buildCallsForTemplate(\n templateKey: string,\n clone: Address,\n asset: Address,\n assetAmount: bigint,\n extraApprovals?: { token: Address; amount: bigint }[],\n): { executeCalls: BatchCall[]; settleCalls: BatchCall[] } {\n if (templateKey === \"moonwell-supply\") {\n return {\n executeCalls: moonwellBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: moonwellBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"venice-inference\") {\n return {\n executeCalls: veniceBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: veniceBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"aerodrome-lp\") {\n const tokenB = extraApprovals?.[0]?.token ?? ZERO;\n const amountB = extraApprovals?.[0]?.amount ?? 0n;\n return {\n executeCalls: aerodromeBuilder.buildExecuteCalls(clone, asset, assetAmount, tokenB, amountB),\n settleCalls: aerodromeBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"wsteth-moonwell\") {\n return {\n executeCalls: wstethBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: wstethBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"mamo-yield\") {\n return {\n executeCalls: mamoBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: mamoBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"portfolio\") {\n return {\n executeCalls: portfolioBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: portfolioBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"hyperliquid-perp\") {\n return {\n executeCalls: hyperliquidPerpBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: hyperliquidPerpBuilder.buildSettleCalls(clone),\n };\n }\n\n if (templateKey === \"hyperliquid-grid\") {\n return {\n executeCalls: hyperliquidGridBuilder.buildExecuteCalls(clone, asset, assetAmount),\n settleCalls: hyperliquidGridBuilder.buildSettleCalls(clone),\n };\n }\n\n throw new Error(`No call builder for template: ${templateKey}`);\n}\n\n// ── Token resolution ──\n\nfunction resolveSwapAdapter(): Address {\n const network = getNetwork();\n if (network === \"robinhood-testnet\") {\n if (SYNTHRA().ROUTER === ZERO) { console.error(chalk.red(\"Synthra DEX not available\")); process.exit(1); }\n return \"0xdae81cDCfcB14c56fCeB788A147Fcd6CbEdfEeca\" as Address;\n }\n const adapterAddr = UNISWAP().SWAP_ADAPTER;\n if (adapterAddr !== ZERO) return adapterAddr;\n console.error(chalk.red(\"UniswapSwapAdapter not deployed yet. Use --swap-adapter to specify manually.\"));\n process.exit(1);\n}\n\nfunction resolveToken(symbolOrAddress: string): Address {\n const tokens = TOKENS();\n const tokenMap: Record<string, Address> = {\n USDC: tokens.USDC,\n WETH: tokens.WETH,\n DAI: tokens.DAI,\n AERO: tokens.AERO,\n AAVE: tokens.AAVE,\n VVV: VENICE().VVV,\n };\n try {\n return resolveTokenInput(symbolOrAddress, tokenMap);\n } catch (err) {\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n}\n\nfunction resolveMToken(tokenSymbol: string): Address {\n const upper = tokenSymbol.toUpperCase();\n const moonwell = MOONWELL();\n const mTokenMap: Record<string, Address> = {\n USDC: moonwell.mUSDC,\n WETH: moonwell.mWETH,\n };\n const addr = mTokenMap[upper];\n if (!addr || addr === ZERO) {\n console.error(chalk.red(`No Moonwell market for: ${tokenSymbol}`));\n process.exit(1);\n }\n return addr;\n}\n\nfunction serializeCalls(calls: BatchCall[]): string {\n return JSON.stringify(\n calls.map((c) => ({\n target: c.target,\n data: c.data,\n value: c.value.toString(),\n })),\n null,\n 2,\n );\n}\n\n// ── Commands ──\n\nexport function registerStrategyTemplateCommands(strategy: Command): void {\n // ── strategy list ──\n\n strategy\n .command(\"list\")\n .description(\"List available strategy templates\")\n .action(() => {\n const templates = STRATEGY_TEMPLATES();\n const network = getNetwork();\n\n console.log();\n console.log(chalk.bold(\"Strategy Templates\"), chalk.dim(`(${network})`));\n console.log(chalk.dim(\"─\".repeat(60)));\n\n let availableCount = 0;\n for (const t of TEMPLATES) {\n const addr = templates[t.addressKey];\n if (addr !== ZERO) {\n availableCount++;\n console.log();\n console.log(` ${chalk.bold(t.name)} (${chalk.cyan(t.key)})`);\n console.log(` ${t.description}`);\n console.log(` Template: ${chalk.green(addr)}`);\n }\n }\n\n if (availableCount === 0) {\n console.log();\n console.log(chalk.yellow(\" No strategy templates deployed on this network.\"));\n }\n\n const unavailable = TEMPLATES.filter((t) => templates[t.addressKey] === ZERO);\n if (unavailable.length > 0) {\n console.log();\n console.log(chalk.dim(` Not available on ${network}:`));\n for (const t of unavailable) {\n console.log(chalk.dim(` ${t.name} (${t.key})`));\n }\n }\n\n console.log();\n console.log(chalk.dim(\"Clone a template: sherwood strategy clone <template> --vault <addr> ...\"));\n console.log(chalk.dim(\"Full proposal: sherwood strategy propose <template> --vault <addr> ...\"));\n console.log();\n });\n\n // ── strategy clone ──\n\n strategy\n .command(\"clone\")\n .description(\"Clone a strategy template and initialize it\")\n .argument(\"<template>\", \"Template: moonwell-supply, aerodrome-lp, venice-inference, wsteth-moonwell, mamo-yield, portfolio, hyperliquid-perp, hyperliquid-grid\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n // moonwell-supply / wsteth-moonwell\n .option(\"--amount <n>\", \"Asset amount to deploy\")\n .option(\"--min-redeem <n>\", \"Min asset on settlement (Moonwell)\")\n .option(\"--token <symbol>\", \"Asset token symbol (default: USDC)\")\n // venice-inference\n .option(\"--asset <symbol>\", \"Asset token (USDC, VVV, or address)\")\n .option(\"--agent <address>\", \"Agent wallet (Venice, default: your wallet)\")\n .option(\"--min-vvv <n>\", \"Min VVV from swap (Venice)\")\n .option(\"--single-hop\", \"Single-hop Aerodrome swap (Venice)\")\n // aerodrome-lp\n .option(\"--token-a <address>\", \"Token A (Aerodrome)\")\n .option(\"--token-b <address>\", \"Token B (Aerodrome)\")\n .option(\"--amount-a <n>\", \"Token A amount (Aerodrome)\")\n .option(\"--amount-b <n>\", \"Token B amount (Aerodrome)\")\n .option(\"--stable\", \"Stable pool (Aerodrome)\")\n .option(\"--gauge <address>\", \"Gauge address (Aerodrome)\")\n .option(\"--lp-token <address>\", \"LP token address (Aerodrome)\")\n .option(\"--min-a-out <n>\", \"Min token A on settle (Aerodrome)\")\n .option(\"--min-b-out <n>\", \"Min token B on settle (Aerodrome)\")\n // wsteth-moonwell\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (wstETH, default: 500 = 5%)\")\n // mamo-yield\n .option(\"--mamo-factory <address>\", \"Mamo StrategyFactory address (Mamo)\")\n // portfolio\n .option(\"--tokens <list>\", \"Comma-separated token addresses or symbols (Portfolio)\")\n .option(\"--weights <list>\", \"Comma-separated weights in bps, must sum to 10000 (Portfolio)\")\n .option(\"--max-slippage <bps>\", \"Max slippage bps (Portfolio, default: 500)\")\n .option(\"--fee-tier <n>\", \"Pool fee tier (Portfolio, default: 3000)\")\n .option(\"--swap-adapter <address>\", \"Swap adapter address (Portfolio)\")\n // hyperliquid-perp\n .option(\"--leverage <number>\", \"Leverage multiplier (Hyperliquid Perp, default: 10)\")\n .option(\"--asset-index <number>\", \"Perp asset index (Hyperliquid Perp, default: 0 for BTC)\")\n .option(\"--max-position <amount>\", \"Max position size in USD (Hyperliquid Perp, default: 100000)\")\n .option(\"--max-trades-per-day <n>\", \"Max trades per day (Hyperliquid Perp, default: 50)\")\n .option(\"--max-order-size <amount>\", \"Max single-order size in asset units (Hyperliquid Grid, default: 10000)\")\n .option(\"--max-orders-per-tick <n>\", \"Max orders per tick (Hyperliquid Grid, default: 20)\")\n .option(\"--asset-indices <list>\", \"Comma-separated perp asset indices (Hyperliquid Grid, default: 0)\")\n .action(async (templateKey: string, opts) => {\n const vault = opts.vault as Address;\n if (!isAddress(vault)) {\n console.error(chalk.red(\"Invalid vault address\"));\n process.exit(1);\n }\n\n const { def, address: templateAddr } = resolveTemplate(templateKey);\n\n // 1. Clone\n const cloneSpinner = ora(`Cloning ${def.name} template...`).start();\n let clone: Address;\n let cloneHash: Hex;\n try {\n const result = await cloneTemplate(templateAddr);\n clone = result.clone;\n cloneHash = result.hash;\n cloneSpinner.succeed(`Cloned: ${chalk.green(clone)}`);\n console.log(chalk.dim(` Tx: ${getExplorerUrl(cloneHash)}`));\n } catch (err) {\n cloneSpinner.fail(\"Clone failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 2. Initialize\n const initSpinner = ora(\"Initializing strategy...\").start();\n try {\n const { initData } = await buildInitDataForTemplate(templateKey, opts, vault);\n const account = getAccount();\n\n const initHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"initialize\",\n args: [vault, account.address, initData],\n });\n\n const receipt = await waitForReceipt(initHash);\n if (receipt.status === \"reverted\") {\n throw new Error(\"Initialize transaction reverted on-chain\");\n }\n initSpinner.succeed(\"Initialized\");\n } catch (err) {\n initSpinner.fail(\"Initialize failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 3. HyperCore registration (grid + perp)\n // BaseStrategy.initialize() writes address(this) to slot 0 (_hcSelf). HC\n // reads slot 0 post-block via FirstStorageSlot variant — no nonce\n // derivation needed.\n if (templateKey === \"hyperliquid-grid\" || templateKey === \"hyperliquid-perp\") {\n const hcSpinner = ora(\"Registering clone with HyperCore...\").start();\n try {\n const account = getAccount();\n const hcHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: templateKey === \"hyperliquid-grid\" ? HYPERLIQUID_GRID_STRATEGY_ABI : HYPERLIQUID_PERP_STRATEGY_ABI,\n functionName: \"finalizeForHyperCore\",\n args: [0n, 1, 0n], // token=USDC, variant=FirstStorageSlot(1), nonce unused\n });\n await waitForReceipt(hcHash);\n hcSpinner.succeed(\"HyperCore registration sent (active after next block)\");\n } catch (err) {\n hcSpinner.warn(\"HyperCore registration failed — run finalizeForHyperCore manually\");\n console.error(chalk.yellow(formatContractError(err)));\n }\n }\n\n console.log();\n console.log(chalk.bold(\"Strategy clone ready:\"), chalk.green(clone));\n console.log(chalk.dim(\"Use this address in your proposal batch calls.\"));\n console.log();\n });\n\n // ── strategy init ──\n\n strategy\n .command(\"init\")\n .description(\"Initialize an already-deployed but uninitialized strategy clone\")\n .argument(\"<template>\", \"Template: moonwell-supply, aerodrome-lp, venice-inference, wsteth-moonwell, mamo-yield, portfolio, hyperliquid-perp, hyperliquid-grid\")\n .requiredOption(\"--clone <address>\", \"Clone address to initialize\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n // moonwell-supply / wsteth-moonwell\n .option(\"--amount <n>\", \"Asset amount to deploy\")\n .option(\"--min-redeem <n>\", \"Min asset on settlement (Moonwell)\")\n .option(\"--token <symbol>\", \"Asset token symbol (default: USDC)\")\n // venice-inference\n .option(\"--asset <symbol>\", \"Asset token (USDC, VVV, or address)\")\n .option(\"--agent <address>\", \"Agent wallet (Venice, default: your wallet)\")\n .option(\"--min-vvv <n>\", \"Min VVV from swap (Venice)\")\n .option(\"--single-hop\", \"Single-hop Aerodrome swap (Venice)\")\n // aerodrome-lp\n .option(\"--token-a <address>\", \"Token A (Aerodrome)\")\n .option(\"--token-b <address>\", \"Token B (Aerodrome)\")\n .option(\"--amount-a <n>\", \"Token A amount (Aerodrome)\")\n .option(\"--amount-b <n>\", \"Token B amount (Aerodrome)\")\n .option(\"--stable\", \"Stable pool (Aerodrome)\")\n .option(\"--gauge <address>\", \"Gauge address (Aerodrome)\")\n .option(\"--lp-token <address>\", \"LP token address (Aerodrome)\")\n .option(\"--min-a-out <n>\", \"Min token A on settle (Aerodrome)\")\n .option(\"--min-b-out <n>\", \"Min token B on settle (Aerodrome)\")\n // wsteth-moonwell\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (wstETH, default: 500 = 5%)\")\n // mamo-yield\n .option(\"--mamo-factory <address>\", \"Mamo StrategyFactory address (Mamo)\")\n // portfolio\n .option(\"--tokens <list>\", \"Comma-separated token addresses or symbols (Portfolio)\")\n .option(\"--weights <list>\", \"Comma-separated weights in bps, must sum to 10000 (Portfolio)\")\n .option(\"--max-slippage <bps>\", \"Max slippage bps (Portfolio, default: 500)\")\n .option(\"--fee-tier <n>\", \"Pool fee tier (Portfolio, default: 3000)\")\n .option(\"--swap-adapter <address>\", \"Swap adapter address (Portfolio)\")\n // hyperliquid-perp\n .option(\"--leverage <number>\", \"Leverage multiplier (Hyperliquid Perp, default: 10)\")\n .option(\"--asset-index <number>\", \"Perp asset index (Hyperliquid Perp, default: 0 for BTC)\")\n .option(\"--max-position <amount>\", \"Max position size in USD (Hyperliquid Perp, default: 100000)\")\n .option(\"--max-trades-per-day <n>\", \"Max trades per day (Hyperliquid Perp, default: 50)\")\n .option(\"--max-order-size <amount>\", \"Max single-order size in asset units (Hyperliquid Grid, default: 10000)\")\n .option(\"--max-orders-per-tick <n>\", \"Max orders per tick (Hyperliquid Grid, default: 20)\")\n .option(\"--asset-indices <list>\", \"Comma-separated perp asset indices (Hyperliquid Grid, default: 0)\")\n .action(async (templateKey: string, opts) => {\n const clone = opts.clone as Address;\n const vault = opts.vault as Address;\n if (!isAddress(clone)) {\n console.error(chalk.red(\"Invalid clone address\"));\n process.exit(1);\n }\n if (!isAddress(vault)) {\n console.error(chalk.red(\"Invalid vault address\"));\n process.exit(1);\n }\n\n resolveTemplate(templateKey); // validate template exists\n\n // Check if already initialized\n const publicClient = getPublicClient();\n const currentVault = await publicClient.readContract({\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"vault\",\n }) as Address;\n\n if (currentVault !== \"0x0000000000000000000000000000000000000000\") {\n console.error(chalk.red(`Clone already initialized (vault: ${currentVault})`));\n process.exit(1);\n }\n\n const initSpinner = ora(\"Initializing strategy clone...\").start();\n try {\n const { initData } = await buildInitDataForTemplate(templateKey, opts, vault);\n const account = getAccount();\n\n const initHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"initialize\",\n args: [vault, account.address, initData],\n });\n\n const receipt = await waitForReceipt(initHash);\n if (receipt.status === \"reverted\") {\n throw new Error(\"Initialize transaction reverted on-chain\");\n }\n initSpinner.succeed(\"Initialized\");\n console.log(chalk.dim(` Tx: ${getExplorerUrl(initHash)}`));\n } catch (err) {\n initSpinner.fail(\"Initialize failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Verify\n const verifiedVault = await publicClient.readContract({\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"vault\",\n }) as Address;\n\n console.log();\n console.log(chalk.bold(\"Clone initialized:\"), chalk.green(clone));\n console.log(` Vault: ${chalk.green(verifiedVault)}`);\n console.log(` Proposer: ${chalk.green(getAccount().address)}`);\n console.log();\n });\n\n // ── strategy propose ──\n\n strategy\n .command(\"propose\")\n .description(\"Clone + init + build calls + submit governance proposal (all-in-one)\")\n .argument(\"<template>\", \"Template: moonwell-supply, aerodrome-lp, venice-inference, wsteth-moonwell, mamo-yield, portfolio, hyperliquid-perp, hyperliquid-grid\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .option(\"--write-calls <dir>\", \"Write execute/settle JSON to directory (skip proposal submission)\")\n // proposal metadata (required unless --write-calls)\n .option(\"--name <name>\", \"Proposal name\")\n .option(\"--description <text>\", \"Proposal description\")\n .option(\"--performance-fee <bps>\", \"Agent fee in bps\")\n .option(\"--duration <duration>\", \"Strategy duration (7d, 24h, etc.)\")\n // external-signer (--calldata-only) flow\n .option(\"--proposer <address>\", \"Proposer/agent address (required for --calldata-only — the external signer)\")\n .option(\"--metadata-uri <uri>\", \"Metadata URI (required for --calldata-only — IPFS pin needs a signer)\")\n .option(\"--salt <bytes32>\", \"CREATE2 salt for the deterministic clone (--calldata-only; default: derived from inputs)\")\n // template-specific (same as clone)\n .option(\"--amount <n>\", \"Asset amount to deploy\")\n .option(\"--min-redeem <n>\", \"Min asset on settlement (Moonwell)\")\n .option(\"--token <symbol>\", \"Asset token symbol (default: USDC)\")\n .option(\"--asset <symbol>\", \"Asset token (USDC, VVV, or address)\")\n .option(\"--agent <address>\", \"Agent wallet (Venice, default: your wallet)\")\n .option(\"--min-vvv <n>\", \"Min VVV from swap (Venice)\")\n .option(\"--single-hop\", \"Single-hop Aerodrome swap (Venice)\")\n .option(\"--token-a <address>\", \"Token A (Aerodrome)\")\n .option(\"--token-b <address>\", \"Token B (Aerodrome)\")\n .option(\"--amount-a <n>\", \"Token A amount (Aerodrome)\")\n .option(\"--amount-b <n>\", \"Token B amount (Aerodrome)\")\n .option(\"--stable\", \"Stable pool (Aerodrome)\")\n .option(\"--gauge <address>\", \"Gauge address (Aerodrome)\")\n .option(\"--lp-token <address>\", \"LP token address (Aerodrome)\")\n .option(\"--min-a-out <n>\", \"Min token A on settle (Aerodrome)\")\n .option(\"--min-b-out <n>\", \"Min token B on settle (Aerodrome)\")\n // wsteth-moonwell\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (wstETH, default: 500 = 5%)\")\n // mamo-yield\n .option(\"--mamo-factory <address>\", \"Mamo StrategyFactory address (Mamo)\")\n // portfolio\n .option(\"--tokens <list>\", \"Comma-separated token addresses or symbols (Portfolio)\")\n .option(\"--weights <list>\", \"Comma-separated weights in bps, must sum to 10000 (Portfolio)\")\n .option(\"--max-slippage <bps>\", \"Max slippage bps (Portfolio, default: 500)\")\n .option(\"--fee-tier <n>\", \"Pool fee tier (Portfolio, default: 3000)\")\n .option(\"--swap-adapter <address>\", \"Swap adapter address (Portfolio)\")\n // hyperliquid-perp\n .option(\"--leverage <number>\", \"Leverage multiplier (Hyperliquid Perp, default: 10)\")\n .option(\"--asset-index <number>\", \"Perp asset index (Hyperliquid Perp, default: 0 for BTC)\")\n .option(\"--max-position <amount>\", \"Max position size in USD (Hyperliquid Perp, default: 100000)\")\n .option(\"--max-trades-per-day <n>\", \"Max trades per day (Hyperliquid Perp, default: 50)\")\n .option(\"--max-order-size <amount>\", \"Max single-order size in asset units (Hyperliquid Grid, default: 10000)\")\n .option(\"--max-orders-per-tick <n>\", \"Max orders per tick (Hyperliquid Grid, default: 20)\")\n .option(\"--asset-indices <list>\", \"Comma-separated perp asset indices (Hyperliquid Grid, default: 0)\")\n .action(async (templateKey: string, opts) => {\n const vault = opts.vault as Address;\n if (!isAddress(vault)) {\n console.error(chalk.red(\"Invalid vault address\"));\n process.exit(1);\n }\n\n const { def, address: templateAddr } = resolveTemplate(templateKey);\n\n // --calldata-only: deploy the clone DETERMINISTICALLY (CREATE2 via\n // StrategyFactory) so its address is known up front, then emit BOTH the\n // clone+init tx and the propose tx as unsigned calldata. propose only\n // stores the strategy address (it doesn't call the clone), so the two txs\n // just need to land before the proposal executes. Template-agnostic — the\n // only per-template piece is initData. Closes the #387 keyless gap.\n if (isCalldataOnly()) {\n // Note: when --metadata-uri is omitted we pin proposal metadata ourselves\n // (the IPFS upload endpoint is unauthenticated HTTP — no signer needed), so\n // --name feeds that pinned JSON. --metadata-uri stays as an override that\n // carries its own name/description.\n const missing: string[] = [];\n if (!opts.proposer) missing.push(\"--proposer <address> (the external signer)\");\n if (!opts.metadataUri && !opts.name) missing.push(\"--name <name> (or --metadata-uri <uri>)\");\n if (!opts.performanceFee) missing.push(\"--performance-fee <bps>\");\n if (!opts.duration) missing.push(\"--duration <d>\");\n if (missing.length > 0) {\n console.error(chalk.red(`--calldata-only requires: ${missing.join(\", \")}`));\n process.exit(1);\n }\n const proposer = opts.proposer as Address;\n if (!isAddress(proposer)) {\n console.error(chalk.red(\"Invalid --proposer address\"));\n process.exit(1);\n }\n const performanceFeeBps = Number(opts.performanceFee);\n if (!Number.isInteger(performanceFeeBps) || performanceFeeBps < 0 || performanceFeeBps > 10000) {\n console.error(chalk.red(\"--performance-fee must be an integer 0-10000 (bps)\"));\n process.exit(1);\n }\n\n // Read-only preflight (no private key needed). Fail fast instead of\n // emitting calldata that will revert: cloneAndInitDeterministic + propose\n // both require the proposer to be a registered agent of the vault, and a\n // sub-balance vault reverts at execute. (The template-allowlist and\n // proposer == msg.sender checks can't be done off-chain — the emitted\n // note covers them: don't broadcast tx 2 unless tx 1 confirms.)\n try {\n const publicClient = getPublicClient();\n const [isRegistered, paused] = await Promise.all([\n publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"isAgent\",\n args: [proposer],\n }) as Promise<boolean>,\n publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"paused\",\n }) as Promise<boolean>,\n ]);\n if (!isRegistered) {\n console.error(\n chalk.red(\n `--proposer ${proposer} is not a registered agent on ${vault}; cloneAndInitDeterministic and propose will both revert.`,\n ),\n );\n console.error(chalk.yellow(` Register first: sherwood syndicate approve --wallet ${proposer}`));\n process.exit(1);\n }\n if (paused) {\n console.error(chalk.red(`Vault ${vault} is paused — the proposal would revert.`));\n process.exit(1);\n }\n for (const check of computeProposalAssetChecks(templateKey, opts)) {\n if (check.amount === 0n) continue;\n const [balance, decimals] = await Promise.all([\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [vault],\n }) as Promise<bigint>,\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"decimals\",\n }) as Promise<number>,\n ]);\n if (balance < check.amount) {\n console.error(\n chalk.red(\n `Vault ${vault} holds ${formatUnits(balance, decimals)} ${check.label} but the proposal needs ${formatUnits(check.amount, decimals)} ${check.label}.`,\n ),\n );\n console.error(chalk.yellow(` Hint: --amount is in human units (e.g. \"10\" = 10 ${check.label}), not raw decimals.`));\n process.exit(1);\n }\n }\n } catch (err) {\n console.error(chalk.red(`Preflight read failed: ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n // The venice builder defaults its agent to the signer's wallet; pin it to\n // the proposer so buildInitDataForTemplate never reaches for getAccount()\n // (there's no private key in calldata-only mode).\n if (!opts.agent) opts.agent = proposer;\n\n const { parseDuration } = await import(\"../lib/governor.js\");\n const strategyDuration = parseDuration(opts.duration as string);\n const chainId = getChain().id as ChainId;\n\n try {\n const built = await buildInitDataForTemplate(templateKey, opts, vault);\n const deploy = encodeStrategyDeploy(\n {\n template: templateAddr,\n vault,\n proposer,\n initData: built.initData,\n salt: opts.salt as Hex | undefined,\n },\n chainId,\n );\n const { executeCalls, settleCalls } = buildCallsForTemplate(\n templateKey, deploy.clone, built.asset, built.assetAmount, built.extraApprovals,\n );\n let metadataURI = opts.metadataUri as string | undefined;\n if (!metadataURI) {\n const { pinJSON } = await import(\"../lib/ipfs.js\");\n try {\n metadataURI = await pinJSON(\n {\n name: opts.name,\n description: opts.description || \"\",\n proposer,\n vault,\n strategyClone: deploy.clone,\n template: def.key,\n performanceFeeBps,\n strategyDuration: Number(strategyDuration),\n createdAt: new Date().toISOString(),\n },\n opts.name as string,\n );\n } catch {\n metadataURI = `data:application/json;base64,${Buffer.from(\n JSON.stringify({ name: opts.name, description: opts.description || \"\", vault }),\n ).toString(\"base64\")}`;\n }\n }\n const proposeAction = encodePropose(\n {\n vault,\n strategy: deploy.clone,\n metadataURI,\n performanceFeeBps,\n strategyDuration,\n executeCalls,\n settlementCalls: settleCalls,\n },\n chainId,\n );\n emitCalldata({\n txs: [...deploy.txs, ...proposeAction.txs],\n preconditions: [...deploy.preconditions, ...proposeAction.preconditions],\n // Surface the deterministic clone + salt as structured fields (also\n // baked into tx 2's `strategy` arg + the execute/settle calls).\n clone: deploy.clone,\n salt: deploy.salt,\n description:\n `Keyless ${def.name} proposal on ${vault}: (1) deploy clone at ${deploy.clone} ` +\n `(deterministic CREATE2, salt ${deploy.salt}); (2) governor.propose referencing it.`,\n note:\n \"Broadcast SEQUENTIALLY: send tx 1 (cloneAndInitDeterministic) and WAIT for it to confirm, then send tx 2 (propose). \" +\n \"If tx 1 reverts — proposer not a registered agent, proposer != tx-1 signer, template not allowlisted, or vault unregistered — do NOT send tx 2: it would create a proposal referencing an undeployed strategy. \" +\n \"Send tx 1 from the --proposer wallet (the factory requires proposer == msg.sender, and msg.sender must be a vault owner/agent). \" +\n \"The clone address is pinned by (factory, template, vault, salt) and is already baked into tx 2 + the execute/settle calls. \" +\n \"The factory binds the salt to the vault and only the vault's owner/agents may deploy there, so the predicted address can't be front-run.\",\n } as Parameters<typeof emitCalldata>[0]);\n } catch (err) {\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n return;\n }\n\n // 0. Preflight — bail out before burning gas on clone + init for a\n // proposal the governor will refuse anyway. Two read-only checks,\n // no gas cost.\n const account = getAccount();\n const preflightSpinner = ora(\"Preflight checks...\").start();\n try {\n const publicClient = getPublicClient();\n\n // (a) Signer must be a registered active agent on this vault.\n const isRegistered = await publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"isAgent\",\n args: [account.address],\n });\n if (!isRegistered) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(\n chalk.red(\n ` Signer ${account.address} is not a registered agent on ${vault}.\\n` +\n ` Register first via: sherwood syndicate approve --wallet ${account.address}`,\n ),\n );\n process.exit(1);\n }\n\n // (b) Vault must not be paused (deposits + governance ops would revert).\n const paused = await publicClient.readContract({\n address: vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"paused\",\n });\n if (paused) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(chalk.red(` Vault ${vault} is paused. Cannot propose.`));\n process.exit(1);\n }\n\n // (c) Vault must hold enough of the proposal's asset to fund execute.\n // Catches the most common --amount footgun (passing raw decimal\n // units, e.g. 10000000, when the CLI already applies parseUnits\n // and the vault only holds 10 USDC). Without this guard the\n // proposal still passes propose+vote but `_pullFromVault` reverts\n // at execute with \"ERC20: transfer amount exceeds balance\".\n const checks = computeProposalAssetChecks(templateKey, opts);\n for (const check of checks) {\n if (check.amount === 0n) continue;\n const [balance, decimals] = await Promise.all([\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [vault],\n }) as Promise<bigint>,\n publicClient.readContract({\n address: check.asset,\n abi: erc20Abi,\n functionName: \"decimals\",\n }) as Promise<number>,\n ]);\n if (balance < check.amount) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(\n chalk.red(\n ` Vault ${vault} holds ${formatUnits(balance, decimals)} ${check.label} ` +\n `but proposal requires ${formatUnits(check.amount, decimals)} ${check.label}.`,\n ),\n );\n console.error(\n chalk.yellow(\n ` Hint: --amount is in human units (e.g. \\\"10\\\" = 10 ${check.label}), not raw decimals.`,\n ),\n );\n process.exit(1);\n }\n }\n\n preflightSpinner.succeed(\"Preflight OK\");\n } catch (err) {\n preflightSpinner.fail(\"Preflight failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 1. Clone\n const cloneSpinner = ora(`Cloning ${def.name} template...`).start();\n let clone: Address;\n try {\n const result = await cloneTemplate(templateAddr);\n clone = result.clone;\n cloneSpinner.succeed(`Cloned: ${chalk.green(clone)}`);\n console.log(chalk.dim(` Tx: ${getExplorerUrl(result.hash)}`));\n } catch (err) {\n cloneSpinner.fail(\"Clone failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 2. Initialize\n const initSpinner = ora(\"Initializing strategy...\").start();\n let asset: Address;\n let assetAmount: bigint;\n let extraApprovals: { token: Address; amount: bigint }[] | undefined;\n try {\n const built = await buildInitDataForTemplate(templateKey, opts, vault);\n asset = built.asset;\n assetAmount = built.assetAmount;\n extraApprovals = built.extraApprovals;\n\n // account hoisted above during preflight — reuse.\n const initHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: BASE_STRATEGY_ABI,\n functionName: \"initialize\",\n args: [vault, account.address, built.initData],\n });\n\n const initReceipt = await waitForReceipt(initHash);\n if (initReceipt.status === \"reverted\") {\n throw new Error(\"Initialize transaction reverted on-chain\");\n }\n initSpinner.succeed(\"Initialized\");\n } catch (err) {\n initSpinner.fail(\"Initialize failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 2b. HyperCore registration (grid + perp) — hard prerequisite before propose.\n // BaseStrategy.initialize() writes address(this) to slot 0 (_hcSelf). HC\n // reads slot 0 post-block via FirstStorageSlot variant. Without\n // registration the proposal will execute but the bridge can't credit\n // HC spot, burning a governance cycle on a doomed batch.\n if (templateKey === \"hyperliquid-grid\" || templateKey === \"hyperliquid-perp\") {\n const hcSpinner = ora(\"Registering clone with HyperCore...\").start();\n try {\n const hcHash = await writeContractWithRetry({\n account,\n chain: getChain(),\n address: clone,\n abi: templateKey === \"hyperliquid-grid\" ? HYPERLIQUID_GRID_STRATEGY_ABI : HYPERLIQUID_PERP_STRATEGY_ABI,\n functionName: \"finalizeForHyperCore\",\n args: [0n, 1, 0n], // token=USDC, variant=FirstStorageSlot(1), nonce unused\n });\n await waitForReceipt(hcHash);\n hcSpinner.succeed(\"HyperCore registration sent (active after next block)\");\n } catch (err) {\n hcSpinner.fail(\"HyperCore registration failed — aborting proposal submission\");\n console.error(chalk.red(formatContractError(err)));\n console.error(\n chalk.yellow(\n `Retry by calling finalizeForHyperCore(0, 1, 0) on ${clone}, then re-run propose.`,\n ),\n );\n process.exit(1);\n }\n }\n\n // 3. Build batch calls\n const { executeCalls, settleCalls } = buildCallsForTemplate(\n templateKey, clone, asset, assetAmount, extraApprovals,\n );\n\n console.log();\n console.log(chalk.bold(`Execute calls (${executeCalls.length}):`));\n console.log(formatBatch(executeCalls));\n console.log(chalk.bold(`Settle calls (${settleCalls.length}):`));\n console.log(formatBatch(settleCalls));\n\n // 4. Write files or submit proposal\n if (opts.writeCalls) {\n const dir = resolve(opts.writeCalls as string);\n mkdirSync(dir, { recursive: true });\n\n const execPath = resolve(dir, \"execute.json\");\n const settlePath = resolve(dir, \"settle.json\");\n writeFileSync(execPath, serializeCalls(executeCalls));\n writeFileSync(settlePath, serializeCalls(settleCalls));\n\n console.log();\n console.log(chalk.green(`Execute calls: ${execPath}`));\n console.log(chalk.green(`Settle calls: ${settlePath}`));\n console.log(chalk.green(`Clone address: ${clone}`));\n console.log();\n console.log(chalk.dim(\"Submit with:\"));\n console.log(chalk.dim(` sherwood proposal create \\\\`));\n console.log(chalk.dim(` --vault ${vault} \\\\`));\n console.log(chalk.dim(` --name \"...\" --description \"...\" \\\\`));\n console.log(chalk.dim(` --performance-fee 0 --duration 7d \\\\`));\n console.log(chalk.dim(` --execute-calls ${execPath} \\\\`));\n console.log(chalk.dim(` --settle-calls ${settlePath}`));\n\n if (templateKey === \"venice-inference\") {\n console.log();\n console.log(chalk.yellow(\"Reminder: before settlement, agent must approve repayment:\"));\n console.log(chalk.yellow(` asset.approve(${clone}, <repaymentAmount>)`));\n console.log(chalk.yellow(\" Agent can update repayment via strategy.updateParams(newRepayment, 0, 0)\"));\n }\n\n console.log();\n return;\n }\n\n // Direct proposal submission requires metadata flags\n if (!opts.name || !opts.performanceFee || !opts.duration) {\n console.error(chalk.red(\"Missing --name, --performance-fee, or --duration. Use --write-calls to skip proposal submission.\"));\n process.exit(1);\n }\n\n // Lazy import governor to avoid pulling it in for --write-calls path\n const { propose } = await import(\"../lib/governor.js\");\n const { pinJSON } = await import(\"../lib/ipfs.js\");\n const { parseDuration } = await import(\"../lib/governor.js\");\n\n const performanceFeeBps = BigInt(opts.performanceFee as string);\n if (performanceFeeBps < 0n || performanceFeeBps > 10000n) {\n console.error(chalk.red(\"--performance-fee must be 0-10000 (basis points)\"));\n process.exit(1);\n }\n const strategyDuration = parseDuration(opts.duration as string);\n // account already hoisted at preflight.\n\n const metaSpinner = ora(\"Pinning metadata to IPFS...\").start();\n let metadataURI: string;\n try {\n const metadata = {\n name: opts.name,\n description: opts.description || \"\",\n proposer: account.address,\n vault,\n strategyClone: clone,\n template: def.key,\n performanceFeeBps: Number(performanceFeeBps),\n strategyDuration: Number(strategyDuration),\n createdAt: new Date().toISOString(),\n };\n metadataURI = await pinJSON(metadata, opts.name as string);\n metaSpinner.succeed(`Metadata pinned: ${metadataURI}`);\n } catch (err) {\n metaSpinner.fail(\"IPFS pin failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Submit proposal with the freshly-cloned strategy address. Under the\n // strategy-on-proposal model the strategy is set immutably at propose\n // time — no separate bind step. If the strategy doesn't implement\n // `positionValue()` (legacy clones, perp-only) the vault's runtime\n // try/catch falls back to queue-only redemptions during execution.\n const proposeSpinner = ora(\"Submitting proposal...\").start();\n try {\n const { hash, proposalId } = await propose(\n vault,\n clone,\n metadataURI,\n performanceFeeBps,\n strategyDuration,\n executeCalls,\n settleCalls,\n );\n proposeSpinner.succeed(`Proposal #${proposalId} created — strategy=${clone} set on proposal`);\n console.log(`Proposal #${proposalId}`);\n console.log(chalk.dim(` Tx: ${getExplorerUrl(hash)}`));\n console.log(chalk.dim(` Clone: ${clone}`));\n } catch (err) {\n proposeSpinner.fail(\"Proposal failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n if (templateKey === \"venice-inference\") {\n console.log();\n console.log(chalk.yellow(\"Next steps:\"));\n console.log(chalk.yellow(\" 1. After execution: sherwood venice provision\"));\n console.log(chalk.yellow(\" 2. Use inference: sherwood venice infer --model <id> --prompt '...'\"));\n console.log(chalk.yellow(\" 3. Before settlement: approve repayment (principal + profit):\"));\n console.log(chalk.yellow(` asset.approve(${clone}, <repaymentAmount>)`));\n }\n\n console.log();\n });\n\n // ── strategy status ──\n\n strategy\n .command(\"status\")\n .description(\"Show portfolio strategy status — allocations, balances, drift, PnL (Portfolio only)\")\n .argument(\"<clone>\", \"Strategy clone address\")\n .option(\"--json\", \"Output machine-readable JSON for agent consumption\")\n .action(async (cloneArg: string, opts) => {\n if (!isAddress(cloneArg)) {\n console.error(chalk.red(\"Invalid clone address\"));\n process.exit(1);\n }\n const clone = cloneArg as Address;\n const publicClient = getPublicClient();\n const network = getNetwork();\n const jsonMode = !!opts.json;\n\n const spinner = jsonMode ? null : ora(\"Reading strategy state...\").start();\n try {\n // Read strategy state + swap extra data (for fee tiers)\n const [stateRaw, vault, proposer, assetAddr, totalAmount, maxSlippage, allocations, swapExtraData] = await Promise.all([\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"state\" }),\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"vault\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"proposer\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"asset\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"totalAmount\" }) as Promise<bigint>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"maxSlippageBps\" }) as Promise<bigint>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"getAllocations\" }) as Promise<readonly { token: Address; targetWeightBps: bigint; tokenAmount: bigint; investedAmount: bigint }[]>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"getSwapExtraData\" }) as Promise<readonly `0x${string}`[]>,\n ]);\n\n const stateNames = [\"Pending\", \"Executed\", \"Settled\"];\n const stateStr = stateNames[Number(stateRaw)] || `Unknown(${stateRaw})`;\n\n // Read asset decimals & symbol\n const [assetDecimals, assetSymbol] = await Promise.all([\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"decimals\" }),\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"symbol\" }),\n ]);\n\n // Read current token balances & symbols in parallel\n const tokenReads = allocations.map((a) => Promise.all([\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"balanceOf\", args: [clone] }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"symbol\" }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"decimals\" }),\n ]));\n const tokenData = await Promise.all(tokenReads);\n\n // Read asset balance held by strategy\n const assetBalance = await publicClient.readContract({\n address: assetAddr,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [clone],\n });\n\n // Extract fee tiers from swapExtraData (abi.encode(uint24 fee))\n const feeTiers = swapExtraData.map((data) => {\n try {\n const [fee] = decodeAbiParameters([{ type: \"uint24\" }], data);\n return Number(fee) > 0 && Number(fee) <= 100000 ? Number(fee) : 3000;\n } catch {\n return 3000;\n }\n });\n\n // Fetch prices (graceful — continues without if unavailable)\n let prices: (import(\"../lib/price.js\").TokenPrice | null)[] = [];\n let priceSource: \"uniswap\" | \"synthra\" | null = null;\n try {\n const { getTokenPricesInAsset } = await import(\"../lib/price.js\");\n prices = await getTokenPricesInAsset({\n tokens: allocations.map((a, i) => ({\n token: a.token,\n tokenDecimals: tokenData[i][2] as number,\n feeTier: feeTiers[i],\n })),\n asset: assetAddr,\n assetDecimals,\n });\n priceSource = prices.find((p) => p !== null)?.source ?? null;\n } catch {\n // Prices unavailable — continue with balance-only\n }\n\n const pricesAvailable = prices.some((p) => p !== null);\n\n // Compute enriched allocation data\n const assetBalanceNum = Number(formatUnits(assetBalance as bigint, assetDecimals));\n let totalPortfolioValue = assetBalanceNum;\n let totalInvested = 0n;\n\n interface AllocStatus {\n token: Address;\n symbol: string;\n decimals: number;\n targetWeightBps: number;\n balance: string;\n balanceRaw: string;\n investedAmount: string;\n currentPrice: number | null;\n currentValue: number | null;\n actualWeightBps: number | null;\n driftBps: number | null;\n pnl: number | null;\n pnlPct: number | null;\n }\n\n const allocStatuses: AllocStatus[] = allocations.map((alloc, i) => {\n const [balance, symbol, decimals] = tokenData[i];\n const balanceNum = Number(formatUnits(balance as bigint, decimals));\n const investedNum = Number(formatUnits(alloc.investedAmount, assetDecimals));\n totalInvested += alloc.investedAmount;\n\n const price = prices[i];\n let currentValue: number | null = null;\n\n if (price) {\n currentValue = balanceNum * price.price;\n totalPortfolioValue += currentValue;\n }\n\n return {\n token: alloc.token,\n symbol: symbol as string,\n decimals: decimals as number,\n targetWeightBps: Number(alloc.targetWeightBps),\n balance: formatUnits(balance as bigint, decimals),\n balanceRaw: (balance as bigint).toString(),\n investedAmount: formatUnits(alloc.investedAmount, assetDecimals),\n currentPrice: price?.price ?? null,\n currentValue,\n actualWeightBps: null, // computed after totals\n driftBps: null,\n pnl: currentValue !== null ? currentValue - investedNum : null,\n pnlPct: currentValue !== null && investedNum > 0\n ? ((currentValue - investedNum) / investedNum) * 100\n : null,\n };\n });\n\n // Second pass: compute actual weights and drift (needs totalPortfolioValue)\n let maxDriftBps = 0;\n let maxDriftToken = \"\";\n if (pricesAvailable && totalPortfolioValue > 0) {\n for (const a of allocStatuses) {\n if (a.currentValue !== null) {\n a.actualWeightBps = Math.round((a.currentValue / totalPortfolioValue) * 10000);\n a.driftBps = a.actualWeightBps - a.targetWeightBps;\n if (Math.abs(a.driftBps) > Math.abs(maxDriftBps)) {\n maxDriftBps = a.driftBps;\n maxDriftToken = a.symbol;\n }\n }\n }\n }\n\n // Total PnL\n const totalInvestedNum = Number(formatUnits(totalInvested, assetDecimals));\n const totalPnl = pricesAvailable ? totalPortfolioValue - totalInvestedNum : null;\n const totalPnlPct = totalPnl !== null && totalInvestedNum > 0\n ? (totalPnl / totalInvestedNum) * 100\n : null;\n\n spinner?.succeed(\"Strategy state loaded\");\n\n // ── JSON output ──\n if (jsonMode) {\n const result = {\n clone,\n vault,\n proposer,\n state: stateStr,\n network,\n asset: { address: assetAddr, symbol: assetSymbol as string, decimals: assetDecimals as number },\n totalDeployed: formatUnits(totalAmount, assetDecimals),\n maxSlippageBps: Number(maxSlippage),\n assetBalance: formatUnits(assetBalance as bigint, assetDecimals),\n pricesAvailable,\n priceSource,\n portfolio: {\n totalValue: pricesAvailable ? totalPortfolioValue : null,\n totalPnl,\n totalPnlPct,\n },\n allocations: allocStatuses,\n maxDriftBps: pricesAvailable ? maxDriftBps : null,\n maxDriftToken: pricesAvailable ? maxDriftToken : null,\n timestamp: new Date().toISOString(),\n };\n process.stdout.write(JSON.stringify(result) + \"\\n\");\n return;\n }\n\n // ── Human-friendly output ──\n const stateColor = stateStr === \"Executed\" ? chalk.green : stateStr === \"Settled\" ? chalk.blue : chalk.yellow;\n\n console.log();\n console.log(chalk.bold(\"Portfolio Strategy Status\"));\n console.log(chalk.dim(\"─\".repeat(70)));\n console.log(` Clone: ${chalk.cyan(clone)}`);\n console.log(` Vault: ${chalk.cyan(vault)}`);\n console.log(` Proposer: ${chalk.cyan(proposer)}`);\n console.log(` State: ${stateColor(stateStr)}`);\n console.log(` Asset: ${assetSymbol} (${assetAddr})`);\n console.log(` Deployed: ${formatUnits(totalAmount, assetDecimals)} ${assetSymbol}`);\n console.log(` Max Slip: ${Number(maxSlippage) / 100}%`);\n console.log(` Asset held: ${formatUnits(assetBalance as bigint, assetDecimals)} ${assetSymbol}`);\n\n if (pricesAvailable) {\n const pvStr = totalPortfolioValue.toFixed(6);\n const pnlStr = totalPnl !== null ? (totalPnl >= 0 ? \"+\" : \"\") + totalPnl.toFixed(6) : \"n/a\";\n const pnlPctStr = totalPnlPct !== null ? (totalPnlPct >= 0 ? \"+\" : \"\") + totalPnlPct.toFixed(1) + \"%\" : \"\";\n const pnlColor = totalPnl !== null && totalPnl >= 0 ? chalk.green : chalk.red;\n console.log(` Value: ${pvStr} ${assetSymbol} | PnL: ${pnlColor(`${pnlStr} (${pnlPctStr})`)}`);\n console.log(` Price src: ${priceSource}`);\n }\n\n console.log();\n console.log(chalk.bold(\"Allocations\"));\n console.log(chalk.dim(\"─\".repeat(70)));\n\n if (pricesAvailable) {\n // Price-enriched table\n console.log(\n chalk.dim(\" Token\".padEnd(10)) +\n chalk.dim(\"Target\".padEnd(9)) +\n chalk.dim(\"Actual\".padEnd(9)) +\n chalk.dim(\"Drift\".padEnd(8)) +\n chalk.dim(\"Value\".padEnd(16)) +\n chalk.dim(\"PnL\".padEnd(16)) +\n chalk.dim(\"Balance\"),\n );\n\n for (const a of allocStatuses) {\n const targetStr = (a.targetWeightBps / 100).toFixed(1) + \"%\";\n const actualStr = a.actualWeightBps !== null ? (a.actualWeightBps / 100).toFixed(1) + \"%\" : \"—\";\n const driftStr = a.driftBps !== null\n ? (a.driftBps >= 0 ? \"+\" : \"\") + a.driftBps\n : \"—\";\n const driftColor = a.driftBps !== null\n ? (Math.abs(a.driftBps) > 500 ? chalk.red : Math.abs(a.driftBps) > 200 ? chalk.yellow : chalk.dim)\n : chalk.dim;\n const valueStr = a.currentValue !== null ? a.currentValue.toFixed(6) : \"—\";\n const pnlPctStr = a.pnlPct !== null ? (a.pnlPct >= 0 ? \"+\" : \"\") + a.pnlPct.toFixed(1) + \"%\" : \"—\";\n const pnlColor = a.pnlPct !== null ? (a.pnlPct >= 0 ? chalk.green : chalk.red) : chalk.dim;\n\n console.log(\n ` ${chalk.bold(a.symbol.padEnd(8))}` +\n `${targetStr.padEnd(9)}` +\n `${actualStr.padEnd(9)}` +\n `${driftColor(driftStr.toString().padEnd(8))}` +\n `${valueStr.padEnd(16)}` +\n `${pnlColor(pnlPctStr.padEnd(16))}` +\n `${a.balance}`,\n );\n }\n } else {\n // Balance-only table (no prices available)\n console.log(chalk.dim(\" Prices unavailable — showing raw balances only.\"));\n console.log();\n console.log(\n chalk.dim(\" Token\".padEnd(12)) +\n chalk.dim(\"Weight\".padEnd(10)) +\n chalk.dim(\"Invested\".padEnd(18)) +\n chalk.dim(\"Balance\".padEnd(18)) +\n chalk.dim(\"Address\"),\n );\n\n for (const a of allocStatuses) {\n const weightPct = (a.targetWeightBps / 100).toFixed(1) + \"%\";\n console.log(\n ` ${chalk.bold(a.symbol.padEnd(10))}` +\n `${weightPct.padEnd(10)}` +\n `${a.investedAmount.padEnd(18)}` +\n `${a.balance.padEnd(18)}` +\n `${chalk.dim(a.token)}`,\n );\n }\n }\n\n console.log(chalk.dim(\"─\".repeat(70)));\n console.log(` Total invested: ${formatUnits(totalInvested, assetDecimals)} ${assetSymbol}`);\n\n if (pricesAvailable && maxDriftToken) {\n const absMaxDrift = Math.abs(maxDriftBps);\n const driftColor = absMaxDrift > 500 ? chalk.red : absMaxDrift > 200 ? chalk.yellow : chalk.green;\n console.log(` Max drift: ${driftColor(`${maxDriftBps > 0 ? \"+\" : \"\"}${maxDriftBps} bps`)} (${maxDriftToken})`);\n }\n\n if (stateStr === \"Executed\") {\n console.log();\n console.log(chalk.dim(\"Rebalance: sherwood strategy rebalance \" + clone));\n console.log(chalk.dim(\"With new weights: sherwood strategy rebalance \" + clone + \" --new-weights 2500,2500,2000,1500,1500\"));\n }\n\n console.log();\n } catch (err) {\n spinner?.fail(\"Failed to read strategy state\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── strategy rebalance ──\n\n strategy\n .command(\"rebalance\")\n .description(\"Rebalance a portfolio strategy — sell all positions, re-buy at target weights (Portfolio only)\")\n .argument(\"<clone>\", \"Strategy clone address\")\n .option(\"--new-weights <list>\", \"Comma-separated new weights in bps (must sum to 10000). Updates weights before rebalancing.\")\n .option(\"--max-slippage <bps>\", \"New max slippage bps (used with --new-weights)\")\n .option(\"--dry-run\", \"Show what would happen without executing\")\n .action(async (cloneArg: string, opts) => {\n if (!isAddress(cloneArg)) {\n console.error(chalk.red(\"Invalid clone address\"));\n process.exit(1);\n }\n const clone = cloneArg as Address;\n const publicClient = getPublicClient();\n const account = getAccount();\n const chain = getChain();\n\n // 1. Verify strategy state\n const verifySpinner = ora(\"Verifying strategy state...\").start();\n try {\n const [stateRaw, proposer, assetAddr, allocations] = await Promise.all([\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"state\" }),\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"proposer\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"asset\" }) as Promise<Address>,\n publicClient.readContract({ address: clone, abi: PORTFOLIO_STRATEGY_ABI, functionName: \"getAllocations\" }) as Promise<readonly { token: Address; targetWeightBps: bigint; tokenAmount: bigint; investedAmount: bigint }[]>,\n ]);\n\n // Check state\n if (Number(stateRaw) !== 1) { // State.Executed = 1\n const stateNames = [\"Pending\", \"Executed\", \"Settled\"];\n verifySpinner.fail(`Strategy is ${stateNames[Number(stateRaw)] || \"Unknown\"}, must be Executed to rebalance`);\n process.exit(1);\n }\n\n // Check proposer\n if (proposer.toLowerCase() !== account.address.toLowerCase()) {\n verifySpinner.fail(`Only the proposer (${proposer}) can rebalance. Your wallet: ${account.address}`);\n process.exit(1);\n }\n\n const [assetDecimals, assetSymbol] = await Promise.all([\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"decimals\" }),\n publicClient.readContract({ address: assetAddr, abi: erc20Abi, functionName: \"symbol\" }),\n ]);\n\n // Read current balances\n const tokenReads = allocations.map((a) => Promise.all([\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"balanceOf\", args: [clone] }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"symbol\" }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"decimals\" }),\n ]));\n const tokenData = await Promise.all(tokenReads);\n\n verifySpinner.succeed(\"Strategy is Executed — ready to rebalance\");\n\n // Show current allocations\n console.log();\n console.log(chalk.bold(\"Current Allocations\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (let i = 0; i < allocations.length; i++) {\n const alloc = allocations[i];\n const [balance, symbol, decimals] = tokenData[i];\n const weightPct = (Number(alloc.targetWeightBps) / 100).toFixed(1) + \"%\";\n console.log(\n ` ${chalk.bold((symbol as string).padEnd(8))} ` +\n `${weightPct.padEnd(8)} ` +\n `bal: ${formatUnits(balance as bigint, decimals)}`,\n );\n }\n\n // Parse new weights if provided\n let newWeightsBps: number[] | undefined;\n if (opts.newWeights) {\n newWeightsBps = (opts.newWeights as string).split(\",\").map((w) => Number(w.trim()));\n if (newWeightsBps.length !== allocations.length) {\n console.error(chalk.red(`--new-weights must have ${allocations.length} values (one per token)`));\n process.exit(1);\n }\n const weightSum = newWeightsBps.reduce((a, b) => a + b, 0);\n if (weightSum !== 10000) {\n console.error(chalk.red(`Weights must sum to 10000, got ${weightSum}`));\n process.exit(1);\n }\n\n console.log();\n console.log(chalk.bold(\"New Target Weights\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (let i = 0; i < allocations.length; i++) {\n const [, symbol] = tokenData[i];\n const oldPct = (Number(allocations[i].targetWeightBps) / 100).toFixed(1);\n const newPct = (newWeightsBps[i] / 100).toFixed(1);\n const arrow = oldPct !== newPct ? chalk.yellow(\"→\") : chalk.dim(\"→\");\n console.log(` ${chalk.bold((symbol as string).padEnd(8))} ${oldPct}% ${arrow} ${newPct}%`);\n }\n }\n\n if (opts.dryRun) {\n console.log();\n console.log(chalk.yellow(\"Dry run — no transactions sent.\"));\n console.log(chalk.dim(\"The rebalance would:\"));\n console.log(chalk.dim(\" 1. Sell all current token positions back to \" + assetSymbol));\n console.log(chalk.dim(\" 2. Re-buy at \" + (newWeightsBps ? \"new\" : \"current\") + \" target weights\"));\n console.log();\n return;\n }\n\n // 2. Update weights first (if specified)\n if (newWeightsBps) {\n const maxSlip = Number((opts.maxSlippage as string) || \"0\");\n const swapData = await publicClient.readContract({\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"getSwapExtraData\",\n }) as Hex[];\n\n const updateSpinner = ora(\"Updating target weights...\").start();\n try {\n const innerData = encodeAbiParameters(\n [{ type: \"uint256[]\" }, { type: \"uint256\" }, { type: \"bytes[]\" }],\n [newWeightsBps.map((w: number) => BigInt(w)), BigInt(maxSlip), swapData],\n );\n\n const updateHash = await writeContractWithRetry({\n account,\n chain,\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"updateParams\",\n args: [innerData],\n });\n\n const receipt = await waitForReceipt(updateHash);\n if (receipt.status === \"reverted\") throw new Error(\"updateParams reverted\");\n updateSpinner.succeed(\"Target weights updated\");\n console.log(chalk.dim(` Tx: ${getExplorerUrl(updateHash)}`));\n } catch (err) {\n updateSpinner.fail(\"Failed to update weights\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n }\n\n // 3. Execute rebalance\n const rebalanceSpinner = ora(\"Rebalancing portfolio (sell all → re-buy at targets)...\").start();\n try {\n const rebalanceHash = await writeContractWithRetry({\n account,\n chain,\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"rebalance\",\n });\n\n const receipt = await waitForReceipt(rebalanceHash);\n if (receipt.status === \"reverted\") throw new Error(\"rebalance() reverted on-chain\");\n rebalanceSpinner.succeed(\"Portfolio rebalanced\");\n console.log(chalk.dim(` Tx: ${getExplorerUrl(rebalanceHash)}`));\n } catch (err) {\n rebalanceSpinner.fail(\"Rebalance failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // 4. Show updated balances\n const postSpinner = ora(\"Reading updated allocations...\").start();\n const postAllocations = await publicClient.readContract({\n address: clone,\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"getAllocations\",\n }) as readonly { token: Address; targetWeightBps: bigint; tokenAmount: bigint; investedAmount: bigint }[];\n\n const postReads = postAllocations.map((a) => Promise.all([\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"balanceOf\", args: [clone] }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"symbol\" }),\n publicClient.readContract({ address: a.token, abi: erc20Abi, functionName: \"decimals\" }),\n ]));\n const postData = await Promise.all(postReads);\n postSpinner.succeed(\"Updated allocations\");\n\n console.log();\n console.log(chalk.bold(\"Post-Rebalance Allocations\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (let i = 0; i < postAllocations.length; i++) {\n const alloc = postAllocations[i];\n const [balance, symbol, decimals] = postData[i];\n const weightPct = (Number(alloc.targetWeightBps) / 100).toFixed(1) + \"%\";\n const investedStr = formatUnits(alloc.investedAmount, assetDecimals);\n console.log(\n ` ${chalk.bold((symbol as string).padEnd(8))} ` +\n `${weightPct.padEnd(8)} ` +\n `invested: ${investedStr.padEnd(14)} ` +\n `bal: ${formatUnits(balance as bigint, decimals)}`,\n );\n }\n\n console.log();\n console.log(chalk.green(\"✓ Rebalance complete\"));\n console.log();\n } catch (err: any) {\n if (err.code === \"ERR_MODULE_NOT_FOUND\" || err instanceof TypeError) throw err;\n verifySpinner.fail(\"Pre-flight check failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * ERC-1167 minimal proxy cloning from TypeScript.\n *\n * Mirrors OpenZeppelin's Clones.clone() — constructs the creation\n * bytecode for a minimal proxy and deploys via a raw transaction.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { concat } from \"viem\";\nimport { getAccount, sendTxWithRetry, waitForReceipt } from \"./client.js\";\nimport { getChain } from \"./network.js\";\n\n/**\n * Deploy an ERC-1167 minimal proxy clone of a template contract.\n *\n * @param template - Address of the deployed template (implementation)\n * @returns The clone address and deployment tx hash.\n */\nexport async function cloneTemplate(\n template: Address,\n): Promise<{ clone: Address; hash: Hex }> {\n // ERC-1167 creation code (matches OpenZeppelin Clones.sol):\n // Init code: 3d602d80600a3d3981f3\n // Runtime code: 363d3d373d3d3d363d73 <address> 5af43d82803e903d91602b57fd5bf3\n const creationCode = concat([\n \"0x3d602d80600a3d3981f3363d3d373d3d3d363d73\",\n template,\n \"0x5af43d82803e903d91602b57fd5bf3\",\n ]);\n\n const account = getAccount();\n const chain = getChain();\n\n const hash = await sendTxWithRetry({\n account,\n chain,\n data: creationCode as Hex,\n value: 0n,\n });\n\n const receipt = await waitForReceipt(hash);\n\n if (!receipt.contractAddress) {\n throw new Error(`Clone deployment failed — no contract address in receipt (tx: ${hash})`);\n }\n\n return { clone: receipt.contractAddress, hash };\n}\n","/**\n * Token-input resolution: accept a 0x address (any case) or a symbol from\n * the current network's registry. Pure — throws on failure so callers own\n * the exit behavior.\n */\n\nimport { type Address, isAddress, getAddress } from \"viem\";\n\nconst ZERO: Address = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Resolve a token input (address or symbol) to a checksummed address.\n * - Any 40-hex-char 0x string (regardless of case) → normalized EIP-55 address.\n * - Otherwise a symbol lookup against `tokens` (case-insensitive).\n * Throws with a message distinguishing a malformed address from an unknown symbol.\n */\nexport function resolveTokenInput(input: string, tokens: Record<string, Address>): Address {\n const trimmed = input.trim();\n if (isAddress(trimmed, { strict: false })) return getAddress(trimmed);\n // Anything else starting with 0x was an attempted address, not a symbol.\n if (/^0x/i.test(trimmed)) {\n throw new Error(`Invalid token address: ${trimmed}`);\n }\n const resolved = tokens[trimmed.toUpperCase()];\n if (resolved && resolved !== ZERO) return resolved;\n throw new Error(`Unknown token symbol: ${trimmed} (also accepts a 0x address)`);\n}\n","/**\n * Minimal ABI for HyperliquidGridStrategy: updateParams (proposer-callable\n * entrypoint) + maxOrdersPerTick getter for read-side chunking.\n */\nexport const HYPERLIQUID_GRID_STRATEGY_ABI = [\n {\n type: 'function',\n name: 'updateParams',\n inputs: [{ name: 'data', type: 'bytes' }],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n name: 'maxOrdersPerTick',\n inputs: [],\n outputs: [{ type: 'uint32' }],\n stateMutability: 'view',\n },\n {\n // Registers the clone with HyperCore so ERC-20 USDC transfers auto-credit\n // HC spot. Call post-init with variant=1 (FirstStorageSlot) and nonce=0.\n // _initialize() already wrote address(this) to slot 0 (_hcSelf); HC reads\n // it post-block to confirm the contract address.\n type: 'function',\n name: 'finalizeForHyperCore',\n inputs: [\n { name: 'token', type: 'uint64' },\n { name: 'variant', type: 'uint8' },\n { name: 'createNonce', type: 'uint64' },\n ],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n] as const;\n","/**\n * Types and helpers for batch call construction.\n *\n * Calls go directly to vault.executeBatch() — no separate executor contract.\n */\n\nimport type { Address, Hex } from \"viem\";\n\nexport interface BatchCall {\n target: Address;\n data: Hex;\n value: bigint;\n}\n\n/**\n * Format a batch for human-readable display (CLI output before simulation).\n */\nexport function formatBatch(calls: BatchCall[]): string {\n return calls\n .map((call, i) => {\n const selector = call.data.slice(0, 10);\n return ` ${i + 1}. ${call.target} :: ${selector}... (${call.value > 0n ? call.value + \" wei\" : \"no value\"})`;\n })\n .join(\"\\n\");\n}\n","/**\n * `--calldata-only` support.\n *\n * When the global `--calldata-only` flag is set, state-changing commands build\n * the unsigned EIP-5792-style calldata via the shared `@sherwoodagent/sdk`\n * encoders and print it as JSON instead of signing/sending — so an external\n * signer (MetaMask Agent Wallet, Frame, Privy, …) that can't export a private\n * key can take the final step. Output matches the HTTP API's `/v1/prepare/*`\n * envelope (the SDK `PreparedAction` shape).\n */\nimport type { PreparedAction } from \"@sherwoodagent/sdk\";\n\nlet _calldataOnly = false;\n\n/** Set by the root preAction hook from the global `--calldata-only` flag. */\nexport function setCalldataOnly(value: boolean): void {\n _calldataOnly = value;\n}\n\nexport function isCalldataOnly(): boolean {\n return _calldataOnly;\n}\n\n/**\n * Print a PreparedAction as pretty JSON. Each tx is `{ to, data, value, chainId }`\n * with a hex `value` (EIP-5792). `chainId` is per-tx, so multi-chain flows\n * (e.g. approve-agent: registerAgent on the syndicate chain + attest on Base)\n * are explicit.\n */\nexport function emitCalldata(action: PreparedAction): void {\n process.stdout.write(JSON.stringify(action, null, 2) + \"\\n\");\n}\n","export const CHAIN_IDS = {\n BASE: 8453,\n HYPEREVM: 999,\n ROBINHOOD_L2: 46630,\n};\nexport const SUPPORTED_CHAIN_IDS = [\n CHAIN_IDS.BASE,\n CHAIN_IDS.HYPEREVM,\n CHAIN_IDS.ROBINHOOD_L2,\n];\nexport function isSupportedChainId(value) {\n return SUPPORTED_CHAIN_IDS.includes(value);\n}\nexport const PROPOSAL_STATES = [\n \"Draft\",\n \"Pending\",\n \"GuardianReview\",\n \"Approved\",\n \"Rejected\",\n \"Cancelled\",\n \"Vetoed\",\n \"Executed\",\n \"Settled\",\n];\n","export class SdkError extends Error {\n code;\n cause;\n constructor(code, message, cause) {\n super(message);\n this.code = code;\n this.cause = cause;\n this.name = \"SdkError\";\n }\n}\nexport const usage = (message) => new SdkError(\"USAGE\", message);\nexport const unsupported = (message) => new SdkError(\"UNSUPPORTED\", message);\nexport const unavailable = (message, cause) => new SdkError(\"UNAVAILABLE\", message, cause);\nexport const internal = (message, cause) => new SdkError(\"INTERNAL\", message, cause);\nexport const notFound = (message) => new SdkError(\"NOT_FOUND\", message);\n","// Minimal ABI fragments for the v1 SDK encoders + reads.\n// Source of truth: cli/src/lib/abis.ts. Keep in lockstep.\nexport const SYNDICATE_VAULT_ABI = [\n // ERC-4626\n {\n name: \"deposit\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"assets\", type: \"uint256\" },\n { name: \"receiver\", type: \"address\" },\n ],\n outputs: [{ name: \"shares\", type: \"uint256\" }],\n },\n {\n name: \"redeem\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"shares\", type: \"uint256\" },\n { name: \"receiver\", type: \"address\" },\n { name: \"owner\", type: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"requestRedeem\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"shares\", type: \"uint256\" },\n { name: \"owner\", type: \"address\" },\n ],\n outputs: [{ name: \"requestId\", type: \"uint256\" }],\n },\n // Reads\n {\n name: \"asset\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n {\n name: \"totalAssets\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"totalSupply\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"decimals\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint8\" }],\n },\n {\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"account\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"owner\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n {\n name: \"governor\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n {\n name: \"redemptionsLocked\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"paused\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"openDeposits\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"getAgentCount\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"isApprovedDepositor\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"depositor\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n // Owner-side write surface\n {\n name: \"approveDepositor\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"depositor\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"removeDepositor\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"depositor\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"registerAgent\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"agentAddress\", type: \"address\" },\n { name: \"agentId\", type: \"uint256\" },\n ],\n outputs: [],\n },\n];\nexport const SYNDICATE_GOVERNOR_ABI = [\n // Propose (multi-arg). Order MUST match contract: vault, strategy,\n // metadataURI, performanceFeeBps, strategyDuration, executeCalls,\n // settlementCalls, coProposers.\n {\n name: \"propose\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"vault\", type: \"address\" },\n { name: \"strategy\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"performanceFeeBps\", type: \"uint256\" },\n { name: \"strategyDuration\", type: \"uint256\" },\n {\n name: \"executeCalls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n {\n name: \"settlementCalls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n {\n name: \"coProposers\",\n type: \"tuple[]\",\n components: [\n { name: \"agent\", type: \"address\" },\n { name: \"splitBps\", type: \"uint256\" },\n ],\n },\n ],\n outputs: [{ name: \"proposalId\", type: \"uint256\" }],\n },\n // Lifecycle writes\n {\n name: \"vote\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"proposalId\", type: \"uint256\" },\n { name: \"support\", type: \"uint8\" },\n ],\n outputs: [],\n },\n {\n name: \"executeProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"settleProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"cancelProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"vetoProposal\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n // Emergency settlement (GovernorEmergency, V1.5). `unstick` is the\n // owner-instant pre-committed-calls path; `emergencySettleWithCalls` commits\n // a new calldata hash and opens a guardian-reviewed window. The removed\n // `emergencySettle` is intentionally absent — it is not on the deployed impl.\n {\n name: \"unstick\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"emergencySettleWithCalls\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"proposalId\", type: \"uint256\" },\n {\n name: \"calls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n ],\n outputs: [],\n },\n // Parameter setters (GovernorParameters, V1.5 — owner-instant, no timelock).\n { name: \"setVotingPeriod\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setExecutionWindow\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setVetoThresholdBps\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setMaxPerformanceFeeBps\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setMaxStrategyDuration\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setCooldownPeriod\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n { name: \"setProtocolFeeBps\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"newValue\", type: \"uint256\" }], outputs: [] },\n // Reads\n {\n name: \"getProposal\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n components: [\n { name: \"id\", type: \"uint256\" },\n { name: \"proposer\", type: \"address\" },\n { name: \"vault\", type: \"address\" },\n { name: \"strategy\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"performanceFeeBps\", type: \"uint256\" },\n { name: \"strategyDuration\", type: \"uint256\" },\n { name: \"votesFor\", type: \"uint256\" },\n { name: \"votesAgainst\", type: \"uint256\" },\n { name: \"votesAbstain\", type: \"uint256\" },\n { name: \"snapshotTimestamp\", type: \"uint256\" },\n { name: \"voteEnd\", type: \"uint256\" },\n { name: \"reviewEnd\", type: \"uint256\" },\n { name: \"executeBy\", type: \"uint256\" },\n { name: \"executedAt\", type: \"uint256\" },\n { name: \"state\", type: \"uint8\" },\n { name: \"vetoThresholdBps\", type: \"uint256\" },\n ],\n },\n ],\n },\n {\n name: \"getProposalState\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint8\" }],\n },\n {\n name: \"getActiveProposal\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"vault\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"proposalCount\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"getGovernorParams\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n components: [\n { name: \"votingPeriod\", type: \"uint256\" },\n { name: \"executionWindow\", type: \"uint256\" },\n { name: \"vetoThresholdBps\", type: \"uint256\" },\n { name: \"maxPerformanceFeeBps\", type: \"uint256\" },\n { name: \"cooldownPeriod\", type: \"uint256\" },\n { name: \"collaborationWindow\", type: \"uint256\" },\n { name: \"maxCoProposers\", type: \"uint256\" },\n { name: \"minStrategyDuration\", type: \"uint256\" },\n { name: \"maxStrategyDuration\", type: \"uint256\" },\n ],\n },\n ],\n },\n {\n name: \"protocolFeeBps\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"guardianFeeBps\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"protocolFeeRecipient\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n];\nexport const SYNDICATE_FACTORY_ABI = [\n {\n name: \"createSyndicate\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"creatorAgentId\", type: \"uint256\" },\n {\n name: \"config\",\n type: \"tuple\",\n components: [\n { name: \"metadataURI\", type: \"string\" },\n { name: \"asset\", type: \"address\" },\n { name: \"name\", type: \"string\" },\n { name: \"symbol\", type: \"string\" },\n { name: \"openDeposits\", type: \"bool\" },\n { name: \"subdomain\", type: \"string\" },\n ],\n },\n ],\n outputs: [\n { name: \"syndicateId\", type: \"uint256\" },\n { name: \"vault\", type: \"address\" },\n ],\n },\n {\n name: \"syndicateCount\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"subdomainToSyndicate\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"subdomain\", type: \"string\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"vaultToSyndicate\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"vault\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"syndicates\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"uint256\" }],\n outputs: [\n { name: \"id\", type: \"uint256\" },\n { name: \"vault\", type: \"address\" },\n { name: \"creator\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"createdAt\", type: \"uint256\" },\n { name: \"active\", type: \"bool\" },\n { name: \"subdomain\", type: \"string\" },\n ],\n },\n {\n name: \"getAllActiveSyndicates\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple[]\",\n components: [\n { name: \"id\", type: \"uint256\" },\n { name: \"vault\", type: \"address\" },\n { name: \"creator\", type: \"address\" },\n { name: \"metadataURI\", type: \"string\" },\n { name: \"createdAt\", type: \"uint256\" },\n { name: \"active\", type: \"bool\" },\n { name: \"subdomain\", type: \"string\" },\n ],\n },\n ],\n },\n];\nexport const GUARDIAN_REGISTRY_ABI = [\n // Guardian stake\n {\n name: \"stakeAsGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"amount\", type: \"uint256\" },\n { name: \"agentId\", type: \"uint256\" },\n ],\n outputs: [],\n },\n {\n name: \"requestUnstakeGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [],\n outputs: [],\n },\n {\n name: \"cancelUnstakeGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [],\n outputs: [],\n },\n {\n name: \"claimUnstakeGuardian\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [],\n outputs: [],\n },\n // Delegation\n {\n name: \"delegateStake\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"delegate\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [],\n },\n {\n name: \"requestUnstakeDelegation\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"delegate\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"cancelUnstakeDelegation\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"delegate\", type: \"address\" }],\n outputs: [],\n },\n {\n name: \"claimUnstakeDelegation\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"delegate\", type: \"address\" }],\n outputs: [],\n },\n // Commission\n {\n name: \"setCommission\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"bps\", type: \"uint16\" }],\n outputs: [],\n },\n // Claims\n {\n name: \"claimProposalReward\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"proposalId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n name: \"claimDelegatorProposalReward\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"delegate\", type: \"address\" },\n { name: \"proposalId\", type: \"uint256\" },\n ],\n outputs: [],\n },\n // Reads\n {\n name: \"guardianStake\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"guardian\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"isActiveGuardian\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"guardian\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n];\nexport const ERC20_ABI = [\n {\n name: \"approve\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n {\n name: \"allowance\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"account\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"decimals\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint8\" }],\n },\n {\n name: \"symbol\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\" }],\n },\n];\n// ── ERC-8004 Identity Registry (Agent0) ──\n//\n// Only the `register(string agentURI, MetadataEntry[] metadata)` overload — the\n// one Agent0's `registerOnChain()` actually calls for on-chain data-URI mints.\n// agentURI is a base64 `data:application/json` URI; metadata is `[]` for a basic\n// agent. Selector 0x8ea42286.\nexport const IDENTITY_REGISTRY_ABI = [\n {\n name: \"register\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"agentURI\", type: \"string\" },\n {\n name: \"metadata\",\n type: \"tuple[]\",\n components: [\n { name: \"metadataKey\", type: \"string\" },\n { name: \"metadataValue\", type: \"bytes\" },\n ],\n },\n ],\n outputs: [{ name: \"agentId\", type: \"uint256\" }],\n },\n];\n// ── EAS (Ethereum Attestation Service) — `attest` only ──\n//\n// Used for SYNDICATE_JOIN_REQUEST and AGENT_APPROVED coordination attestations,\n// which always live on Base. Selector 0xf17325e7.\nexport const EAS_ABI = [\n {\n name: \"attest\",\n type: \"function\",\n stateMutability: \"payable\",\n inputs: [\n {\n name: \"request\",\n type: \"tuple\",\n components: [\n { name: \"schema\", type: \"bytes32\" },\n {\n name: \"data\",\n type: \"tuple\",\n components: [\n { name: \"recipient\", type: \"address\" },\n { name: \"expirationTime\", type: \"uint64\" },\n { name: \"revocable\", type: \"bool\" },\n { name: \"refUID\", type: \"bytes32\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"value\", type: \"uint256\" },\n ],\n },\n ],\n },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n },\n];\n// StrategyFactory — atomic clone+initialize wrapper for strategy templates.\n// `cloneAndInitDeterministic` deploys the ERC-1167 clone via CREATE2, so the\n// clone address is predictable BEFORE the tx is mined (see\n// `predictStrategyCloneAddress` in encoders/strategy.ts). This is what unblocks\n// keyless / external-signer strategy proposals (issue #387): the proposal's\n// executeCalls + the `strategy` arg can be built against the predicted address\n// up front, so deploy + propose can both be emitted as unsigned calldata.\nexport const STRATEGY_FACTORY_ABI = [\n {\n name: \"cloneAndInit\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"template\", type: \"address\" },\n { name: \"vault\", type: \"address\" },\n { name: \"proposer\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n ],\n outputs: [{ name: \"clone\", type: \"address\" }],\n },\n {\n name: \"cloneAndInitDeterministic\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"template\", type: \"address\" },\n { name: \"vault\", type: \"address\" },\n { name: \"proposer\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"salt\", type: \"bytes32\" },\n ],\n outputs: [{ name: \"clone\", type: \"address\" }],\n },\n {\n name: \"syndicateFactory\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n];\n","import { CHAIN_IDS } from \"./types.js\";\nimport { unsupported } from \"./errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ZERO_BYTES32 = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n// Base EAS predeploy + registered Sherwood coordination schema UIDs. Shared\n// across any chain whose attestations are pinned to Base.\nconst BASE_EAS = {\n chainId: CHAIN_IDS.BASE,\n address: \"0x4200000000000000000000000000000000000021\",\n schemas: {\n joinRequest: \"0x1e7ce17b16233977ba913b156033e98f52029f4bee273a4abefe6c15ce11d5ef\",\n agentApproved: \"0x1013f7b38f433b2a93fc5ac162482813081c64edd67cea9b5a90698531ddb607\",\n },\n};\nconst NO_EAS = {\n chainId: CHAIN_IDS.BASE,\n address: ZERO_ADDRESS,\n schemas: { joinRequest: ZERO_BYTES32, agentApproved: ZERO_BYTES32 },\n};\n// Source of truth for each chain: contracts/chains/{chainId}.json.\n// Mirror manually until cli/contracts/sdk all share a generated table.\nconst BASE = {\n chainId: CHAIN_IDS.BASE,\n name: \"Base\",\n slug: \"base\",\n sherwood: {\n factory: \"0xAC74EC56858d7F1f7618c8e77F65Fc26aDf33c82\",\n governor: \"0x9Fd3c87B34F254e3c5652A0394B9780c2F05d367\",\n guardianRegistry: \"0x49E4163b5e4b23F8f3d469Cf6fa197FB6b06A26E\",\n vaultImpl: \"0xfce4bcE08E9C047E4736f75C2B8557e2754Ce36A\",\n batchExecutorLib: \"0xbC79FbD5036C1Cc4A9d10BDf8628BF09a558496E\",\n // Not yet deployed on Base — fill in `STRATEGY_FACTORY` from\n // contracts/chains/8453.json when it lands (issue #387).\n strategyFactory: ZERO_ADDRESS,\n },\n identityRegistry: \"0x8004A169FB4a3325136EB29fA0ceB6D2e539a432\",\n eas: BASE_EAS,\n tokens: {\n usdc: {\n address: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n symbol: \"USDC\",\n decimals: 6,\n },\n weth: {\n address: \"0x4200000000000000000000000000000000000006\",\n symbol: \"WETH\",\n decimals: 18,\n },\n },\n explorer: \"https://basescan.org\",\n rpcs: [\"https://mainnet.base.org\"],\n};\nconst HYPEREVM = {\n chainId: CHAIN_IDS.HYPEREVM,\n name: \"HyperEVM\",\n slug: \"hyperevm\",\n sherwood: {\n factory: \"0xd05Ae0E8bcf13075C29817c805d6Cc14F214393a\",\n governor: \"0x67AD3D5F3d127Ef923Fd6f67b178633c408D3fd3\",\n guardianRegistry: \"0x8b5710EB4e2fA639F364Dcc3F3B30c8f12F460b9\",\n vaultImpl: \"0x2cbBe36Cf907A2BB410bacB0e4Fd632C7b012846\",\n batchExecutorLib: \"0x2c454bEF1b09c8a306a7058b8B510bF0DfF7179D\",\n strategyFactory: ZERO_ADDRESS,\n },\n // ERC-8004 identity is minted on Base; HyperEVM syndicates reference the\n // Base-minted token id. Coordination attestations are pinned to Base EAS.\n identityRegistry: ZERO_ADDRESS,\n eas: BASE_EAS,\n tokens: {\n usdc: {\n address: \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\",\n symbol: \"USDC\",\n decimals: 6,\n },\n },\n explorer: \"https://hyperliquid.cloud.blockscout.com\",\n rpcs: [\"https://rpc.hyperliquid.xyz/evm\"],\n};\nconst ROBINHOOD_L2 = {\n chainId: CHAIN_IDS.ROBINHOOD_L2,\n name: \"Robinhood L2 Testnet\",\n slug: \"robinhood-l2\",\n sherwood: {\n factory: \"0x6d026e2f5Ff0C34A01690EC46Cb601B8fF391985\",\n governor: \"0xd882056ba6b0aEd8908c541884B327121E2f2C9C\",\n // Robinhood L2 doesn't have a guardian registry yet; use zero so callers\n // get a clear UNSUPPORTED rather than a confusing revert downstream.\n guardianRegistry: \"0x0000000000000000000000000000000000000000\",\n vaultImpl: \"0xF4720523325f9A4546F43391484DCd1D28dFc266\",\n batchExecutorLib: \"0x1493f5a7E5d82e1e56c34e2Ba300f56F97186017\",\n strategyFactory: ZERO_ADDRESS,\n },\n // No ERC-8004 registry and no EAS path on Robinhood L2.\n identityRegistry: ZERO_ADDRESS,\n eas: NO_EAS,\n tokens: {},\n explorer: \"https://explorer-robinhood-l2.t.conduit.xyz\",\n rpcs: [\"https://rpc-robinhood-l2.t.conduit.xyz\"],\n};\nconst REGISTRY = {\n [CHAIN_IDS.BASE]: BASE,\n [CHAIN_IDS.HYPEREVM]: HYPEREVM,\n [CHAIN_IDS.ROBINHOOD_L2]: ROBINHOOD_L2,\n};\nexport function getDeployment(chainId) {\n const entry = REGISTRY[chainId];\n if (!entry)\n throw unsupported(`No Sherwood deployment for chain ${chainId}`);\n return entry;\n}\nexport function listDeployments() {\n return Object.values(REGISTRY);\n}\n/** Network slug for join-request message prefixes (e.g. 8453 → \"base\"). */\nexport function chainSlug(chainId) {\n return getDeployment(chainId).slug;\n}\n","import { encodeFunctionData, getAddress, maxUint256 } from \"viem\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { usage } from \"../errors.js\";\n/** Minimal WETH9 `deposit()` (payable) fragment — for the ETH→WETH wrap leg. */\nconst WETH_ABI = [\n {\n name: \"deposit\",\n type: \"function\",\n stateMutability: \"payable\",\n inputs: [],\n outputs: [],\n },\n];\nconst ZERO_VALUE = \"0x0\";\nfunction toHexValue(value) {\n return `0x${value.toString(16)}`;\n}\nfunction encodeApproveTx(token, spender, amount, chainId) {\n return {\n to: token,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [spender, amount],\n }),\n value: ZERO_VALUE,\n chainId,\n };\n}\nfunction encodeDepositTx(vault, assets, receiver, chainId) {\n return {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"deposit\",\n args: [assets, receiver],\n }),\n value: ZERO_VALUE,\n chainId,\n };\n}\n/**\n * Encode the calldata for an ERC-4626 vault deposit.\n *\n * Returns 1–2 transactions:\n * - If `currentAllowance` is provided and >= `assets`, only the `deposit` tx.\n * - Otherwise, an `approve(spender=vault, amount=assets)` tx followed by the\n * `deposit` tx. Agents that already have an unlimited allowance can drop\n * the first tx after checking the `allowance` precondition.\n *\n * The SDK never reads chain state — pass `currentAllowance` if you want a\n * precise plan; otherwise expect the conservative two-tx default.\n */\nexport function encodeDeposit(args, chainId) {\n if (args.assets <= 0n) {\n throw usage(\"`assets` must be > 0\");\n }\n const vault = getAddress(args.vault);\n const receiver = getAddress(args.receiver);\n const asset = getAddress(args.asset);\n const txs = [];\n // Optional ETH→WETH wrap leg (WETH vaults only). Prepended so the wrap lands\n // before the approve/deposit. Wraps only the shortfall when a balance is given.\n let wrapped = false;\n if (args.wrapEth) {\n const weth = getDeployment(chainId).tokens.weth;\n if (!weth || getAddress(weth.address) !== asset) {\n throw usage(\"`wrapEth` is only valid for WETH vaults — the vault asset must be the chain's WETH.\");\n }\n const held = args.currentWethBalance ?? 0n;\n const shortfall = held >= args.assets ? 0n : args.assets - held;\n if (shortfall > 0n) {\n txs.push({\n to: asset,\n data: encodeFunctionData({ abi: WETH_ABI, functionName: \"deposit\", args: [] }),\n value: toHexValue(shortfall),\n chainId,\n });\n wrapped = true;\n }\n }\n const needsApprove = args.currentAllowance === undefined || args.currentAllowance < args.assets;\n if (needsApprove) {\n txs.push(encodeApproveTx(asset, vault, maxUint256, chainId));\n }\n txs.push(encodeDepositTx(vault, args.assets, receiver, chainId));\n const minDecimal = formatUnits(args.assets, args.assetDecimals);\n let description;\n if (wrapped) {\n description = needsApprove\n ? `Wrap ETH→WETH, approve ${args.assetSymbol} for ${vault}, then deposit ${minDecimal} ${args.assetSymbol}.`\n : `Wrap ETH→WETH, then deposit ${minDecimal} ${args.assetSymbol}.`;\n }\n else {\n description = needsApprove\n ? `Approve ${args.assetSymbol} for ${vault}, then deposit ${minDecimal} ${args.assetSymbol}.`\n : `Deposit ${minDecimal} ${args.assetSymbol} into ${vault}.`;\n }\n return {\n txs,\n preconditions: [\n {\n type: \"balance\",\n asset,\n assetSymbol: args.assetSymbol,\n min: args.assets.toString(),\n minDecimal,\n },\n {\n type: \"allowance\",\n token: asset,\n spender: vault,\n min: args.assets.toString(),\n minDecimal,\n },\n { type: \"vault-not-locked\", vault },\n { type: \"depositor-approved\", vault, depositor: receiver },\n ],\n description,\n note: \"Both txs are gated by vault state. If `redemptionsLocked()` is true the deposit reverts unless live NAV is available; check the vault read endpoint before broadcasting.\",\n };\n}\n/** Internal: decimal-string formatter so we don't pull in a heavy dep. */\nfunction formatUnits(value, decimals) {\n if (decimals === 0)\n return value.toString();\n const negative = value < 0n;\n const abs = negative ? -value : value;\n const str = abs.toString().padStart(decimals + 1, \"0\");\n const head = str.slice(0, str.length - decimals);\n const tail = str.slice(str.length - decimals).replace(/0+$/, \"\");\n const out = tail.length > 0 ? `${head}.${tail}` : head;\n return negative ? `-${out}` : out;\n}\n// Re-export for tests / callers that want to pre-format previews.\nexport { formatUnits };\n// Tiny helpers exported for the API layer to convert plan-level UnsignedTx\n// into the on-the-wire JSON shape with a hex `value`. Kept here so encoders\n// own their wire representation end to end.\nexport { toHexValue };\nexport function encodeRedeem(args, chainId) {\n if (args.shares <= 0n)\n throw usage(\"`shares` must be > 0\");\n const vault = getAddress(args.vault);\n const receiver = getAddress(args.receiver);\n const owner = getAddress(args.owner);\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"redeem\",\n args: [args.shares, receiver, owner],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [\n { type: \"vault-not-locked\", vault },\n ],\n description: `Redeem ${args.shares.toString()} shares of ${vault} → ${receiver}.`,\n note: \"Synchronous path. Reverts if the vault has an active proposal AND live NAV is unavailable; in that case use /prepare/request-redeem (queue path) instead.\",\n };\n}\nexport function encodeRequestRedeem(args, chainId) {\n if (args.shares <= 0n)\n throw usage(\"`shares` must be > 0\");\n const vault = getAddress(args.vault);\n const owner = getAddress(args.owner);\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"requestRedeem\",\n args: [args.shares, owner],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [],\n description: `Queue a redeem request for ${args.shares.toString()} shares of ${vault}.`,\n note: \"Only callable while `redemptionsLocked() == true`. Shares are escrowed in the per-vault queue; claim with the queue's `claim(requestId)` once the proposal settles.\",\n };\n}\n// ── Owner-side admin encoders ─────────────────────────────\nexport function encodeApproveDepositor(args, chainId) {\n const vault = getAddress(args.vault);\n const depositor = getAddress(args.depositor);\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"approveDepositor\",\n args: [depositor],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [],\n description: `Approve depositor ${depositor} on vault ${vault}.`,\n note: \"Vault owner only.\",\n };\n}\nexport function encodeRegisterAgent(args, chainId) {\n const vault = getAddress(args.vault);\n const agentAddress = getAddress(args.agentAddress);\n const id = typeof args.agentId === \"bigint\" ? args.agentId : BigInt(args.agentId);\n if (id < 0n)\n throw usage(\"`agentId` must be a non-negative integer\");\n return {\n txs: [\n {\n to: vault,\n data: encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"registerAgent\",\n args: [agentAddress, id],\n }),\n value: ZERO_VALUE,\n chainId,\n },\n ],\n preconditions: [],\n description: `Register agent ${agentAddress} (id ${id.toString()}) on vault ${vault}.`,\n note: \"Vault owner only. The ERC-8004 NFT must be owned by `agentAddress` or by the vault owner at registration time.\",\n };\n}\n","import { encodeFunctionData, getAddress, isAddress } from \"viem\";\nimport { SYNDICATE_GOVERNOR_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { usage } from \"../errors.js\";\nconst ZERO_VALUE = \"0x0\";\nexport const VOTE_TYPES = {\n For: 0,\n Against: 1,\n Abstain: 2,\n};\nfunction governorTx(chainId, data) {\n return {\n to: getDeployment(chainId).sherwood.governor,\n data,\n value: ZERO_VALUE,\n chainId,\n };\n}\nfunction parseProposalId(value) {\n if (typeof value === \"bigint\") {\n if (value < 0n)\n throw usage(\"`proposalId` must be a non-negative integer\");\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0) {\n throw usage(\"`proposalId` must be a non-negative integer\");\n }\n return BigInt(value);\n }\n if (!/^\\d+$/.test(value)) {\n throw usage(`\\`proposalId\\` must be a non-negative integer string, got \"${value}\"`);\n }\n return BigInt(value);\n}\nexport function encodeVote(args, chainId) {\n const support = VOTE_TYPES[args.vote];\n if (support === undefined) {\n throw usage(`Unsupported vote \"${args.vote}\" — must be one of: ${Object.keys(VOTE_TYPES).join(\", \")}`);\n }\n const proposalId = parseProposalId(args.proposalId);\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"vote\",\n args: [proposalId, support],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Vote ${args.vote} on proposal ${proposalId.toString()}.`,\n note: \"Voter must hold ERC20Votes shares of the vault at the proposal's snapshot timestamp; double-voting reverts. Use the proposal read endpoint to check `voteEnd` first.\",\n };\n}\nfunction lifecycleAction(fn, proposalId, chainId, description, note) {\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: fn,\n args: [proposalId],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description,\n note,\n };\n}\nexport function encodeExecute(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"executeProposal\", id, chainId, `Execute proposal ${id.toString()} (open the strategy).`, \"Reverts if the proposal is not in the `Approved` state. Check `state == Approved` via the proposal read endpoint first.\");\n}\nexport function encodeSettle(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"settleProposal\", id, chainId, `Settle proposal ${id.toString()} (close the strategy and distribute fees).`, \"Proposer can settle anytime; anyone can settle after the strategy duration elapses.\");\n}\nexport function encodeCancel(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"cancelProposal\", id, chainId, `Cancel proposal ${id.toString()} (proposer-only).`, \"Only the proposer can cancel, and only while the proposal is in `Pending`, `GuardianReview`, or `Approved`.\");\n}\nexport function encodeVeto(args, chainId) {\n const id = parseProposalId(args.proposalId);\n return lifecycleAction(\"vetoProposal\", id, chainId, `Veto proposal ${id.toString()} (vault-owner only, only while \\`Pending\\`).`, \"Vault owner only. Reverts after the proposal enters `GuardianReview`. To block at that point, depend on guardian block-quorum.\");\n}\nexport { parseProposalId };\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nfunction validateBatchCall(call, scope, idx) {\n if (!call || typeof call !== \"object\") {\n throw usage(`\\`${scope}[${idx}]\\` must be an object`);\n }\n const c = call;\n if (typeof c.target !== \"string\" || !isAddress(c.target)) {\n throw usage(`\\`${scope}[${idx}].target\\` must be a 0x-prefixed address`);\n }\n if (typeof c.data !== \"string\" || !/^0x[0-9a-fA-F]*$/.test(c.data)) {\n throw usage(`\\`${scope}[${idx}].data\\` must be a 0x-prefixed hex string`);\n }\n let value;\n if (typeof c.value === \"string\") {\n if (!/^\\d+$/.test(c.value)) {\n throw usage(`\\`${scope}[${idx}].value\\` must be a non-negative integer string`);\n }\n value = BigInt(c.value);\n }\n else if (typeof c.value === \"bigint\") {\n if (c.value < 0n) {\n throw usage(`\\`${scope}[${idx}].value\\` must be non-negative`);\n }\n value = c.value;\n }\n else if (c.value === undefined || c.value === null) {\n value = 0n;\n }\n else {\n throw usage(`\\`${scope}[${idx}].value\\` must be a non-negative integer string (or omitted for 0)`);\n }\n return { target: getAddress(c.target), data: c.data, value };\n}\nexport function encodePropose(args, chainId) {\n const vault = getAddress(args.vault);\n const strategy = args.strategy === ZERO_ADDRESS ? ZERO_ADDRESS : getAddress(args.strategy);\n if (typeof args.metadataURI !== \"string\" || args.metadataURI.length === 0) {\n throw usage(\"`metadataURI` must be a non-empty string (e.g. ipfs://...)\");\n }\n if (!Number.isInteger(args.performanceFeeBps) ||\n args.performanceFeeBps < 0 ||\n args.performanceFeeBps > 10_000) {\n throw usage(\"`performanceFeeBps` must be an integer in [0, 10000]\");\n }\n const strategyDuration = typeof args.strategyDuration === \"bigint\"\n ? args.strategyDuration\n : BigInt(args.strategyDuration);\n if (strategyDuration <= 0n) {\n throw usage(\"`strategyDuration` must be > 0 (seconds)\");\n }\n if (!Array.isArray(args.executeCalls)) {\n throw usage(\"`executeCalls` must be an array of {target, data, value} objects\");\n }\n if (!Array.isArray(args.settlementCalls)) {\n throw usage(\"`settlementCalls` must be an array of {target, data, value} objects\");\n }\n const executeCalls = args.executeCalls.map((c, i) => validateBatchCall(c, \"executeCalls\", i));\n const settlementCalls = args.settlementCalls.map((c, i) => validateBatchCall(c, \"settlementCalls\", i));\n const coProposers = (args.coProposers ?? []).map((cp, i) => {\n if (!cp || typeof cp !== \"object\") {\n throw usage(`\\`coProposers[${i}]\\` must be an object`);\n }\n const agent = cp.agent;\n const splitBps = cp.splitBps;\n if (typeof agent !== \"string\" || !isAddress(agent)) {\n throw usage(`\\`coProposers[${i}].agent\\` must be a 0x-prefixed address`);\n }\n let bps;\n if (typeof splitBps === \"string\" && /^\\d+$/.test(splitBps)) {\n bps = BigInt(splitBps);\n }\n else if (typeof splitBps === \"bigint\") {\n bps = splitBps;\n }\n else if (typeof splitBps === \"number\" && Number.isInteger(splitBps) && splitBps >= 0) {\n bps = BigInt(splitBps);\n }\n else {\n throw usage(`\\`coProposers[${i}].splitBps\\` must be a non-negative integer (string, number, or bigint)`);\n }\n if (bps < 0n || bps > 10000n) {\n throw usage(`\\`coProposers[${i}].splitBps\\` must be in [0, 10000]`);\n }\n return { agent: getAddress(agent), splitBps: bps };\n });\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"propose\",\n args: [\n vault,\n strategy,\n args.metadataURI,\n BigInt(args.performanceFeeBps),\n strategyDuration,\n executeCalls,\n settlementCalls,\n coProposers,\n ],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [\n { type: \"vault-not-locked\", vault },\n ],\n description: `Propose a strategy on ${vault} (duration ${strategyDuration.toString()}s, fee ${args.performanceFeeBps} bps).`,\n note: \"Reverts if the vault has an active proposal (cooldown not elapsed). The strategy address is immutable post-propose; pass address(0) to opt out of live NAV. `coProposers[].splitBps` total must satisfy contract-side constraints.\",\n };\n}\n// ── Emergency settlement (GovernorEmergency, V1.5) ───────\nexport function encodeUnstick(args, chainId) {\n const id = parseProposalId(args.proposalId);\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"unstick\",\n args: [id],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Unstick proposal ${id.toString()} — run its governance-approved settlement calls (owner-instant, no funds beyond the approved calls).`,\n note: \"Vault-owner only. Valid only when the proposal is Executed AND its strategy duration has elapsed. Runs the proposal's pre-committed settlement calls and finalizes settlement; no owner stake required. Reverts if those calls revert — if they can't succeed, open an emergency-settle with custom unwind calls instead.\",\n };\n}\nexport function encodeEmergencySettle(args, chainId) {\n const id = parseProposalId(args.proposalId);\n if (!Array.isArray(args.calls)) {\n throw usage(\"`calls` must be an array of {target, data, value} objects\");\n }\n const calls = args.calls.map((c, i) => validateBatchCall(c, \"calls\", i));\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: \"emergencySettleWithCalls\",\n args: [id, calls],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Open an emergency-settle review on proposal ${id.toString()} with ${calls.length} unwind call(s).`,\n note: \"Vault-owner only, requires bonded owner stake. Does NOT execute immediately — it commits the calls' hash and opens a guardian-reviewed window (default ~24h). After the window, finalize with finalizeEmergencySettle; guardians can block within it (owner stake burned on block-quorum).\",\n };\n}\n// ── Parameter setters (GovernorParameters, V1.5) ─────────\nfunction parseUintArg(value, label) {\n if (typeof value === \"bigint\") {\n if (value < 0n)\n throw usage(`\\`${label}\\` must be a non-negative integer`);\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0) {\n throw usage(`\\`${label}\\` must be a non-negative integer`);\n }\n return BigInt(value);\n }\n if (!/^\\d+$/.test(value)) {\n throw usage(`\\`${label}\\` must be a non-negative integer string, got \"${value}\"`);\n }\n return BigInt(value);\n}\n/**\n * Maps a friendly parameter name to its on-chain setter. Every setter takes a\n * single uint256 and is owner-instant (V1.5 dropped the on-chain timelock).\n */\nconst GOVERNOR_PARAM_SETTERS = {\n votingPeriod: \"setVotingPeriod\",\n executionWindow: \"setExecutionWindow\",\n vetoThresholdBps: \"setVetoThresholdBps\",\n maxPerformanceFeeBps: \"setMaxPerformanceFeeBps\",\n maxStrategyDuration: \"setMaxStrategyDuration\",\n cooldownPeriod: \"setCooldownPeriod\",\n protocolFeeBps: \"setProtocolFeeBps\",\n};\nexport function encodeGovernorParam(args, chainId) {\n const fn = GOVERNOR_PARAM_SETTERS[args.param];\n if (!fn) {\n throw usage(`Unknown governor param \"${args.param}\" — must be one of: ${Object.keys(GOVERNOR_PARAM_SETTERS).join(\", \")}`);\n }\n const value = parseUintArg(args.value, args.param);\n const data = encodeFunctionData({\n abi: SYNDICATE_GOVERNOR_ABI,\n functionName: fn,\n args: [value],\n });\n return {\n txs: [governorTx(chainId, data)],\n preconditions: [],\n description: `Set governor parameter ${args.param} = ${value.toString()}.`,\n note: \"Owner-only (the owner multisig). V1.5 has no on-chain parameter timelock — the change applies immediately on this call. Bounds are validated on-chain; out-of-range values revert. Setting a non-zero protocolFeeBps reverts unless protocolFeeRecipient is already set.\",\n };\n}\n","import { encodeFunctionData, getAddress } from \"viem\";\nimport { SYNDICATE_FACTORY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { usage } from \"../errors.js\";\nconst ZERO_VALUE = \"0x0\";\nconst SUBDOMAIN_RE = /^[a-z0-9-]{1,63}$/;\nexport function encodeCreateSyndicate(args, chainId) {\n if (typeof args.metadataURI !== \"string\" || args.metadataURI.length === 0) {\n throw usage(\"`metadataURI` must be a non-empty string (e.g. ipfs://...)\");\n }\n if (typeof args.name !== \"string\" || args.name.length === 0) {\n throw usage(\"`name` must be a non-empty string\");\n }\n if (typeof args.symbol !== \"string\" || args.symbol.length === 0) {\n throw usage(\"`symbol` must be a non-empty string\");\n }\n if (typeof args.openDeposits !== \"boolean\") {\n throw usage(\"`openDeposits` must be a boolean\");\n }\n if (!SUBDOMAIN_RE.test(args.subdomain)) {\n throw usage(\"`subdomain` must match /^[a-z0-9-]{1,63}$/ (lowercase letters, digits, hyphens)\");\n }\n const asset = getAddress(args.asset);\n const creatorAgentId = typeof args.creatorAgentId === \"bigint\"\n ? args.creatorAgentId\n : BigInt(args.creatorAgentId);\n if (creatorAgentId < 0n)\n throw usage(\"`creatorAgentId` must be non-negative\");\n const factory = getDeployment(chainId).sherwood.factory;\n const data = encodeFunctionData({\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"createSyndicate\",\n args: [\n creatorAgentId,\n {\n metadataURI: args.metadataURI,\n asset,\n name: args.name,\n symbol: args.symbol,\n openDeposits: args.openDeposits,\n subdomain: args.subdomain,\n },\n ],\n });\n return {\n txs: [{ to: factory, data, value: ZERO_VALUE, chainId }],\n preconditions: [\n // Creator must own the ERC-8004 NFT for `creatorAgentId` and have\n // pre-staked the owner bond via guardianRegistry.prepareOwnerStake.\n // No on-chain check from the SDK side — agent verifies upstream.\n ],\n description: `Create syndicate \"${args.subdomain}\" with ${args.openDeposits ? \"open\" : \"whitelisted\"} deposits.`,\n note: \"Caller must own the ERC-8004 NFT for `creatorAgentId` and must have called `guardianRegistry.prepareOwnerStake` first to bond the owner stake. The factory's `createSyndicate` deploys a vault proxy + binds the owner stake atomically.\",\n };\n}\n","import { concatHex, encodeAbiParameters, encodeFunctionData, encodePacked, getAddress, getCreate2Address, isHex, keccak256, } from \"viem\";\nimport { STRATEGY_FACTORY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { unavailable, usage } from \"../errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ZERO_VALUE = \"0x0\";\n// ERC-1167 minimal-proxy creation code, split around the 20-byte implementation\n// address. Byte-identical to OpenZeppelin `Clones.sol` (the same bytes\n// `StrategyFactory.cloneAndInitDeterministic` deploys via CREATE2), so the\n// CREATE2 address derived from it matches `Clones.predictDeterministicAddress`.\nconst ERC1167_PREFIX = \"0x3d602d80600a3d3981f3363d3d373d3d3d363d73\";\nconst ERC1167_SUFFIX = \"0x5af43d82803e903d91602b57fd5bf3\";\n/**\n * Predict the CREATE2 address of an ERC-1167 clone of `template` deployed by\n * `factory` with `salt`. Mirrors OpenZeppelin `Clones.predictDeterministicAddress`.\n *\n * Pure — no RPC. The clone is deterministic in `(factory, template, salt)`\n * ONLY; it does NOT depend on `vault`/`proposer`. See `deriveStrategySalt` and\n * the note in `encodeStrategyDeploy` for the front-running implication.\n */\nexport function predictStrategyCloneAddress(factory, template, salt) {\n const initCode = concatHex([\n ERC1167_PREFIX,\n getAddress(template),\n ERC1167_SUFFIX,\n ]);\n return getCreate2Address({\n from: getAddress(factory),\n salt,\n bytecode: initCode,\n });\n}\n/**\n * Default CREATE2 salt for a strategy deploy: a keccak of the inputs. Two deploys\n * with identical `(vault, proposer, template, initData)` collide (the second\n * `cloneAndInitDeterministic` reverts, address already taken) — pass an explicit\n * `salt` to re-deploy the same parameters (e.g. propose → cancel → re-propose).\n */\nexport function deriveStrategySalt(vault, proposer, template, initData) {\n return keccak256(encodePacked([\"address\", \"address\", \"address\", \"bytes\"], [getAddress(vault), getAddress(proposer), getAddress(template), initData]));\n}\n/**\n * The actual CREATE2 salt the factory uses: `keccak256(abi.encode(vault, salt))`.\n *\n * `StrategyFactory.cloneAndInitDeterministic` folds the vault into the salt so\n * the predicted address lives in a per-vault namespace; combined with the\n * factory's `_authClone(vault)` gate (only the vault's owner/agents may deploy),\n * a front-runner who reads `salt` from the mempool cannot occupy the address.\n * This MUST stay byte-identical to the on-chain fold or predictions diverge from\n * the deployed address.\n */\nexport function effectiveStrategySalt(vault, salt) {\n return keccak256(encodeAbiParameters([{ type: \"address\" }, { type: \"bytes32\" }], [getAddress(vault), salt]));\n}\nfunction requireSalt(value) {\n if (typeof value !== \"string\" || !isHex(value) || value.length !== 66) {\n throw usage(\"`salt` must be a 0x-prefixed 32-byte hex string (66 chars)\");\n }\n return value;\n}\n/**\n * Encode `StrategyFactory.cloneAndInitDeterministic(template, vault, proposer,\n * initData, salt)` — one unsigned tx that atomically clones the template via\n * CREATE2 and initializes it. Returns the predicted clone address so the caller\n * can build the proposal's `strategy` arg + executeCalls/settlementCalls against\n * it BEFORE the tx is mined — which is what unblocks keyless strategy proposals\n * (#387). Works for any template (Moonwell, Aerodrome, Venice, Portfolio, …):\n * the mechanism is template-agnostic, only `initData` differs.\n */\nexport function encodeStrategyDeploy(args, chainId) {\n const template = getAddress(args.template);\n const vault = getAddress(args.vault);\n const proposer = getAddress(args.proposer);\n if (typeof args.initData !== \"string\" || !isHex(args.initData)) {\n throw usage(\"`initData` must be a 0x-prefixed hex string\");\n }\n if (template === ZERO_ADDRESS) {\n throw usage(\"`template` must be a non-zero address\");\n }\n if (proposer === ZERO_ADDRESS) {\n throw usage(\"`proposer` must be a non-zero address\");\n }\n const factory = args.factory\n ? getAddress(args.factory)\n : getDeployment(chainId).sherwood.strategyFactory;\n if (factory === ZERO_ADDRESS) {\n throw unavailable(`StrategyFactory is not yet deployed on chain ${chainId} — mirror its address into the SDK once it lands (issue #387), or pass an explicit \\`factory\\`.`);\n }\n // `salt` is what's passed in the calldata; the factory folds the vault in\n // (keccak256(abi.encode(vault, salt))) before CREATE2, so the prediction must\n // fold too — see `effectiveStrategySalt`.\n const salt = args.salt\n ? requireSalt(args.salt)\n : deriveStrategySalt(vault, proposer, template, args.initData);\n const clone = predictStrategyCloneAddress(factory, template, effectiveStrategySalt(vault, salt));\n const data = encodeFunctionData({\n abi: STRATEGY_FACTORY_ABI,\n functionName: \"cloneAndInitDeterministic\",\n args: [template, vault, proposer, args.initData, salt],\n });\n const tx = { to: factory, data, value: ZERO_VALUE, chainId };\n return {\n txs: [tx],\n preconditions: [],\n clone,\n salt,\n factory,\n description: `Deploy a strategy clone of ${template} for vault ${vault} (deterministic — clone at ${clone}).`,\n note: \"Broadcast this tx from `proposer` — the factory requires proposer == msg.sender, and msg.sender must be the vault owner or a registered agent. The vault must be registered on the SyndicateFactory and `template` must be on the factory's allowlist (the factory reverts otherwise). The clone address is fixed by (factory, template, vault, salt) — reference it as the proposal `strategy` and inside executeCalls/settlementCalls. The factory binds the salt to the vault, and `_authClone` lets only the vault's owner/agents deploy there, so the predicted address can't be front-run.\",\n };\n}\n","import { encodeFunctionData, getAddress } from \"viem\";\nimport { IDENTITY_REGISTRY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { unsupported, usage } from \"../errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ERC8004_TYPE = \"https://eips.ethereum.org/EIPS/eip-8004#registration-v1\";\nconst B64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n/**\n * Standard base64 of a UTF-8 string using only ES built-ins (no Buffer / btoa /\n * TextEncoder) so the SDK stays browser-safe and Node-types-free. Byte-identical\n * to `Buffer.from(str, \"utf8\").toString(\"base64\")` — pinned by the golden mint\n * test against the confirmed on-chain calldata.\n */\nfunction toBase64Utf8(str) {\n // UTF-8 bytes as a Latin1 (\"binary\") string via encodeURIComponent.\n const bin = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));\n let out = \"\";\n for (let i = 0; i < bin.length; i += 3) {\n const a = bin.charCodeAt(i);\n const hasB = i + 1 < bin.length;\n const hasC = i + 2 < bin.length;\n const b = hasB ? bin.charCodeAt(i + 1) : 0;\n const c = hasC ? bin.charCodeAt(i + 2) : 0;\n out += B64_ALPHABET[a >> 2];\n out += B64_ALPHABET[((a & 3) << 4) | (b >> 4)];\n out += hasB ? B64_ALPHABET[((b & 15) << 2) | (c >> 6)] : \"=\";\n out += hasC ? B64_ALPHABET[c & 63] : \"=\";\n }\n return out;\n}\n/**\n * Encode an ERC-8004 agent-identity mint as a single `register(agentURI, [])`\n * call against the IdentityRegistry — the same on-chain shape Agent0's\n * `registerOnChain()` produces, but built with viem only (no Agent0 SDK / IPFS).\n *\n * `agentURI` is a `data:application/json;base64,…` URI carrying the ERC-8004\n * registration JSON. The registry assigns the next token id and stores the URI;\n * the soft metadata fields don't affect the mint. The minted `chainId:tokenId`\n * is referenced cross-chain when creating/joining syndicates.\n *\n * ERC-8004 lives on Base only — throws UNSUPPORTED on other chains.\n */\nexport function encodeIdentityMint(args, chainId) {\n const registry = getDeployment(chainId).identityRegistry;\n if (registry === ZERO_ADDRESS) {\n throw unsupported(`ERC-8004 identity registry is not deployed on chain ${chainId} — mint on Base (8453).`);\n }\n if (!args.name)\n throw usage(\"`name` is required\");\n if (!args.description)\n throw usage(\"`description` is required\");\n // Key order is significant for byte-stable output — mirrors Agent0's\n // on-chain data-URI registration JSON: type, name, description, image?,\n // services, active, x402Support.\n const reg = {\n type: ERC8004_TYPE,\n name: args.name,\n description: args.description,\n };\n if (args.image)\n reg.image = args.image;\n reg.services = [];\n reg.active = args.active ?? true;\n reg.x402Support = args.x402Support ?? false;\n const json = JSON.stringify(reg);\n const dataUri = `data:application/json;base64,${toBase64Utf8(json)}`;\n return {\n txs: [\n {\n to: getAddress(registry),\n data: encodeFunctionData({\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"register\",\n args: [dataUri, []],\n }),\n value: \"0x0\",\n chainId,\n },\n ],\n preconditions: [],\n description: `Mint an ERC-8004 agent identity \"${args.name}\" on chain ${chainId}.`,\n note: \"ERC-8004 identity is minted on Base. Read the resulting token id from the mint receipt (chainId:tokenId); reference it when creating or joining syndicates.\",\n };\n}\n","import { encodeAbiParameters, encodeFunctionData, getAddress, parseAbiParameters, } from \"viem\";\nimport { EAS_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { encodeRegisterAgent } from \"./vault.js\";\nimport { unsupported } from \"../errors.js\";\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nconst ZERO_BYTES32 = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\nconst JOIN_REQUEST_PARAMS = parseAbiParameters(\"uint256, uint256, address, string\");\nconst AGENT_APPROVED_PARAMS = parseAbiParameters(\"uint256, uint256, address\");\nconst toBig = (x) => (typeof x === \"bigint\" ? x : BigInt(x));\n// ── Message-prefix helpers (ported from cli/src/lib/eas.ts) ──\n//\n// Join-request messages carry CLI metadata as bracketed prefixes so a creator\n// querying Base EAS can recover the source chain + referrer. Order is\n// `[chain:<slug>] [ref:<id>] body` — chain outer, ref inner. Kept byte-identical\n// to the CLI so calldata-built join requests are indistinguishable from\n// CLI-signed ones in `sherwood syndicate requests`.\nfunction formatMessageWithRef(message, referrerAgentId) {\n if (referrerAgentId == null)\n return message;\n return `[ref:${referrerAgentId}] ${message}`;\n}\nfunction formatMessageWithChain(message, sourceSlug, easSlug) {\n if (sourceSlug === easSlug)\n return message;\n return `[chain:${sourceSlug}] ${message}`;\n}\n/** Build an EAS `attest` tx (revocable, no expiry, no refUID, zero value). */\nfunction buildAttestTx(easAddress, schema, recipient, data, chainId) {\n return {\n to: getAddress(easAddress),\n data: encodeFunctionData({\n abi: EAS_ABI,\n functionName: \"attest\",\n args: [\n {\n schema,\n data: {\n recipient,\n expirationTime: 0n,\n revocable: true,\n refUID: ZERO_BYTES32,\n data,\n value: 0n,\n },\n },\n ],\n }),\n value: \"0x0\",\n chainId,\n };\n}\n/**\n * Encode a SYNDICATE_JOIN_REQUEST EAS attestation (agent → creator).\n *\n * The attest tx ALWAYS lands on Base (where coordination attestations live),\n * even when the syndicate runs on another chain — a `[chain:<slug>]` prefix is\n * added to the message so the creator can recover the source chain. Throws\n * UNSUPPORTED on chains with no EAS path (Robinhood).\n */\nexport function encodeJoinRequest(args, chainId) {\n const dep = getDeployment(chainId);\n const eas = dep.eas;\n if (eas.address === ZERO_ADDRESS) {\n throw unsupported(`No EAS coordination path on chain ${chainId} — join requests require a chain whose attestations are pinned to Base.`);\n }\n const easSlug = getDeployment(eas.chainId).slug;\n const message = formatMessageWithChain(formatMessageWithRef(args.message, args.referrerAgentId), dep.slug, easSlug);\n const data = encodeAbiParameters(JOIN_REQUEST_PARAMS, [\n toBig(args.syndicateId),\n toBig(args.agentId),\n getAddress(args.vault),\n message,\n ]);\n return {\n txs: [\n buildAttestTx(eas.address, eas.schemas.joinRequest, getAddress(args.creator), data, eas.chainId),\n ],\n preconditions: [],\n description: `Request to join syndicate ${toBig(args.syndicateId).toString()} (vault ${getAddress(args.vault)}).`,\n note: \"EAS coordination attestation — always submitted on Base, even for syndicates on another chain. Revocable; the creator discovers it via the join-request schema.\",\n };\n}\n/**\n * Encode the two txs a creator submits to approve an agent:\n * 1. `vault.registerAgent(agentAddress, agentId)` on the syndicate's own chain\n * 2. AGENT_APPROVED EAS attestation on Base\n *\n * These land on two different chains — `txs[0].chainId` is the syndicate chain,\n * `txs[1].chainId` is Base.\n */\nexport function encodeApproveAgent(args, chainId) {\n const dep = getDeployment(chainId);\n const eas = dep.eas;\n if (eas.address === ZERO_ADDRESS) {\n throw unsupported(`No EAS coordination path on chain ${chainId} — approvals require a chain whose attestations are pinned to Base.`);\n }\n const registerTx = encodeRegisterAgent({\n vault: args.vault,\n agentAddress: args.agentAddress,\n agentId: toBig(args.agentId),\n }, chainId).txs[0];\n const data = encodeAbiParameters(AGENT_APPROVED_PARAMS, [\n toBig(args.syndicateId),\n toBig(args.agentId),\n getAddress(args.vault),\n ]);\n const attestTx = buildAttestTx(eas.address, eas.schemas.agentApproved, getAddress(args.agentAddress), data, eas.chainId);\n return {\n txs: [registerTx, attestTx],\n preconditions: [],\n description: `Approve agent ${toBig(args.agentId).toString()} for syndicate ${toBig(args.syndicateId).toString()}: register on the vault (chain ${chainId}) + AGENT_APPROVED attestation on Base.`,\n note: \"Vault owner only. Two txs on two chains: registerAgent runs on the syndicate's chain; the approval attestation runs on Base.\",\n };\n}\n","import { encodeFunctionData, getAddress } from \"viem\";\nimport { GUARDIAN_REGISTRY_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { unsupported, usage } from \"../errors.js\";\nconst ZERO_VALUE = \"0x0\";\nfunction registryTx(chainId, data) {\n const registry = getDeployment(chainId).sherwood.guardianRegistry;\n if (registry === \"0x0000000000000000000000000000000000000000\") {\n throw unsupported(`Guardian registry is not deployed on chain ${chainId} yet`);\n }\n return { to: registry, data, value: ZERO_VALUE, chainId };\n}\nfunction parseUint(value, field) {\n if (typeof value === \"bigint\") {\n if (value < 0n)\n throw usage(`\\`${field}\\` must be a non-negative integer`);\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value < 0) {\n throw usage(`\\`${field}\\` must be a non-negative integer`);\n }\n return BigInt(value);\n }\n if (!/^\\d+$/.test(value)) {\n throw usage(`\\`${field}\\` must be a non-negative integer string, got \"${value}\"`);\n }\n return BigInt(value);\n}\n// ── Guardian self-stake ───────────────────────────────────\nexport function encodeGuardianStake(args, chainId) {\n if (args.amount <= 0n)\n throw usage(\"`amount` must be > 0\");\n const agentId = parseUint(args.agentId, \"agentId\");\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"stakeAsGuardian\",\n args: [args.amount, agentId],\n });\n const registry = getDeployment(chainId).sherwood.guardianRegistry;\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [\n // Caller must have approved WOOD for the registry; agent should\n // check this client-side and prepend an ERC20.approve if needed.\n {\n type: \"allowance\",\n token: registry,\n spender: registry,\n min: args.amount.toString(),\n minDecimal: args.amount.toString(),\n },\n ],\n description: `Stake ${args.amount.toString()} WOOD as guardian (agent ${agentId.toString()}).`,\n note: \"Caller must have approved WOOD for the registry first. Stake locks the WOOD; use /prepare/guardian-unstake later to start the 7d unstake cooldown.\",\n };\n}\nconst GUARDIAN_UNSTAKE_FN = {\n request: \"requestUnstakeGuardian\",\n cancel: \"cancelUnstakeGuardian\",\n claim: \"claimUnstakeGuardian\",\n};\nexport function encodeGuardianUnstake(args, chainId) {\n const fn = GUARDIAN_UNSTAKE_FN[args.action];\n if (!fn) {\n throw usage(`\\`action\\` must be one of: ${Object.keys(GUARDIAN_UNSTAKE_FN).join(\", \")}`);\n }\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: fn,\n args: [],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Guardian unstake ${args.action}.`,\n note: args.action === \"request\"\n ? \"Starts a 7-day cooldown. After it elapses, call again with action=claim to withdraw.\"\n : args.action === \"claim\"\n ? \"Withdraws the unstake amount once the 7-day cooldown has elapsed.\"\n : \"Cancels a pending unstake request and re-activates the guardian.\",\n };\n}\n// ── Delegation ────────────────────────────────────────────\nexport function encodeGuardianDelegate(args, chainId) {\n if (args.amount <= 0n)\n throw usage(\"`amount` must be > 0\");\n const delegate = getAddress(args.delegate);\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"delegateStake\",\n args: [delegate, args.amount],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Delegate ${args.amount.toString()} WOOD to ${delegate}.`,\n note: \"Caller must have approved WOOD for the registry first. Delegation does NOT activate the delegate as a guardian — they must self-stake separately.\",\n };\n}\nconst DELEGATION_UNSTAKE_FN = {\n request: \"requestUnstakeDelegation\",\n cancel: \"cancelUnstakeDelegation\",\n claim: \"claimUnstakeDelegation\",\n};\nexport function encodeDelegationUnstake(args, chainId) {\n const fn = DELEGATION_UNSTAKE_FN[args.action];\n if (!fn) {\n throw usage(`\\`action\\` must be one of: ${Object.keys(DELEGATION_UNSTAKE_FN).join(\", \")}`);\n }\n const delegate = getAddress(args.delegate);\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: fn,\n args: [delegate],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Delegation unstake ${args.action} for delegate ${delegate}.`,\n note: args.action === \"request\"\n ? \"Starts a 7-day cooldown on the delegated amount.\"\n : args.action === \"claim\"\n ? \"Withdraws the delegated amount once the 7-day cooldown has elapsed.\"\n : \"Cancels a pending unstake of the delegation.\",\n };\n}\n// ── Commission ────────────────────────────────────────────\nexport function encodeSetCommission(args, chainId) {\n if (!Number.isInteger(args.bps) || args.bps < 0 || args.bps > 5000) {\n throw usage(\"`bps` must be an integer in [0, 5000] (0–50%)\");\n }\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"setCommission\",\n args: [args.bps],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Set DPoS commission to ${args.bps} bps.`,\n note: \"Raise-rate is capped at 500 bps above the epoch-start rate; first set on a delegate is exempt. Decreases are unbounded.\",\n };\n}\n// ── Reward claims ─────────────────────────────────────────\nexport function encodeClaimProposalReward(args, chainId) {\n const proposalId = parseUint(args.proposalId, \"proposalId\");\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"claimProposalReward\",\n args: [proposalId],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Claim guardian-fee reward for proposal ${proposalId.toString()}.`,\n note: \"Approver-side claim. Pulls the DPoS commission slice and seeds the delegator pool atomically.\",\n };\n}\nexport function encodeClaimDelegatorProposalReward(args, chainId) {\n const proposalId = parseUint(args.proposalId, \"proposalId\");\n const delegate = getAddress(args.delegate);\n const data = encodeFunctionData({\n abi: GUARDIAN_REGISTRY_ABI,\n functionName: \"claimDelegatorProposalReward\",\n args: [delegate, proposalId],\n });\n return {\n txs: [registryTx(chainId, data)],\n preconditions: [],\n description: `Claim delegator-share reward from delegate ${delegate} for proposal ${proposalId.toString()}.`,\n note: \"Delegator-side claim. The approver must have claimed first to seed the delegator pool.\",\n };\n}\n","import { getAddress } from \"viem\";\nimport { SYNDICATE_FACTORY_ABI, SYNDICATE_VAULT_ABI } from \"../abis.js\";\nimport { getDeployment } from \"../addresses.js\";\nimport { notFound, unavailable, usage } from \"../errors.js\";\nconst SECONDS_PER_DAY = 86400n;\nexport async function readActiveSyndicates(client, chainId, opts = {}) {\n const factory = getDeployment(chainId).sherwood.factory;\n let raw;\n try {\n raw = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"getAllActiveSyndicates\",\n }));\n }\n catch (err) {\n throw unavailable(`Failed to read getAllActiveSyndicates from chain ${chainId}`, err);\n }\n // Newest-first, then truncate to `limit`. Default 25, hard cap 100 — same\n // shape as /v1/proposals.\n const limit = Math.min(opts.limit ?? 25, 100);\n const sorted = [...raw].sort((a, b) => a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0);\n const page = sorted.slice(0, limit);\n if (page.length === 0)\n return [];\n // One round-trip per vault: totalAssets + getAgentCount + paused +\n // openDeposits. Use Promise.all rather than multicall3 because the SDK\n // doesn't ship the multicall3 ABI today (would add weight + a new dep).\n // Page is small (default 25) so the parallel-RPC fan-out is fine.\n const enriched = await Promise.all(page.map(async (s) => {\n const [totalAssets, agentCount, paused, openDeposits] = await Promise.all([\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"totalAssets\",\n })\n .catch(() => 0n),\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"getAgentCount\",\n })\n .catch(() => 0n),\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"paused\",\n })\n .catch(() => false),\n client\n .readContract({\n address: s.vault,\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"openDeposits\",\n })\n .catch(() => false),\n ]);\n const nowSec = BigInt(Math.floor(Date.now() / 1000));\n const ageSec = nowSec > s.createdAt ? nowSec - s.createdAt : 0n;\n return {\n id: s.id.toString(),\n vault: s.vault,\n creator: s.creator,\n subdomain: s.subdomain,\n metadataURI: s.metadataURI,\n createdAt: s.createdAt.toString(),\n ageDays: Number(ageSec / SECONDS_PER_DAY),\n agentCount: Number(agentCount),\n totalAssets: totalAssets.toString(),\n paused,\n openDeposits,\n };\n }));\n return enriched;\n}\n/**\n * Resolve a syndicate's id (and canonical vault/creator/subdomain) from either\n * its vault address or its subdomain — the reliable path the issue's reporter\n * lacked. `vault.syndicateId()` does not exist; resolution goes through the\n * factory's `vaultToSyndicate` / `subdomainToSyndicate` → `syndicates(id)`.\n *\n * Throws USAGE when neither key is given, NOT_FOUND when nothing maps.\n */\nexport async function readSyndicateResolution(client, chainId, by) {\n const factory = getDeployment(chainId).sherwood.factory;\n let id;\n if (by.vault) {\n id = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"vaultToSyndicate\",\n args: [getAddress(by.vault)],\n }));\n }\n else if (by.subdomain) {\n id = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"subdomainToSyndicate\",\n args: [by.subdomain],\n }));\n }\n else {\n throw usage(\"Provide `vault` or `subdomain` to resolve a syndicate\");\n }\n if (id === 0n) {\n throw notFound(`No syndicate found for ${by.vault ? `vault ${by.vault}` : `subdomain ${by.subdomain}`} on chain ${chainId}`);\n }\n const s = (await client.readContract({\n address: factory,\n abi: SYNDICATE_FACTORY_ABI,\n functionName: \"syndicates\",\n args: [id],\n }));\n return {\n syndicateId: s[0].toString(),\n vault: s[1],\n creator: s[2],\n subdomain: s[6],\n };\n}\n","/**\n * MoonwellSupplyStrategy call builder.\n *\n * InitParams (Solidity): (address underlying, address mToken, uint256 supplyAmount, uint256 minRedeemAmount)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n underlying: Address,\n mToken: Address,\n supplyAmount: bigint,\n minRedeemAmount: bigint,\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"uint256\" },\n ],\n [underlying, mToken, supplyAmount, minRedeemAmount],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n underlying: Address,\n supplyAmount: bigint,\n): BatchCall[] {\n return [\n {\n target: underlying,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, supplyAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * VeniceInferenceStrategy call builder.\n *\n * InitParams (Solidity struct):\n * address asset, address weth, address vvv, address sVVV,\n * address aeroRouter, address aeroFactory, address agent,\n * uint256 assetAmount, uint256 minVVV, uint256 deadlineOffset, bool singleHop\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface VeniceInferenceInitParams {\n asset: Address;\n weth: Address;\n vvv: Address;\n sVVV: Address;\n aeroRouter: Address;\n aeroFactory: Address;\n agent: Address;\n assetAmount: bigint;\n minVVV: bigint;\n deadlineOffset: bigint;\n singleHop: boolean;\n}\n\nconst INIT_PARAMS_TYPES = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"asset\", type: \"address\" as const },\n { name: \"weth\", type: \"address\" as const },\n { name: \"vvv\", type: \"address\" as const },\n { name: \"sVVV\", type: \"address\" as const },\n { name: \"aeroRouter\", type: \"address\" as const },\n { name: \"aeroFactory\", type: \"address\" as const },\n { name: \"agent\", type: \"address\" as const },\n { name: \"assetAmount\", type: \"uint256\" as const },\n { name: \"minVVV\", type: \"uint256\" as const },\n { name: \"deadlineOffset\", type: \"uint256\" as const },\n { name: \"singleHop\", type: \"bool\" as const },\n ],\n },\n] as const;\n\nexport function buildInitData(params: VeniceInferenceInitParams): Hex {\n return encodeAbiParameters(INIT_PARAMS_TYPES, [params]);\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n assetAmount: bigint,\n): BatchCall[] {\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, assetAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * AerodromeLPStrategy call builder.\n *\n * InitParams (Solidity struct):\n * address tokenA, address tokenB, bool stable,\n * address factory, address router, address gauge, address lpToken,\n * uint256 amountADesired, uint256 amountBDesired,\n * uint256 amountAMin, uint256 amountBMin,\n * uint256 minAmountAOut, uint256 minAmountBOut\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface AerodromeLPInitParams {\n tokenA: Address;\n tokenB: Address;\n stable: boolean;\n factory: Address;\n router: Address;\n gauge: Address;\n lpToken: Address;\n amountADesired: bigint;\n amountBDesired: bigint;\n amountAMin: bigint;\n amountBMin: bigint;\n minAmountAOut: bigint;\n minAmountBOut: bigint;\n}\n\nconst INIT_PARAMS_TYPES = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"tokenA\", type: \"address\" as const },\n { name: \"tokenB\", type: \"address\" as const },\n { name: \"stable\", type: \"bool\" as const },\n { name: \"factory\", type: \"address\" as const },\n { name: \"router\", type: \"address\" as const },\n { name: \"gauge\", type: \"address\" as const },\n { name: \"lpToken\", type: \"address\" as const },\n { name: \"amountADesired\", type: \"uint256\" as const },\n { name: \"amountBDesired\", type: \"uint256\" as const },\n { name: \"amountAMin\", type: \"uint256\" as const },\n { name: \"amountBMin\", type: \"uint256\" as const },\n { name: \"minAmountAOut\", type: \"uint256\" as const },\n { name: \"minAmountBOut\", type: \"uint256\" as const },\n ],\n },\n] as const;\n\nexport function buildInitData(params: AerodromeLPInitParams): Hex {\n return encodeAbiParameters(INIT_PARAMS_TYPES, [params]);\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n tokenA: Address,\n amountA: bigint,\n tokenB: Address,\n amountB: bigint,\n): BatchCall[] {\n return [\n {\n target: tokenA,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, amountA],\n }),\n value: 0n,\n },\n {\n target: tokenB,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, amountB],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * WstETHMoonwellStrategy call builder.\n *\n * InitParams (Solidity struct):\n * address weth, address wsteth, address mwsteth,\n * address aeroRouter, address aeroFactory, address chainlinkWstethEthFeed,\n * uint256 supplyAmount, uint256 minWstethOutPerWeth, uint256 minWethOutPerWsteth, uint256 deadlineOffset\n * supplyAmount = 0 means use the vault's full WETH balance at execute time\n * min*PerX are 1e18-scaled per-unit rates so slippage protection scales with amountIn.\n * chainlinkWstethEthFeed is the Chainlink WSTETH/ETH price feed used by the\n * strategy's `_positionValue` for live NAV during an active proposal. Base\n * mainnet: 0x43a5C292A453A3bF3606fa856197f09D7B74251a (heartbeat 24h, 18 decimals).\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData, maxUint256 } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface WstETHMoonwellInitParams {\n weth: Address;\n wsteth: Address;\n mwsteth: Address;\n aeroRouter: Address;\n aeroFactory: Address;\n chainlinkWstethEthFeed: Address;\n supplyAmount: bigint;\n minWstethOutPerWeth: bigint;\n minWethOutPerWsteth: bigint;\n deadlineOffset: bigint;\n}\n\nconst INIT_PARAMS_TYPES = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"weth\", type: \"address\" as const },\n { name: \"wsteth\", type: \"address\" as const },\n { name: \"mwsteth\", type: \"address\" as const },\n { name: \"aeroRouter\", type: \"address\" as const },\n { name: \"aeroFactory\", type: \"address\" as const },\n { name: \"chainlinkWstethEthFeed\", type: \"address\" as const },\n { name: \"supplyAmount\", type: \"uint256\" as const },\n { name: \"minWstethOutPerWeth\", type: \"uint256\" as const },\n { name: \"minWethOutPerWsteth\", type: \"uint256\" as const },\n { name: \"deadlineOffset\", type: \"uint256\" as const },\n ],\n },\n] as const;\n\nexport function buildInitData(params: WstETHMoonwellInitParams): Hex {\n return encodeAbiParameters(INIT_PARAMS_TYPES, [params]);\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n weth: Address,\n supplyAmount: bigint,\n): BatchCall[] {\n // In dynamic-all mode (supplyAmount == 0) we can't know the exact amount\n // at proposal-build time, so approve maxUint256 then revoke to 0 after\n // execute() in the same batch. This bounds the residual allowance to a\n // single atomic tx — any leftover approval is cleared before control\n // returns to the governor.\n const approveAmount = supplyAmount === 0n ? maxUint256 : supplyAmount;\n\n return [\n {\n target: weth,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, approveAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n {\n target: weth,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, 0n],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * MamoYieldStrategy call builder.\n *\n * InitParams (Solidity): (address underlying, address mamoFactory, uint256 minRedeemAmount)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n underlying: Address,\n mamoFactory: Address,\n minRedeemAmount: bigint,\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"address\" },\n { type: \"uint256\" },\n ],\n [underlying, mamoFactory, minRedeemAmount],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n underlying: Address,\n amount: bigint,\n): BatchCall[] {\n return [\n {\n target: underlying,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, amount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}","/**\n * PortfolioStrategy call builder.\n *\n * InitParams (Solidity): (address asset, address swapAdapter, address chainlinkVerifier,\n * address[] tokens, uint256[] weightsBps, uint256 totalAmount, uint256 maxSlippageBps,\n * bytes[] swapExtraData, uint8[] priceDecimals)\n *\n * `priceDecimals[i]` declares the raw Chainlink Data Streams report scale for\n * allocation `i` (typically 8 for tokenized stocks, 18 for crypto pairs). It\n * is used by `_positionValue` to normalize live NAV into the vault asset's\n * decimals — see PortfolioStrategy `_positionValue` for the formula.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport interface BasketAllocation {\n token: Address;\n weightBps: number; // e.g. 4000 = 40%\n swapExtraData: Hex; // adapter-specific (fee tier, path, etc.)\n priceDecimals: number; // Chainlink Data Streams report decimals (8 or 18)\n}\n\nexport function buildInitData(\n asset: Address,\n swapAdapter: Address,\n chainlinkVerifier: Address,\n allocations: BasketAllocation[],\n totalAmount: bigint,\n maxSlippageBps: number,\n): Hex {\n const tokens = allocations.map((a) => a.token);\n const weightsBps = allocations.map((a) => BigInt(a.weightBps));\n const swapExtraData = allocations.map((a) => a.swapExtraData);\n const priceDecimals = allocations.map((a) => a.priceDecimals);\n\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"address\" },\n { type: \"address\" },\n { type: \"address[]\" },\n { type: \"uint256[]\" },\n { type: \"uint256\" },\n { type: \"uint256\" },\n { type: \"bytes[]\" },\n { type: \"uint8[]\" },\n ],\n [\n asset,\n swapAdapter,\n chainlinkVerifier,\n tokens,\n weightsBps,\n totalAmount,\n BigInt(maxSlippageBps),\n swapExtraData,\n priceDecimals,\n ],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n totalAmount: bigint,\n): BatchCall[] {\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, totalAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildUpdateParamsCalls(\n clone: Address,\n newWeightsBps: number[],\n newMaxSlippageBps: number,\n newSwapExtraData: Hex[],\n): BatchCall[] {\n const data = encodeAbiParameters(\n [{ type: \"uint256[]\" }, { type: \"uint256\" }, { type: \"bytes[]\" }],\n [\n newWeightsBps.map((w) => BigInt(w)),\n BigInt(newMaxSlippageBps),\n newSwapExtraData,\n ],\n );\n\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: [\n {\n type: \"function\",\n name: \"updateParams\",\n inputs: [{ type: \"bytes\", name: \"data\" }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n ],\n functionName: \"updateParams\",\n args: [data],\n }),\n value: 0n,\n },\n ];\n}\n\n// ── Rebalancing ──\n\nimport { PORTFOLIO_STRATEGY_ABI } from \"../lib/abis.js\";\n\n/**\n * Encode calldata for the simple `rebalance()` call.\n * This is called directly by the proposer (not via vault batch).\n */\nexport function encodeRebalanceCalldata(): Hex {\n return encodeFunctionData({\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"rebalance\",\n });\n}\n\n/**\n * Encode calldata for `updateParams()` to change weights before rebalancing.\n */\nexport function encodeUpdateWeightsCalldata(\n newWeightsBps: number[],\n newMaxSlippageBps: number,\n newSwapExtraData: Hex[],\n): Hex {\n const data = encodeAbiParameters(\n [{ type: \"uint256[]\" }, { type: \"uint256\" }, { type: \"bytes[]\" }],\n [\n newWeightsBps.map((w) => BigInt(w)),\n BigInt(newMaxSlippageBps),\n newSwapExtraData,\n ],\n );\n\n return encodeFunctionData({\n abi: PORTFOLIO_STRATEGY_ABI,\n functionName: \"updateParams\",\n args: [data],\n });\n}\n","/**\n * HyperliquidPerpStrategy call builder.\n *\n * InitParams (Solidity): (address asset, uint256 depositAmount, uint32 perpAssetIndex, uint32 leverage, uint256 maxPositionSize, uint32 maxTradesPerDay)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData, maxUint256 } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI, HYPERLIQUID_PERP_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n asset: Address,\n depositAmount: bigint,\n perpAssetIndex: number,\n leverage: number,\n maxPositionSize: bigint,\n maxTradesPerDay: number,\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n { type: \"uint32\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n ],\n [asset, depositAmount, perpAssetIndex, leverage, maxPositionSize, maxTradesPerDay],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n amount: bigint,\n): BatchCall[] {\n // In dynamic-all mode (amount == 0) we approve maxUint256 up front and\n // revoke to 0 after execute() in the same atomic batch — the residual\n // allowance never persists beyond the tx.\n const approveAmount = amount === 0n ? maxUint256 : amount;\n\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, approveAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, 0n],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n\n/** Phase 2: sweep USDC back to vault after async HyperCore transfer completes. */\nexport function buildSweepToVaultCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: HYPERLIQUID_PERP_STRATEGY_ABI,\n functionName: \"sweepToVault\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * HyperliquidGridStrategy call builder.\n *\n * InitParams (Solidity): (address asset, uint256 depositAmount, uint32 leverage, uint256 maxOrderSize, uint32 maxOrdersPerTick, uint32[] assetIndices)\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeAbiParameters, encodeFunctionData, maxUint256 } from \"viem\";\nimport { ERC20_ABI, BASE_STRATEGY_ABI } from \"../lib/abis.js\";\nimport type { BatchCall } from \"../lib/batch.js\";\n\nexport function buildInitData(\n asset: Address,\n depositAmount: bigint,\n leverage: number,\n maxOrderSize: bigint,\n maxOrdersPerTick: number,\n assetIndices: number[],\n): Hex {\n return encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n { type: \"uint256\" },\n { type: \"uint32\" },\n { type: \"uint32[]\" },\n ],\n [asset, depositAmount, leverage, maxOrderSize, maxOrdersPerTick, assetIndices],\n );\n}\n\nexport function buildExecuteCalls(\n clone: Address,\n asset: Address,\n amount: bigint,\n): BatchCall[] {\n const approveAmount = amount === 0n ? maxUint256 : amount;\n\n return [\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, approveAmount],\n }),\n value: 0n,\n },\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"execute\",\n }),\n value: 0n,\n },\n {\n target: asset,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [clone, 0n],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildSettleCalls(clone: Address): BatchCall[] {\n return [\n {\n target: clone,\n data: encodeFunctionData({\n abi: BASE_STRATEGY_ABI,\n functionName: \"settle\",\n }),\n value: 0n,\n },\n ];\n}\n","/**\n * Subgraph query wrapper for syndicate discovery.\n *\n * Queries The Graph's hosted/studio subgraph for indexed\n * factory + vault events. Much faster than on-chain iteration.\n *\n * Requires SUBGRAPH_URL env var pointing to the subgraph's\n * query endpoint (from The Graph Studio).\n */\n\nexport interface SubgraphSyndicate {\n id: string;\n vault: string;\n creator: string;\n metadataURI: string;\n createdAt: string;\n active: boolean;\n totalDeposits: string;\n totalWithdrawals: string;\n}\n\nexport interface SubgraphAgent {\n id: string;\n agentAddress: string;\n active: boolean;\n registeredAt: string;\n totalBatches: string;\n totalAssetAmount: string;\n}\n\nexport interface SubgraphDeposit {\n id: string;\n sender: string;\n owner: string;\n assets: string;\n shares: string;\n timestamp: string;\n txHash: string;\n}\n\nexport interface SyndicateDetails extends SubgraphSyndicate {\n agents: SubgraphAgent[];\n deposits: SubgraphDeposit[];\n}\n\nfunction getSubgraphUrl(): string {\n const url = process.env.SUBGRAPH_URL;\n if (!url) {\n throw new Error(\n \"SUBGRAPH_URL env var is required. Set it to your The Graph Studio query endpoint.\",\n );\n }\n return url;\n}\n\nasync function query<T>(graphql: string, variables?: Record<string, unknown>): Promise<T> {\n const url = getSubgraphUrl();\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ query: graphql, variables }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Subgraph query failed (${response.status}): ${text}`);\n }\n\n const result = (await response.json()) as { data?: T; errors?: { message: string }[] };\n\n if (result.errors?.length) {\n throw new Error(`Subgraph query error: ${result.errors.map((e) => e.message).join(\", \")}`);\n }\n\n if (!result.data) {\n throw new Error(\"Subgraph returned no data\");\n }\n\n return result.data;\n}\n\n/**\n * Get all active syndicates, optionally filtered by creator.\n */\nexport async function getActiveSyndicates(\n creator?: string,\n): Promise<SubgraphSyndicate[]> {\n if (creator) {\n const data = await query<{ syndicates: SubgraphSyndicate[] }>(\n `query($creator: String!) {\n syndicates(where: { active: true, creator: $creator }, orderBy: createdAt, orderDirection: desc, first: 100) {\n id\n vault\n creator\n metadataURI\n createdAt\n active\n totalDeposits\n totalWithdrawals\n }\n }`,\n { creator: creator.toLowerCase() },\n );\n return data.syndicates;\n }\n\n const data = await query<{ syndicates: SubgraphSyndicate[] }>(`\n {\n syndicates(where: { active: true }, orderBy: createdAt, orderDirection: desc, first: 100) {\n id\n vault\n creator\n metadataURI\n createdAt\n active\n totalDeposits\n totalWithdrawals\n }\n }\n `);\n\n return data.syndicates;\n}\n\n/**\n * Get detailed syndicate info including agents, recent deposits, and batch executions.\n */\nexport async function getSyndicateDetails(\n syndicateId: string,\n): Promise<SyndicateDetails | null> {\n const data = await query<{ syndicate: SyndicateDetails | null }>(\n `query($id: ID!) {\n syndicate(id: $id) {\n id\n vault\n creator\n metadataURI\n createdAt\n active\n totalDeposits\n totalWithdrawals\n agents(first: 50) {\n id\n agentAddress\n active\n registeredAt\n totalBatches\n totalAssetAmount\n }\n deposits(first: 10, orderBy: timestamp, orderDirection: desc) {\n id\n sender\n owner\n assets\n shares\n timestamp\n txHash\n }\n }\n }`,\n { id: syndicateId },\n );\n\n return data.syndicate;\n}\n\n/**\n * Get deposit/withdrawal history for a specific depositor across all syndicates.\n */\nexport async function getDepositorHistory(\n depositorAddress: string,\n): Promise<{ deposits: SubgraphDeposit[]; withdrawals: SubgraphDeposit[] }> {\n const addr = depositorAddress.toLowerCase();\n\n const data = await query<{\n deposits: SubgraphDeposit[];\n withdrawals: SubgraphDeposit[];\n }>(\n `query($owner: String!) {\n deposits(where: { owner: $owner }, orderBy: timestamp, orderDirection: desc, first: 50) {\n id\n sender\n owner\n assets\n shares\n timestamp\n txHash\n }\n withdrawals: withdrawals(where: { owner: $owner }, orderBy: timestamp, orderDirection: desc, first: 50) {\n id\n sender\n owner\n assets\n shares\n timestamp\n txHash\n }\n }`,\n { owner: addr },\n );\n\n return { deposits: data.deposits, withdrawals: data.withdrawals };\n}\n","/**\n * Venice commands — sherwood venice <subcommand>\n *\n * Manages Venice private inference: provision API keys, check status,\n * list models, run inference.\n *\n * Venice funding uses the VeniceInferenceStrategy template via the\n * proposal flow (sherwood proposal create).\n */\n\nimport { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { formatUnits, isAddress, parseUnits } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getPublicClient, getAccount, writeContractWithRetry, waitForReceipt, formatContractError } from \"../lib/client.js\";\nimport { getChain } from \"../lib/network.js\";\nimport { VENICE } from \"../lib/addresses.js\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI, VENICE_STAKING_ABI } from \"../lib/abis.js\";\nimport { provisionApiKey, checkApiKeyValid, chatCompletion, listModels } from \"../lib/venice.js\";\nimport { getVeniceApiKey } from \"../lib/config.js\";\nimport { readFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline/promises\";\n\nexport function registerVeniceCommands(program: Command): void {\n const venice = program.command(\"venice\").description(\"Venice private inference — provision API keys, run inference\");\n\n // ── venice provision ──\n\n venice\n .command(\"provision\")\n .description(\"Self-provision a Venice API key (requires sVVV in wallet)\")\n .action(async () => {\n const account = getAccount();\n const client = getPublicClient();\n\n // Check sVVV balance\n const checkSpinner = ora(\"Checking sVVV balance...\").start();\n try {\n const sVvvBalance = await client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n if (sVvvBalance === 0n) {\n checkSpinner.fail(\"No sVVV found in wallet\");\n console.log(chalk.yellow(\" Your wallet must hold staked VVV (sVVV) to provision a Venice API key.\"));\n console.log(chalk.yellow(\" Use the VeniceInferenceStrategy via a proposal to distribute sVVV to agents.\"));\n process.exit(1);\n }\n\n checkSpinner.succeed(`sVVV balance: ${formatUnits(sVvvBalance, 18)}`);\n } catch (err) {\n checkSpinner.fail(\"Failed to check sVVV balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Provision API key\n const keySpinner = ora(\"Provisioning Venice API key...\").start();\n try {\n const apiKey = await provisionApiKey();\n keySpinner.succeed(\"Venice API key provisioned\");\n console.log(chalk.dim(` Key: ${apiKey.slice(0, 8)}...${apiKey.slice(-4)}`));\n console.log(chalk.dim(\" Saved to ~/.sherwood/config.json\"));\n\n // Create EAS attestation\n try {\n const { createVeniceProvisionAttestation, getEasScanUrl } = await import(\"../lib/eas.js\");\n const { uid } = await createVeniceProvisionAttestation(account.address);\n if (uid !== \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n console.log(chalk.dim(` Attested: ${getEasScanUrl(uid)}`));\n }\n } catch {\n // Attestation is best-effort\n }\n } catch (err) {\n keySpinner.fail(\"Failed to provision API key\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice stake ──\n\n venice\n .command(\"stake\")\n .description(\"Stake VVV tokens to receive sVVV (required for API key provisioning)\")\n .requiredOption(\"--amount <n>\", \"Amount of VVV to stake (human-readable, e.g. 13)\")\n .action(async (opts) => {\n const account = getAccount();\n const client = getPublicClient();\n const chain = getChain();\n const veniceAddrs = VENICE();\n const amount = parseUnits(opts.amount, 18);\n\n // Check VVV balance\n const balSpinner = ora(\"Checking VVV balance...\").start();\n try {\n const vvvBalance = await client.readContract({\n address: veniceAddrs.VVV,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n if (vvvBalance < amount) {\n balSpinner.fail(`Insufficient VVV: have ${formatUnits(vvvBalance, 18)}, need ${opts.amount}`);\n process.exit(1);\n }\n balSpinner.succeed(`VVV balance: ${formatUnits(vvvBalance, 18)}`);\n } catch (err) {\n balSpinner.fail(\"Failed to check VVV balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Approve VVV spend\n const approveSpinner = ora(\"Approving VVV for staking contract...\").start();\n try {\n const approveHash = await writeContractWithRetry({\n account,\n chain,\n address: veniceAddrs.VVV,\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [veniceAddrs.STAKING, amount],\n });\n await waitForReceipt(approveHash);\n approveSpinner.succeed(\"VVV approved\");\n } catch (err) {\n approveSpinner.fail(\"Approve failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n // Stake VVV → sVVV\n const stakeSpinner = ora(`Staking ${opts.amount} VVV...`).start();\n try {\n const stakeHash = await writeContractWithRetry({\n account,\n chain,\n address: veniceAddrs.STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"stake\",\n args: [account.address, amount],\n });\n await waitForReceipt(stakeHash);\n\n // Read new sVVV balance\n const sVvvBalance = await client.readContract({\n address: veniceAddrs.STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n stakeSpinner.succeed(`Staked ${opts.amount} VVV → ${formatUnits(sVvvBalance, 18)} sVVV`);\n console.log(chalk.dim(\" You can now run: sherwood venice provision\"));\n } catch (err) {\n stakeSpinner.fail(\"Stake failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice mint-diem ──\n\n venice\n .command(\"mint-diem\")\n .description(\"Lock sVVV to mint DIEM (Venice inference credits; ~1d cooldown)\")\n .requiredOption(\"--amount <n>\", \"Amount of sVVV to lock (human-readable, 18 decimals)\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps (default 500 = 5%)\", \"500\")\n .option(\"--yes\", \"Skip the cooldown confirmation prompt\")\n .action(async (opts) => {\n const account = getAccount();\n const client = getPublicClient();\n const chain = getChain();\n const { STAKING, DIEM } = VENICE();\n\n const amount = parseUnits(opts.amount, 18);\n const slippageBps = BigInt(opts.slippage ?? \"500\");\n if (slippageBps < 0n || slippageBps > 10000n) {\n console.error(chalk.red(`Invalid slippage bps: ${opts.slippage} (must be 0–10000)`));\n process.exit(1);\n }\n\n // 1. Check sVVV balance\n const balSpinner = ora(\"Checking sVVV balance...\").start();\n let sVvvBalance: bigint;\n try {\n sVvvBalance = await client.readContract({\n address: STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n } catch (err) {\n balSpinner.fail(\"Failed to read sVVV balance\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n if (sVvvBalance < amount) {\n balSpinner.fail(\n `Insufficient sVVV: have ${formatUnits(sVvvBalance, 18)}, need ${opts.amount}`,\n );\n console.log(chalk.yellow(\" Stake VVV first (see VeniceInferenceStrategy proposal flow).\"));\n process.exit(1);\n }\n balSpinner.succeed(`sVVV balance: ${formatUnits(sVvvBalance, 18)}`);\n\n // 2. Quote DIEM out\n const quoteSpinner = ora(\"Quoting DIEM output...\").start();\n let expected: bigint;\n try {\n expected = await client.readContract({\n address: STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"getDiemAmountOut\",\n args: [amount],\n }) as bigint;\n } catch (err) {\n quoteSpinner.fail(\"Failed to quote DIEM output\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n if (expected === 0n) {\n quoteSpinner.fail(\"Quote returned 0 DIEM — refusing to mint\");\n process.exit(1);\n }\n const minOut = (expected * (10000n - slippageBps)) / 10000n;\n quoteSpinner.succeed(\n `Expected: ${formatUnits(expected, 18)} DIEM (minOut @ ${slippageBps}bps: ${formatUnits(minOut, 18)})`,\n );\n\n // 3. Spendability check — Venice requires >= 0.1 DIEM minimum before any\n // DIEM credit becomes spendable on inference calls. Warn the agent\n // upfront so they can size up sVVV (or switch to x402) before locking.\n const MIN_SPENDABLE_DIEM = parseUnits(\"0.1\", 18);\n let currentDiem = 0n;\n try {\n currentDiem = await client.readContract({\n address: DIEM,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n } catch {\n // best-effort\n }\n const projectedDiem = currentDiem + expected;\n if (projectedDiem < MIN_SPENDABLE_DIEM) {\n const shortfall = MIN_SPENDABLE_DIEM - projectedDiem;\n // Linear extrapolation: scale up amount by the ratio shortfall/expected\n const sVvvNeeded = (amount * shortfall + expected - 1n) / expected; // ceil-div\n console.log();\n console.log(chalk.red(\" ⚠ Venice requires ≥ 0.1 DIEM minimum before ANY DIEM credit\"));\n console.log(chalk.red(\" becomes spendable on inference calls.\"));\n console.log(chalk.red(` Projected DIEM after mint: ${formatUnits(projectedDiem, 18)} (short by ${formatUnits(shortfall, 18)})`));\n console.log(chalk.red(` Approx additional sVVV needed: ${formatUnits(sVvvNeeded, 18)}`));\n console.log(chalk.dim(\" Below threshold, this DIEM sits idle — consider acquiring\"));\n console.log(chalk.dim(\" more sVVV first, or use x402 USDC pay-per-request.\"));\n }\n\n // 4. Lockup warning + confirmation\n console.log();\n console.log(chalk.yellow(\" ⚠ Locked sVVV cannot be unstaked directly. To recover it you must\"));\n console.log(chalk.yellow(\" first call `staking.burnDiem(amount)` (burns DIEM, unlocks sVVV\"));\n console.log(chalk.yellow(\" at your average mint rate), then `initiateUnstake` + wait the\"));\n console.log(chalk.yellow(\" 7-day staking cooldown, then `finalizeUnstake`.\"));\n console.log(chalk.dim(\" x402 alternative (pay-per-request in USDC, no DIEM lock):\"));\n console.log(chalk.dim(\" https://docs.venice.ai/overview/guides/generating-api-key-agent#paying-for-inference\"));\n console.log();\n\n if (!opts.yes) {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = (await rl.question(` Lock ${opts.amount} sVVV for DIEM credits? [y/N] `)).trim().toLowerCase();\n if (answer !== \"y\" && answer !== \"yes\") {\n console.log(chalk.dim(\" Aborted.\"));\n process.exit(0);\n }\n } finally {\n rl.close();\n }\n }\n\n // 5. Mint DIEM (reuses `currentDiem` read in step 3 as the pre-balance)\n const diemBefore = currentDiem;\n const mintSpinner = ora(`Minting DIEM from ${opts.amount} sVVV...`).start();\n try {\n const hash = await writeContractWithRetry({\n account,\n chain,\n address: STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"mintDiem\",\n args: [amount, minOut],\n });\n await waitForReceipt(hash);\n\n const diemAfter = await client.readContract({\n address: DIEM,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n const delta = diemAfter - diemBefore;\n\n mintSpinner.succeed(\n `Minted ${formatUnits(delta > 0n ? delta : diemAfter, 18)} DIEM` +\n (delta > 0n ? ` (balance: ${formatUnits(diemAfter, 18)})` : \"\"),\n );\n console.log(chalk.dim(` Tx: ${hash}`));\n console.log(chalk.yellow(\" Note: Venice requires ≥ 0.1 DIEM to spend ANY DIEM credit, and\"));\n console.log(chalk.yellow(\" refreshes daily allocation at 00:00 UTC. Below threshold,\"));\n console.log(chalk.yellow(\" inference will continue to 402.\"));\n console.log(chalk.dim(\" Once over threshold: sherwood venice infer --model <id> --prompt \\\"...\\\"\"));\n } catch (err) {\n mintSpinner.fail(\"mintDiem failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice status ──\n\n venice\n .command(\"status\")\n .description(\"Show Venice inference status: sVVV balances, DIEM, API key\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .action(async (opts) => {\n const vaultAddress = opts.vault as Address;\n if (!isAddress(vaultAddress)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const client = getPublicClient();\n const account = getAccount();\n const spinner = ora(\"Loading Venice status...\").start();\n\n try {\n // Read vault state\n const [assetAddress, totalDeposited, agents] = await Promise.all([\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"asset\" }) as Promise<Address>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"totalDeposited\" }) as Promise<bigint>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"getAgentAddresses\" }) as Promise<Address[]>,\n ]);\n\n const [assetDecimals, assetSymbol, assetBalance] = await Promise.all([\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"balanceOf\", args: [vaultAddress] }) as Promise<bigint>,\n ]);\n\n // Read VVV balance on vault\n const vaultVvvBalance = await client.readContract({\n address: VENICE().VVV,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [vaultAddress],\n }) as bigint;\n\n // Read per-agent sVVV balances\n const agentBalances = await Promise.all(\n agents.map(async (agent) => {\n const bal = await client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [agent],\n }) as bigint;\n return { agent, balance: bal };\n })\n );\n\n // Check current agent's sVVV + pending rewards + DIEM\n const [mySvvv, myPending, myDiem] = await Promise.all([\n client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as Promise<bigint>,\n client.readContract({\n address: VENICE().STAKING,\n abi: VENICE_STAKING_ABI,\n functionName: \"pendingRewards\",\n args: [account.address],\n }) as Promise<bigint>,\n client.readContract({\n address: VENICE().DIEM,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as Promise<bigint>,\n ]);\n\n // Check API key\n const apiKeyValid = await checkApiKeyValid();\n const apiKey = getVeniceApiKey();\n\n spinner.stop();\n\n const profit = assetBalance > totalDeposited ? assetBalance - totalDeposited : 0n;\n\n console.log();\n console.log(chalk.bold(\"Venice Inference Status\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n\n console.log(chalk.bold(\"\\n Vault\"));\n console.log(` Profit available: ${formatUnits(profit, assetDecimals)} ${assetSymbol}`);\n console.log(` VVV (unstaked): ${formatUnits(vaultVvvBalance, 18)}`);\n\n console.log(chalk.bold(\"\\n Agent sVVV Balances\"));\n for (const { agent, balance } of agentBalances) {\n const isMe = agent.toLowerCase() === account.address.toLowerCase();\n const label = isMe ? chalk.green(`${agent} (you)`) : agent;\n console.log(` ${label}: ${formatUnits(balance, 18)} sVVV`);\n }\n\n console.log(chalk.bold(\"\\n Your Wallet\"));\n console.log(` sVVV: ${formatUnits(mySvvv, 18)}`);\n console.log(` Pending rewards: ${formatUnits(myPending, 18)} VVV`);\n console.log(` DIEM (credits): ${formatUnits(myDiem, 18)}`);\n console.log(chalk.dim(\" (mint via `sherwood venice mint-diem --amount <sVVV>`)\"));\n\n console.log(chalk.bold(\"\\n Venice API\"));\n console.log(` Key: ${apiKey ? `${apiKey.slice(0, 8)}...${apiKey.slice(-4)}` : chalk.dim(\"not provisioned\")}`);\n console.log(` Status: ${apiKeyValid ? chalk.green(\"valid\") : chalk.red(\"invalid/missing\")}`);\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load status\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice models ──\n\n venice\n .command(\"models\")\n .description(\"List available Venice inference models\")\n .action(async () => {\n const spinner = ora(\"Fetching Venice models...\").start();\n try {\n const models = await listModels();\n spinner.succeed(`${models.length} models available`);\n console.log();\n for (const model of models) {\n console.log(` ${model}`);\n }\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to list models\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── venice infer ──\n\n venice\n .command(\"infer\")\n .description(\"Run private inference via Venice chat completions\")\n .requiredOption(\"--prompt <text>\", \"User prompt\")\n .requiredOption(\"--model <id>\", \"Venice model ID (use 'venice models' to list)\")\n .option(\"--system <text>\", \"System prompt\")\n .option(\"--data <path>\", \"Path to data file — contents prepended to prompt as context\")\n .option(\"--web-search\", \"Enable Venice web search\", false)\n .option(\"--no-thinking\", \"Disable chain-of-thought reasoning\")\n .option(\"--temperature <n>\", \"Sampling temperature (0-2)\")\n .option(\"--max-tokens <n>\", \"Maximum completion tokens\")\n .option(\"--json\", \"Output raw JSON response\", false)\n .option(\"--vault <address>\", \"Vault address — attestation recipient (defaults to config vault)\")\n .action(async (opts) => {\n // Build messages\n const messages: { role: \"system\" | \"user\" | \"assistant\"; content: string }[] = [];\n\n if (opts.system) {\n messages.push({ role: \"system\", content: opts.system });\n }\n\n let userContent = opts.prompt;\n if (opts.data) {\n try {\n const data = readFileSync(opts.data, \"utf-8\");\n userContent = `Context data:\\n\\`\\`\\`\\n${data}\\n\\`\\`\\`\\n\\n${opts.prompt}`;\n } catch (err) {\n console.error(chalk.red(`Failed to read data file: ${opts.data}`));\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n }\n messages.push({ role: \"user\", content: userContent });\n\n const spinner = ora(`Running inference (${opts.model})...`).start();\n try {\n const result = await chatCompletion({\n model: opts.model,\n messages,\n temperature: opts.temperature !== undefined ? Number(opts.temperature) : undefined,\n maxTokens: opts.maxTokens !== undefined ? Number(opts.maxTokens) : undefined,\n enableWebSearch: opts.webSearch,\n disableThinking: opts.thinking === false,\n });\n\n spinner.succeed(\"Inference complete\");\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log();\n console.log(result.content);\n console.log();\n console.log(chalk.dim(`Model: ${result.model} | Tokens: ${result.usage.promptTokens} in, ${result.usage.completionTokens} out, ${result.usage.totalTokens} total`));\n }\n\n // Create EAS attestation (best-effort)\n try {\n const { createVeniceInferenceAttestation, getEasScanUrl } = await import(\"../lib/eas.js\");\n const { keccak256, toHex, isAddress: isAddr } = await import(\"viem\");\n const { getChainContracts } = await import(\"../lib/config.js\");\n const { getChain: getActiveChain } = await import(\"../lib/network.js\");\n const vaultRecipient = (opts.vault && isAddr(opts.vault)) ? opts.vault : getChainContracts(getActiveChain().id).vault;\n const promptHash = keccak256(toHex(userContent)).slice(0, 18); // short hash\n const { uid } = await createVeniceInferenceAttestation(\n result.model,\n result.usage.promptTokens,\n result.usage.completionTokens,\n promptHash,\n vaultRecipient as `0x${string}` | undefined,\n );\n if (uid !== \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n console.log(chalk.dim(`Attested: ${getEasScanUrl(uid)}`));\n }\n } catch {\n // Attestation is best-effort\n }\n } catch (err) {\n spinner.fail(\"Inference failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * Allowance commands — sherwood allowance <subcommand>\n *\n * Disburses vault profits as USDC to agent operator wallets for\n * operational expenses (gas, x402 API payments, etc.).\n */\n\nimport { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { parseUnits, formatUnits, isAddress } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getPublicClient, getAccount, formatContractError } from \"../lib/client.js\";\nimport { getExplorerUrl } from \"../lib/network.js\";\nimport { TOKENS } from \"../lib/addresses.js\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI } from \"../lib/abis.js\";\nimport { getQuote, getMultiHopQuote, encodeSwapPath, applySlippage } from \"../lib/quote.js\";\nimport { formatBatch } from \"../lib/batch.js\";\nimport { executeBatch } from \"../lib/vault.js\";\nimport { buildDisburseBatch, type AllowanceDisbursConfig } from \"../strategies/allowance-disburse.js\";\n\nconst VALID_FEES = [500, 3000, 10000] as const;\n\nexport function registerAllowanceCommands(program: Command): void {\n const allowance = program.command(\"allowance\").description(\"Disburse vault profits to agent wallets\");\n\n // ── allowance disburse ──\n\n allowance\n .command(\"disburse\")\n .description(\"Swap vault profits → USDC → distribute to all agent operator wallets\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .requiredOption(\"--amount <amount>\", \"Deposit token amount to convert & distribute (e.g. 500)\")\n .option(\"--fee <tier>\", \"Fee tier for asset → USDC swap (500, 3000, 10000)\", \"3000\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps\", \"100\")\n .option(\"--execute\", \"Execute on-chain (default: simulate only)\", false)\n .action(async (opts) => {\n const vaultAddress = opts.vault as Address;\n if (!isAddress(vaultAddress)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const fee = Number(opts.fee);\n if (!VALID_FEES.includes(fee as 500 | 3000 | 10000)) {\n console.error(chalk.red(`Invalid fee tier. Valid: ${VALID_FEES.join(\", \")}`));\n process.exit(1);\n }\n const slippageBps = Number(opts.slippage);\n\n const client = getPublicClient();\n\n // ── Read vault state ──\n\n const spinner = ora(\"Reading vault state...\").start();\n let assetAddress: Address;\n let assetDecimals: number;\n let assetSymbol: string;\n let totalDeposited: bigint;\n let assetBalance: bigint;\n let agents: Address[];\n\n try {\n [assetAddress, totalDeposited, agents] = await Promise.all([\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"asset\" }) as Promise<Address>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"totalDeposited\" }) as Promise<bigint>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"getAgentAddresses\" }) as Promise<Address[]>,\n ]);\n\n [assetDecimals, assetSymbol, assetBalance] = await Promise.all([\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"balanceOf\", args: [vaultAddress] }) as Promise<bigint>,\n ]);\n spinner.stop();\n } catch (err) {\n spinner.fail(\"Failed to read vault state\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n\n if (agents.length === 0) {\n console.error(chalk.red(\"No agents registered in vault. Register agents first.\"));\n process.exit(1);\n }\n\n const requestedAmount = parseUnits(opts.amount, assetDecimals);\n const profit = assetBalance > totalDeposited ? assetBalance - totalDeposited : 0n;\n\n // ── Display config ──\n\n const isUsdc = assetAddress.toLowerCase() === TOKENS().USDC.toLowerCase();\n const isWeth = assetAddress.toLowerCase() === TOKENS().WETH.toLowerCase();\n\n console.log();\n console.log(chalk.bold(\"Allowance Disburse\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Asset: ${assetSymbol} (${assetDecimals} decimals)`);\n console.log(` Amount: ${opts.amount} ${assetSymbol}`);\n console.log(` Vault balance: ${formatUnits(assetBalance, assetDecimals)} ${assetSymbol}`);\n console.log(` Deposited: ${formatUnits(totalDeposited, assetDecimals)} ${assetSymbol}`);\n console.log(` Profit: ${formatUnits(profit, assetDecimals)} ${assetSymbol}`);\n console.log(` Agents: ${agents.length} (USDC will be split equally)`);\n if (!isUsdc) {\n console.log(` Routing: ${isWeth ? `WETH → USDC (fee ${fee})` : `${assetSymbol} → WETH → USDC (fee ${fee})`}`);\n console.log(` Slippage: ${(slippageBps / 100).toFixed(2)}%`);\n }\n console.log(` Vault: ${vaultAddress}`);\n console.log();\n\n if (requestedAmount > profit) {\n console.warn(chalk.yellow(` Warning: amount (${opts.amount}) exceeds available profit (${formatUnits(profit, assetDecimals)})`));\n console.warn(chalk.yellow(\" This will use deposited capital, not just profits.\"));\n console.log();\n }\n\n // ── Get USDC amount (quote or direct) ──\n\n let minUsdc: bigint;\n let swapPath: `0x${string}` | null = null;\n\n if (isUsdc) {\n // No swap needed — distribute the asset directly\n minUsdc = requestedAmount;\n } else {\n const quoteSpinner = ora(\"Fetching Uniswap quote...\").start();\n try {\n let amountOut: bigint;\n\n if (isWeth) {\n // Single-hop: WETH → USDC\n const quote = await getQuote({\n tokenIn: TOKENS().WETH,\n tokenOut: TOKENS().USDC,\n amountIn: requestedAmount,\n fee,\n });\n amountOut = quote.amountOut;\n } else {\n // Multi-hop: asset → WETH → USDC\n swapPath = encodeSwapPath(\n [assetAddress, TOKENS().WETH, TOKENS().USDC],\n [fee, 500], // WETH→USDC typically uses 500 (0.05%) fee tier\n );\n const quote = await getMultiHopQuote({\n path: swapPath,\n amountIn: requestedAmount,\n });\n amountOut = quote.amountOut;\n }\n\n minUsdc = applySlippage(amountOut, slippageBps);\n\n quoteSpinner.succeed(\n `Quote: ${formatUnits(amountOut, 6)} USDC ` +\n `(min: ${formatUnits(minUsdc, 6)}, per agent: ${formatUnits(minUsdc / BigInt(agents.length), 6)})`\n );\n } catch (err) {\n quoteSpinner.fail(\"Failed to fetch quote\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n }\n\n // ── Per-agent display ──\n\n const perAgent = minUsdc / BigInt(agents.length);\n if (isUsdc) {\n console.log(chalk.dim(` Per agent: ${formatUnits(perAgent, 6)} USDC`));\n console.log();\n }\n\n // ── Build batch ──\n\n const config: AllowanceDisbursConfig = {\n amount: opts.amount,\n fee,\n slippageBps,\n };\n\n const calls = buildDisburseBatch(config, vaultAddress, agents, assetAddress, assetDecimals, minUsdc, swapPath);\n\n console.log();\n console.log(chalk.bold(`Batch calls (${calls.length}):`));\n console.log(formatBatch(calls));\n console.log();\n\n // ── Execute ──\n\n if (!opts.execute) {\n console.log();\n console.log(chalk.yellow(\"Dry run complete. Add --execute to submit on-chain.\"));\n return;\n }\n\n const execSpinner = ora(\"Executing batch via vault...\").start();\n try {\n const txHash = await executeBatch(calls);\n execSpinner.succeed(`Batch executed: ${txHash}`);\n console.log(chalk.dim(` ${getExplorerUrl(txHash)}`));\n } catch (err) {\n execSpinner.fail(\"Execution failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── allowance status ──\n\n allowance\n .command(\"status\")\n .description(\"Show vault profit and agent USDC balances\")\n .requiredOption(\"--vault <address>\", \"Vault address\")\n .action(async (opts) => {\n const vaultAddress = opts.vault as Address;\n if (!isAddress(vaultAddress)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const client = getPublicClient();\n const spinner = ora(\"Loading allowance status...\").start();\n\n try {\n // Read vault state\n const [assetAddress, totalDeposited, agents] = await Promise.all([\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"asset\" }) as Promise<Address>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"totalDeposited\" }) as Promise<bigint>,\n client.readContract({ address: vaultAddress, abi: SYNDICATE_VAULT_ABI, functionName: \"getAgentAddresses\" }) as Promise<Address[]>,\n ]);\n\n const [assetDecimals, assetSymbol, assetBalance] = await Promise.all([\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"decimals\" }) as Promise<number>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"symbol\" }) as Promise<string>,\n client.readContract({ address: assetAddress, abi: ERC20_ABI, functionName: \"balanceOf\", args: [vaultAddress] }) as Promise<bigint>,\n ]);\n\n // Read per-agent USDC balances\n const agentBalances = await Promise.all(\n agents.map(async (agent) => {\n const bal = await client.readContract({\n address: TOKENS().USDC,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [agent],\n }) as bigint;\n return { agent, balance: bal };\n })\n );\n\n spinner.stop();\n\n const profit = assetBalance > totalDeposited ? assetBalance - totalDeposited : 0n;\n const account = getAccount();\n\n console.log();\n console.log(chalk.bold(\"Allowance Status\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n\n console.log(chalk.bold(\"\\n Vault\"));\n console.log(` Asset: ${assetSymbol}`);\n console.log(` Balance: ${formatUnits(assetBalance, assetDecimals)} ${assetSymbol}`);\n console.log(` Deposited: ${formatUnits(totalDeposited, assetDecimals)} ${assetSymbol}`);\n console.log(` Profit: ${formatUnits(profit, assetDecimals)} ${assetSymbol}`);\n\n console.log(chalk.bold(\"\\n Agent USDC Balances\"));\n for (const { agent, balance } of agentBalances) {\n const isMe = agent.toLowerCase() === account.address.toLowerCase();\n const label = isMe ? chalk.green(`${agent} (you)`) : agent;\n console.log(` ${label}: ${formatUnits(balance, 6)} USDC`);\n }\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load status\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * Allowance Disburse Strategy — swap vault profits to USDC and distribute to agents.\n *\n * If the vault's deposit token is already USDC, transfers directly to each agent.\n * Otherwise, swaps asset → USDC via Uniswap V3 (single-hop or multi-hop via WETH),\n * then distributes USDC equally to each agent's operator wallet.\n *\n * Agents use USDC for operational expenses: gas, x402 API payments, etc.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseUnits } from \"viem\";\nimport type { BatchCall } from \"../lib/batch.js\";\nimport { TOKENS, UNISWAP } from \"../lib/addresses.js\";\nimport {\n ERC20_ABI,\n SWAP_ROUTER_EXACT_INPUT_SINGLE_ABI,\n SWAP_ROUTER_ABI as SWAP_ROUTER_EXACT_INPUT_ABI,\n} from \"../lib/abis.js\";\n\n// ── Strategy Config ──\n\nexport interface AllowanceDisbursConfig {\n /** Deposit token amount to convert & distribute (human-readable, e.g. \"500\") */\n amount: string;\n /** Fee tier for asset → USDC swap (ignored if asset = USDC) */\n fee: number;\n /** Max slippage in basis points (e.g. 100 = 1%) */\n slippageBps: number;\n}\n\n// ── Batch Builder ──\n\n/**\n * Build the allowance disburse batch.\n *\n * @param config - Strategy parameters\n * @param vaultAddress - Vault contract address (delegatecall identity)\n * @param agents - Agent operator EOA addresses to receive USDC\n * @param assetAddress - Vault's deposit token address\n * @param assetDecimals - Deposit token decimals\n * @param minUsdc - Minimum USDC output (post-slippage), or raw amount if asset IS USDC\n * @param swapPath - Encoded Uniswap V3 path for multi-hop (null if single-hop or no swap)\n */\nexport function buildDisburseBatch(\n config: AllowanceDisbursConfig,\n vaultAddress: Address,\n agents: Address[],\n assetAddress: Address,\n assetDecimals: number,\n minUsdc: bigint,\n swapPath: Hex | null,\n): BatchCall[] {\n const assetAmount = parseUnits(config.amount, assetDecimals);\n const isUsdc = assetAddress.toLowerCase() === TOKENS().USDC.toLowerCase();\n const isWeth = assetAddress.toLowerCase() === TOKENS().WETH.toLowerCase();\n const calls: BatchCall[] = [];\n\n if (!isUsdc) {\n // 1. Approve SwapRouter to spend vault asset\n calls.push({\n target: assetAddress,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [UNISWAP().SWAP_ROUTER, assetAmount],\n }),\n value: 0n,\n });\n\n // 2. Swap asset → USDC\n if (isWeth) {\n // Single-hop: WETH → USDC\n calls.push({\n target: UNISWAP().SWAP_ROUTER,\n data: encodeFunctionData({\n abi: SWAP_ROUTER_EXACT_INPUT_SINGLE_ABI,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: TOKENS().WETH,\n tokenOut: TOKENS().USDC,\n fee: config.fee,\n recipient: vaultAddress,\n amountIn: assetAmount,\n amountOutMinimum: minUsdc,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n value: 0n,\n });\n } else {\n // Multi-hop: asset → WETH → USDC\n calls.push({\n target: UNISWAP().SWAP_ROUTER,\n data: encodeFunctionData({\n abi: SWAP_ROUTER_EXACT_INPUT_ABI,\n functionName: \"exactInput\",\n args: [\n {\n path: swapPath!,\n recipient: vaultAddress,\n amountIn: assetAmount,\n amountOutMinimum: minUsdc,\n },\n ],\n }),\n value: 0n,\n });\n }\n }\n\n // 3. Transfer USDC to each agent equally\n const perAgent = minUsdc / BigInt(agents.length);\n for (const agent of agents) {\n calls.push({\n target: TOKENS().USDC,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"transfer\",\n args: [agent, perAgent],\n }),\n value: 0n,\n });\n }\n\n return calls;\n}\n","/**\n * Identity commands — sherwood identity <subcommand>\n *\n * Wraps the Agent0 SDK (@agent0-sdk) for ERC-8004 agent identity management.\n * Handles: mint (register), set metadata, check status, load existing agent.\n * Required before creating or joining syndicates.\n */\n\nimport { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { SDK } from \"agent0-sdk\";\nimport { getPublicClient, getAccount, formatContractError } from \"../lib/client.js\";\nimport { getExplorerUrl, getChain, getRpcUrl } from \"../lib/network.js\";\nimport { AGENT_REGISTRY } from \"../lib/addresses.js\";\nimport { setAgentId, getAgentId, loadConfig } from \"../lib/config.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeIdentityMint, type ChainId } from \"@sherwoodagent/sdk\";\n\n// ── ABI (minimal, for status reads without SDK) ──\n\nconst IDENTITY_REGISTRY_ABI = [\n {\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"ownerOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"tokenId\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n] as const;\n\n/**\n * Initialize the Agent0 SDK with the current network config.\n */\nfunction getAgent0SDK(): SDK {\n // Read key from config first, env var as fallback\n const config = loadConfig();\n const key = config.privateKey || process.env.PRIVATE_KEY;\n if (!key) {\n throw new Error(\n \"Private key not found. Run 'sherwood config set --private-key <key>' or set PRIVATE_KEY env var.\",\n );\n }\n\n return new SDK({\n chainId: getChain().id,\n rpcUrl: getRpcUrl(),\n privateKey: key.startsWith(\"0x\") ? key : `0x${key}`,\n });\n}\n\nexport function registerIdentityCommands(program: Command): void {\n const identity = program.command(\"identity\").description(\"Manage ERC-8004 agent identity (via Agent0 SDK)\");\n\n // ── identity mint ──\n\n identity\n .command(\"mint\")\n .description(\"Register a new ERC-8004 agent identity (required before creating/joining syndicates)\")\n .requiredOption(\"--name <name>\", \"Agent name (e.g. 'Alpha Seeker Agent')\")\n .option(\"--description <desc>\", \"Agent description\", \"Sherwood syndicate agent\")\n .option(\"--image <uri>\", \"Agent image URI (IPFS recommended)\")\n .action(async (opts) => {\n // --calldata-only: emit the unsigned ERC-8004 register() calldata and\n // stop. No Agent0 SDK init, no IPFS, no private key.\n if (isCalldataOnly()) {\n emitCalldata(\n encodeIdentityMint(\n {\n name: opts.name,\n description: opts.description,\n image: opts.image,\n },\n getChain().id as ChainId,\n ),\n );\n return;\n }\n\n const account = getAccount();\n\n // Check if wallet already has an identity\n const existingId = getAgentId();\n if (existingId) {\n console.log(chalk.yellow(`You already have an agent identity saved: #${existingId}`));\n console.log(chalk.dim(\" Minting a new one anyway. The old ID is not affected.\"));\n console.log();\n }\n\n const spinner = ora(\"Initializing Agent0 SDK...\").start();\n try {\n const sdk = getAgent0SDK();\n\n // Create agent with metadata\n spinner.text = \"Creating agent profile...\";\n const agent = sdk.createAgent(opts.name, opts.description, opts.image);\n\n // Register on-chain (mints ERC-8004 NFT)\n spinner.text = \"Registering on-chain (minting ERC-8004 identity)...\";\n const txHandle = await agent.registerOnChain();\n\n spinner.text = \"Waiting for confirmation...\";\n await txHandle.waitMined();\n\n const agentId = agent.agentId;\n if (!agentId) {\n spinner.warn(\"Identity registered but could not read agentId\");\n console.log(chalk.dim(\" Check the transaction on the explorer.\"));\n return;\n }\n\n // Agent0 agentId format is \"chainId:tokenId\" — extract the token ID\n const tokenId = Number(agentId.includes(\":\") ? agentId.split(\":\")[1] : agentId);\n\n // Save to config\n setAgentId(tokenId);\n\n spinner.succeed(`Agent identity registered: #${tokenId}`);\n console.log(chalk.dim(` Agent0 ID: ${agentId}`));\n console.log(chalk.dim(` Name: ${opts.name}`));\n console.log(chalk.dim(` Owner: ${account.address}`));\n console.log(chalk.dim(` Saved to ~/.sherwood/config.json`));\n console.log();\n console.log(chalk.green(\"You can now create syndicates:\"));\n console.log(chalk.dim(` sherwood syndicate create --agent-id ${tokenId} --subdomain <name> --name <name>`));\n } catch (err) {\n spinner.fail(\"Failed to register identity\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── identity load ──\n\n identity\n .command(\"load\")\n .description(\"Load an existing ERC-8004 agent identity into your config\")\n .requiredOption(\"--id <tokenId>\", \"Agent token ID to load\")\n .action(async (opts) => {\n const account = getAccount();\n const client = getPublicClient();\n const registry = AGENT_REGISTRY().IDENTITY_REGISTRY;\n const tokenId = Number(opts.id);\n\n const spinner = ora(`Verifying ownership of agent #${tokenId}...`).start();\n try {\n const owner = await client.readContract({\n address: registry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"ownerOf\",\n args: [BigInt(tokenId)],\n }) as Address;\n\n if (owner.toLowerCase() !== account.address.toLowerCase()) {\n spinner.fail(`Agent #${tokenId} is owned by ${owner}, not your wallet`);\n process.exit(1);\n }\n\n setAgentId(tokenId);\n spinner.succeed(`Agent #${tokenId} loaded and saved to config`);\n console.log(chalk.dim(` Owner: ${account.address}`));\n console.log(chalk.dim(` Saved to ~/.sherwood/config.json`));\n } catch (err) {\n spinner.fail(\"Failed to load identity\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── identity find ──\n\n identity\n .command(\"find\")\n .description(\"Search ERC-8004 agents by wallet address or name (recover a lost agent ID)\")\n .option(\"--wallet <address>\", \"Filter by owner / wallet address\")\n .option(\"--name <text>\", \"Filter by agent name (exact or substring match, depending on registry)\")\n .option(\"--all-chains\", \"Search across all chains, not just the active one\")\n .action(async (opts) => {\n if (!opts.wallet && !opts.name) {\n console.error(chalk.red(\"Pass --wallet <address> or --name <text> (or both).\"));\n process.exit(1);\n }\n\n const spinner = ora(\"Searching ERC-8004 registry...\").start();\n try {\n const sdk = getAgent0SDK();\n const filters: Record<string, unknown> = {};\n if (opts.wallet) filters.walletAddress = opts.wallet;\n if (opts.name) filters.name = opts.name;\n // SearchFilters['chains']: explicit list per-chain or 'all'\n filters.chains = opts.allChains ? \"all\" : [getChain().id];\n\n const results = await sdk.searchAgents(filters);\n spinner.stop();\n\n if (results.length === 0) {\n console.log(chalk.dim(\"No agents found matching those filters.\"));\n console.log(chalk.dim(\"If you minted on a different chain, retry with --all-chains.\"));\n return;\n }\n\n console.log();\n console.log(chalk.bold(`Found ${results.length} agent${results.length === 1 ? \"\" : \"s\"}`));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (const a of results) {\n // Agent0 agentId format is \"chainId:tokenId\" — split for display\n const idStr = String(a.agentId);\n const tokenId = idStr.includes(\":\") ? idStr.split(\":\")[1] : idStr;\n console.log(` ${chalk.bold(`#${tokenId}`)} ${a.name || chalk.dim(\"(no name)\")}`);\n console.log(chalk.dim(` Chain: ${a.chainId}`));\n console.log(chalk.dim(` Full: ${idStr}`));\n if (a.owners?.length) {\n console.log(chalk.dim(` Owner: ${a.owners[0]}`));\n }\n if (a.walletAddress) {\n console.log(chalk.dim(` Wallet: ${a.walletAddress}`));\n }\n }\n console.log();\n console.log(chalk.green(\"To bind one of these to this machine:\"));\n console.log(chalk.dim(` sherwood identity load --id <tokenId>`));\n } catch (err) {\n spinner.fail(\"Search failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── identity status ──\n\n identity\n .command(\"status\")\n .description(\"Show your agent identity status\")\n .action(async () => {\n const account = getAccount();\n const registry = AGENT_REGISTRY().IDENTITY_REGISTRY;\n const client = getPublicClient();\n\n const spinner = ora(\"Checking identity...\").start();\n try {\n const balance = await client.readContract({\n address: registry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"balanceOf\",\n args: [account.address],\n }) as bigint;\n\n spinner.stop();\n\n const savedId = getAgentId();\n\n console.log();\n console.log(chalk.bold(\"Agent Identity (ERC-8004)\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(` Wallet: ${account.address}`);\n console.log(` Registry: ${registry}`);\n console.log(` NFTs owned: ${balance.toString()}`);\n\n if (savedId) {\n // Verify the saved ID is still owned by this wallet\n try {\n const owner = await client.readContract({\n address: registry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: \"ownerOf\",\n args: [BigInt(savedId)],\n }) as Address;\n\n const isOwner = owner.toLowerCase() === account.address.toLowerCase();\n console.log(` Saved ID: #${savedId} ${isOwner ? chalk.green(\"(verified)\") : chalk.red(\"(owned by \" + owner + \")\")}`);\n\n // Load full agent details via SDK if verified\n if (isOwner) {\n try {\n const sdk = getAgent0SDK();\n const agent = await sdk.loadAgent(`${getChain().id}:${savedId}`);\n if (agent.name) console.log(` Name: ${agent.name}`);\n if (agent.description) console.log(` Desc: ${chalk.dim(agent.description)}`);\n if (agent.walletAddress) console.log(` Wallet: ${agent.walletAddress}`);\n } catch {\n // SDK load failed — not critical, basic info already shown\n }\n }\n } catch {\n console.log(` Saved ID: #${savedId} ${chalk.red(\"(token not found)\")}`);\n }\n console.log();\n } else if (balance > 0n) {\n // Wallet owns identities but none saved locally — fetch and surface\n // them so the user can pick one to bind. Closes the trap where a\n // fresh CLI install on a wallet with prior identities reports\n // \"Saved ID: none\" without explaining what's actually on-chain.\n console.log(` Saved ID: ${chalk.yellow(\"none (but this wallet owns NFTs — listing below)\")}`);\n console.log();\n\n const lookupSpinner = ora(\"Resolving owned token IDs via Agent0 SDK...\").start();\n try {\n const sdk = getAgent0SDK();\n const results = await sdk.searchAgents({\n walletAddress: account.address,\n chains: [getChain().id],\n });\n lookupSpinner.stop();\n\n if (results.length === 0) {\n console.log(chalk.dim(\" No agents resolved for this wallet on the active chain.\"));\n console.log(chalk.dim(\" If you minted on a different chain, try:\"));\n console.log(chalk.dim(\" sherwood identity find --wallet \" + account.address + \" --all-chains\"));\n } else {\n console.log(chalk.bold(` Owned identities on this chain (${results.length}):`));\n for (const a of results) {\n const idStr = String(a.agentId);\n const tokenId = idStr.includes(\":\") ? idStr.split(\":\")[1] : idStr;\n console.log(` ${chalk.bold(`#${tokenId}`)} ${a.name || chalk.dim(\"(no name)\")}`);\n }\n console.log();\n console.log(chalk.green(\" Bind one to this machine:\"));\n if (results.length === 1) {\n const idStr = String(results[0].agentId);\n const tokenId = idStr.includes(\":\") ? idStr.split(\":\")[1] : idStr;\n console.log(chalk.dim(` sherwood identity load --id ${tokenId}`));\n } else {\n console.log(chalk.dim(\" sherwood identity load --id <tokenId>\"));\n }\n }\n } catch (err) {\n lookupSpinner.warn(\"Could not resolve owned token IDs via Agent0 SDK\");\n console.log(chalk.dim(` ${(err as Error).message}`));\n console.log(chalk.dim(\" Try: sherwood identity find --wallet \" + account.address));\n }\n console.log();\n } else {\n console.log(` Saved ID: ${chalk.dim(\"none — run 'sherwood identity mint --name <name>'\")}`);\n console.log();\n }\n } catch (err) {\n spinner.fail(\"Failed to check identity\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n","/**\n * Proposal commands — sherwood proposal <subcommand>\n *\n * Manages the full proposal lifecycle: create, list, show, vote,\n * execute, settle, cancel, simulate.\n */\n\nimport { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { isAddress, encodeFunctionData } from \"viem\";\nimport { getVaultOwner, getAssetAddress } from \"../lib/vault.js\";\nimport { ERC20_ABI } from \"../lib/abis.js\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { readFileSync } from \"node:fs\";\nimport { getAccount, formatContractError } from \"../lib/client.js\";\nimport { getExplorerUrl, getNetwork, getChain } from \"../lib/network.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeVote, encodeExecute, encodeSettle, encodeCancel, encodeUnstick, encodeEmergencySettle, encodePropose, type ChainId } from \"@sherwoodagent/sdk\";\nimport { uploadMetadata } from \"../lib/ipfs.js\";\nimport type { SyndicateMetadata } from \"../lib/ipfs.js\";\nimport { fetchMetadata } from \"../lib/ipfs.js\";\nimport {\n getGovernorAddress,\n getGovernorParams,\n getProposal,\n getProposalState,\n proposalCount,\n propose,\n vote,\n executeProposal,\n settleProposal,\n emergencySettle,\n getExecuteCalls,\n getSettlementCalls,\n cancelProposal,\n emergencyCancel,\n getVoteWeight,\n hasVoted,\n getCapitalSnapshot,\n getActiveProposal,\n parseDuration,\n PROPOSAL_STATES,\n PROPOSAL_STATE,\n VOTE_TYPE,\n} from \"../lib/governor.js\";\nimport type { BatchCall } from \"../lib/governor.js\";\nimport { formatDurationShort as formatDuration, formatShares, formatUSDC, parseBigIntArg } from \"../lib/format.js\";\nimport { simulateBatchCalls, printSimulationResult, sendSimulationAlert } from \"../lib/simulate.js\";\nimport type { RiskContext } from \"../lib/simulate.js\";\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\nfunction formatTimestamp(ts: bigint): string {\n if (ts === 0n) return \"—\";\n return new Date(Number(ts) * 1000).toLocaleString();\n}\n\nfunction parseCallsFile(path: string): BatchCall[] {\n const raw = readFileSync(path, \"utf-8\");\n const parsed = JSON.parse(raw) as { target: string; data: string; value: string }[];\n return parsed.map((c) => ({\n target: c.target as Address,\n data: c.data as Hex,\n value: BigInt(c.value || \"0\"),\n }));\n}\n\nexport function registerProposalCommands(program: Command): void {\n const proposal = program.command(\"proposal\").description(\"Governance proposals — create, vote, execute, settle\");\n\n // ── proposal create ──\n\n proposal\n .command(\"create\")\n .description(\"Submit a strategy proposal\")\n .requiredOption(\"--vault <address>\", \"Vault address the proposal targets\")\n .requiredOption(\"--name <name>\", \"Strategy name\")\n .requiredOption(\"--description <text>\", \"Strategy rationale and risk summary\")\n .requiredOption(\"--performance-fee <bps>\", \"Agent fee in bps (e.g. 1500 = 15%)\")\n .requiredOption(\"--duration <duration>\", \"Strategy duration (e.g. 7d, 24h, 3600)\")\n .requiredOption(\"--execute-calls <path>\", \"Path to JSON file with execute Call[] array\")\n .requiredOption(\"--settle-calls <path>\", \"Path to JSON file with settlement Call[] array\")\n .option(\"--strategy <address>\", \"Live-NAV strategy clone address (default: none — queue-only)\")\n .option(\"--metadata-uri <uri>\", \"Override — skip metadata pinning and use this URI directly\")\n .option(\"--simulate\", \"Simulate calls via Tenderly before submitting\")\n .option(\"--force\", \"Submit even if simulation fails (requires --simulate)\")\n .action(async (opts) => {\n try {\n const vault = opts.vault as Address;\n if (!isAddress(vault)) {\n console.error(chalk.red(`Invalid vault address: ${opts.vault}`));\n process.exit(1);\n }\n\n const performanceFeeBps = parseBigIntArg(opts.performanceFee, \"performance-fee\");\n const strategyDuration = parseDuration(opts.duration);\n const executeCalls = parseCallsFile(opts.executeCalls);\n const settleCalls = parseCallsFile(opts.settleCalls);\n\n // Live-NAV strategy clone (optional). Zero address = queue-only. The\n // strategy-template `propose --write-calls` flow prints the clone\n // address to pass here for an external-signer submission.\n const ZERO_STRATEGY = \"0x0000000000000000000000000000000000000000\" as Address;\n let strategy: Address = ZERO_STRATEGY;\n if (opts.strategy) {\n if (!isAddress(opts.strategy)) {\n console.error(chalk.red(`Invalid strategy address: ${opts.strategy}`));\n process.exit(1);\n }\n strategy = opts.strategy as Address;\n }\n\n // Pin proposal metadata to IPFS, falling back to an inline data: URI on\n // failure. The upload endpoint is unauthenticated HTTP, so this works\n // without a signing account (proposer omitted in calldata-only mode).\n const pinProposalMetadata = async (proposer?: Address): Promise<string> => {\n const proposalMeta = {\n schema: \"sherwood/proposal/v1\",\n name: opts.name,\n description: opts.description,\n chain: getNetwork(),\n strategies: [],\n terms: {},\n links: {},\n ...(proposer ? { proposer } : {}),\n vault,\n performanceFeeBps: Number(performanceFeeBps),\n strategyDuration: Number(strategyDuration),\n createdAt: Math.floor(Date.now() / 1000),\n };\n try {\n return await uploadMetadata(proposalMeta as unknown as SyndicateMetadata);\n } catch {\n const json = JSON.stringify({ name: opts.name, description: opts.description, vault });\n return `data:application/json;base64,${Buffer.from(json).toString(\"base64\")}`;\n }\n };\n\n // --calldata-only: emit propose calldata. Pin metadata ourselves when no\n // --metadata-uri override is supplied (no signing account required).\n if (isCalldataOnly()) {\n try {\n const metadataURI = opts.metadataUri || (await pinProposalMetadata());\n emitCalldata(\n encodePropose(\n {\n vault,\n strategy,\n metadataURI,\n performanceFeeBps: Number(performanceFeeBps),\n strategyDuration,\n executeCalls,\n settlementCalls: settleCalls,\n },\n getChain().id as ChainId,\n ),\n );\n } catch (err) {\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n process.exit(1);\n }\n return;\n }\n\n // ── Pin metadata ──\n let metadataURI = opts.metadataUri || \"\";\n\n if (!metadataURI) {\n const spinner = ora({ text: W(\"Uploading metadata to IPFS...\"), color: \"green\" }).start();\n metadataURI = await pinProposalMetadata(getAccount().address);\n if (metadataURI.startsWith(\"data:\")) {\n spinner.warn(chalk.yellow(\"IPFS upload failed — using inline metadata\"));\n } else {\n spinner.succeed(G(`Metadata pinned: ${DIM(metadataURI)}`));\n }\n }\n\n // ── Summary ──\n console.log();\n console.log(LABEL(\" ◆ Proposal Summary\"));\n SEP();\n console.log(W(` Name: ${BOLD(opts.name)}`));\n console.log(W(` Vault: ${G(vault)}`));\n console.log(W(` Performance Fee: ${Number(performanceFeeBps) / 100}%`));\n console.log(W(` Duration: ${formatDuration(strategyDuration)}`));\n console.log(W(` Calls: ${executeCalls.length} execute + ${settleCalls.length} settle`));\n console.log(W(` Metadata: ${DIM(metadataURI.length > 50 ? metadataURI.slice(0, 50) + \"...\" : metadataURI)}`));\n SEP();\n\n // ── Simulate (optional) ──\n if (opts.simulate) {\n // Build risk context from the proposal parameters\n let createRiskContext: RiskContext = { vault, performanceFeeBps, strategyDuration };\n try {\n const govParams = await getGovernorParams();\n createRiskContext = { ...createRiskContext, governorParams: govParams };\n } catch { /* non-fatal — skip parameter bounds checks */ }\n\n const simSpinner = ora({ text: W(\"Simulating execute calls...\"), color: \"green\" }).start();\n const execResult = await simulateBatchCalls(vault, executeCalls, \"execute\", createRiskContext);\n simSpinner.stop();\n printSimulationResult(execResult, \"execute\");\n\n if (settleCalls.length > 0) {\n const settleSpinner = ora({ text: W(\"Simulating settlement calls...\"), color: \"green\" }).start();\n const settleResult = await simulateBatchCalls(vault, settleCalls, \"settlement\", createRiskContext);\n settleSpinner.stop();\n printSimulationResult(settleResult, \"settlement\");\n\n if (!settleResult.success && !opts.force) {\n console.error(chalk.red(\"\\n ✖ Settlement simulation failed. Use --force to submit anyway.\"));\n process.exit(1);\n }\n }\n\n if (!execResult.success && !opts.force) {\n console.error(chalk.red(\"\\n ✖ Execution simulation failed. Use --force to submit anyway.\"));\n process.exit(1);\n }\n\n // Block on critical risks\n const hasCriticalRisks = execResult.risks.some((r) => r.level === \"critical\");\n if (hasCriticalRisks && !opts.force) {\n console.error(chalk.red(\"\\n ✖ Critical risks detected. Use --force to submit anyway.\"));\n process.exit(1);\n }\n }\n\n // ── Submit ──\n // Strategy address: zero for queue-only behavior, or the `--strategy`\n // clone for live NAV. The `strategy-template propose` command resolves\n // a freshly-cloned strategy address you can pass via `--strategy`.\n const spinner = ora({ text: W(\"Submitting proposal...\"), color: \"green\" }).start();\n const result = await propose(\n vault,\n strategy,\n metadataURI,\n performanceFeeBps,\n strategyDuration,\n executeCalls,\n settleCalls,\n );\n spinner.succeed(G(\"Proposal submitted\"));\n\n console.log();\n console.log(LABEL(\" ◆ Proposal Created\"));\n SEP();\n console.log(W(` Proposal ID: ${G(`#${result.proposalId}`)}`));\n console.log(W(` Tx: ${DIM(getExplorerUrl(result.hash))}`));\n SEP();\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal list ──\n\n proposal\n .command(\"list\")\n .description(\"List proposals\")\n .option(\"--vault <address>\", \"Filter by vault\")\n .option(\"--state <filter>\", \"Filter by state: draft, pending, approved, executed, settled, all\", \"all\")\n .action(async (opts) => {\n const spinner = ora(\"Loading proposals...\").start();\n try {\n const count = await proposalCount();\n if (count === 0n) {\n spinner.stop();\n console.log(DIM(\"\\n No proposals found.\\n\"));\n return;\n }\n\n const vaultFilter = opts.vault ? (opts.vault as string).toLowerCase() : null;\n const stateFilter = opts.state.toLowerCase();\n const stateIndex = PROPOSAL_STATES.findIndex((s) => s.toLowerCase() === stateFilter);\n\n // Fetch all proposals + computed states concurrently\n const ids = Array.from({ length: Number(count) }, (_, i) => BigInt(i + 1));\n const results = await Promise.all(\n ids.map(async (id) => {\n const [p, state] = await Promise.all([getProposal(id), getProposalState(id)]);\n return { ...p, computedState: state };\n }),\n );\n\n const proposals = results.filter((p) => {\n if (vaultFilter && p.vault.toLowerCase() !== vaultFilter) return false;\n if (stateFilter !== \"all\" && stateIndex >= 0 && p.computedState !== stateIndex) return false;\n return true;\n });\n\n spinner.stop();\n\n if (proposals.length === 0) {\n console.log(DIM(\"\\n No matching proposals.\\n\"));\n return;\n }\n\n console.log();\n console.log(BOLD(`Proposals (${proposals.length})`));\n console.log(DIM(\"─\".repeat(90)));\n console.log(\n DIM(\" ID \") +\n DIM(\"Agent\".padEnd(14)) +\n DIM(\"State\".padEnd(12)) +\n DIM(\"Votes (For/Against)\".padEnd(22)) +\n DIM(\"Fee\".padEnd(8)) +\n DIM(\"Duration\".padEnd(10)) +\n DIM(\"Created\"),\n );\n console.log(DIM(\"─\".repeat(90)));\n\n for (const p of proposals) {\n const state = PROPOSAL_STATES[p.computedState] || \"Unknown\";\n const created = p.snapshotTimestamp > 0n\n ? new Date(Number(p.snapshotTimestamp) * 1000).toLocaleDateString()\n : \"—\";\n const agent = `${p.proposer.slice(0, 6)}...${p.proposer.slice(-4)}`;\n const fee = `${Number(p.performanceFeeBps) / 100}%`;\n const dur = formatDuration(p.strategyDuration);\n const votes = `${formatShares(p.votesFor)}/${formatShares(p.votesAgainst)}`;\n\n console.log(\n ` ${String(p.id).padEnd(4)}` +\n `${agent.padEnd(14)}` +\n `${state.padEnd(12)}` +\n `${votes.padEnd(22)}` +\n `${fee.padEnd(8)}` +\n `${dur.padEnd(10)}` +\n `${created}`,\n );\n }\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load proposals\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── proposal show ──\n\n proposal\n .command(\"show\")\n .description(\"Show full proposal details\")\n .argument(\"<id>\", \"Proposal ID\")\n .action(async (idStr) => {\n const spinner = ora(\"Loading proposal...\").start();\n try {\n const id = parseBigIntArg(idStr, \"proposal ID\");\n const p = await getProposal(id);\n const state = await getProposalState(id);\n const params = await getGovernorParams();\n\n spinner.stop();\n\n const stateLabel = PROPOSAL_STATES[state] || \"Unknown\";\n const totalVotes = p.votesFor + p.votesAgainst;\n const quorumNeeded = totalVotes > 0n ? `${Number(params.vetoThresholdBps) / 100}%` : \"—\";\n\n console.log();\n console.log(LABEL(` ◆ Proposal #${p.id}`));\n SEP();\n\n // Try to resolve IPFS metadata\n if (p.metadataURI && p.metadataURI.startsWith(\"ipfs://\")) {\n try {\n const meta = await fetchMetadata(p.metadataURI);\n console.log(W(` Name: ${BOLD(meta.name)}`));\n console.log(W(` Description: ${DIM(meta.description)}`));\n } catch {\n console.log(W(` Metadata: ${DIM(p.metadataURI)}`));\n }\n } else if (p.metadataURI) {\n console.log(W(` Metadata: ${DIM(p.metadataURI)}`));\n }\n\n console.log(W(` State: ${BOLD(stateLabel)}`));\n console.log(W(` Proposer: ${G(p.proposer)}`));\n console.log(W(` Vault: ${G(p.vault)}`));\n console.log(W(` Performance Fee: ${Number(p.performanceFeeBps) / 100}%`));\n console.log(W(` Duration: ${formatDuration(p.strategyDuration)}`));\n\n console.log();\n console.log(LABEL(\" Timestamps\"));\n console.log(W(` Snapshot: ${formatTimestamp(p.snapshotTimestamp)}`));\n console.log(W(` Vote End: ${formatTimestamp(p.voteEnd)}`));\n console.log(W(` Execute By: ${formatTimestamp(p.executeBy)}`));\n console.log(W(` Executed At: ${formatTimestamp(p.executedAt)}`));\n\n console.log();\n console.log(LABEL(\" Votes\"));\n console.log(W(` For: ${formatShares(p.votesFor)}`));\n console.log(W(` Against: ${formatShares(p.votesAgainst)}`));\n console.log(W(` Abstain: ${formatShares(p.votesAbstain)}`));\n console.log(W(` Veto Threshold: ${quorumNeeded}`));\n\n if (state === PROPOSAL_STATE.Executed || state === PROPOSAL_STATE.Settled) {\n try {\n const cap = await getCapitalSnapshot(id);\n console.log();\n console.log(LABEL(\" Capital\"));\n // TODO: formatUSDC hardcodes 6 decimals — should use the vault's actual asset decimals\n console.log(W(` Snapshot: ${formatUSDC(cap)}`));\n } catch { /* no snapshot */ }\n }\n\n const execCalls = await getExecuteCalls(id);\n const settlCalls = await getSettlementCalls(id);\n\n console.log();\n console.log(LABEL(` Execute Calls (${execCalls.length})`));\n for (let i = 0; i < execCalls.length; i++) {\n console.log(DIM(` [${i}] target=${execCalls[i].target}`));\n console.log(DIM(` data=${execCalls[i].data.slice(0, 20)}... value=${execCalls[i].value}`));\n }\n console.log(LABEL(` Settlement Calls (${settlCalls.length})`));\n for (let i = 0; i < settlCalls.length; i++) {\n console.log(DIM(` [${i}] target=${settlCalls[i].target}`));\n console.log(DIM(` data=${settlCalls[i].data.slice(0, 20)}... value=${settlCalls[i].value}`));\n }\n\n SEP();\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load proposal\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── proposal vote ──\n\n proposal\n .command(\"vote\")\n .description(\"Cast a vote on a pending proposal\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .requiredOption(\"--support <for|against|abstain>\", \"Vote direction: for, against, or abstain\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n const supportRaw = String(opts.support).toLowerCase();\n const support = supportRaw === \"yes\" || supportRaw === \"for\"\n ? VOTE_TYPE.For\n : supportRaw === \"no\" || supportRaw === \"against\"\n ? VOTE_TYPE.Against\n : supportRaw === \"abstain\"\n ? VOTE_TYPE.Abstain\n : null;\n if (support === null) {\n console.error(chalk.red(`Invalid support value \"${opts.support}\". Use for|against|abstain.`));\n process.exit(1);\n }\n\n if (isCalldataOnly()) {\n const voteDir = support === VOTE_TYPE.For ? \"For\" : support === VOTE_TYPE.Against ? \"Against\" : \"Abstain\";\n emitCalldata(encodeVote({ proposalId, vote: voteDir }, getChain().id as ChainId));\n return;\n }\n\n const account = getAccount();\n\n const spinner = ora(\"Loading proposal...\").start();\n const p = await getProposal(proposalId);\n const state = await getProposalState(proposalId);\n\n if (state !== PROPOSAL_STATE.Pending) {\n spinner.fail(`Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"}, not Pending`);\n process.exit(1);\n }\n\n const alreadyVoted = await hasVoted(proposalId, account.address);\n if (alreadyVoted) {\n spinner.fail(\"You have already voted on this proposal\");\n process.exit(1);\n }\n\n const weight = await getVoteWeight(proposalId, account.address);\n spinner.stop();\n\n console.log();\n console.log(LABEL(\" ◆ Cast Vote\"));\n SEP();\n console.log(W(` Proposal: #${proposalId}`));\n console.log(W(` Vault: ${G(p.vault)}`));\n console.log(W(\n ` Support: ${\n support === VOTE_TYPE.For ? G(\"FOR\")\n : support === VOTE_TYPE.Against ? chalk.red(\"AGAINST\")\n : DIM(\"ABSTAIN\")\n }`,\n ));\n console.log(W(` Weight: ${formatShares(weight)} shares`));\n SEP();\n\n const voteSpinner = ora({ text: W(\"Submitting vote...\"), color: \"green\" }).start();\n const hash = await vote(proposalId, support);\n voteSpinner.succeed(G(\"Vote cast\"));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // NOTE: `proposal bind-adapter` was removed. The strategy address is now\n // a `propose()` parameter (`strategy` field on `StrategyProposal`), set\n // immutably at propose time — no separate bind step. `strategy propose`\n // resolves the freshly-cloned strategy address and passes it through.\n\n // ── proposal execute ──\n\n proposal\n .command(\"execute\")\n .description(\"Execute an approved proposal\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .option(\"--dry-run\", \"Simulate execution without sending a transaction\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n if (isCalldataOnly()) {\n emitCalldata(encodeExecute({ proposalId }, getChain().id as ChainId));\n return;\n }\n\n const spinner = ora(\"Loading proposal...\").start();\n const state = await getProposalState(proposalId);\n\n if (state !== PROPOSAL_STATE.Approved) {\n spinner.fail(`Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"}, not Approved`);\n process.exit(1);\n }\n\n // Dry run — simulate instead of executing\n if (opts.dryRun) {\n const p = await getProposal(proposalId);\n const execCalls = await getExecuteCalls(proposalId);\n const dryRunContext: RiskContext = {\n vault: p.vault,\n performanceFeeBps: p.performanceFeeBps,\n strategyDuration: p.strategyDuration,\n };\n spinner.text = W(\"Simulating execution...\");\n const result = await simulateBatchCalls(p.vault, execCalls, \"execute\", dryRunContext);\n spinner.stop();\n printSimulationResult(result, \"execute\");\n const hasCritical = result.risks.some((r) => r.level === \"critical\");\n process.exit(result.success && !hasCritical ? 0 : 1);\n }\n\n spinner.text = W(\"Executing proposal...\");\n const hash = await executeProposal(proposalId);\n spinner.succeed(G(\"Proposal executed\"));\n\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n\n try {\n const cap = await getCapitalSnapshot(proposalId);\n // TODO: formatUSDC hardcodes 6 decimals — should use the vault's actual asset decimals\n console.log(DIM(` Capital snapshot: ${formatUSDC(cap)}`));\n } catch { /* no snapshot yet */ }\n\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal settle ──\n\n proposal\n .command(\"settle\")\n .description(\"Settle an executed proposal (auto-routes settlement path)\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .option(\"--calls <path>\", \"Path to JSON file with settle Call[] (for agent/emergency settle)\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n if (isCalldataOnly()) {\n // With --calls this is an owner-opened emergency-settle review\n // (emergencySettleWithCalls); without, the standard settle path.\n if (opts.calls) {\n const calls = parseCallsFile(opts.calls);\n emitCalldata(\n encodeEmergencySettle({ proposalId, calls }, getChain().id as ChainId),\n );\n } else {\n emitCalldata(encodeSettle({ proposalId }, getChain().id as ChainId));\n }\n return;\n }\n\n const account = getAccount();\n\n const spinner = ora(\"Loading proposal...\").start();\n const p = await getProposal(proposalId);\n const state = await getProposalState(proposalId);\n\n if (state !== PROPOSAL_STATE.Executed) {\n spinner.fail(`Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"}, not Executed`);\n process.exit(1);\n }\n\n const isProposer = account.address.toLowerCase() === p.proposer.toLowerCase();\n const now = BigInt(Math.floor(Date.now() / 1000));\n const durationElapsed = p.executedAt > 0n && now >= p.executedAt + p.strategyDuration;\n\n let hash: Hex;\n\n if (isProposer && !durationElapsed) {\n // Proposer can settle anytime\n spinner.text = W(\"Settling (proposer)...\");\n hash = await settleProposal(proposalId);\n spinner.succeed(G(\"Settled by proposer\"));\n } else if (durationElapsed && !opts.calls) {\n // Permissionless settle after duration\n spinner.text = W(\"Settling (permissionless)...\");\n hash = await settleProposal(proposalId);\n spinner.succeed(G(\"Settled (permissionless)\"));\n } else if (durationElapsed && opts.calls) {\n // Emergency settle — owner with custom calls\n spinner.text = W(\"Emergency settling...\");\n const calls = parseCallsFile(opts.calls);\n hash = await emergencySettle(proposalId, calls);\n spinner.succeed(G(\"Emergency settled\"));\n } else {\n spinner.fail(\"Cannot settle: duration not elapsed and you are not the proposer.\");\n process.exit(1);\n }\n\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal unstick ──\n // Guardian-only recovery path. Hidden from `--help` on purpose: this is a\n // last-resort command used by the syndicate-owner skill when an Executed\n // proposal's pre-committed settlement calls revert, leaving the vault\n // locked (`redemptionsLocked() == true`, `getActiveProposal(vault) != 0`).\n //\n // It calls `emergencySettle(id, [noopCall])` where `noopCall` is a\n // harmless `asset.balanceOf(vault)` view-call on the vault's underlying\n // asset. The governor's `_tryPrecommittedThenFallback` catches the\n // pre-committed revert and runs this no-op fallback, causing\n // `_finishSettlement` to mark the proposal `Settled` and clear\n // `_activeProposal[vault]`. LPs can redeem afterwards.\n //\n // Docs: skill/skills/syndicate-owner/SKILL.md § \"Recovering a stuck proposal\"\n\n proposal\n .command(\"unstick\", { hidden: true })\n .description(\n \"Guardian-only: unstick a vault whose Executed proposal cannot settle (no funds moved)\",\n )\n .requiredOption(\"--id <proposalId>\", \"Proposal ID to unstick\")\n .option(\"--yes\", \"Skip the interactive confirmation\")\n .option(\n \"--dry-run\",\n \"Check preconditions and print the fallback call without broadcasting\",\n )\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n // --calldata-only: emit the V1.5 unstick(proposalId) call. The contract\n // enforces the owner / Executed / duration-elapsed preconditions, so we\n // skip the (account-requiring) pre-flight checks below.\n if (isCalldataOnly()) {\n emitCalldata(encodeUnstick({ proposalId }, getChain().id as ChainId));\n return;\n }\n\n const account = getAccount();\n\n const spinner = ora(\"Loading proposal...\").start();\n const p = await getProposal(proposalId);\n const state = await getProposalState(proposalId);\n\n // 1. State must be Executed\n if (state !== PROPOSAL_STATE.Executed) {\n spinner.fail(\n `Proposal ${proposalId} is ${PROPOSAL_STATES[state] || \"Unknown\"} — unstick only applies to Executed proposals.`,\n );\n console.error(\n DIM(\n \"\\n Other states have their own recovery path:\\n\" +\n \" Draft/Pending/GuardianReview/Approved → sherwood proposal cancel --id <id> (proposer)\\n\" +\n \" Draft/Pending (vault owner) → sherwood proposal cancel --id <id> --emergency\\n\" +\n \" Pending (vault owner) → sherwood proposal veto --id <id>\\n\" +\n \" Expired → vault is not locked, nothing to do\\n\" +\n \" Settled → already settled\\n\" +\n \" Cancelled → governor upgrade required (issue #177)\\n\",\n ),\n );\n process.exit(1);\n }\n\n // 2. Strategy duration must have elapsed (emergencySettle requires it)\n const now = BigInt(Math.floor(Date.now() / 1000));\n const expiresAt = p.executedAt + p.strategyDuration;\n if (p.executedAt === 0n || now < expiresAt) {\n spinner.fail(\"Strategy duration has not elapsed yet.\");\n const remaining = expiresAt - now;\n console.error(\n DIM(\n `\\n Can unstick after: ${new Date(Number(expiresAt) * 1000).toLocaleString()} (in ~${formatDuration(remaining)})\\n`,\n ),\n );\n process.exit(1);\n }\n\n // 3. Vault must actually be locked by this proposal\n const vault = p.vault as Address;\n const active = await getActiveProposal(vault);\n if (active !== proposalId) {\n spinner.fail(\n `Vault ${vault} active proposal is ${active}, not ${proposalId} — nothing to unstick for this proposal.`,\n );\n process.exit(1);\n }\n\n // 4. Caller must be vault owner\n const vaultOwner = await getVaultOwner(vault);\n if (account.address.toLowerCase() !== vaultOwner.toLowerCase()) {\n spinner.fail(\"Only the vault owner can unstick a proposal.\");\n console.error(\n DIM(`\\n Vault owner: ${vaultOwner}\\n Your wallet: ${account.address}\\n`),\n );\n process.exit(1);\n }\n\n // 5. Craft the no-op fallback call: asset.balanceOf(vault)\n // Cannot revert, costs ~2.5k gas, satisfies fallbackCalls.length > 0\n // requirement in _tryPrecommittedThenFallback.\n const asset = await getAssetAddress();\n const noopCalldata = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [vault],\n });\n const fallbackCalls: BatchCall[] = [\n { target: asset, data: noopCalldata, value: 0n },\n ];\n\n spinner.stop();\n\n // Print plan\n console.log();\n console.log(BOLD(\"Unstick plan\"));\n SEP();\n console.log(` Proposal: ${proposalId}`);\n console.log(` Vault: ${vault}`);\n console.log(` Asset: ${asset}`);\n console.log(` State: ${PROPOSAL_STATES[state]} (duration elapsed)`);\n console.log(` Caller: ${account.address} (vault owner ✓)`);\n console.log();\n console.log(LABEL(\" Fallback call (no-op, cannot revert):\"));\n console.log(DIM(` target: ${asset}`));\n console.log(DIM(` data: ${noopCalldata} // balanceOf(${vault})`));\n console.log(DIM(\" value: 0\"));\n console.log();\n console.log(\n DIM(\n \" This calls emergencySettle(id, [noop]). The governor catches any revert\\n\" +\n \" from the pre-committed settlement calls and runs the no-op instead. No\\n\" +\n \" funds move. The proposal transitions to Settled and the vault unlocks.\\n\" +\n \" LPs can then redeem via `sherwood vault redeem`.\",\n ),\n );\n console.log();\n\n if (opts.dryRun) {\n console.log(G(\" (dry-run) Preconditions OK — not broadcasting.\\n\"));\n return;\n }\n\n if (!opts.yes) {\n process.stdout.write(chalk.yellow(\" Proceed? [y/N] \"));\n const answer = await new Promise<string>((resolve) => {\n process.stdin.resume();\n process.stdin.setEncoding(\"utf-8\");\n process.stdin.once(\"data\", (d) => resolve(String(d).trim().toLowerCase()));\n });\n process.stdin.pause();\n if (answer !== \"y\" && answer !== \"yes\") {\n console.log(DIM(\" Cancelled.\\n\"));\n return;\n }\n }\n\n const send = ora(\"Broadcasting emergencySettle...\").start();\n const hash = await emergencySettle(proposalId, fallbackCalls);\n send.succeed(G(\"Vault unstuck — proposal Settled\"));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n\n // Verify unlock\n const stillActive = await getActiveProposal(vault);\n if (stillActive === 0n) {\n console.log(G(\" redemptionsLocked cleared ✓\"));\n } else {\n console.log(\n chalk.yellow(\n ` ⚠ getActiveProposal(vault) still returns ${stillActive} — check manually.`,\n ),\n );\n }\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal cancel ──\n\n proposal\n .command(\"cancel\")\n .description(\"Cancel a proposal (proposer or vault owner)\")\n .requiredOption(\"--id <proposalId>\", \"Proposal ID\")\n .option(\"--emergency\", \"Emergency cancel (vault owner only, any non-settled state)\")\n .action(async (opts) => {\n try {\n const proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n\n if (isCalldataOnly()) {\n emitCalldata(encodeCancel({ proposalId }, getChain().id as ChainId));\n return;\n }\n\n const spinner = ora(\"Loading proposal...\").start();\n const state = await getProposalState(proposalId);\n\n if (state === PROPOSAL_STATE.Settled || state === PROPOSAL_STATE.Cancelled) {\n spinner.fail(`Proposal is already ${PROPOSAL_STATES[state]}`);\n process.exit(1);\n }\n\n // Allowlists mirror SyndicateGovernor.cancelProposal (proposer path,\n // Draft / Pending / GuardianReview / Approved) and emergencyCancel\n // (vault-owner path, Draft / Pending only). Earlier versions of this\n // CLI rejected proposer-side cancels from GuardianReview / Approved\n // with the misleading hint \"use --emergency for non-pending/approved\"\n // — but emergencyCancel reverts on those states. Keep these in sync\n // with the contract; treating the on-chain revert as the only gate\n // gives a worse error than this pre-check does.\n const PROPOSER_CANCELLABLE: ReadonlySet<number> = new Set([\n PROPOSAL_STATE.Draft,\n PROPOSAL_STATE.Pending,\n PROPOSAL_STATE.GuardianReview,\n PROPOSAL_STATE.Approved,\n ]);\n const OWNER_EMERGENCY_CANCELLABLE: ReadonlySet<number> = new Set([\n PROPOSAL_STATE.Draft,\n PROPOSAL_STATE.Pending,\n ]);\n\n let hash: Hex;\n\n if (opts.emergency) {\n if (!OWNER_EMERGENCY_CANCELLABLE.has(state)) {\n spinner.fail(\n `Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"} — emergencyCancel only works in Draft or Pending. ` +\n `For GuardianReview / Approved, the proposer can run: sherwood proposal cancel --id ${proposalId}`,\n );\n process.exit(1);\n }\n spinner.text = W(\"Emergency cancelling...\");\n hash = await emergencyCancel(proposalId);\n spinner.succeed(G(\"Emergency cancelled\"));\n } else {\n if (!PROPOSER_CANCELLABLE.has(state)) {\n spinner.fail(\n `Proposal is ${PROPOSAL_STATES[state] || \"Unknown\"} — not cancellable in this state. ` +\n `cancelProposal accepts Draft / Pending / GuardianReview / Approved (proposer only).`,\n );\n process.exit(1);\n }\n spinner.text = W(\"Cancelling proposal...\");\n hash = await cancelProposal(proposalId);\n spinner.succeed(G(\"Proposal cancelled\"));\n }\n\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n console.log();\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${formatContractError(err)}`));\n process.exit(1);\n }\n });\n\n // ── proposal simulate ──\n\n proposal\n .command(\"simulate\")\n .description(\"Simulate proposal calls via Tenderly (or eth_call fallback)\")\n .option(\"--id <proposalId>\", \"Proposal ID to simulate\")\n .option(\"--vault <address>\", \"Vault address (required with --execute-calls)\")\n .option(\"--execute-calls <path>\", \"Path to JSON execute calls file\")\n .option(\"--settle-calls <path>\", \"Path to JSON settlement calls file\")\n .option(\"--notify <subdomain>\", \"Send results to syndicate XMTP chat\")\n .action(async (opts) => {\n try {\n let vault: Address;\n let executeCalls: BatchCall[];\n let settlementCalls: BatchCall[] = [];\n let riskContext: RiskContext = {};\n let proposalId: bigint | undefined;\n\n if (opts.id) {\n // By proposal ID — fetch calls and build full risk context\n proposalId = parseBigIntArg(opts.id, \"proposal ID\");\n const spinner = ora(\"Loading proposal...\").start();\n\n const p = await getProposal(proposalId);\n vault = p.vault;\n executeCalls = await getExecuteCalls(proposalId);\n settlementCalls = await getSettlementCalls(proposalId);\n\n riskContext = {\n vault,\n performanceFeeBps: p.performanceFeeBps,\n strategyDuration: p.strategyDuration,\n };\n\n try {\n const govParams = await getGovernorParams();\n riskContext.governorParams = govParams;\n } catch { /* non-fatal */ }\n\n spinner.stop();\n console.log(DIM(`\\n Simulating proposal #${proposalId} on vault ${vault.slice(0, 10)}...`));\n } else if (opts.executeCalls) {\n // By call files — minimal risk context (no proposal params)\n if (!opts.vault || !isAddress(opts.vault)) {\n console.error(chalk.red(\"\\n ✖ --vault is required when using --execute-calls\"));\n process.exit(1);\n }\n vault = opts.vault as Address;\n executeCalls = parseCallsFile(opts.executeCalls);\n if (opts.settleCalls) {\n settlementCalls = parseCallsFile(opts.settleCalls);\n }\n riskContext = { vault };\n } else {\n console.error(chalk.red(\"\\n ✖ Provide --id <proposalId> or --execute-calls <path>\"));\n process.exit(1);\n }\n\n // Simulate execute calls\n const spinner = ora({ text: W(\"Simulating execute calls...\"), color: \"green\" }).start();\n const execResult = await simulateBatchCalls(vault, executeCalls, \"execute\", riskContext);\n spinner.stop();\n printSimulationResult(execResult, \"execute\");\n\n // Simulate settlement calls if present\n let settleResult;\n if (settlementCalls.length > 0) {\n const settleSpinner = ora({ text: W(\"Simulating settlement calls...\"), color: \"green\" }).start();\n settleResult = await simulateBatchCalls(vault, settlementCalls, \"settlement\", riskContext);\n settleSpinner.stop();\n printSimulationResult(settleResult, \"settlement\");\n }\n\n // Send XMTP notification if requested\n if (opts.notify && proposalId !== undefined) {\n const notifySpinner = ora({ text: W(\"Sending XMTP alert...\"), color: \"green\" }).start();\n await sendSimulationAlert(opts.notify, proposalId, vault, execResult, settleResult);\n notifySpinner.succeed(G(\"Risk report sent to chat\"));\n }\n\n // Exit with failure code if simulation or risks are critical\n const hasCritical = execResult.risks.some((r) => r.level === \"critical\")\n || (settleResult?.risks.some((r) => r.level === \"critical\") ?? false);\n\n if (!execResult.success || (settleResult && !settleResult.success) || hasCritical) {\n process.exit(1);\n }\n } catch (err) {\n console.error(chalk.red(`\\n ✖ ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n });\n}\n","/**\n * Shared formatting helpers for CLI output.\n */\n\n/** Compact duration: \"3d\", \"2.5h\", \"15m\", \"30s\" */\nexport function formatDurationShort(seconds: bigint): string {\n const s = Number(seconds);\n if (s >= 86400) return `${(s / 86400).toFixed(s % 86400 === 0 ? 0 : 1)}d`;\n if (s >= 3600) return `${(s / 3600).toFixed(s % 3600 === 0 ? 0 : 1)}h`;\n if (s >= 60) return `${(s / 60).toFixed(0)}m`;\n return `${s}s`;\n}\n\n/** Verbose duration: \"3 days\", \"2.5 hours\", \"15 min\", \"30s\" */\nexport function formatDurationLong(seconds: bigint): string {\n const s = Number(seconds);\n if (s >= 86400) return `${(s / 86400).toFixed(s % 86400 === 0 ? 0 : 1)} day${s >= 172800 ? \"s\" : \"\"}`;\n if (s >= 3600) return `${(s / 3600).toFixed(s % 3600 === 0 ? 0 : 1)} hour${s >= 7200 ? \"s\" : \"\"}`;\n if (s >= 60) return `${(s / 60).toFixed(0)} min`;\n return `${s}s`;\n}\n\n/** Format raw share amounts to human-readable (e.g. 124000000000 → \"124,000\") */\nexport function formatShares(raw: bigint, decimals: number = 6): string {\n const num = Number(raw) / 10 ** decimals;\n return num.toLocaleString(\"en-US\", { minimumFractionDigits: 0, maximumFractionDigits: 2 });\n}\n\n/** Format USDC amount (6 decimals) to human-readable (e.g. 50000000000 → \"$50,000.00\") */\nexport function formatUSDC(raw: bigint): string {\n const num = Number(raw) / 1e6;\n return `$${num.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;\n}\n\n/** Validate string as BigInt, throw user-friendly error */\nexport function parseBigIntArg(value: string, name: string): bigint {\n if (!/^-?\\d+$/.test(value)) {\n throw new Error(`Invalid ${name}: \"${value}\" is not a valid integer`);\n }\n return BigInt(value);\n}\n","/**\n * Proposal simulation — Tenderly API client, eth_call fallback,\n * calldata decoder, and CLI output formatter.\n *\n * The Tenderly integration is proxied through the Sherwood app API\n * (/api/simulate) so credentials stay server-side.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { decodeFunctionData, encodeFunctionData } from \"viem\";\nimport chalk from \"chalk\";\nimport { getPublicClient } from \"./client.js\";\nimport { getChain } from \"./network.js\";\nimport { getGovernorAddress } from \"./governor.js\";\nimport { SYNDICATE_VAULT_ABI, ERC20_ABI, SWAP_ROUTER_ABI } from \"./abis.js\";\nimport { TOKENS, MOONWELL, UNISWAP, SHERWOOD, AERODROME, VENICE, STRATEGY_TEMPLATES } from \"./addresses.js\";\nimport type { BatchCall } from \"./batch.js\";\n\n// ── Risk analyzer — canonical home is ./risk.ts ──────────\n// Re-exported from here so downstream files that imported these\n// from ./simulate.js keep working without changes.\nimport {\n analyzeRisk,\n truncAddr,\n type RiskContext,\n type RiskFlag,\n type RiskLevel,\n type KnownAddresses,\n} from \"./risk.js\";\n\nexport {\n analyzeRisk,\n verdictOf,\n buildLabelMapFromKnown,\n truncAddr,\n decodeCallArgs,\n type BatchCall,\n type RiskFlag,\n type RiskLevel,\n type RiskContext,\n type KnownAddresses,\n type Verdict,\n} from \"./risk.js\";\n\n// ── Styling (matches proposal.ts conventions) ────────────\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\n// ── Types ────────────────────────────────────────────────\n\nexport interface SimulationCallResult {\n index: number;\n target: Address;\n decodedFunction: string | null;\n selector: Hex;\n success: boolean;\n gasUsed: number;\n}\n\nexport interface SimulationResult {\n success: boolean;\n totalGasUsed: number;\n callResults: SimulationCallResult[];\n warnings: string[];\n risks: RiskFlag[];\n source: \"api\" | \"eth_call\";\n errorMessage?: string;\n}\n\n// ── Moonwell cToken ABI fragment (not in main abis.ts) ───\n\nconst MOONWELL_CTOKEN_ABI = [\n {\n name: \"mint\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"mintAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"redeem\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"redeemTokens\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"redeemUnderlying\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"redeemAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"borrow\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"borrowAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n {\n name: \"repayBorrow\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"repayAmount\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Moonwell Comptroller ABI fragment ────────────────────\n\nconst MOONWELL_COMPTROLLER_ABI = [\n {\n name: \"enterMarkets\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"mTokens\", type: \"address[]\" }],\n outputs: [{ name: \"\", type: \"uint256[]\" }],\n },\n {\n name: \"exitMarket\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"mToken\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Uniswap SwapRouter exactInputSingle ABI fragment ─────\n\nconst SWAP_ROUTER_SINGLE_ABI = [\n {\n name: \"exactInputSingle\",\n type: \"function\",\n stateMutability: \"nonpayable\",\n inputs: [\n {\n name: \"params\",\n type: \"tuple\",\n components: [\n { name: \"tokenIn\", type: \"address\" },\n { name: \"tokenOut\", type: \"address\" },\n { name: \"fee\", type: \"uint24\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"amountOutMinimum\", type: \"uint256\" },\n { name: \"sqrtPriceLimitX96\", type: \"uint160\" },\n ],\n },\n ],\n outputs: [{ name: \"amountOut\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Address label registry ───────────────────────────────\n\nfunction buildLabelMap(): Map<string, string> {\n const map = new Map<string, string>();\n const add = (addr: Address, label: string) => {\n if (addr !== \"0x0000000000000000000000000000000000000000\") {\n map.set(addr.toLowerCase(), label);\n }\n };\n\n try {\n const tokens = TOKENS();\n add(tokens.USDC, \"USDC\");\n add(tokens.WETH, \"WETH\");\n add(tokens.cbETH, \"cbETH\");\n add(tokens.wstETH, \"wstETH\");\n add(tokens.cbBTC, \"cbBTC\");\n add(tokens.DAI, \"DAI\");\n add(tokens.AERO, \"AERO\");\n\n const mw = MOONWELL();\n add(mw.COMPTROLLER, \"Moonwell Comptroller\");\n add(mw.mUSDC, \"mUSDC\");\n add(mw.mWETH, \"mWETH\");\n add(mw.mCbETH, \"mCbETH\");\n add(mw.mWstETH, \"mWstETH\");\n add(mw.mCbBTC, \"mCbBTC\");\n add(mw.mDAI, \"mDAI\");\n add(mw.mAERO, \"mAERO\");\n\n const uni = UNISWAP();\n add(uni.SWAP_ROUTER, \"SwapRouter\");\n add(uni.QUOTER_V2, \"QuoterV2\");\n\n const sw = SHERWOOD();\n add(sw.FACTORY, \"SyndicateFactory\");\n add(sw.GOVERNOR, \"SyndicateGovernor\");\n\n const aero = AERODROME();\n add(aero.ROUTER, \"Aerodrome Router\");\n add(aero.FACTORY, \"Aerodrome Factory\");\n\n const venice = VENICE();\n add(venice.VVV, \"VVV\");\n add(venice.STAKING, \"sVVV Staking\");\n add(venice.DIEM, \"DIEM\");\n\n const strats = STRATEGY_TEMPLATES();\n add(strats.MOONWELL_SUPPLY, \"MoonwellSupplyStrategy\");\n add(strats.AERODROME_LP, \"AerodromeLPStrategy\");\n add(strats.VENICE_INFERENCE, \"VeniceInferenceStrategy\");\n add(strats.WSTETH_MOONWELL, \"WstETHMoonwellStrategy\");\n } catch {\n // Network not set yet — return partial map\n }\n\n return map;\n}\n\n/** Known token decimals for human-readable formatting */\nfunction buildDecimalsMap(): Map<string, { decimals: number; symbol: string }> {\n const map = new Map<string, { decimals: number; symbol: string }>();\n try {\n const tokens = TOKENS();\n map.set(tokens.USDC.toLowerCase(), { decimals: 6, symbol: \"USDC\" });\n map.set(tokens.WETH.toLowerCase(), { decimals: 18, symbol: \"WETH\" });\n map.set(tokens.cbETH.toLowerCase(), { decimals: 18, symbol: \"cbETH\" });\n map.set(tokens.wstETH.toLowerCase(), { decimals: 18, symbol: \"wstETH\" });\n map.set(tokens.cbBTC.toLowerCase(), { decimals: 8, symbol: \"cbBTC\" });\n map.set(tokens.DAI.toLowerCase(), { decimals: 18, symbol: \"DAI\" });\n map.set(tokens.AERO.toLowerCase(), { decimals: 18, symbol: \"AERO\" });\n } catch {\n // Network not set\n }\n return map;\n}\n\n/** Moonwell mToken → underlying token address mapping */\nfunction buildMTokenToUnderlying(): Map<string, string> {\n const map = new Map<string, string>();\n try {\n const mw = MOONWELL();\n const tokens = TOKENS();\n map.set(mw.mUSDC.toLowerCase(), tokens.USDC.toLowerCase());\n map.set(mw.mWETH.toLowerCase(), tokens.WETH.toLowerCase());\n map.set(mw.mCbETH.toLowerCase(), tokens.cbETH.toLowerCase());\n map.set(mw.mWstETH.toLowerCase(), tokens.wstETH.toLowerCase());\n map.set(mw.mCbBTC.toLowerCase(), tokens.cbBTC.toLowerCase());\n map.set(mw.mDAI.toLowerCase(), tokens.DAI.toLowerCase());\n map.set(mw.mAERO.toLowerCase(), tokens.AERO.toLowerCase());\n } catch {\n // Network not set\n }\n return map;\n}\n\nexport function getAddressLabel(addr: Address): string | null {\n const labels = buildLabelMap();\n return labels.get(addr.toLowerCase()) ?? null;\n}\n\n// ── Human-readable formatting helpers ────────────────────\n\nfunction labeledAddr(addr: string): string {\n const label = buildLabelMap().get(addr.toLowerCase());\n const short = truncAddr(addr);\n return label ? `${short} (${label})` : short;\n}\n\nfunction formatTokenAmount(amount: bigint, target: string): string {\n const decimalsMap = buildDecimalsMap();\n\n // Direct match: target is a token\n const tokenInfo = decimalsMap.get(target.toLowerCase());\n if (tokenInfo) {\n return formatWithDecimals(amount, tokenInfo.decimals, tokenInfo.symbol);\n }\n\n // mToken: use underlying token's decimals\n const mTokenMap = buildMTokenToUnderlying();\n const underlying = mTokenMap.get(target.toLowerCase());\n if (underlying) {\n const underlyingInfo = decimalsMap.get(underlying);\n if (underlyingInfo) {\n return formatWithDecimals(amount, underlyingInfo.decimals, underlyingInfo.symbol);\n }\n }\n\n // Unknown — return raw\n return amount.toString();\n}\n\nfunction formatWithDecimals(amount: bigint, decimals: number, symbol: string): string {\n const num = Number(amount) / 10 ** decimals;\n const formatted = num.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: decimals <= 8 ? 2 : 4,\n });\n return `${formatted} ${symbol}`;\n}\n\n// ── Calldata decoder ─────────────────────────────────────\n\n/**\n * Decode calldata into a human-readable function call string.\n * Returns null for unknown selectors.\n */\nexport function decodeCallData(target: Address, data: Hex): string | null {\n if (data.length < 10) return null;\n\n const labels = buildLabelMap();\n const targetLower = target.toLowerCase();\n\n // Build a list of (abi, contextLabel) pairs to try, ordered by target match\n type AbiEntry = { abi: readonly unknown[]; context: string };\n const candidates: AbiEntry[] = [];\n\n // Moonwell mTokens\n const mw = safeCall(() => MOONWELL());\n if (mw) {\n const isMToken = [mw.mUSDC, mw.mWETH, mw.mCbETH, mw.mWstETH, mw.mCbBTC, mw.mDAI, mw.mAERO]\n .some((a) => a.toLowerCase() === targetLower);\n if (isMToken) {\n candidates.push({ abi: MOONWELL_CTOKEN_ABI, context: labels.get(targetLower) || \"mToken\" });\n }\n\n if (mw.COMPTROLLER.toLowerCase() === targetLower) {\n candidates.push({ abi: MOONWELL_COMPTROLLER_ABI, context: \"Comptroller\" });\n }\n }\n\n // Uniswap SwapRouter\n const uni = safeCall(() => UNISWAP());\n if (uni && uni.SWAP_ROUTER.toLowerCase() === targetLower) {\n candidates.push({ abi: SWAP_ROUTER_ABI, context: \"SwapRouter\" });\n candidates.push({ abi: SWAP_ROUTER_SINGLE_ABI, context: \"SwapRouter\" });\n }\n\n // ERC20 as generic fallback (always try last)\n candidates.push({ abi: ERC20_ABI, context: labels.get(targetLower) || \"ERC20\" });\n\n for (const { abi, context } of candidates) {\n try {\n const decoded = decodeFunctionData({\n abi: abi as readonly unknown[],\n data,\n });\n\n const args = formatArgs(decoded.args as readonly unknown[], decoded.functionName, target);\n return `${decoded.functionName}(${args})`;\n } catch {\n continue;\n }\n }\n\n return null;\n}\n\nfunction formatArgs(args: readonly unknown[], functionName: string, target: Address): string {\n if (!args || args.length === 0) return \"\";\n\n const parts: string[] = [];\n\n for (const arg of args) {\n if (typeof arg === \"bigint\") {\n parts.push(formatTokenAmount(arg, target));\n } else if (typeof arg === \"string\" && arg.startsWith(\"0x\") && arg.length === 42) {\n parts.push(labeledAddr(arg));\n } else if (typeof arg === \"object\" && arg !== null && !Array.isArray(arg)) {\n // Struct (e.g. exactInput params)\n const entries = Object.entries(arg as Record<string, unknown>);\n const structParts: string[] = [];\n for (const [key, val] of entries) {\n if (typeof val === \"bigint\") {\n structParts.push(`${key}: ${formatTokenAmount(val, target)}`);\n } else if (typeof val === \"string\" && val.startsWith(\"0x\") && val.length === 42) {\n structParts.push(`${key}: ${labeledAddr(val)}`);\n } else if (typeof val === \"string\" && val.startsWith(\"0x\") && key === \"path\") {\n structParts.push(`path: ${decodeUniswapPath(val)}`);\n } else {\n structParts.push(`${key}: ${String(val)}`);\n }\n }\n parts.push(`{${structParts.join(\", \")}}`);\n } else if (Array.isArray(arg)) {\n const arrParts = (arg as unknown[]).map((item) => {\n if (typeof item === \"string\" && item.startsWith(\"0x\") && item.length === 42) {\n return labeledAddr(item);\n }\n return String(item);\n });\n parts.push(`[${arrParts.join(\", \")}]`);\n } else {\n parts.push(String(arg));\n }\n }\n\n return parts.join(\", \");\n}\n\n/** Decode a Uniswap V3 packed path (address + fee + address + ...) */\nfunction decodeUniswapPath(pathHex: string): string {\n const labels = buildLabelMap();\n const path = pathHex.startsWith(\"0x\") ? pathHex.slice(2) : pathHex;\n const tokens: string[] = [];\n\n // Path format: 20 bytes address, 3 bytes fee, 20 bytes address, ...\n let offset = 0;\n while (offset + 40 <= path.length) {\n const addr = `0x${path.slice(offset, offset + 40)}`;\n const label = labels.get(addr.toLowerCase());\n tokens.push(label || truncAddr(addr));\n offset += 40;\n if (offset + 6 <= path.length) {\n offset += 6; // skip 3-byte fee\n } else {\n break;\n }\n }\n\n return tokens.join(\" → \");\n}\n\nfunction safeCall<T>(fn: () => T): T | null {\n try {\n return fn();\n } catch {\n return null;\n }\n}\n\n// ── API simulation ───────────────────────────────────────\n\nconst API_URLS: Record<string, string> = {\n \"base\": \"https://app.sherwood.sh\",\n \"base-sepolia\": \"https://testnet.app.sherwood.sh\",\n};\n\nfunction getApiBaseUrl(): string {\n // Allow override for local development\n if (process.env.SHERWOOD_API_URL) return process.env.SHERWOOD_API_URL;\n\n const chain = getChain();\n return API_URLS[chain.testnet ? \"base-sepolia\" : \"base\"] || API_URLS[\"base\"];\n}\n\nasync function simulateViaApi(\n vault: Address,\n calls: BatchCall[],\n): Promise<SimulationResult> {\n const baseUrl = getApiBaseUrl();\n const chainId = getChain().id;\n\n const response = await fetch(`${baseUrl}/api/simulate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n vault,\n chainId,\n calls: calls.map((c) => ({\n target: c.target,\n data: c.data,\n value: c.value.toString(),\n })),\n }),\n });\n\n if (!response.ok) {\n const body = await response.json().catch(() => ({ error: \"Unknown error\" })) as { error?: string; details?: string };\n throw new Error(body.error || `Simulation API returned ${response.status}`);\n }\n\n const result = await response.json() as {\n success: boolean;\n totalGasUsed: number;\n errorMessage: string | null;\n calls: Array<{\n index: number;\n target: string;\n success: boolean;\n gasUsed: number;\n returnData: string;\n }>;\n };\n\n const callResults: SimulationCallResult[] = result.calls.map((c, i) => ({\n index: c.index,\n target: (calls[i]?.target || c.target) as Address,\n decodedFunction: calls[i] ? decodeCallData(calls[i].target, calls[i].data) : null,\n selector: (calls[i]?.data.slice(0, 10) || \"0x\") as Hex,\n success: c.success,\n gasUsed: c.gasUsed,\n }));\n\n // Add decoded functions for any calls the API returned that weren't in our original list\n // (shouldn't happen, but defensive)\n for (const cr of callResults) {\n if (!cr.decodedFunction) {\n const matchingCall = calls[cr.index];\n if (matchingCall) {\n cr.decodedFunction = decodeCallData(matchingCall.target, matchingCall.data);\n }\n }\n }\n\n const warnings: string[] = [];\n for (const cr of callResults) {\n if (!cr.success) {\n warnings.push(`Call #${cr.index + 1} to ${labeledAddr(cr.target)} failed`);\n }\n }\n\n return {\n success: result.success,\n totalGasUsed: result.totalGasUsed,\n callResults,\n warnings,\n risks: [],\n source: \"api\",\n errorMessage: result.errorMessage ?? undefined,\n };\n}\n\n// ── eth_call fallback ────────────────────────────────────\n\nasync function simulateViaEthCall(\n vault: Address,\n calls: BatchCall[],\n): Promise<SimulationResult> {\n const governor = getGovernorAddress();\n const client = getPublicClient();\n\n const input = encodeFunctionData({\n abi: SYNDICATE_VAULT_ABI,\n functionName: \"executeGovernorBatch\",\n args: [calls.map((c) => ({ target: c.target, data: c.data, value: c.value }))],\n });\n\n // Decode calldata for display regardless of simulation result\n const callResults: SimulationCallResult[] = calls.map((c, i) => ({\n index: i,\n target: c.target,\n decodedFunction: decodeCallData(c.target, c.data),\n selector: c.data.slice(0, 10) as Hex,\n success: true, // will be set after simulation\n gasUsed: 0,\n }));\n\n try {\n await client.call({\n account: governor,\n to: vault,\n data: input,\n });\n\n return {\n success: true,\n totalGasUsed: 0,\n callResults,\n warnings: [],\n risks: [],\n source: \"eth_call\",\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n\n // Mark all calls as potentially failed (no per-call granularity)\n for (const cr of callResults) {\n cr.success = false;\n }\n\n return {\n success: false,\n totalGasUsed: 0,\n callResults,\n warnings: [`Batch reverted: ${message.slice(0, 200)}`],\n risks: [],\n source: \"eth_call\",\n errorMessage: message,\n };\n }\n}\n\n// ── Public API ───────────────────────────────────────────\n\nexport async function simulateBatchCalls(\n vault: Address,\n calls: BatchCall[],\n callType: \"execute\" | \"settlement\",\n riskContext?: RiskContext,\n): Promise<SimulationResult> {\n let result: SimulationResult;\n\n try {\n result = await simulateViaApi(vault, calls);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.log(DIM(` Simulation API unavailable (${message}), falling back to eth_call...`));\n\n result = await simulateViaEthCall(vault, calls);\n }\n\n // Run risk analysis on the results\n // Build a KnownAddresses dict from the CLI's chain-aware label map so\n // risk.ts stays decoupled from ./addresses.ts.\n const inlineLabels = buildLabelMap();\n const knownAddresses: KnownAddresses = {};\n for (const [addr, label] of inlineLabels) {\n knownAddresses[label] = addr as `0x${string}`;\n }\n const ctx: RiskContext = { vault, ...riskContext, knownAddresses };\n result.risks = analyzeRisk(calls, result.callResults, ctx);\n\n return result;\n}\n\n// ── Output formatter ─────────────────────────────────────\n\nexport function printSimulationResult(result: SimulationResult, callType: string): void {\n console.log();\n console.log(LABEL(` ◆ Simulation — ${callType} calls`));\n SEP();\n\n const sourceLabel = result.source === \"api\"\n ? \"Tenderly (via API)\"\n : `eth_call ${DIM(\"(configure Tenderly for detailed results)\")}`;\n console.log(W(` Source: ${sourceLabel}`));\n\n const statusIcon = result.success ? G(\"✓ PASS\") : chalk.red(\"✖ FAIL\");\n console.log(W(` Status: ${statusIcon}`));\n\n if (result.totalGasUsed > 0) {\n console.log(W(` Total Gas: ${result.totalGasUsed.toLocaleString()}`));\n }\n\n if (result.errorMessage && !result.success) {\n console.log(chalk.red(` Error: ${result.errorMessage.slice(0, 120)}`));\n }\n\n console.log();\n\n for (const cr of result.callResults) {\n const icon = cr.success ? G(\"✓\") : chalk.red(\"✖\");\n const funcName = cr.decodedFunction || `${cr.selector}... ${DIM(\"(unknown)\")}`;\n console.log(W(` [${cr.index + 1}] ${icon} ${funcName}`));\n\n const label = getAddressLabel(cr.target);\n const targetDisplay = label ? `${cr.target} (${label})` : cr.target;\n console.log(DIM(` Target: ${targetDisplay}`));\n\n if (cr.gasUsed > 0) {\n console.log(DIM(` Gas: ${cr.gasUsed.toLocaleString()}`));\n }\n\n console.log();\n }\n\n // ── Risk assessment ──\n if (result.risks.length > 0) {\n const criticals = result.risks.filter((r) => r.level === \"critical\");\n const warnings = result.risks.filter((r) => r.level === \"warning\");\n const infos = result.risks.filter((r) => r.level === \"info\");\n\n if (criticals.length > 0) {\n console.log(chalk.red.bold(` ✖ CRITICAL RISKS (${criticals.length})`));\n for (const r of criticals) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n console.log(chalk.red(` ✖${ref} ${r.code} — ${r.message}`));\n }\n console.log();\n }\n\n if (warnings.length > 0) {\n console.log(chalk.yellow.bold(` ⚠ WARNINGS (${warnings.length})`));\n for (const r of warnings) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n console.log(chalk.yellow(` ⚠${ref} ${r.code} — ${r.message}`));\n }\n console.log();\n }\n\n if (criticals.length === 0 && warnings.length === 0 && infos.length > 0) {\n console.log(G.bold(` ✓ RISK ASSESSMENT: CLEAN`));\n for (const r of infos) {\n console.log(G(` ✓ ${r.message}`));\n }\n console.log();\n }\n }\n\n if (result.warnings.length > 0) {\n console.log(chalk.yellow(` ⚠ Simulation Warnings`));\n for (const w of result.warnings) {\n console.log(chalk.yellow(` - ${w}`));\n }\n console.log();\n }\n\n SEP();\n}\n\n// ── XMTP escalation ─────────────────────────────────────\n\n/**\n * Send a simulation risk report to the syndicate's XMTP chat.\n * Uses RISK_ALERT message type for critical findings, POSITION_UPDATE otherwise.\n * Fails silently if XMTP is not configured.\n */\nexport async function sendSimulationAlert(\n subdomain: string,\n proposalId: bigint,\n vault: Address,\n execResult: SimulationResult,\n settleResult?: SimulationResult,\n): Promise<void> {\n try {\n const xmtp = await import(\"./xmtp.js\");\n const { getAccount } = await import(\"./client.js\");\n\n const group = await xmtp.getGroup(\"\", subdomain);\n\n // Collect all risks across both results\n const allRisks = [...execResult.risks, ...(settleResult?.risks ?? [])];\n const criticals = allRisks.filter((r) => r.level === \"critical\");\n const warnings = allRisks.filter((r) => r.level === \"warning\");\n\n const highestLevel: RiskLevel = criticals.length > 0 ? \"critical\" : warnings.length > 0 ? \"warning\" : \"info\";\n\n // Build markdown report\n const lines: string[] = [];\n const statusEmoji = highestLevel === \"critical\" ? \"🚨\" : highestLevel === \"warning\" ? \"⚠️\" : \"✅\";\n const statusText = highestLevel === \"critical\" ? \"RISKS DETECTED\" : highestLevel === \"warning\" ? \"WARNINGS\" : \"CLEAN\";\n\n lines.push(`## ${statusEmoji} Proposal #${proposalId} — Simulation Report`);\n lines.push(`**Vault**: \\`${truncAddr(vault)}\\``);\n lines.push(`**Status**: ${statusText}`);\n lines.push(`**Source**: ${execResult.source === \"api\" ? \"Tenderly\" : \"eth_call\"}`);\n lines.push(\"\");\n\n // Execute calls summary\n lines.push(`### Execute Calls ${execResult.success ? \"✓\" : \"✖\"}`);\n for (const cr of execResult.callResults) {\n const icon = cr.success ? \"✓\" : \"✖\";\n const fn = cr.decodedFunction || `${cr.selector}...`;\n const flag = allRisks.find((r) => r.callIndex === cr.index);\n const suffix = flag && flag.level === \"critical\" ? \" ← **\" + flag.code + \"**\" : \"\";\n lines.push(`${cr.index + 1}. ${icon} \\`${fn}\\`${suffix}`);\n }\n lines.push(\"\");\n\n // Settlement calls summary (if present)\n if (settleResult && settleResult.callResults.length > 0) {\n lines.push(`### Settlement Calls ${settleResult.success ? \"✓\" : \"✖\"}`);\n for (const cr of settleResult.callResults) {\n const icon = cr.success ? \"✓\" : \"✖\";\n const fn = cr.decodedFunction || `${cr.selector}...`;\n lines.push(`${cr.index + 1}. ${icon} \\`${fn}\\``);\n }\n lines.push(\"\");\n }\n\n // Risk flags\n if (criticals.length > 0) {\n lines.push(`### 🚨 Critical Risks`);\n for (const r of criticals) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n lines.push(`- **${r.code}**${ref}: ${r.message}`);\n }\n lines.push(\"\");\n }\n\n if (warnings.length > 0) {\n lines.push(`### ⚠️ Warnings`);\n for (const r of warnings) {\n const ref = r.callIndex !== undefined ? ` [call #${r.callIndex + 1}]` : \"\";\n lines.push(`- **${r.code}**${ref}: ${r.message}`);\n }\n lines.push(\"\");\n }\n\n // Action recommendation\n if (highestLevel === \"critical\") {\n lines.push(`### Action Required`);\n lines.push(`Recommend **VETO** — critical risks detected.`);\n } else if (highestLevel === \"warning\") {\n lines.push(`### Review Required`);\n lines.push(`Warnings detected — manual review recommended before execution.`);\n } else {\n lines.push(`### ✅ No Risks Detected`);\n lines.push(`All call targets verified. All calldata decoded. Safe to proceed.`);\n }\n\n const markdown = lines.join(\"\\n\");\n const messageType = highestLevel === \"critical\" ? \"RISK_ALERT\" as const : \"POSITION_UPDATE\" as const;\n\n await xmtp.sendEnvelope(group, {\n type: messageType,\n from: getAccount().address,\n text: markdown,\n data: {\n format: \"markdown\",\n proposalId: Number(proposalId),\n vault,\n riskLevel: highestLevel,\n riskCodes: allRisks.filter((r) => r.level !== \"info\").map((r) => r.code),\n simulationSuccess: execResult.success && (settleResult?.success ?? true),\n },\n timestamp: Math.floor(Date.now() / 1000),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.log(chalk.yellow(` ⚠ Failed to send XMTP alert: ${message.slice(0, 100)}`));\n }\n}\n","// cli/src/lib/risk.ts\n// SPDX-License-Identifier: MIT\n//\n// Pure risk-code analyzer for proposal batch calls. Self-contained: also owns\n// the calldata decoder and its inline ABI fragments (ERC-20, Moonwell cToken /\n// comptroller, Uniswap SwapRouter single- and multi-hop) plus the verdict\n// helper. No coupling to ./addresses.ts — callers inject KnownAddresses, so the\n// module can be MIT-vendored as-is.\n// Extracted from simulate.ts so it can be vendored by the public\n// sherwood-guardian repo at https://github.com/sherwoodagent/sherwood-guardian.\n\nimport { decodeFunctionData, erc20Abi, type Abi, type Address, type Hex } from \"viem\";\n\n// ── Types ────────────────────────────────────────────────\n\nexport interface BatchCall {\n target: Address;\n data: Hex;\n value: bigint;\n}\n\nexport interface SimulationCallResult {\n index: number;\n target: Address;\n decodedFunction: string | null;\n selector: Hex;\n success: boolean;\n gasUsed: number;\n}\n\nexport type RiskLevel = \"critical\" | \"warning\" | \"info\";\n\nexport interface RiskFlag {\n level: RiskLevel;\n code: string;\n message: string;\n callIndex?: number;\n}\n\nexport interface KnownAddresses {\n [label: string]: Address | undefined;\n}\n\nexport interface GovernorParamsLike {\n maxPerformanceFeeBps?: bigint;\n}\n\nexport interface RiskContext {\n vault?: Address;\n knownAddresses?: KnownAddresses;\n performanceFeeBps?: bigint;\n strategyDuration?: bigint;\n governorParams?: GovernorParamsLike;\n}\n\ninterface DecodedCall {\n functionName: string;\n args: readonly unknown[];\n}\n\n// ── ABI fragments (decoder coverage) ─────────────────────\n\nconst MOONWELL_CTOKEN_ABI = [\n { name: \"mint\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"mintAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"redeem\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"redeemTokens\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"redeemUnderlying\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"redeemAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"borrow\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"borrowAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n { name: \"repayBorrow\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"repayAmount\", type: \"uint256\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n] as const;\n\nconst MOONWELL_COMPTROLLER_ABI = [\n { name: \"enterMarkets\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"mTokens\", type: \"address[]\" }], outputs: [{ name: \"\", type: \"uint256[]\" }] },\n { name: \"exitMarket\", type: \"function\", stateMutability: \"nonpayable\", inputs: [{ name: \"mToken\", type: \"address\" }], outputs: [{ name: \"\", type: \"uint256\" }] },\n] as const;\n\nconst SWAP_ROUTER_SINGLE_ABI = [\n {\n name: \"exactInputSingle\", type: \"function\", stateMutability: \"nonpayable\",\n inputs: [{\n name: \"params\", type: \"tuple\",\n components: [\n { name: \"tokenIn\", type: \"address\" },\n { name: \"tokenOut\", type: \"address\" },\n { name: \"fee\", type: \"uint24\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"amountOutMinimum\", type: \"uint256\" },\n { name: \"sqrtPriceLimitX96\", type: \"uint160\" },\n ],\n }],\n outputs: [{ name: \"amountOut\", type: \"uint256\" }],\n },\n] as const;\n\nconst SWAP_ROUTER_MULTI_ABI = [\n {\n name: \"exactInput\", type: \"function\", stateMutability: \"nonpayable\",\n inputs: [{\n name: \"params\", type: \"tuple\",\n components: [\n { name: \"path\", type: \"bytes\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"amountOutMinimum\", type: \"uint256\" },\n ],\n }],\n outputs: [{ name: \"amountOut\", type: \"uint256\" }],\n },\n] as const;\n\n// ── Address helpers ──────────────────────────────────────\n\nexport function buildLabelMapFromKnown(known: KnownAddresses): Map<string, string> {\n const map = new Map<string, string>();\n for (const [label, addr] of Object.entries(known)) {\n if (addr && addr !== \"0x0000000000000000000000000000000000000000\") {\n map.set(addr.toLowerCase(), label);\n }\n }\n return map;\n}\n\nexport function truncAddr(addr: string): string {\n return `${addr.slice(0, 6)}…${addr.slice(-4)}`;\n}\n\nfunction labeledAddr(addr: string, labels: Map<string, string>): string {\n const label = labels.get(addr.toLowerCase());\n return label ? `${label} (${truncAddr(addr)})` : truncAddr(addr);\n}\n\n// ── Calldata decoder ─────────────────────────────────────\n\nfunction tryDecode(abi: Abi, data: Hex): DecodedCall | null {\n try {\n const decoded = decodeFunctionData({ abi, data });\n return { functionName: decoded.functionName, args: (decoded.args ?? []) as readonly unknown[] };\n } catch {\n return null;\n }\n}\n\n// Candidate ABIs are tried in order; the first selector match wins. Correctness\n// depends on the 4-byte selectors being DISJOINT across every fragment below\n// (ERC-20 transfer/transferFrom/approve, Moonwell cToken mint/redeem/borrow/...,\n// comptroller enterMarkets/exitMarket, SwapRouter exactInputSingle, exactInput).\n// They are today; adding a fragment to any pile without re-checking selector\n// disjointness could silently mis-decode a call against the wrong ABI.\nexport function decodeCallArgs(data: Hex): DecodedCall | null {\n return (\n tryDecode(erc20Abi, data) ??\n tryDecode(MOONWELL_CTOKEN_ABI, data) ??\n tryDecode(MOONWELL_COMPTROLLER_ABI, data) ??\n tryDecode(SWAP_ROUTER_SINGLE_ABI, data) ?? // exactInputSingle (single-hop)\n tryDecode(SWAP_ROUTER_MULTI_ABI, data) // exactInput (multi-hop) — restored, was dropped in extraction\n );\n}\n\n// ── Risk analyzer ────────────────────────────────────────\n\nexport function analyzeRisk(\n calls: BatchCall[],\n callResults: SimulationCallResult[],\n context?: RiskContext,\n): RiskFlag[] {\n const risks: RiskFlag[] = [];\n const labels = buildLabelMapFromKnown(context?.knownAddresses ?? {});\n const vaultLower = context?.vault?.toLowerCase();\n\n const isKnown = (addr: string): boolean => {\n const lower = addr.toLowerCase();\n return labels.has(lower) || lower === vaultLower;\n };\n\n // A 0-call proposal (e.g. a performance-fee-only check) starts both false so it\n // doesn't emit vacuously-true ALL_TARGETS_VERIFIED / ALL_CALLS_DECODED info\n // flags. (Intentional change from the in-simulate.ts version, which started true.)\n let allTargetsVerified = calls.length > 0;\n let allCallsDecoded = calls.length > 0;\n\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const result = callResults[i];\n const callNum = i + 1;\n\n if (result && !result.success) {\n risks.push({ level: \"critical\", code: \"SIMULATION_FAILED\",\n message: `Call #${callNum} to ${labeledAddr(call.target, labels)} reverted during simulation`, callIndex: i });\n }\n\n const targetKnown = isKnown(call.target);\n if (!targetKnown) {\n allTargetsVerified = false;\n risks.push({ level: \"critical\", code: \"UNKNOWN_TARGET\",\n message: `Call #${callNum} targets ${labeledAddr(call.target, labels)} which is not in the known address registry`, callIndex: i });\n }\n\n const decoded = decodeCallArgs(call.data);\n if (!decoded) {\n allCallsDecoded = false;\n if (!targetKnown) {\n risks.push({ level: \"critical\", code: \"UNDECODED_CALLDATA\",\n message: `Call #${callNum} has unrecognized calldata (selector ${call.data.slice(0, 10)}) targeting unknown contract`, callIndex: i });\n }\n continue;\n }\n\n if (decoded.functionName === \"transfer\" && decoded.args.length >= 2) {\n const to = decoded.args[0] as string;\n if (typeof to === \"string\" && to.startsWith(\"0x\") && !isKnown(to)) {\n risks.push({ level: \"critical\", code: \"TRANSFER_TO_UNKNOWN\",\n message: `Call #${callNum} transfer() sends funds to ${truncAddr(to)} which is not a known protocol`, callIndex: i });\n }\n }\n if (decoded.functionName === \"transferFrom\" && decoded.args.length >= 3) {\n const to = decoded.args[1] as string;\n if (typeof to === \"string\" && to.startsWith(\"0x\") && !isKnown(to)) {\n risks.push({ level: \"critical\", code: \"TRANSFER_FROM_TO_UNKNOWN\",\n message: `Call #${callNum} transferFrom() sends funds to ${truncAddr(to)} which is not a known protocol`, callIndex: i });\n }\n }\n if (decoded.functionName === \"approve\" && decoded.args.length >= 2) {\n const spender = decoded.args[0] as string;\n if (typeof spender === \"string\" && spender.startsWith(\"0x\") && !isKnown(spender)) {\n risks.push({ level: \"critical\", code: \"APPROVE_TO_UNKNOWN\",\n message: `Call #${callNum} approve() grants allowance to ${truncAddr(spender)} which is not a known protocol`, callIndex: i });\n }\n }\n }\n\n if (context?.performanceFeeBps !== undefined) {\n const fee = context.performanceFeeBps;\n const maxFee = context.governorParams?.maxPerformanceFeeBps;\n if (maxFee !== undefined && fee > (maxFee * 80n) / 100n) {\n risks.push({ level: \"critical\", code: \"EXCESSIVE_PERFORMANCE_FEE\",\n message: `Performance fee ${Number(fee) / 100}% is within 20% of the hard cap (${Number(maxFee) / 100}%)` });\n } else if (fee > 2000n) {\n risks.push({ level: \"warning\", code: \"HIGH_PERFORMANCE_FEE\",\n message: `Performance fee ${Number(fee) / 100}% exceeds 20% threshold` });\n }\n }\n\n if (context?.strategyDuration !== undefined) {\n const dur = context.strategyDuration;\n if (dur < 3600n) {\n risks.push({ level: \"warning\", code: \"SHORT_STRATEGY_DURATION\",\n message: `Strategy duration ${Number(dur)}s is under 1 hour — flash-loan-style risk` });\n }\n if (dur > 2_592_000n) {\n risks.push({ level: \"warning\", code: \"LONG_STRATEGY_DURATION\",\n message: `Strategy duration ${Number(dur) / 86400} days exceeds 30-day threshold` });\n }\n }\n\n const hasCritical = risks.some((r) => r.level === \"critical\");\n const hasWarning = risks.some((r) => r.level === \"warning\");\n if (!hasCritical && !hasWarning) {\n if (allTargetsVerified) {\n risks.push({ level: \"info\", code: \"ALL_TARGETS_VERIFIED\", message: \"All call targets are verified protocol addresses\" });\n }\n if (allCallsDecoded) {\n risks.push({ level: \"info\", code: \"ALL_CALLS_DECODED\", message: \"All calldata successfully decoded\" });\n }\n }\n\n return risks;\n}\n\n// ── Verdict helper ───────────────────────────────────────\n\nexport type Verdict = \"CLEAN\" | \"WARNING\" | \"CRITICAL\";\n\nexport function verdictOf(risks: RiskFlag[]): Verdict {\n if (risks.some((r) => r.level === \"critical\")) return \"CRITICAL\";\n if (risks.some((r) => r.level === \"warning\")) return \"WARNING\";\n return \"CLEAN\";\n}\n","/**\n * Governor commands — sherwood governor <subcommand>\n *\n * View and manage SyndicateGovernor parameters (owner-only setters).\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getExplorerUrl, getChain } from \"../lib/network.js\";\nimport { formatContractError } from \"../lib/errors.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport { encodeGovernorParam, type ChainId, type GovernorParam } from \"@sherwoodagent/sdk\";\nimport {\n getGovernorAddress,\n getGovernorParams,\n getRegisteredVaults,\n setVotingPeriod,\n setExecutionWindow,\n setVetoThresholdBps,\n setProtocolFeeBps,\n setMaxPerformanceFeeBps,\n setMaxStrategyDuration,\n setCooldownPeriod,\n} from \"../lib/governor.js\";\nimport { formatDurationLong as formatDuration, parseBigIntArg } from \"../lib/format.js\";\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\n/**\n * Register one owner-only parameter setter. V1.5 setters are owner-instant\n * (no on-chain timelock — the owner multisig enforces its own delay), so the\n * success copy says \"updated\", not \"queued\". With `--calldata-only` it prints\n * the unsigned `setX(value)` calldata via the shared SDK encoder instead.\n */\nfunction registerParamSetter(\n governor: Command,\n spec: {\n command: string;\n description: string;\n flag: string;\n flagDescription: string;\n valueLabel: string;\n param: GovernorParam;\n setter: (value: bigint) => Promise<`0x${string}`>;\n spinnerText: string;\n succeed: (rawValue: string) => string;\n failText: string;\n },\n): void {\n governor\n .command(spec.command)\n .description(spec.description)\n .requiredOption(spec.flag, spec.flagDescription)\n .action(async (opts) => {\n // `valueLabel` (\"seconds\" | \"bps\") matches the camelCased option key.\n const rawValue = String(opts[spec.valueLabel]);\n\n if (isCalldataOnly()) {\n try {\n const value = parseBigIntArg(rawValue, spec.valueLabel);\n emitCalldata(\n encodeGovernorParam({ param: spec.param, value }, getChain().id as ChainId),\n );\n } catch (err) {\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n return;\n }\n\n const spinner = ora(spec.spinnerText).start();\n try {\n const hash = await spec.setter(parseBigIntArg(rawValue, spec.valueLabel));\n spinner.succeed(G(spec.succeed(rawValue)));\n console.log(DIM(` ${getExplorerUrl(hash)}`));\n } catch (err) {\n spinner.fail(spec.failText);\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n}\n\nexport function registerGovernorCommands(program: Command): void {\n const governor = program.command(\"governor\").description(\"Governor parameters and vault management\");\n\n // ── governor info ──\n\n governor\n .command(\"info\")\n .description(\"Display current governor parameters and registered vaults\")\n .action(async () => {\n const spinner = ora(\"Loading governor info...\").start();\n try {\n const [params, vaults] = await Promise.all([\n getGovernorParams(),\n getRegisteredVaults(),\n ]);\n\n spinner.stop();\n\n console.log();\n console.log(LABEL(\" ◆ Governor Parameters\"));\n SEP();\n console.log(W(` Address: ${G(getGovernorAddress())}`));\n console.log(W(` Voting Period: ${BOLD(formatDuration(params.votingPeriod))}`));\n console.log(W(` Execution Window: ${BOLD(formatDuration(params.executionWindow))}`));\n console.log(W(` Veto Threshold: ${BOLD(`${Number(params.vetoThresholdBps) / 100}%`)}`));\n console.log(W(` Max Performance Fee: ${BOLD(`${Number(params.maxPerformanceFeeBps) / 100}%`)}`));\n console.log(W(` Max Strategy Duration:${BOLD(` ${formatDuration(params.maxStrategyDuration)}`)}`));\n console.log(W(` Cooldown Period: ${BOLD(formatDuration(params.cooldownPeriod))}`));\n\n console.log();\n console.log(LABEL(` Registered Vaults (${vaults.length})`));\n if (vaults.length === 0) {\n console.log(DIM(\" (none)\"));\n } else {\n for (const v of vaults) {\n console.log(W(` ${G(v)}`));\n }\n }\n\n SEP();\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load governor info\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── governor parameter setters (owner-only, owner-instant in V1.5) ──\n\n registerParamSetter(governor, {\n command: \"set-voting-period\",\n description: \"Set the voting period (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New voting period in seconds\",\n valueLabel: \"seconds\",\n param: \"votingPeriod\",\n setter: setVotingPeriod,\n spinnerText: \"Setting voting period...\",\n succeed: (v) => `Voting period updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set voting period\",\n });\n\n registerParamSetter(governor, {\n command: \"set-execution-window\",\n description: \"Set the execution window (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New execution window in seconds\",\n valueLabel: \"seconds\",\n param: \"executionWindow\",\n setter: setExecutionWindow,\n spinnerText: \"Setting execution window...\",\n succeed: (v) => `Execution window updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set execution window\",\n });\n\n registerParamSetter(governor, {\n command: \"set-veto-threshold\",\n description: \"Set the veto threshold in bps (owner only)\",\n flag: \"--bps <n>\",\n flagDescription: \"New veto threshold in bps (e.g. 4000 = 40%)\",\n valueLabel: \"bps\",\n param: \"vetoThresholdBps\",\n setter: setVetoThresholdBps,\n spinnerText: \"Setting veto threshold...\",\n succeed: (v) => `Veto threshold updated to ${Number(v) / 100}% (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set veto threshold\",\n });\n\n registerParamSetter(governor, {\n command: \"set-max-fee\",\n description: \"Set the max performance fee in bps (owner only)\",\n flag: \"--bps <n>\",\n flagDescription: \"New max fee in bps (e.g. 3000 = 30%)\",\n valueLabel: \"bps\",\n param: \"maxPerformanceFeeBps\",\n setter: setMaxPerformanceFeeBps,\n spinnerText: \"Setting max fee...\",\n succeed: (v) => `Max performance fee updated to ${Number(v) / 100}% (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set max fee\",\n });\n\n registerParamSetter(governor, {\n command: \"set-max-duration\",\n description: \"Set the max strategy duration in seconds (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New max duration in seconds\",\n valueLabel: \"seconds\",\n param: \"maxStrategyDuration\",\n setter: setMaxStrategyDuration,\n spinnerText: \"Setting max duration...\",\n succeed: (v) => `Max strategy duration updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set max duration\",\n });\n\n registerParamSetter(governor, {\n command: \"set-cooldown\",\n description: \"Set the cooldown period in seconds (owner only)\",\n flag: \"--seconds <n>\",\n flagDescription: \"New cooldown in seconds\",\n valueLabel: \"seconds\",\n param: \"cooldownPeriod\",\n setter: setCooldownPeriod,\n spinnerText: \"Setting cooldown...\",\n succeed: (v) => `Cooldown period updated to ${v}s (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set cooldown\",\n });\n\n registerParamSetter(governor, {\n command: \"set-protocol-fee\",\n description: \"Set the protocol fee in bps (owner only)\",\n flag: \"--bps <n>\",\n flagDescription: \"New protocol fee in bps (e.g. 500 = 5%, max 1000 = 10%)\",\n valueLabel: \"bps\",\n param: \"protocolFeeBps\",\n setter: setProtocolFeeBps,\n spinnerText: \"Setting protocol fee...\",\n succeed: (v) => `Protocol fee updated to ${Number(v) / 100}% (owner-instant — the owner multisig enforces its own delay).`,\n failText: \"Failed to set protocol fee\",\n });\n}\n","/**\n * Guardian delegation commands — sherwood guardian <subcommand>\n *\n * V1.5: stake-pool delegation into GuardianRegistry, DPoS commission\n * configuration, and Merkl reward-claim navigation. Rewards claim itself\n * happens on merkl.xyz; this CLI prints a deep link + pending-reward\n * summary when the API key is configured.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport type { Address } from \"viem\";\nimport { formatUnits, isAddress, parseUnits } from \"viem\";\nimport { getPublicClient, getWalletClient } from \"../lib/client.js\";\nimport { getNetwork, getChain } from \"../lib/network.js\";\nimport { SHERWOOD } from \"../lib/addresses.js\";\nimport { formatContractError } from \"../lib/errors.js\";\nimport { isCalldataOnly, emitCalldata } from \"../lib/calldata.js\";\nimport {\n encodeGuardianStake,\n encodeGuardianUnstake,\n encodeGuardianDelegate,\n encodeDelegationUnstake,\n encodeSetCommission,\n encodeClaimProposalReward,\n encodeClaimDelegatorProposalReward,\n type ChainId,\n} from \"@sherwoodagent/sdk\";\n\nconst G = chalk.green;\nconst W = chalk.white;\nconst DIM = chalk.gray;\nconst BOLD = chalk.white.bold;\nconst LABEL = chalk.green.bold;\nconst WARN = chalk.yellow;\nconst SEP = () => console.log(DIM(\"─\".repeat(60)));\n\n// Minimal ABI fragments — only what this command set touches.\nconst GUARDIAN_REGISTRY_ABI = [\n // Guardian stake\n { type: \"function\", name: \"stakeAsGuardian\", inputs: [{ type: \"uint256\" }, { type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"requestUnstakeGuardian\", inputs: [], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"cancelUnstakeGuardian\", inputs: [], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"claimUnstakeGuardian\", inputs: [], outputs: [], stateMutability: \"nonpayable\" },\n // Delegation\n { type: \"function\", name: \"delegateStake\", inputs: [{ type: \"address\" }, { type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"requestUnstakeDelegation\", inputs: [{ type: \"address\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"cancelUnstakeDelegation\", inputs: [{ type: \"address\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"claimUnstakeDelegation\", inputs: [{ type: \"address\" }], outputs: [], stateMutability: \"nonpayable\" },\n // Commission\n { type: \"function\", name: \"setCommission\", inputs: [{ type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n // Views\n { type: \"function\", name: \"guardianStake\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"isActiveGuardian\", inputs: [{ type: \"address\" }], outputs: [{ type: \"bool\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"commissionOf\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"delegationOf\", inputs: [{ type: \"address\" }, { type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"delegatedInbound\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n // Guardian-fee claim (vault asset)\n { type: \"function\", name: \"claimProposalReward\", inputs: [{ type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"claimDelegatorProposalReward\", inputs: [{ type: \"address\" }, { type: \"uint256\" }], outputs: [], stateMutability: \"nonpayable\" },\n] as const;\n\nconst ERC20_ABI = [\n { type: \"function\", name: \"approve\", inputs: [{ type: \"address\" }, { type: \"uint256\" }], outputs: [{ type: \"bool\" }], stateMutability: \"nonpayable\" },\n { type: \"function\", name: \"balanceOf\", inputs: [{ type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" },\n { type: \"function\", name: \"decimals\", inputs: [], outputs: [{ type: \"uint8\" }], stateMutability: \"view\" },\n] as const;\n\nfunction requireAddress(name: string, addr: Address): Address {\n if (addr === \"0x0000000000000000000000000000000000000000\") {\n console.error(chalk.red(`${name} is not deployed on ${getNetwork()}. Update cli/src/lib/addresses.ts after deploy.`));\n process.exit(1);\n }\n return addr;\n}\n\nfunction registry(): Address {\n return requireAddress(\"GUARDIAN_REGISTRY\", SHERWOOD().GUARDIAN_REGISTRY);\n}\n\nfunction wood(): Address {\n return requireAddress(\"WOOD_TOKEN\", SHERWOOD().WOOD_TOKEN);\n}\n\nasync function ensureWoodAllowance(amount: bigint): Promise<void> {\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const addr = wallet.account!.address;\n const current = (await pc.readContract({\n address: wood(),\n abi: [{ type: \"function\", name: \"allowance\", inputs: [{ type: \"address\" }, { type: \"address\" }], outputs: [{ type: \"uint256\" }], stateMutability: \"view\" }] as const,\n functionName: \"allowance\",\n args: [addr, registry()],\n })) as bigint;\n if (current >= amount) return;\n const spinner = ora(\"Approving WOOD...\").start();\n try {\n const hash = await wallet.writeContract({\n address: wood(), abi: ERC20_ABI, functionName: \"approve\", args: [registry(), 2n ** 256n - 1n], chain: null, account: wallet.account!,\n });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(\"WOOD approval granted\");\n } catch (err) {\n spinner.fail(\"WOOD approval failed\");\n throw err;\n }\n}\n\nexport function registerGuardianCommands(program: Command): void {\n const guardian = program.command(\"guardian\").description(\"Guardian staking, delegation, and rewards (V1.5)\");\n\n // ── status ──\n\n guardian\n .command(\"status [address]\")\n .description(\"Show guardian stake + commission + active status for an address (default: caller)\")\n .action(async (addressArg?: string) => {\n const pc = getPublicClient();\n let target: Address;\n if (addressArg) {\n if (!isAddress(addressArg)) {\n console.error(chalk.red(\"Invalid address\"));\n process.exit(1);\n }\n target = addressArg;\n } else {\n const wallet = getWalletClient();\n target = wallet.account!.address;\n }\n\n const spinner = ora(\"Loading...\").start();\n try {\n const [stake, active, commission] = await Promise.all([\n pc.readContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"guardianStake\", args: [target] }) as Promise<bigint>,\n pc.readContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"isActiveGuardian\", args: [target] }) as Promise<boolean>,\n pc.readContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"commissionOf\", args: [target] }) as Promise<bigint>,\n ]);\n const delegatedIn = (await pc.readContract({\n address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"delegatedInbound\", args: [target],\n })) as bigint;\n spinner.stop();\n\n console.log();\n console.log(LABEL(\" ◆ Guardian Status\"));\n SEP();\n console.log(W(` Address: ${G(target)}`));\n console.log(W(` Active guardian: ${active ? G(\"yes\") : DIM(\"no\")}`));\n console.log(W(` Own stake: ${BOLD(formatUnits(stake, 18))} WOOD`));\n console.log(W(` Delegated inbound: ${BOLD(formatUnits(delegatedIn, 18))} WOOD`));\n console.log(W(` Commission: ${BOLD(`${Number(commission) / 100}%`)}`));\n SEP();\n console.log();\n } catch (err) {\n spinner.fail(\"Failed to load\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── stake ──\n\n guardian\n .command(\"stake <amount>\")\n .description(\"Stake as a guardian. Amount in WOOD (min = registry.minGuardianStake).\")\n .option(\"--agent-id <id>\", \"ERC-8004 agent ID to associate (first-stake only)\", \"0\")\n .action(async (amountStr: string, opts: { agentId: string }) => {\n const amount = parseUnits(amountStr, 18);\n const agentId = BigInt(opts.agentId);\n if (isCalldataOnly()) {\n emitCalldata(encodeGuardianStake({ amount, agentId: opts.agentId }, getChain().id as ChainId));\n return;\n }\n await ensureWoodAllowance(amount);\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`Staking ${amountStr} WOOD...`).start();\n try {\n const hash = await wallet.writeContract({\n address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"stakeAsGuardian\", args: [amount, agentId], chain: null, account: wallet.account!,\n });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Staked. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Stake failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── unstake (request / cancel / claim) ──\n\n guardian\n .command(\"unstake <action>\")\n .description(\"Unstake flow: 'request' | 'cancel' | 'claim' (7d cooldown)\")\n .action(async (action: string) => {\n const fn = { request: \"requestUnstakeGuardian\", cancel: \"cancelUnstakeGuardian\", claim: \"claimUnstakeGuardian\" }[action];\n if (!fn) {\n console.error(chalk.red(`Unknown action '${action}'. Use request | cancel | claim.`));\n process.exit(1);\n }\n if (isCalldataOnly()) {\n emitCalldata(encodeGuardianUnstake({ action: action as \"request\" | \"cancel\" | \"claim\" }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`${action}...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: fn as any, args: [], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`${action} confirmed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(`${action} failed`);\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── delegate ──\n\n guardian\n .command(\"delegate <delegate> <amount>\")\n .description(\"Delegate WOOD stake to a guardian. Amount in WOOD.\")\n .action(async (delegate: string, amountStr: string) => {\n if (!isAddress(delegate)) {\n console.error(chalk.red(\"Invalid delegate address\"));\n process.exit(1);\n }\n const amount = parseUnits(amountStr, 18);\n if (isCalldataOnly()) {\n emitCalldata(encodeGuardianDelegate({ delegate, amount }, getChain().id as ChainId));\n return;\n }\n await ensureWoodAllowance(amount);\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`Delegating ${amountStr} WOOD to ${delegate}...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"delegateStake\", args: [delegate, amount], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Delegated. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Delegation failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n guardian\n .command(\"undelegate <delegate> <action>\")\n .description(\"Unstake-delegation flow: 'request' | 'cancel' | 'claim'\")\n .action(async (delegate: string, action: string) => {\n if (!isAddress(delegate)) {\n console.error(chalk.red(\"Invalid delegate address\"));\n process.exit(1);\n }\n const fn = { request: \"requestUnstakeDelegation\", cancel: \"cancelUnstakeDelegation\", claim: \"claimUnstakeDelegation\" }[action];\n if (!fn) {\n console.error(chalk.red(`Unknown action '${action}'. Use request | cancel | claim.`));\n process.exit(1);\n }\n if (isCalldataOnly()) {\n emitCalldata(encodeDelegationUnstake({ action: action as \"request\" | \"cancel\" | \"claim\", delegate }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`${action}...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: fn as any, args: [delegate], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`${action} confirmed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(`${action} failed`);\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── commission ──\n\n guardian\n .command(\"set-commission <bps>\")\n .description(\"Set your commission rate in bps (0-5000 = 0-50%). Raises capped cumulatively at 500 bps/epoch.\")\n .action(async (bpsStr: string) => {\n const bps = BigInt(bpsStr);\n if (bps > 5000n) {\n console.error(chalk.red(\"Commission cannot exceed 5000 bps (50%)\"));\n process.exit(1);\n }\n if (isCalldataOnly()) {\n emitCalldata(encodeSetCommission({ bps: Number(bps) }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(`Setting commission to ${Number(bps) / 100}%...`).start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"setCommission\", args: [bps], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Commission set. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"setCommission failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── reward claims ──\n\n guardian\n .command(\"claim-proposal <proposalId>\")\n .description(\"Claim guardian-fee commission for a settled proposal you voted Approve on (vault asset).\")\n .action(async (pidStr: string) => {\n const pid = BigInt(pidStr);\n if (isCalldataOnly()) {\n emitCalldata(encodeClaimProposalReward({ proposalId: pid }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(\"Claiming...\").start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"claimProposalReward\", args: [pid], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Claimed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Claim failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n guardian\n .command(\"claim-delegator <delegate> <proposalId>\")\n .description(\"Claim your delegator share of a delegate's guardian-fee pool for a specific proposal.\")\n .action(async (delegate: string, pidStr: string) => {\n if (!isAddress(delegate)) {\n console.error(chalk.red(\"Invalid delegate address\"));\n process.exit(1);\n }\n const pid = BigInt(pidStr);\n if (isCalldataOnly()) {\n emitCalldata(encodeClaimDelegatorProposalReward({ delegate, proposalId: pid }, getChain().id as ChainId));\n return;\n }\n const wallet = getWalletClient();\n const pc = getPublicClient();\n const spinner = ora(\"Claiming delegator share...\").start();\n try {\n const hash = await wallet.writeContract({ address: registry(), abi: GUARDIAN_REGISTRY_ABI, functionName: \"claimDelegatorProposalReward\", args: [delegate, pid], chain: null, account: wallet.account! });\n await pc.waitForTransactionReceipt({ hash });\n spinner.succeed(`Claimed. Tx: ${hash}`);\n } catch (err) {\n spinner.fail(\"Claim failed\");\n console.error(chalk.red(formatContractError(err)));\n process.exit(1);\n }\n });\n\n // ── WOOD epoch rewards — Merkl ──\n\n guardian\n .command(\"claim-wood\")\n .description(\"Open merkl.xyz to claim WOOD epoch block-rewards (off-chain distribution).\")\n .action(async () => {\n const wallet = getWalletClient();\n const addr = wallet.account!.address;\n const url = `https://merkl.angle.money/user/${addr}`;\n console.log();\n console.log(LABEL(\" ◆ Merkl Reward Claim\"));\n SEP();\n console.log(W(\" WOOD epoch block-rewards are distributed off-chain via Merkl.\"));\n console.log(W(\" Open this URL in your browser to view + claim pending rewards:\"));\n console.log();\n console.log(G(` ${url}`));\n console.log();\n console.log(WARN(\" Note: guardian-fee rewards (vault assets) are claimed on-chain\"));\n console.log(WARN(\" via `sherwood guardian claim-proposal <pid>`.\"));\n SEP();\n console.log();\n });\n}\n","/**\n * Grid commands — sherwood grid start|status\n *\n * Runs the ATR-based grid trading strategy as a standalone loop,\n * parallel to the directional agent. Isolated capital and portfolio.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createInterface } from 'node:readline/promises';\nimport { GridLoop } from '../grid/loop.js';\nimport { GridPortfolio } from '../grid/portfolio.js';\nimport { GridHedgeManager } from '../grid/hedge.js';\nimport { OnchainGridExecutor } from '../grid/onchain-executor.js';\nimport { HyperliquidProvider } from '../providers/data/hyperliquid.js';\nimport { DEFAULT_GRID_CONFIG } from '../grid/config.js';\nimport { runBacktest } from '../grid/backtest.js';\nimport type { BacktestResult } from '../grid/backtest.js';\nimport type { GridConfig } from '../grid/config.js';\nimport { runSweep, type SweepResult, type SweepableField } from '../grid/sweep.js';\n\n/**\n * Default reason strings recorded on `state.pauseReason` when an operator\n * halts a grid. Stable strings so log-grep / dashboard filters can match\n * operator-initiated halts deterministically.\n */\nconst DEFAULT_PAUSE_REASON = 'Manually paused by operator';\nconst DEFAULT_FLATTEN_REASON = 'Manually flattened by operator';\n\n/** Seconds to wait at the y/N confirmation prompt before aborting. */\nconst CONFIRM_TIMEOUT_SECONDS = 60;\n\nconst DIM = chalk.gray;\nconst G = chalk.green;\nconst BOLD = chalk.white.bold;\nconst W = chalk.white;\nconst SEP = () => console.log(DIM('─'.repeat(60)));\n\nfunction printSummary(r: BacktestResult): void {\n const dd = r.drawdown;\n const days = r.window.days;\n const rtPerDay = (r.totals.roundTrips / Math.max(days, 1)).toFixed(1);\n const fillPerDay = (r.totals.fills / Math.max(days, 1)).toFixed(1);\n const pnlSign = r.capital.pnlUsd >= 0 ? '+' : '-';\n const pnlAbs = Math.abs(r.capital.pnlUsd).toFixed(2);\n const pnlPctStr = (r.capital.pnlPct * 100).toFixed(2);\n\n console.log();\n console.log(G.bold(` Grid Backtest — ${r.runId}`));\n console.log(DIM('─'.repeat(64)));\n console.log(W(` Window: ${r.window.fromIso.slice(0, 10)} → ${r.window.toIso.slice(0, 10)} (${days.toFixed(0)} days)`));\n console.log(W(` Capital: $${r.capital.initialUsd.toLocaleString()} → $${r.capital.finalUsd.toFixed(2)} (${pnlSign}$${pnlAbs}, ${pnlSign}${pnlPctStr}%)`));\n console.log(W(` Gross PnL: $${r.capital.grossPnlUsd.toFixed(2)} (before fees)`));\n console.log(W(` Fees (${r.fees.bps}bps): -$${r.fees.totalUsd.toFixed(2)} ($${r.fees.perFill.toFixed(4)}/fill)`));\n if (r.hedge.enabled) {\n const hedgeNet = r.hedge.realizedPnlUsd + r.hedge.unrealizedPnlUsd;\n const hedgeSign = hedgeNet >= 0 ? '+' : '-';\n const hedgeAbs = Math.abs(hedgeNet).toFixed(2);\n console.log(W(` Hedge: ${hedgeSign}$${hedgeAbs} (realized $${r.hedge.realizedPnlUsd.toFixed(2)} + unrealized $${r.hedge.unrealizedPnlUsd.toFixed(2)}, ${r.hedge.adjustments} adj)`));\n } else {\n console.log(W(` Hedge: disabled`));\n }\n console.log(W(` Round trips: ${r.totals.roundTrips} (${rtPerDay}/day)`));\n console.log(W(` Fills: ${r.totals.fills} (${fillPerDay}/day)`));\n console.log(W(` Rebuilds: ${r.totals.rebuilds}`));\n console.log(W(` Max drawdown: -$${dd.maxUsd.toFixed(2)} (-${(dd.maxPct * 100).toFixed(2)}%)`));\n console.log(W(` Paused: ${r.totals.pausedSteps} steps (${((r.totals.pausedSteps / Math.max(r.totals.totalSteps, 1)) * 100).toFixed(1)}%)`));\n console.log(W(` Skipped: ${r.totals.skippedSteps} steps`));\n console.log();\n console.log(BOLD(' Per token:'));\n for (const t of r.perToken) {\n const tokPnl = t.pnlUsd >= 0 ? G(`+$${t.pnlUsd.toFixed(2)}`) : chalk.red(`-$${Math.abs(t.pnlUsd).toFixed(2)}`);\n console.log(W(` ${t.token.padEnd(10)} $${t.allocation.initial.toFixed(0).padStart(6)} → $${t.allocation.final.toFixed(0).padStart(6)} ${tokPnl} RTs=${t.roundTrips} fills=${t.fills}`));\n }\n if (r.liquidations.events.length > 0) {\n console.log();\n console.log(BOLD(' Liquidations:'));\n for (const ev of r.liquidations.events) {\n const date = new Date(ev.timestamp).toISOString().slice(0, 10);\n console.log(W(` ${ev.token.padEnd(10)} ${date} unrealized=$${ev.unrealizedPnlAtLiquidation.toFixed(0)} threshold=$${ev.thresholdUsd.toFixed(0)}`));\n }\n if (r.liquidations.haltedAt !== null) {\n const haltDate = new Date(r.liquidations.haltedAt).toISOString().slice(0, 10);\n console.log(chalk.red.bold(` RUN HALTED on ${haltDate} — all tokens liquidated.`));\n }\n }\n console.log();\n console.log(W(` Wall time: ${(r.durationMs / 1000).toFixed(1)}s`));\n console.log(DIM('─'.repeat(64)));\n}\n\nfunction printSweepSummary(s: SweepResult): void {\n const days = s.window.days;\n console.log();\n console.log(G.bold(` Grid Sweep — ${s.sweepId}`));\n console.log(DIM('─'.repeat(96)));\n console.log(W(` Window: ${new Date(s.window.fromMs).toISOString().slice(0, 10)} → ${new Date(s.window.toMs).toISOString().slice(0, 10)} (${days.toFixed(0)} days)`));\n console.log(W(` Tokens: ${s.tokens.join(', ')}`));\n console.log(W(` Capital: $${s.capital.toLocaleString()}`));\n console.log(W(` Fees: ${s.feeBps} bps/fill`));\n console.log(W(` Runs: ${s.runs.length}`));\n console.log(W(` Wall: ${(s.durationMs / 1000).toFixed(1)}s`));\n console.log(DIM('─'.repeat(96)));\n console.log();\n console.log(BOLD(' Rank Surv Lev Levels ATR× Drift RTs NetPnL$ NetPnL% DD% Risk-Adj'));\n console.log(DIM(' ' + '─'.repeat(102)));\n for (let i = 0; i < s.runs.length; i++) {\n const r = s.runs[i]!;\n const rank = String(i + 1).padStart(4);\n const surv = r.survived ? G(' ✓ ') : chalk.red(' ✗ ');\n const lev = String(r.config.leverage ?? '').padStart(3);\n const lvls = String(r.config.levelsPerSide ?? '').padStart(6);\n const atr = String(r.config.atrMultiplier ?? '').padStart(4);\n const drift = String(r.config.rebalanceDriftPct ?? '').padStart(5);\n const rts = String(r.totals.roundTrips).padStart(5);\n const netPnl = `$${r.capital.pnlUsd.toFixed(0)}`.padStart(11);\n const netPct = `${(r.capital.pnlPct * 100).toFixed(1)}%`.padStart(8);\n const ddPct = `${(r.drawdown.maxPct * 100).toFixed(1)}%`.padStart(8);\n const ra = r.riskAdjusted.toFixed(2).padStart(8);\n const pnlColor = r.capital.pnlUsd >= 0 ? G : chalk.red;\n console.log(` ${rank} ${surv} ${lev} ${lvls} ${atr} ${drift} ${rts} ${pnlColor(netPnl)} ${pnlColor(netPct)} ${ddPct} ${ra}`);\n }\n console.log(DIM(' ' + '─'.repeat(102)));\n console.log();\n console.log(W(` Saved: ${s.sweepId}/sweep.json + per-run JSONs in ~/.sherwood/grid/sweeps/`));\n console.log();\n}\n\n/**\n * Parse `--asset-indices` flag value (e.g. `bitcoin=0,ethereum=1,solana=5`)\n * into `{ bitcoin: 0, ethereum: 1, solana: 5 }`. Validates that each value\n * is a non-negative integer so a typo doesn't quietly become `NaN` in the\n * encoded cancel/place tx.\n */\nfunction parseAssetIndices(raw: string): Record<string, number> {\n const indices: Record<string, number> = {};\n for (const pair of raw.split(',')) {\n const [tok, idx] = pair.split('=');\n if (!tok || !idx) {\n throw new Error(`Bad asset-indices pair: '${pair}' (expected token=index)`);\n }\n const n = Number(idx.trim());\n if (!Number.isInteger(n) || n < 0) {\n throw new Error(`Bad asset-indices value for '${tok}': '${idx}' (must be a non-negative integer)`);\n }\n indices[tok.trim()] = n;\n }\n return indices;\n}\n\nfunction parseTokenSplit(raw: string, tokens: string[]): Record<string, number> {\n const split: Record<string, number> = {};\n for (const pair of raw.split(',')) {\n const [tok, w] = pair.split('=');\n if (!tok || !w) throw new Error(`Bad token-split pair: '${pair}' (expected token=weight)`);\n const weight = Number(w.trim());\n if (!Number.isFinite(weight) || weight < 0) {\n throw new Error(`Bad token-split weight for '${tok}': '${w}'`);\n }\n split[tok.trim()] = weight;\n }\n for (const t of tokens) {\n if (!(t in split)) {\n throw new Error(`--token-split missing weight for '${t}'`);\n }\n }\n const sum = Object.values(split).reduce((a, b) => a + b, 0);\n if (Math.abs(sum - 1.0) > 1e-6) {\n throw new Error(`--token-split weights must sum to 1.0, got ${sum.toFixed(6)}`);\n }\n return split;\n}\n\nexport function registerGridCommand(program: Command): void {\n const grid = program\n .command('grid')\n .description('Grid trading strategy — ATR-based grid on BTC/ETH/SOL');\n\n // ── grid start ──\n grid\n .command('start')\n .description('Start the grid trading loop')\n .option('--capital <usd>', 'Starting capital in USD', '5000')\n .option('--cycle <seconds>', 'Cycle interval in seconds', '60')\n .option('--tokens <list>', 'Comma-separated token list', 'bitcoin,ethereum,solana')\n .option('--leverage <n>', 'Leverage multiplier', String(DEFAULT_GRID_CONFIG.leverage))\n .option('--levels <n>', 'Grid levels per side', String(DEFAULT_GRID_CONFIG.levelsPerSide))\n .option('--live', 'enable live execution (places real orders on Hyperliquid)')\n .option('--asset-indices <pairs>', 'comma-separated token=index pairs (mainnet: bitcoin=0,ethereum=1,solana=5)')\n .option('--strategy <address>', 'on-chain strategy contract address (enables on-chain executor)')\n .option('--token-split <pairs>', 'Comma-separated token=weight pairs (must sum to 1.0). Default: equal-weight.')\n .option('--state-dir <path>', 'Override directory for portfolio.json / hedge.json / cycles.jsonl / onchain-state.json. Defaults to ~/.sherwood/grid. Use a separate dir to run paper and live grids in parallel.')\n .action(async (opts) => {\n const capital = parseFloat(opts.capital);\n const cycleMs = parseInt(opts.cycle, 10) * 1000;\n const tokens = opts.tokens.split(',').map((t: string) => t.trim());\n const leverage = parseFloat(opts.leverage);\n const levels = parseInt(opts.levels, 10);\n const stateDir = opts.stateDir as string | undefined;\n\n const live = !!opts.live;\n let assetIndices: Record<string, number> | undefined;\n if (live) {\n if (!opts.assetIndices) {\n throw new Error('--asset-indices required when --live (mainnet: --asset-indices bitcoin=0,ethereum=1,solana=5)');\n }\n assetIndices = parseAssetIndices(opts.assetIndices as string);\n }\n\n const strategyAddress = opts.strategy as `0x${string}` | undefined;\n if (strategyAddress && !live) {\n throw new Error('--strategy requires --live');\n }\n\n // Build token split (explicit if provided, else equal-weight)\n let tokenSplit: Record<string, number>;\n if (opts.tokenSplit) {\n tokenSplit = parseTokenSplit(opts.tokenSplit as string, tokens);\n } else {\n const weight = 1 / tokens.length;\n tokenSplit = {};\n for (const t of tokens) {\n tokenSplit[t] = weight;\n }\n }\n\n console.log();\n console.log(G.bold(' Grid Strategy'));\n SEP();\n console.log(W(` Capital: $${capital.toLocaleString()}`));\n console.log(W(` Cycle: ${opts.cycle}s`));\n console.log(W(` Tokens: ${tokens.join(', ')}`));\n console.log(W(` Leverage: ${leverage}x`));\n console.log(W(` Levels: ${levels}/side`));\n SEP();\n\n const loop = new GridLoop({\n capital,\n cycle: cycleMs,\n live,\n assetIndices,\n strategyAddress,\n stateDir,\n config: {\n ...DEFAULT_GRID_CONFIG,\n tokens,\n leverage,\n levelsPerSide: levels,\n tokenSplit,\n },\n });\n\n await loop.start();\n });\n\n // ── grid status ──\n grid\n .command('status')\n .description('Show current grid portfolio status')\n .option('--state-dir <path>', 'Read state from a custom directory (defaults to ~/.sherwood/grid)')\n .action(async (opts) => {\n const portfolio = new GridPortfolio(opts.stateDir as string | undefined);\n const state = await portfolio.load();\n\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Run `sherwood grid start` first.\\n'));\n return;\n }\n\n // Reset daily stats if needed before display\n portfolio.resetDailyStats(state);\n const agg = portfolio.aggregateStats(state);\n\n console.log();\n console.log(G.bold(' Grid Portfolio'));\n SEP();\n console.log(W(` Allocation: $${state.totalAllocation.toLocaleString()}`));\n console.log(W(` Status: ${state.paused ? chalk.red('PAUSED — ' + state.pauseReason) : G('Active')}`));\n console.log(W(` Initialized: ${new Date(state.initializedAt).toLocaleString()}`));\n SEP();\n\n // Per-token table\n console.log();\n console.log(BOLD(' Token Alloc RTs PnL Today PnL Fills'));\n console.log(DIM(' ' + '─'.repeat(72)));\n\n for (const g of state.grids) {\n const name = g.token.padEnd(13);\n const alloc = `$${g.allocation.toFixed(0)}`.padStart(8);\n const rts = String(g.stats.totalRoundTrips).padStart(6);\n const pnl = `$${g.stats.totalPnlUsd.toFixed(2)}`.padStart(10);\n const todayPnl = `$${g.stats.todayPnlUsd.toFixed(2)}`.padStart(10);\n const fills = String(g.stats.totalFills).padStart(6);\n const pnlColor = g.stats.totalPnlUsd >= 0 ? G : chalk.red;\n const todayColor = g.stats.todayPnlUsd >= 0 ? G : chalk.red;\n\n console.log(` ${W(name)} ${alloc} ${rts} ${pnlColor(pnl)} ${todayColor(todayPnl)} ${fills}`);\n }\n\n console.log(DIM(' ' + '─'.repeat(72)));\n\n // Totals\n const totalPnlColor = agg.totalPnlUsd >= 0 ? G : chalk.red;\n const todayTotalColor = agg.todayPnlUsd >= 0 ? G : chalk.red;\n console.log(` ${BOLD('TOTAL'.padEnd(13))} ${`$${state.totalAllocation.toFixed(0)}`.padStart(8)} ${String(agg.totalRoundTrips).padStart(6)} ${totalPnlColor(`$${agg.totalPnlUsd.toFixed(2)}`.padStart(10))} ${todayTotalColor(`$${agg.todayPnlUsd.toFixed(2)}`.padStart(10))} ${String(agg.todayFills).padStart(6)}`);\n console.log();\n });\n\n // ── grid backtest ──\n grid\n .command('backtest')\n .description('Replay historical Hyperliquid prices through the grid strategy')\n .option('--from <iso>', 'Window start (ISO date). Default: 30d ago.')\n .option('--to <iso>', 'Window end (ISO date). Default: now.')\n .option('--capital <usd>', 'Starting capital in USD', '5000')\n .option('--tokens <list>', 'Comma-separated token list', 'bitcoin,ethereum,solana')\n .option('--leverage <n>', 'Override leverage')\n .option('--levels <n>', 'Override levels per side')\n .option('--atr-multiplier <n>', 'Override ATR multiplier')\n .option('--rebalance-drift <n>', 'Override rebalanceDriftPct')\n .option('--snapshot-every <min>', 'Equity-curve snapshot cadence (minutes)', '60')\n .option('--verbose', 'Print manager fill logs during replay')\n .option('--no-cache', 'Skip cache; always fetch fresh data')\n .option('--out <path>', 'Override output path')\n .option('--fee-bps <n>', 'Trading fee in basis points per fill (default 5 = 0.05%)', '5')\n .option('--no-hedge', 'Disable hedge simulation (hedge is ON by default to match live grid)')\n .option('--maintenance-pct <n>', 'Per-token maintenance margin fraction (default 0.02 = 2%, typical Hyperliquid)', '0.02')\n .option('--pause-threshold <n>', 'Pool drop fraction that triggers pause (default 0.40, may be too lenient post leverage-fix)')\n .option('--unpause-recovery <n>', 'Pool drop fraction below which paused grid resumes (default 0.10)')\n .option('--token-split <pairs>', 'Comma-separated token=weight pairs (must sum to 1.0). Default: equal-weight or 0.45/0.30/0.25 for BTC/ETH/SOL.')\n .option('--stop-loss <n>', 'Per-fill stop-loss fraction (default 0.10 = 10%, 0 disables)')\n .action(async (opts) => {\n const now = Date.now();\n const toMs = opts.to ? Date.parse(opts.to) : now;\n const fromMs = opts.from ? Date.parse(opts.from) : (now - 30 * 24 * 3600_000);\n if (Number.isNaN(toMs) || Number.isNaN(fromMs)) {\n throw new Error('--from / --to must be ISO dates (e.g. 2026-04-01)');\n }\n\n const tokens = (opts.tokens as string).split(',').map(t => t.trim());\n let tokenSplit: Record<string, number>;\n if (opts.tokenSplit) {\n tokenSplit = parseTokenSplit(opts.tokenSplit as string, tokens);\n } else {\n const weight = 1 / tokens.length;\n tokenSplit = {};\n for (const t of tokens) tokenSplit[t] = weight;\n }\n\n const config: GridConfig = {\n ...DEFAULT_GRID_CONFIG,\n tokens,\n tokenSplit,\n leverage: opts.leverage ? Number(opts.leverage) : DEFAULT_GRID_CONFIG.leverage,\n levelsPerSide: opts.levels ? Number(opts.levels) : DEFAULT_GRID_CONFIG.levelsPerSide,\n atrMultiplier: opts.atrMultiplier ? Number(opts.atrMultiplier) : DEFAULT_GRID_CONFIG.atrMultiplier,\n rebalanceDriftPct: opts.rebalanceDrift ? Number(opts.rebalanceDrift) : DEFAULT_GRID_CONFIG.rebalanceDriftPct,\n maintenanceMarginPct: opts.maintenancePct ? Number(opts.maintenancePct) : DEFAULT_GRID_CONFIG.maintenanceMarginPct,\n pauseThresholdPct: opts.pauseThreshold ? Number(opts.pauseThreshold) : DEFAULT_GRID_CONFIG.pauseThresholdPct,\n unpauseRecoveryPct: opts.unpauseRecovery ? Number(opts.unpauseRecovery) : DEFAULT_GRID_CONFIG.unpauseRecoveryPct,\n stopLossPct: opts.stopLoss !== undefined ? Number(opts.stopLoss) : DEFAULT_GRID_CONFIG.stopLossPct,\n };\n\n const capital = Number(opts.capital);\n const snapshotEveryMinutes = Number(opts.snapshotEvery);\n\n console.log();\n console.log(G.bold(' Grid Backtest'));\n SEP();\n console.log(W(` Window: ${new Date(fromMs).toISOString().slice(0, 10)} → ${new Date(toMs).toISOString().slice(0, 10)}`));\n console.log(W(` Capital: $${capital.toLocaleString()}`));\n console.log(W(` Tokens: ${tokens.join(', ')}`));\n console.log(W(` Leverage: ${config.leverage}x`));\n console.log(W(` Levels: ${config.levelsPerSide}/side`));\n SEP();\n\n const result = await runBacktest({\n fromMs,\n toMs,\n capital,\n config,\n snapshotEveryMinutes,\n verbose: !!opts.verbose,\n noCache: opts.cache === false,\n outPath: opts.out,\n feeBps: Number(opts.feeBps),\n hedge: opts.hedge !== false,\n });\n\n printSummary(result);\n });\n\n // ── grid sweep ──\n grid\n .command('sweep')\n .description('Run a parameter sweep over multiple grid configurations')\n .option('--from <iso>', 'Window start (ISO date). Default: 30d ago.')\n .option('--to <iso>', 'Window end (ISO date). Default: now.')\n .option('--capital <usd>', 'Starting capital in USD', '5000')\n .option('--tokens <list>', 'Comma-separated token list', 'bitcoin,ethereum,solana')\n .option('--leverage <list>', 'Comma-separated leverage values to sweep')\n .option('--levels <list>', 'Comma-separated levels-per-side values to sweep')\n .option('--atr-multiplier <list>', 'Comma-separated ATR multiplier values to sweep')\n .option('--rebalance-drift <list>', 'Comma-separated rebalance drift values to sweep')\n .option('--fee-bps <n>', 'Trading fee in basis points per fill (default 5)', '5')\n .option('--no-cache', 'Skip cache; always fetch fresh data')\n .option('--token-split <pairs>', 'Comma-separated token=weight pairs (must sum to 1.0). Default: equal-weight or 0.45/0.30/0.25 for BTC/ETH/SOL.')\n .action(async (opts) => {\n const now = Date.now();\n const toMs = opts.to ? Date.parse(opts.to) : now;\n const fromMs = opts.from ? Date.parse(opts.from) : (now - 30 * 24 * 3600_000);\n if (Number.isNaN(toMs) || Number.isNaN(fromMs)) {\n throw new Error('--from / --to must be ISO dates (e.g. 2026-04-01)');\n }\n const tokens = (opts.tokens as string).split(',').map(t => t.trim());\n\n const parseList = (s: string | undefined): number[] | undefined => {\n if (!s) return undefined;\n return s.split(',').map(v => Number(v.trim())).filter(n => Number.isFinite(n));\n };\n\n const sweep: Partial<Record<SweepableField, number[]>> = {\n leverage: parseList(opts.leverage),\n levelsPerSide: parseList(opts.levels),\n atrMultiplier: parseList(opts.atrMultiplier),\n rebalanceDriftPct: parseList(opts.rebalanceDrift),\n };\n\n const tokenSplit = opts.tokenSplit\n ? parseTokenSplit(opts.tokenSplit as string, tokens)\n : undefined;\n\n const result = await runSweep({\n fromMs,\n toMs,\n capital: Number(opts.capital),\n tokens,\n tokenSplit,\n sweep,\n feeBps: Number(opts.feeBps),\n noCache: opts.cache === false,\n });\n\n printSweepSummary(result);\n });\n\n // ── grid pause ──\n grid\n .command('pause')\n .description('Manually pause the live grid (sets state.paused=true)')\n .option('--reason <text>', 'Reason for the pause (shown in status output)', DEFAULT_PAUSE_REASON)\n .option('--state-dir <path>', 'Read/write state from a custom directory (defaults to ~/.sherwood/grid)')\n .action(async (opts) => {\n const portfolio = new GridPortfolio(opts.stateDir as string | undefined);\n const state = await portfolio.load();\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Nothing to pause.\\n'));\n return;\n }\n if (state.paused) {\n console.log(DIM(`\\n Grid already paused: ${state.pauseReason}\\n`));\n return;\n }\n state.paused = true;\n state.pauseReason = opts.reason as string;\n await portfolio.save(state);\n console.log();\n console.log(chalk.yellow(` Grid paused. Reason: ${state.pauseReason}`));\n console.log(DIM(' Next manager.tick will be a no-op until you run `sherwood grid resume`.'));\n console.log();\n });\n\n // ── grid resume ──\n grid\n .command('resume')\n .description('Resume a paused grid (clears state.paused)')\n .option('--state-dir <path>', 'Read/write state from a custom directory (defaults to ~/.sherwood/grid)')\n .action(async (opts) => {\n const portfolio = new GridPortfolio(opts.stateDir as string | undefined);\n const state = await portfolio.load();\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Nothing to resume.\\n'));\n return;\n }\n if (!state.paused) {\n console.log(DIM('\\n Grid is not paused. Nothing to do.\\n'));\n return;\n }\n const wasReason = state.pauseReason;\n const wasCircuitBroken = state.circuitBroken === true;\n state.paused = false;\n state.pauseReason = '';\n // Clear the hard circuit breaker if it was tripped — manual `resume`\n // is the documented way to re-engage trading after the deep-drawdown\n // halt. We do NOT auto-clear elsewhere.\n state.circuitBroken = false;\n state.circuitBrokenAt = 0;\n await portfolio.save(state);\n console.log();\n if (wasCircuitBroken) {\n console.log(chalk.yellow(` Hard circuit breaker cleared.`));\n }\n console.log(G(` Grid resumed. (was paused: ${wasReason || '<unknown>'})`));\n console.log();\n });\n\n // ── grid flatten ──\n // Wind a live grid down to no-orders + zero-hedge state, then pause it so\n // the next `start` won't re-enter. Pairs with stopping the systemd unit or\n // killing the loop process — this only cleans up state and (on-chain only)\n // cancels open CLOIDs via the strategy contract.\n grid\n .command('flatten')\n .description('Cancel all open grid orders on-chain, zero the hedge ledger, and pause the grid')\n .option('--state-dir <path>', 'Read/write state from a custom directory (defaults to ~/.sherwood/grid)')\n .option('--strategy <address>', 'Strategy contract address — required to cancel on-chain CLOIDs. Omit for hedge-only flatten.')\n .option('--asset-indices <pairs>', 'comma-separated token=index pairs (required with --strategy, e.g. bitcoin=3,ethereum=4,solana=5)')\n .option('--reason <text>', 'Reason recorded on the paused grid state', DEFAULT_FLATTEN_REASON)\n .option('--dry-run', 'Print intended actions and exit without touching state or chain')\n .option('--yes', 'Skip the confirmation prompt')\n .action(async (opts) => {\n const stateDir = opts.stateDir as string | undefined;\n const portfolio = new GridPortfolio(stateDir);\n const state = await portfolio.load();\n if (!state) {\n console.log(DIM('\\n No grid portfolio found. Nothing to flatten.\\n'));\n return;\n }\n\n // Summarize what we're about to touch — by-token open-fill counts come\n // from the in-memory portfolio rather than re-reading on-chain because\n // (a) the on-chain executor's placedCloids is the local truth, (b) HL\n // order state can lag a tick. The chain call below handles the actual\n // cancel encoding regardless.\n const openFills = state.grids.flatMap(g => g.openFills.filter(f => !f.closed));\n const hedgeMgr = new GridHedgeManager(stateDir);\n const hedgeState = await hedgeMgr.load();\n const openHedges = hedgeState.positions.filter(p => p.quantity > 0);\n\n let strategyAddress: `0x${string}` | undefined;\n let assetIndices: Record<string, number> | undefined;\n if (opts.strategy) {\n strategyAddress = opts.strategy as `0x${string}`;\n if (!opts.assetIndices) {\n throw new Error('--asset-indices required with --strategy (e.g. --asset-indices bitcoin=3,ethereum=4,solana=5)');\n }\n assetIndices = parseAssetIndices(opts.assetIndices as string);\n }\n\n console.log();\n console.log(BOLD(' Flatten plan'));\n SEP();\n console.log(W(` State dir: ${stateDir ?? '~/.sherwood/grid (default)'}`));\n console.log(W(` On-chain: ${strategyAddress ? strategyAddress : DIM('(skipped — no --strategy)')}`));\n console.log(W(` Open fills: ${openFills.length} (informational — on-chain CLOIDs cancelled per-token)`));\n console.log(W(` Hedge legs: ${openHedges.length}${openHedges.length > 0 ? ' (' + openHedges.map(h => h.token).join(', ') + ')' : ''}`));\n console.log(W(` Will pause: yes — reason: \"${opts.reason}\"`));\n SEP();\n\n if (opts.dryRun) {\n console.log(chalk.yellow(' --dry-run set — no state or chain mutation.'));\n console.log();\n return;\n }\n\n if (!opts.yes) {\n // Non-interactive cron / piped invocation must pass --yes; refuse to\n // touch live state without explicit consent so a stray invocation\n // can't quietly wipe a running strategy.\n if (!process.stdin.isTTY) {\n throw new Error('Refusing to flatten without --yes in a non-interactive context. Pass --yes to confirm.');\n }\n // readline gives line-buffered semantics that work even if stdin was\n // touched earlier in the process. AbortController guards against an\n // operator walking away from the prompt — auto-abort after the\n // CONFIRM_TIMEOUT_SECONDS window rather than hanging forever.\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), CONFIRM_TIMEOUT_SECONDS * 1000);\n let answer: string;\n try {\n answer = (await rl.question(chalk.yellow(' Proceed with flatten? [y/N] '), { signal: ac.signal })).trim().toLowerCase();\n } catch (e) {\n if ((e as { name?: string }).name === 'AbortError') {\n console.log(DIM(`\\n Timed out after ${CONFIRM_TIMEOUT_SECONDS}s. Aborted.\\n`));\n return;\n }\n throw e;\n } finally {\n clearTimeout(timer);\n rl.close();\n }\n if (answer !== 'y' && answer !== 'yes') {\n console.log(DIM(' Aborted.\\n'));\n return;\n }\n }\n\n // On-chain cancel — only when a strategy address is supplied. A\n // hedge-only flatten (no --strategy) is the right path for paper grids\n // or when the wallet has been emptied and there's nothing to cancel.\n if (strategyAddress && assetIndices) {\n const executor = new OnchainGridExecutor({ strategyAddress, assetIndices, stateDir });\n await executor.load();\n const res = await executor.flattenAll();\n if (res.cancelled.length > 0) {\n console.log(G(` Cancelled CLOIDs for: ${res.cancelled.join(', ')}`));\n for (const tx of res.txs) console.log(DIM(` tx ${tx}`));\n }\n if (res.skipped.length > 0) {\n console.log(DIM(` Skipped (no tracked CLOIDs): ${res.skipped.join(', ')}`));\n }\n if (res.errors.length > 0) {\n for (const err of res.errors) console.log(chalk.red(` Cancel error: ${err}`));\n }\n }\n\n // Zero the hedge ledger using current HL mark prices. If price-fetch\n // fails for a token we leave its position untouched and surface it —\n // operator can rerun with a working RPC or manually edit hedge.json.\n if (openHedges.length > 0) {\n const hl = new HyperliquidProvider();\n const prices: Record<string, number> = {};\n for (const pos of openHedges) {\n const data = await hl.getHyperliquidData(pos.token);\n if (data?.markPrice && data.markPrice > 0) prices[pos.token] = data.markPrice;\n }\n const hres = await hedgeMgr.flatten(prices);\n if (hres.closed.length > 0) {\n for (const c of hres.closed) {\n const sign = c.realizedPnl >= 0 ? '+' : '-';\n console.log(G(` Hedge closed ${c.token}: qty ${c.quantity.toFixed(6)} → 0 (${sign}$${Math.abs(c.realizedPnl).toFixed(2)} realized)`));\n }\n }\n if (hres.skipped.length > 0) {\n console.log(chalk.yellow(` Hedge skipped (no mark price): ${hres.skipped.join(', ')}`));\n }\n console.log(W(` Total hedge realized PnL: $${hres.totalRealizedPnl.toFixed(2)}`));\n } else {\n console.log(DIM(' No active hedge legs — ledger already flat.'));\n }\n\n // Pause the grid so a future `start` won't re-enter on the same state.\n if (!state.paused) {\n state.paused = true;\n state.pauseReason = opts.reason as string;\n await portfolio.save(state);\n console.log(chalk.yellow(` Grid paused. Reason: ${state.pauseReason}`));\n } else {\n console.log(DIM(` Grid was already paused: ${state.pauseReason}`));\n }\n\n console.log();\n console.log(G(' Flatten complete. Stop the loop process / systemd unit if still running.'));\n console.log();\n });\n}\n","/**\n * Standalone grid event loop — runs the grid strategy independently\n * from the directional agent loop on 1-minute cycles.\n *\n * Usage:\n * const loop = new GridLoop({ capital: 5000, cycle: 60_000 });\n * await loop.start();\n */\n\nimport chalk from 'chalk';\nimport { appendFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { GridManager } from './manager.js';\nimport { GridPortfolio } from './portfolio.js';\nimport { DEFAULT_GRID_CONFIG } from './config.js';\nimport type { GridConfig } from './config.js';\nimport { HyperliquidProvider } from '../providers/data/hyperliquid.js';\nimport { GridHedgeManager } from './hedge.js';\nimport { GridExecutor } from './executor.js';\nimport { OnchainGridExecutor } from './onchain-executor.js';\nimport { gridStateDir, gridStatePath } from './paths.js';\nimport type { Address } from 'viem';\n\nexport interface GridLoopConfig {\n /** Starting capital in USD. */\n capital: number;\n /** Cycle interval in milliseconds. */\n cycle: number;\n /** Optional overrides for the default grid config. */\n config?: Partial<GridConfig>;\n /** Live execution mode — when true, places real orders on Hyperliquid. */\n live?: boolean;\n /** HL asset indices per token (required when live=true). */\n assetIndices?: Record<string, number>;\n /** When set, use on-chain executor (calls strategy contract). */\n strategyAddress?: Address;\n /** Override directory for persisted state. Defaults to ~/.sherwood/grid. */\n stateDir?: string;\n}\n\nexport class GridLoop {\n private cfg: GridLoopConfig;\n private gridConfig: GridConfig;\n private manager: GridManager;\n private hedge: GridHedgeManager;\n private hl: HyperliquidProvider;\n private executor: GridExecutor | OnchainGridExecutor | null = null;\n private running = false;\n private cycleCount = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n private cyclesPath: string;\n\n constructor(cfg: GridLoopConfig) {\n this.cfg = cfg;\n this.gridConfig = { ...DEFAULT_GRID_CONFIG, ...cfg.config };\n this.cyclesPath = gridStatePath('cycles.jsonl', cfg.stateDir);\n this.manager = new GridManager(\n this.gridConfig,\n undefined,\n undefined,\n undefined,\n new GridPortfolio(cfg.stateDir),\n undefined,\n cfg.stateDir,\n );\n this.hedge = new GridHedgeManager(cfg.stateDir);\n this.hl = new HyperliquidProvider();\n\n if (cfg.live) {\n if (!cfg.assetIndices) {\n throw new Error('assetIndices required when live=true');\n }\n if (cfg.strategyAddress) {\n this.executor = new OnchainGridExecutor({\n strategyAddress: cfg.strategyAddress,\n assetIndices: cfg.assetIndices,\n stateDir: cfg.stateDir,\n });\n } else {\n this.executor = new GridExecutor({ assetIndices: cfg.assetIndices });\n }\n }\n }\n\n /** Start the grid loop. Resolves when shut down via SIGINT/SIGTERM. */\n async start(): Promise<void> {\n this.running = true;\n\n // Graceful shutdown\n const shutdown = () => {\n console.error(chalk.yellow('\\n [grid-loop] Shutting down…'));\n this.running = false;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n // Initialize grid if no state exists\n await this.manager.init(this.cfg.capital);\n\n if (this.executor instanceof OnchainGridExecutor) {\n await this.executor.load();\n }\n\n // Startup banner — include resolved state-dir so operators with multiple\n // grid processes can immediately see which one owns this PID.\n console.error(chalk.cyan(\n `\\n [grid-loop] Started — capital=$${this.cfg.capital.toFixed(0)} ` +\n `cycle=${(this.cfg.cycle / 1000).toFixed(0)}s ` +\n `tokens=[${this.gridConfig.tokens.join(', ')}] ` +\n `leverage=${this.gridConfig.leverage}x ` +\n `levels=${this.gridConfig.levelsPerSide}/side ` +\n `state-dir=${gridStateDir(this.cfg.stateDir)}\\n`\n ));\n\n // Main loop\n while (this.running) {\n try {\n await this.tick();\n } catch (err) {\n console.error(chalk.red(` [grid-loop] Tick error: ${(err as Error).message}`));\n }\n\n // Wait for next cycle (interruptible via shutdown)\n if (this.running) {\n await new Promise<void>(resolve => {\n this.timer = setTimeout(resolve, this.cfg.cycle);\n });\n }\n }\n\n // Cleanup listeners\n process.off('SIGINT', shutdown);\n process.off('SIGTERM', shutdown);\n console.error(chalk.yellow(' [grid-loop] Stopped.'));\n }\n\n /** Execute one grid cycle. */\n private async tick(): Promise<void> {\n this.cycleCount++;\n const start = Date.now();\n\n // Fetch mark prices from Hyperliquid\n const prices: Record<string, number> = {};\n for (const token of this.gridConfig.tokens) {\n const data = await this.hl.getHyperliquidData(token);\n if (data?.markPrice && data.markPrice > 0) {\n prices[token] = data.markPrice;\n }\n }\n\n if (Object.keys(prices).length === 0) {\n console.error(chalk.dim(` [grid-loop] #${this.cycleCount} — no prices, skipping`));\n return;\n }\n\n const result = await this.manager.tick(prices);\n const elapsed = Date.now() - start;\n\n // Live mode: submit real orders via executor\n if (this.executor) {\n const plan = this.manager.computeOrders(prices);\n if (plan.ordersToPlace.length > 0 || plan.assetsToCancel.length > 0) {\n const res = await this.executor.execute(plan);\n if (res.errors.length > 0) {\n console.error(chalk.yellow(` [grid-loop] Executor errors: ${res.errors.join('; ')}`));\n }\n if (res.placed > 0 || res.cancelled > 0) {\n console.error(chalk.cyan(` [grid-loop] Live: placed=${res.placed} cancelled=${res.cancelled}`));\n }\n }\n }\n\n // Log round trips when they happen\n if (result.roundTrips > 0) {\n console.error(chalk.green(\n ` [grid-loop] #${this.cycleCount} — ${result.roundTrips} RT(s), ` +\n `+$${result.pnlUsd.toFixed(2)} PnL, ${result.fills} fill(s) [${elapsed}ms]`\n ));\n }\n\n // Log fills (without round trips)\n if (result.fills > 0 && result.roundTrips === 0) {\n console.error(chalk.dim(\n ` [grid-loop] #${this.cycleCount} — ${result.fills} fill(s), 0 RTs [${elapsed}ms]`\n ));\n }\n\n // Delta hedge — adjust short positions to offset underwater grid longs.\n // Pass paused state so the hedge flattens (locks in PnL) when the grid\n // soft-pauses on a pool drawdown instead of letting unrealized erode on\n // mean reversion.\n const openExposure = this.manager.getOpenFillExposure();\n const marketTrend = this.manager.getMarketTrend();\n const hedgeResult = await this.hedge.tick(openExposure, prices, Date.now(), marketTrend, result.paused);\n if (hedgeResult.adjustments > 0) {\n console.error(chalk.magenta(\n ` [hedge] ${hedgeResult.adjustments} adjustment(s), ` +\n `unrealized: $${hedgeResult.unrealizedPnl.toFixed(2)}, ` +\n `total realized: $${hedgeResult.totalRealizedPnl.toFixed(2)}`\n ));\n }\n\n // Write cycle log for cron monitor\n const stats = this.manager.getStats();\n const cycleEntry = {\n cycleNumber: this.cycleCount,\n timestamp: Date.now(),\n gridFills: result.fills,\n gridRoundTrips: result.roundTrips,\n gridPnlUsd: result.pnlUsd,\n totalPnlUsd: stats?.totalPnlUsd ?? 0,\n todayPnlUsd: stats?.todayPnlUsd ?? 0,\n totalRoundTrips: stats?.totalRoundTrips ?? 0,\n allocation: stats?.allocation ?? 0,\n paused: stats?.paused ?? false,\n hedgeUnrealizedPnl: hedgeResult.unrealizedPnl,\n hedgeTotalRealizedPnl: hedgeResult.totalRealizedPnl,\n };\n try {\n await mkdir(dirname(this.cyclesPath), { recursive: true });\n await appendFile(this.cyclesPath, JSON.stringify(cycleEntry) + '\\n');\n } catch { /* non-critical */ }\n\n // Periodic status every ~60 cycles\n if (this.cycleCount % 60 === 0) {\n const stats = this.manager.getStats();\n if (stats) {\n const hedgeStatus = this.hedge.getStatus();\n const hedgeInfo = hedgeStatus && hedgeStatus.positions.length > 0\n ? ` hedge=$${hedgeResult.unrealizedPnl.toFixed(2)}unr/$${hedgeStatus.totalRealizedPnl.toFixed(2)}real`\n : '';\n console.error(chalk.cyan(\n ` [grid-loop] Status #${this.cycleCount} — ` +\n `totalPnL=$${stats.totalPnlUsd.toFixed(2)} ` +\n `todayPnL=$${stats.todayPnlUsd.toFixed(2)} ` +\n `RTs=${stats.totalRoundTrips} ` +\n `alloc=$${stats.allocation.toFixed(0)}` +\n `${hedgeInfo}` +\n `${stats.paused ? ' (PAUSED)' : ''}`\n ));\n }\n }\n }\n}\n","/**\n * Grid Manager — core engine for ATR-based grid trading.\n *\n * Builds grid levels from ATR, simulates fills against real prices each tick,\n * handles paired-order replacement and periodic rebalancing.\n */\n\nimport chalk from 'chalk';\nimport type {\n GridConfig,\n GridLevel,\n GridFill,\n GridTokenState,\n GridPortfolioState,\n} from './config.js';\nimport { GridPortfolio } from './portfolio.js';\nimport { HyperliquidProvider } from '../providers/data/hyperliquid.js';\nimport { getLatestSignals } from '../agent/technical.js';\n\n/** Decides if a level should fire at the current price.\n * Default checks against close; backtest checks against bar.low/high. */\nexport type FillDetector = (level: GridLevel, currentPrice: number) => boolean;\n\n/** Decides if an open fill's target has been reached.\n * Default checks against close; backtest checks against bar.high. */\nexport type CloseFillDetector = (openFill: GridFill, currentPrice: number) => boolean;\n\n/** Fetches OHLCV candles for ATR. Default delegates to HyperliquidProvider. */\nexport type CandleFetcher = (\n tokenId: string,\n interval: '1h' | '4h' | '1d',\n lookbackMs: number,\n) => Promise<Array<{ timestamp: number; open: number; high: number; low: number; close: number; volume: number }> | null>;\n\nconst defaultFillDetector: FillDetector = (level, currentPrice) =>\n level.side === 'buy' ? currentPrice <= level.price : currentPrice >= level.price;\n\nconst defaultCloseFillDetector: CloseFillDetector = (openFill, currentPrice) =>\n currentPrice >= openFill.targetSellPrice;\n\nexport class GridManager {\n private config: GridConfig;\n private portfolio: GridPortfolio;\n private hl: HyperliquidProvider;\n private candleFetcher: CandleFetcher;\n private fillDetector: FillDetector;\n private closeFillDetector: CloseFillDetector;\n private nowProvider: () => number;\n\n constructor(\n config: GridConfig,\n candleFetcher?: CandleFetcher,\n fillDetector?: FillDetector,\n closeFillDetector?: CloseFillDetector,\n portfolio?: GridPortfolio,\n nowProvider?: () => number,\n stateDir?: string,\n ) {\n this.config = config;\n // If no portfolio passed, build the default one against the resolved\n // stateDir so a caller that wants per-process isolation gets it without\n // having to wire a GridPortfolio themselves. Mirrors GridLoop's pattern.\n this.portfolio = portfolio ?? new GridPortfolio(stateDir);\n this.hl = new HyperliquidProvider();\n this.candleFetcher = candleFetcher ?? ((tokenId, interval, lookbackMs) =>\n this.hl.getCandles(tokenId, interval, lookbackMs));\n this.fillDetector = fillDetector ?? defaultFillDetector;\n this.closeFillDetector = closeFillDetector ?? defaultCloseFillDetector;\n this.nowProvider = nowProvider ?? (() => Date.now());\n }\n\n /** Load or initialize grid state.\n * Also syncs new tokens added to config after initial grid setup. */\n async init(totalPortfolioValue: number): Promise<void> {\n const existing = await this.portfolio.load();\n if (!existing) {\n await this.portfolio.initialize(totalPortfolioValue, this.config);\n return;\n }\n\n // Sync: add grids for tokens in config but not yet in state\n let addedAllocation = 0;\n for (const token of this.config.tokens) {\n if (!existing.grids.find(g => g.token === token)) {\n const split = this.config.tokenSplit[token] ?? (1 / this.config.tokens.length);\n const alloc = existing.totalAllocation * split;\n existing.grids.push({\n token,\n levels: [],\n openFills: [],\n allocation: alloc,\n stats: { totalRoundTrips: 0, totalPnlUsd: 0, todayPnlUsd: 0, totalFills: 0, todayFills: 0, lastDailyReset: 0, lastRebalanceAt: 0 },\n centerPrice: 0,\n atr: 0,\n trend: 0,\n lastTrendRefreshAt: 0,\n });\n addedAllocation += alloc;\n console.error(` [grid] Added new token grid: ${token} ($${alloc.toFixed(0)} allocation)`);\n }\n }\n if (addedAllocation > 0) {\n await this.portfolio.save(existing);\n }\n }\n\n /**\n * Run one grid tick — called every cycle from the agent loop.\n *\n * 1. Load state + reset daily counters\n * 2. For each token grid: fetch price, simulate fills, check rebalance\n * 3. Persist state\n *\n * Returns a summary for the cycle log.\n */\n async tick(prices: Record<string, number>, regime?: string): Promise<GridTickResult> {\n const state = await this.portfolio.load();\n if (!state || !this.config.enabled) {\n return { fills: 0, roundTrips: 0, pnlUsd: 0, paused: false };\n }\n\n // When paused, still run the pause/resume check — drawdown may have\n // recovered and the grid should auto-resume via unpauseRecoveryPct.\n if (state.paused) {\n const resumed = this.portfolio.checkPauseThreshold(state, this.config, prices);\n if (resumed) {\n await this.portfolio.save(state);\n }\n return { fills: 0, roundTrips: 0, pnlUsd: 0, paused: state.paused };\n }\n\n // Regime-aware grid control: only pause in high-volatility (dangerous swings).\n // Previously also paused buys in trending regimes, but the global regime\n // detector lags — BTC can be ranging $76-78k for a day while EMA(21,50)\n // still says \"trending-up\". The grid's own rebalance drift check is a\n // better signal: if price hasn't triggered a rebalance, it's range-bound\n // within the grid regardless of what the macro regime says.\n if (regime === 'high-volatility') {\n console.error(chalk.dim(` [grid] Paused: high-volatility regime — too risky for grid`));\n return { fills: 0, roundTrips: 0, pnlUsd: 0, paused: false };\n }\n\n // Reset daily counters at UTC boundary\n this.portfolio.resetDailyStats(state);\n\n let totalFills = 0;\n let totalRoundTrips = 0;\n let totalPnl = 0;\n\n for (const grid of state.grids) {\n const price = prices[grid.token];\n if (!price || price <= 0) continue;\n\n // Refresh trend at most once per hour. Lets the downtrend filter\n // respond to fast crashes between scheduled rebuilds (12h cadence).\n // No-op when buildGrid runs this same tick — it overwrites trend anyway.\n await this.maybeRefreshTrend(grid);\n\n // Build grid on first tick or after full rebuild interval\n if (grid.levels.length === 0 || this.needsFullRebuild(grid)) {\n await this.buildGrid(grid, price);\n }\n\n // Simulate fills — both buys and sells. The grid's own rebalance drift\n // handles directional moves (rebuilds when price drifts 40% toward edge).\n const { fills, roundTrips, pnlUsd } = this.simulateFills(grid, price);\n totalFills += fills;\n totalRoundTrips += roundTrips;\n totalPnl += pnlUsd;\n\n // Check rebalance (shift grid if price drifted)\n if (this.needsShift(grid, price)) {\n await this.shiftGrid(grid, price);\n }\n }\n\n // Check pause threshold (uses current prices for mark-to-market)\n this.portfolio.checkPauseThreshold(state, this.config, prices);\n\n // Persist\n await this.portfolio.save(state);\n\n // `checkPauseThreshold` above may have flipped `state.paused` to true on\n // this very bar. Return the mutated flag (not a hardcoded false) so the\n // live loop (loop.ts → hedge.tick) flattens the hedge on the same bar the\n // backtest does — backtest.ts already reads `stateAfter.paused` directly.\n return { fills: totalFills, roundTrips: totalRoundTrips, pnlUsd: totalPnl, paused: state.paused };\n }\n\n /** Hourly refresh of `grid.trend` from recent 4h candles. Called from\n * tick() so the downtrend filter sees fresh data between buildGrid runs. */\n private async maybeRefreshTrend(grid: GridTokenState): Promise<void> {\n const now = this.nowProvider();\n const ONE_HOUR = 60 * 60 * 1000;\n if (now - grid.lastTrendRefreshAt < ONE_HOUR) return;\n\n // 14 4h bars = 56h lookback (matches buildGrid window).\n const candles = await this.candleFetcher(grid.token, '4h', 14 * 4 * 60 * 60 * 1000);\n if (!candles || candles.length < 2) return;\n\n const TREND_LOOKBACK_BARS = 14;\n const sliceStart = Math.max(0, candles.length - TREND_LOOKBACK_BARS);\n const first = candles[sliceStart]!.close;\n const last = candles[candles.length - 1]!.close;\n if (first <= 0) return;\n\n grid.trend = (last - first) / first;\n grid.lastTrendRefreshAt = now;\n }\n\n /** Build a fresh grid centered on the current price using ATR. */\n private async buildGrid(grid: GridTokenState, currentPrice: number): Promise<void> {\n // Fetch ATR from HL candles\n const candles = await this.candleFetcher(grid.token, '4h', 14 * 24 * 60 * 60 * 1000);\n if (!candles || candles.length < this.config.atrPeriod) {\n console.error(chalk.dim(` [grid] Cannot build grid for ${grid.token}: insufficient candle data`));\n return;\n }\n\n const signals = getLatestSignals(candles);\n const atr = signals.atr;\n if (!Number.isFinite(atr) || atr <= 0) {\n console.error(chalk.dim(` [grid] Cannot build grid for ${grid.token}: invalid ATR (${atr})`));\n return;\n }\n\n // Trend signal: % change over the last 14 4h bars (~56 hours).\n // Using only the recent window so the trend captures local direction,\n // not all-time-vs-now (which would always be ~0 over multi-month\n // backtests where price ends near where it started).\n const TREND_LOOKBACK_BARS = 14;\n let trend = 0;\n if (candles.length >= 2) {\n const sliceStart = Math.max(0, candles.length - TREND_LOOKBACK_BARS);\n const first = candles[sliceStart]!.close;\n const last = candles[candles.length - 1]!.close;\n if (first > 0) {\n trend = (last - first) / first;\n }\n }\n\n const range = atr * this.config.atrMultiplier;\n const spacing = range / this.config.levelsPerSide;\n const effectiveCapital = grid.allocation * this.config.leverage;\n const quantity = effectiveCapital / (this.config.levelsPerSide * currentPrice);\n\n const levels: GridLevel[] = [];\n\n // Asymmetric grid in confirmed downtrend: skip most buy levels so the\n // grid stops adding exposure to a falling knife. Keep ONE buy level just\n // below current price so the grid can re-enter on a chop reversal once\n // trend recovers (otherwise we'd never re-engage). Sell levels still\n // place fully so existing inventory can exit on rallies.\n const inDowntrend = this.config.downtrendBlockPct > 0\n && trend < -this.config.downtrendBlockPct;\n const buyCount = inDowntrend ? 1 : this.config.levelsPerSide;\n\n for (let i = 1; i <= buyCount; i++) {\n levels.push({\n price: currentPrice - spacing * i,\n side: 'buy',\n quantity,\n filled: false,\n filledAt: 0,\n });\n }\n\n // Sell levels above current price\n for (let i = 1; i <= this.config.levelsPerSide; i++) {\n levels.push({\n price: currentPrice + spacing * i,\n side: 'sell',\n quantity,\n filled: false,\n filledAt: 0,\n });\n }\n\n grid.levels = levels;\n grid.centerPrice = currentPrice;\n grid.atr = atr;\n grid.trend = trend;\n grid.stats.lastRebalanceAt = Date.now();\n\n console.error(chalk.dim(\n ` [grid] Built ${grid.token} grid: center=$${currentPrice.toFixed(2)} ` +\n `ATR=$${atr.toFixed(2)} range=$${(currentPrice - range).toFixed(2)}-$${(currentPrice + range).toFixed(2)} ` +\n `spacing=$${spacing.toFixed(2)} qty=${quantity.toFixed(6)} trend=${(trend * 100).toFixed(1)}%` +\n `${inDowntrend ? ' [DOWNTREND: 1 buy / ' + this.config.levelsPerSide + ' sells]' : ''}`\n ));\n }\n\n /** Simulate order fills against the current price. */\n private simulateFills(\n grid: GridTokenState,\n currentPrice: number,\n ): { fills: number; roundTrips: number; pnlUsd: number } {\n let fills = 0;\n let roundTrips = 0;\n let pnlUsd = 0;\n const now = Date.now();\n const spacing = grid.atr > 0\n ? (grid.atr * this.config.atrMultiplier) / this.config.levelsPerSide\n : 0;\n\n if (spacing <= 0) return { fills: 0, roundTrips: 0, pnlUsd: 0 };\n\n // Max-exposure cap: stop placing new BUY fills when total open notional\n // exceeds the configured multiple of effective capital. Existing fills\n // can still close (sell levels and close-outs unaffected). Set\n // `maxOpenNotionalMultiple = Infinity` to disable.\n // Cap measures ENTRY notional (qty × buyPrice), not mark-to-market.\n // Mark-to-market shrinks as price falls, which would loosen the cap\n // exactly when we need it to bite (downtrends accumulating buys).\n const exposureCap = grid.allocation * this.config.leverage * this.config.maxOpenNotionalMultiple;\n const currentOpenNotional = grid.openFills\n .filter(f => !f.closed)\n .reduce((s, f) => s + f.quantity * f.buyPrice, 0);\n const buyExposureFull = currentOpenNotional >= exposureCap;\n\n // Downtrend filter: block new buy fills if the grid was built during a\n // sustained drop (trend < -downtrendBlockPct). Re-evaluated each rebuild\n // so buys resume when trend recovers. Set downtrendBlockPct=0 to disable.\n const inDowntrend = this.config.downtrendBlockPct > 0 && grid.trend < -this.config.downtrendBlockPct;\n\n // Step 1: Fill unfilled grid levels (buy when price drops, sell is just accounting)\n for (const level of grid.levels) {\n if (level.filled) continue;\n\n if (level.side === 'buy' && this.fillDetector(level, currentPrice)) {\n if (buyExposureFull) {\n continue; // skip — would exceed max open exposure\n }\n if (inDowntrend) {\n continue; // skip — sustained downtrend, don't buy into the knife\n }\n level.filled = true;\n level.filledAt = now;\n fills++;\n grid.stats.totalFills++;\n grid.stats.todayFills++;\n\n grid.openFills.push({\n token: grid.token,\n buyPrice: level.price,\n targetSellPrice: level.price + spacing,\n quantity: level.quantity,\n filledAt: now,\n closed: false,\n pnlUsd: 0,\n closedAt: 0,\n });\n\n console.error(chalk.dim(\n ` [grid] BUY fill ${grid.token} @ $${level.price.toFixed(2)} qty=${level.quantity.toFixed(6)}`\n ));\n }\n\n if (level.side === 'sell' && this.fillDetector(level, currentPrice)) {\n level.filled = true;\n level.filledAt = now;\n fills++;\n grid.stats.totalFills++;\n grid.stats.todayFills++;\n\n console.error(chalk.dim(\n ` [grid] SELL level ${grid.token} @ $${level.price.toFixed(2)} qty=${level.quantity.toFixed(6)}`\n ));\n }\n }\n\n // Step 2: Close open fills whose targetSellPrice has been reached.\n // This is decoupled from level fills — an open fill closes when\n // currentPrice >= its specific target, regardless of grid levels.\n // Bug fix: previously this only ran inside the sell-level loop, so\n // once a sell level was marked filled it was skipped on future ticks,\n // orphaning any open fill that wasn't matched at that exact moment.\n for (const openFill of grid.openFills) {\n if (openFill.closed) continue;\n if (this.closeFillDetector(openFill, currentPrice)) {\n // PnL = price_change × quantity. quantity is already the leveraged\n // contract size (effectiveCapital / (levels × price) at build), so\n // multiplying by leverage again would double-count. The realized\n // dollar PnL here is the same as a real futures position would book.\n const profit = (currentPrice - openFill.buyPrice) * openFill.quantity;\n if (profit >= this.config.minProfitPerFillUsd) {\n openFill.closed = true;\n openFill.pnlUsd = profit;\n openFill.closedAt = now;\n pnlUsd += profit;\n roundTrips++;\n grid.stats.totalRoundTrips++;\n grid.stats.totalPnlUsd += profit;\n grid.stats.todayPnlUsd += profit;\n grid.allocation += profit;\n\n console.error(chalk.green(\n ` [grid] ROUND-TRIP ${grid.token}: buy $${openFill.buyPrice.toFixed(2)} → sell $${currentPrice.toFixed(2)} = +$${profit.toFixed(2)}`\n ));\n }\n }\n }\n\n // Step 3: stop-loss — force-close any open buy whose unrealized loss\n // crosses the configured threshold. Acts as a per-position circuit\n // breaker. Without this, the grid can accumulate enough underwater\n // exposure across rebuilds to wipe the cross-margin pool even at\n // low leverage (issue #269). Disabled if stopLossPct = 0.\n if (this.config.stopLossPct > 0) {\n for (const openFill of grid.openFills) {\n if (openFill.closed) continue;\n const stopPrice = openFill.buyPrice * (1 - this.config.stopLossPct);\n if (currentPrice <= stopPrice) {\n const realizedLoss = (currentPrice - openFill.buyPrice) * openFill.quantity;\n openFill.closed = true;\n openFill.pnlUsd = realizedLoss;\n openFill.closedAt = now;\n pnlUsd += realizedLoss; // negative\n grid.stats.totalPnlUsd += realizedLoss;\n grid.stats.todayPnlUsd += realizedLoss;\n grid.allocation += realizedLoss; // pool shrinks; positive contributors do the same\n console.error(chalk.red(\n ` [grid] STOP-LOSS ${grid.token}: buy $${openFill.buyPrice.toFixed(2)} → close $${currentPrice.toFixed(2)} = $${realizedLoss.toFixed(2)}`\n ));\n }\n }\n }\n\n // Prune closed fills older than 24h to prevent unbounded growth\n const pruneThreshold = now - 24 * 60 * 60 * 1000;\n grid.openFills = grid.openFills.filter(f => !f.closed || f.closedAt > pruneThreshold);\n\n return { fills, roundTrips, pnlUsd };\n }\n\n /** Check if the grid needs a full rebuild. */\n private needsFullRebuild(grid: GridTokenState): boolean {\n if (grid.levels.length === 0) return true;\n const elapsed = Date.now() - grid.stats.lastRebalanceAt;\n return elapsed >= this.config.fullRebuildIntervalMs;\n }\n\n /** Check if price has drifted enough to warrant shifting the grid. */\n private needsShift(grid: GridTokenState, currentPrice: number): boolean {\n if (grid.centerPrice <= 0 || grid.atr <= 0) return false;\n const range = grid.atr * this.config.atrMultiplier;\n const distFromCenter = Math.abs(currentPrice - grid.centerPrice);\n return distFromCenter / range >= this.config.rebalanceDriftPct;\n }\n\n /** Shift the grid to re-center on the current price. */\n private async shiftGrid(grid: GridTokenState, currentPrice: number): Promise<void> {\n console.error(chalk.dim(\n ` [grid] Shifting ${grid.token} grid: center $${grid.centerPrice.toFixed(2)} → $${currentPrice.toFixed(2)}`\n ));\n // Full rebuild with the new center — keeps existing open fills\n await this.buildGrid(grid, currentPrice);\n }\n\n /** Recent market trend for hedge sizing — BTC's grid.trend (already\n * maintained at 56h cadence by the asymmetric-grid filter), falling back\n * to the median across tracked tokens if BTC is not in the universe.\n * Used by the trend-adaptive hedge ratio. Returns undefined if no signal\n * is yet available (cold start). */\n getMarketTrend(): number | undefined {\n const state = this.portfolio.getState();\n if (!state || state.grids.length === 0) return undefined;\n\n const btc = state.grids.find(g => g.token === 'bitcoin');\n if (btc && Number.isFinite(btc.trend) && btc.lastTrendRefreshAt > 0) return btc.trend;\n\n const trends = state.grids\n .filter(g => Number.isFinite(g.trend) && g.lastTrendRefreshAt > 0)\n .map(g => g.trend);\n if (trends.length === 0) return undefined;\n trends.sort((a, b) => a - b);\n return trends[Math.floor(trends.length / 2)];\n }\n\n /** Get open fill exposure per token — used by the hedge manager. */\n getOpenFillExposure(): Array<{ token: string; totalQuantity: number; totalNotional: number; avgEntryPrice: number; fillCount: number }> {\n const state = this.portfolio.getState();\n if (!state) return [];\n return state.grids.map(g => {\n const opens = g.openFills.filter(f => !f.closed);\n const totalQty = opens.reduce((s, f) => s + f.quantity, 0);\n const totalNotional = opens.reduce((s, f) => s + f.quantity * f.buyPrice, 0);\n return {\n token: g.token,\n totalQuantity: totalQty,\n totalNotional,\n avgEntryPrice: totalQty > 0 ? totalNotional / totalQty : 0,\n fillCount: opens.length,\n };\n }).filter(e => e.fillCount > 0);\n }\n\n /**\n * Compute the orders that should be placed for the current grid state,\n * without simulating fills. Used by the live executor.\n *\n * Returns:\n * - ordersToPlace: all current grid levels that haven't been filled\n * - assetsToCancel: tokens whose grid was rebalanced (need cancel-and-place)\n * - needsRebalance: whether any grid was rebuilt this tick\n */\n computeOrders(prices: Record<string, number>): GridOrderPlan {\n const state = this.portfolio.getState();\n if (!state || state.paused || !this.config.enabled) {\n return { ordersToPlace: [], assetsToCancel: [], needsRebalance: false };\n }\n\n const ordersToPlace: ComputedOrder[] = [];\n const assetsToCancel: string[] = [];\n let needsRebalance = false;\n\n for (const grid of state.grids) {\n const price = prices[grid.token];\n if (!price || price <= 0) continue;\n\n const wasEmpty = grid.levels.length === 0;\n const fullRebuild = wasEmpty || this.needsFullRebuild(grid);\n const shift = !fullRebuild && grid.centerPrice > 0 && this.needsShift(grid, price);\n\n if (fullRebuild || shift) {\n needsRebalance = true;\n if (!wasEmpty) assetsToCancel.push(grid.token);\n }\n\n for (const level of grid.levels) {\n if (level.filled) continue;\n ordersToPlace.push({\n token: grid.token,\n isBuy: level.side === 'buy',\n price: level.price,\n quantity: level.quantity,\n });\n }\n }\n\n return { ordersToPlace, assetsToCancel, needsRebalance };\n }\n\n /** Get aggregate stats for display. */\n getStats(): { totalPnlUsd: number; todayPnlUsd: number; todayFills: number; totalRoundTrips: number; allocation: number; paused: boolean } | null {\n const state = this.portfolio.getState();\n if (!state) return null;\n const agg = this.portfolio.aggregateStats(state);\n return {\n ...agg,\n allocation: state.totalAllocation,\n paused: state.paused,\n };\n }\n}\n\nexport interface GridTickResult {\n fills: number;\n roundTrips: number;\n pnlUsd: number;\n paused: boolean;\n}\n\nexport interface ComputedOrder {\n token: string;\n isBuy: boolean;\n price: number;\n quantity: number;\n}\n\nexport interface GridOrderPlan {\n ordersToPlace: ComputedOrder[];\n assetsToCancel: string[];\n needsRebalance: boolean;\n}\n","/**\n * Grid portfolio — isolated capital tracking and disk persistence.\n *\n * Separate from the directional portfolio.json. Grid profits compound\n * in the grid pool; directional never touches grid capital.\n */\n\nimport { readFile, writeFile, rename, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { gridStatePath } from './paths.js';\nimport type { GridPortfolioState, GridTokenState, GridStats, GridConfig } from './config.js';\n\nfunction emptyStats(): GridStats {\n return {\n totalRoundTrips: 0,\n totalPnlUsd: 0,\n todayPnlUsd: 0,\n totalFills: 0,\n todayFills: 0,\n lastDailyReset: 0,\n lastRebalanceAt: 0,\n };\n}\n\nexport class GridPortfolio {\n private state: GridPortfolioState | null = null;\n private statePath: string;\n\n constructor(stateDir?: string) {\n this.statePath = gridStatePath('portfolio.json', stateDir);\n }\n\n /** Load grid state from disk. Returns null if no grid initialized yet. */\n async load(): Promise<GridPortfolioState | null> {\n try {\n const raw = await readFile(this.statePath, 'utf-8');\n this.state = JSON.parse(raw) as GridPortfolioState;\n return this.state;\n } catch {\n return null;\n }\n }\n\n /** Save grid state to disk (atomic write). */\n async save(state: GridPortfolioState): Promise<void> {\n this.state = state;\n await mkdir(dirname(this.statePath), { recursive: true });\n const tmp = `${this.statePath}.tmp.${process.pid}`;\n await writeFile(tmp, JSON.stringify(state, null, 2), 'utf-8');\n await rename(tmp, this.statePath);\n }\n\n /**\n * Initialize the grid by carving capital from the directional portfolio.\n * Called once on first startup when grid-portfolio.json doesn't exist.\n *\n * Returns the USD amount carved out (caller must deduct from directional portfolio).\n */\n async initialize(capital: number, config: GridConfig): Promise<void> {\n const allocation = capital;\n\n const grids: GridTokenState[] = config.tokens.map(token => ({\n token,\n levels: [],\n openFills: [],\n allocation: allocation * (config.tokenSplit[token] ?? 1 / config.tokens.length),\n stats: emptyStats(),\n centerPrice: 0,\n atr: 0,\n trend: 0,\n lastTrendRefreshAt: 0,\n }));\n\n const state: GridPortfolioState = {\n totalAllocation: allocation,\n grids,\n paused: false,\n pauseReason: '',\n initializedAt: Date.now(),\n };\n\n await this.save(state);\n this.state = state;\n }\n\n /** Get current state (must load() first). */\n getState(): GridPortfolioState | null {\n return this.state;\n }\n\n /** Reset daily counters if UTC day boundary crossed. `now` is injectable\n * so the backtester can drive resets off backtest time, not wall-clock. */\n resetDailyStats(state: GridPortfolioState, now: number = Date.now()): boolean {\n const todayMidnight = new Date(now);\n todayMidnight.setUTCHours(0, 0, 0, 0);\n const todayMs = todayMidnight.getTime();\n\n let changed = false;\n for (const grid of state.grids) {\n if (!grid.stats.lastDailyReset || grid.stats.lastDailyReset < todayMs) {\n grid.stats.todayPnlUsd = 0;\n grid.stats.todayFills = 0;\n grid.stats.lastDailyReset = now;\n changed = true;\n }\n }\n return changed;\n }\n\n /** Check if grid should be paused or resumed (pool equity dropped/recovered).\n * `prices` is required to mark open buys to market. Hysteresis: pause at\n * `pauseThresholdPct` drop, resume only when drop recovers below\n * `unpauseRecoveryPct`. Returns true iff state.paused was changed. */\n checkPauseThreshold(\n state: GridPortfolioState,\n config: GridConfig,\n prices: Record<string, number>,\n ): boolean {\n const currentValue = state.grids.reduce((sum, g) => {\n const price = prices[g.token];\n // quantity already leveraged at build time — see manager.simulateFills.\n const unrealized = (price && price > 0)\n ? g.openFills\n .filter(f => !f.closed)\n .reduce((s, f) => s + (price - f.buyPrice) * f.quantity, 0)\n : 0;\n return sum + g.allocation + unrealized;\n }, 0);\n\n const dropPct = 1 - (currentValue / state.totalAllocation);\n\n // Hard circuit breaker — checked first because it overrides hysteresis.\n // Once tripped, only manual `sherwood grid resume` can clear it.\n if (!state.circuitBroken && dropPct >= config.circuitBreakerThresholdPct) {\n state.circuitBroken = true;\n state.circuitBrokenAt = Date.now();\n state.paused = true;\n state.pauseReason =\n `Hard circuit breaker tripped — pool dropped ${(dropPct * 100).toFixed(1)}% ` +\n `(>= ${(config.circuitBreakerThresholdPct * 100).toFixed(0)}%). ` +\n `Manual resume required: \\`sherwood grid resume\\`.`;\n return true;\n }\n\n // Soft pause (hysteresis path) — only relevant when circuit not tripped.\n if (!state.circuitBroken && !state.paused && dropPct >= config.pauseThresholdPct) {\n state.paused = true;\n state.pauseReason = `Grid pool dropped ${(dropPct * 100).toFixed(1)}% (pause threshold: ${(config.pauseThresholdPct * 100).toFixed(0)}%, resume when ≤ ${(config.unpauseRecoveryPct * 100).toFixed(0)}%)`;\n return true;\n }\n\n // Auto-resume — gated on circuitBroken to prevent re-engaging mid-crash.\n if (!state.circuitBroken && state.paused && dropPct <= config.unpauseRecoveryPct) {\n state.paused = false;\n state.pauseReason = '';\n return true;\n }\n\n return false;\n }\n\n /** Aggregate stats across all token grids. */\n aggregateStats(state: GridPortfolioState): {\n totalPnlUsd: number;\n todayPnlUsd: number;\n todayFills: number;\n totalRoundTrips: number;\n } {\n return {\n totalPnlUsd: state.grids.reduce((s, g) => s + g.stats.totalPnlUsd, 0),\n todayPnlUsd: state.grids.reduce((s, g) => s + g.stats.todayPnlUsd, 0),\n todayFills: state.grids.reduce((s, g) => s + g.stats.todayFills, 0),\n totalRoundTrips: state.grids.reduce((s, g) => s + g.stats.totalRoundTrips, 0),\n };\n }\n}\n","import { join, resolve } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport const DEFAULT_GRID_STATE_DIR = join(homedir(), '.sherwood', 'grid');\n\n/**\n * Resolve the grid state directory, with optional caller override.\n * Relative paths are resolved against the current working directory at the\n * moment of resolution — important for systemd / cron jobs that may set their\n * own CWD. Empty/whitespace overrides fall back to the default.\n *\n * Note: scope is intentionally narrow — only runtime mutable state\n * (`portfolio.json`, `hedge.json`, `cycles.jsonl`, `onchain-state.json`).\n * Backtest cache, sweep results, and historical-data downloads continue to\n * use `~/.sherwood/grid/` because they are not per-loop state.\n */\nexport function gridStateDir(override?: string): string {\n if (!override || override.trim().length === 0) return DEFAULT_GRID_STATE_DIR;\n return resolve(override);\n}\n\nexport function gridStatePath(file: string, override?: string): string {\n return join(gridStateDir(override), file);\n}\n","/**\n * Grid trading strategy — types and configuration.\n *\n * ATR-based grid that profits from ranging-market volatility on BTC + ETH.\n * Runs as a parallel mode alongside the directional signal-based strategy\n * with isolated capital allocation.\n */\n\n// ── Types ──\n\nexport interface GridLevel {\n /** Price at which this order fills. */\n price: number;\n /** 'buy' below current price, 'sell' above. */\n side: 'buy' | 'sell';\n /** Quantity per fill (in token units, e.g. 0.0124 BTC). */\n quantity: number;\n /** True if this level has been filled and is waiting for its paired order. */\n filled: boolean;\n /** Timestamp of fill (0 if unfilled). */\n filledAt: number;\n}\n\nexport interface GridFill {\n /** Token ID (e.g. 'bitcoin'). */\n token: string;\n /** Price at which we bought. */\n buyPrice: number;\n /** Price at which the paired sell should execute. */\n targetSellPrice: number;\n /** Quantity in token units. */\n quantity: number;\n /** Timestamp of buy fill. */\n filledAt: number;\n /** If this fill has been closed by its paired sell. */\n closed: boolean;\n /** PnL when closed (before leverage). */\n pnlUsd: number;\n /** Timestamp of close. */\n closedAt: number;\n}\n\nexport interface GridStats {\n /** Completed buy→sell round-trips. */\n totalRoundTrips: number;\n /** Cumulative grid profit in USD (after leverage). */\n totalPnlUsd: number;\n /** Today's grid profit (resets UTC midnight). */\n todayPnlUsd: number;\n /** Total fills (buy + sell) since inception. */\n totalFills: number;\n /** Today's fills. */\n todayFills: number;\n /** Last daily reset timestamp. */\n lastDailyReset: number;\n /** Last full grid rebuild timestamp. */\n lastRebalanceAt: number;\n}\n\nexport interface GridTokenState {\n /** CoinGecko token ID. */\n token: string;\n /** Current active grid levels. */\n levels: GridLevel[];\n /** Open fills waiting for their paired sell/buy. */\n openFills: GridFill[];\n /** USD allocated to this token's grid. */\n allocation: number;\n /** Cumulative stats for this token's grid. */\n stats: GridStats;\n /** Price at center when grid was last built/rebalanced. */\n centerPrice: number;\n /** ATR at last build. */\n atr: number;\n /** Trend at last grid build: (latest_4h_close - lookback_first_4h_close) / lookback_first_4h_close. */\n trend: number;\n /** Last time grid.trend was refreshed mid-tick (separate from buildGrid). */\n lastTrendRefreshAt: number;\n}\n\nexport interface GridPortfolioState {\n /** Total USD carved out for the grid strategy. */\n totalAllocation: number;\n /** Per-token grid state. */\n grids: GridTokenState[];\n /** Whether grid is paused (pool dropped below threshold). */\n paused: boolean;\n /** Reason for pause (empty if active). */\n pauseReason: string;\n /** Timestamp of initial allocation. */\n initializedAt: number;\n /** Hard circuit breaker tripped — pool drawdown exceeded\n * `circuitBreakerThresholdPct`. Auto-resume is BLOCKED while this is set;\n * only an explicit `sherwood grid resume` clears it. Persists in\n * portfolio.json so a process restart does not silently re-engage. */\n circuitBroken?: boolean;\n /** Timestamp when the circuit breaker was tripped (0 / undefined = never). */\n circuitBrokenAt?: number;\n}\n\n// ── Configuration ──\n\nexport interface GridConfig {\n /** Enable/disable the grid strategy. */\n enabled: boolean;\n /** Tokens to run grids on. */\n tokens: string[];\n /** Fraction of total portfolio to allocate to grid (0.35 = 35%). */\n allocationPct: number;\n /** Leverage multiplier on grid capital. */\n leverage: number;\n /** Number of buy levels below price (same number of sell levels above). */\n levelsPerSide: number;\n /** Grid range = price ± (atrMultiplier × ATR). */\n atrMultiplier: number;\n /** ATR lookback period. */\n atrPeriod: number;\n /** Shift grid when price drifts past this fraction of the range toward one edge. */\n rebalanceDriftPct: number;\n /** Full grid rebuild interval in ms. */\n fullRebuildIntervalMs: number;\n /** Per-token allocation split (must sum to 1.0). */\n tokenSplit: Record<string, number>;\n /** Skip fills where profit per round-trip < this (fee floor). */\n minProfitPerFillUsd: number;\n /** Pause grid if pool drops this fraction from initial allocation. */\n pauseThresholdPct: number;\n /** Resume paused grid when drawdown recovers below this fraction (hysteresis). */\n unpauseRecoveryPct: number;\n /** Hard circuit-breaker drawdown threshold. When pool MtM drop hits this,\n * the grid is permanently paused (auto-resume disabled) until an operator\n * runs `sherwood grid resume`. Distinct from `pauseThresholdPct` — the\n * soft pause has hysteresis and can re-engage on its own; the circuit\n * breaker requires manual review. Default 0.30 (30% drawdown). */\n circuitBreakerThresholdPct: number;\n /** Per-token maintenance margin fraction. Backtester uses this to model\n * exchange liquidation. Default 0.02 = 2% (typical Hyperliquid). */\n maintenanceMarginPct: number;\n /** Max open notional per token as a multiple of (allocation × leverage).\n * When exceeded, new buy fills are refused (existing fills can still\n * close as sells). Caps unbounded accumulation across rebuilds in\n * downtrends. Default 2.0 (allows up to 2 grid generations). */\n maxOpenNotionalMultiple: number;\n /** Block new buy fills when trend over the ATR lookback is below this\n * threshold. Default 0.10 (10% drop in 56h = clear downtrend → don't\n * buy into the falling knife). Set to 0 to disable filter. */\n downtrendBlockPct: number;\n /** Force-close any open buy if currentPrice drops this fraction below\n * buyPrice. Per-position stop-loss: limits how much any single fill can\n * contribute to the cross-margin pool's drawdown. Default 0.10 (10%\n * adverse from entry — empirical Nov–May: 10% saves the strategy at -4%,\n * 30% lets liquidations through at -37%). 0 = disabled. */\n stopLossPct: number;\n}\n\nexport const DEFAULT_GRID_CONFIG: GridConfig = {\n enabled: true,\n tokens: ['bitcoin', 'ethereum', 'solana'],\n allocationPct: 0.50,\n leverage: 5, // was 4 — +25% profit per RT\n levelsPerSide: 12, // disjoint-window winner — lowest MaxDD (18% vs 21-22%) at modest avg PnL trade-off\n atrMultiplier: 3, // ATR×3 dominates ATR×2 across all tested windows (lower fee burn)\n atrPeriod: 14,\n rebalanceDriftPct: 0.40, // was 0.55 — rebalance faster, keep levels near price\n fullRebuildIntervalMs: 12 * 60 * 60 * 1000, // 12h\n tokenSplit: { bitcoin: 0.55, ethereum: 0.25, solana: 0.20 }, // BTC-tilt — 30d backtest 2026-04-18..05-18 vs prior 0.45/0.30/0.25: net +$464 (+9.28%) vs +$422 (+8.44%) and max DD -$546 vs -$598\n minProfitPerFillUsd: 0.50,\n pauseThresholdPct: 0.20, // post leverage-fix calibration: fires at ~4% adverse move on 5x (real dollar terms); old 0.40 required ~8% which essentially never fired before liquidation\n unpauseRecoveryPct: 0.05, // hysteresis: resume when pool recovers to within 5% of initial (half of pause threshold to avoid ping-pong)\n circuitBreakerThresholdPct: 0.30, // hard halt at 30% drawdown — manual resume required. Bear-sweep: BEAR-60d went from -20% to -53% in second month; halting at -30% saves the rest.\n maintenanceMarginPct: 0.02,\n maxOpenNotionalMultiple: 2.0,\n downtrendBlockPct: 0.10,\n stopLossPct: 0.10, // empirical Nov-May: 10% saves the strategy (-4%); 30% lets liquidations through (-37%)\n};\n","/**\n * Grid Delta Hedge — maintains a partial short to offset underwater long fills.\n *\n * When the grid accumulates open buy fills (price dropped through buy levels),\n * the hedge opens a short position sized at HEDGE_RATIO of the total long exposure.\n * This limits drawdown during directional drops while preserving most grid profit\n * during ranging markets.\n *\n * Mechanics:\n * - Each tick: compute total long exposure from open fills\n * - Desired short = exposure × HEDGE_RATIO\n * - If current hedge size differs by >10%, adjust\n * - Track hedge PnL separately from grid PnL\n * - Close hedge when open fills drop below threshold (price recovered)\n *\n * Cost analysis (30% hedge on $6,400 exposure):\n * - Ranging drag: ~$8/day (5.6% of grid profit)\n * - Funding income: ~$2/day (shorts earn when rate positive)\n * - Net cost: ~$6/day — pays for itself on any >1.3% drop\n */\n\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { gridStatePath } from './paths.js';\nimport chalk from 'chalk';\n\n/** Default fraction of grid long exposure to hedge with a short.\n * Used as the chop/neutral baseline when no `marketTrend` is supplied or\n * trend is in the [-0.10, +0.10] range. See `hedgeRatioFor()` for the\n * trend-adaptive table. Override default via HEDGE_RATIO env var. */\nconst HEDGE_RATIO_DEFAULT = Number.isFinite(Number(process.env.HEDGE_RATIO))\n ? Number(process.env.HEDGE_RATIO)\n : 0.30;\n\n/**\n * Trend-adaptive hedge ratio.\n *\n * `marketTrend` is the recent BTC % move (negative = bearish), computed by\n * the manager over the same 56h / 14-bar window the asymmetric-grid filter\n * uses. Because that window is short, the magnitudes are small even in\n * sustained bears — empirically: BTC dropping ~1% / day prints a 56h\n * trend of −2-3%; the worst 56h slices in BEAR-30d-jan26 hit roughly −7%.\n * The thresholds below are calibrated to that scale, NOT to multi-week\n * cumulative drawdown.\n *\n * Bear-window backtest sweep (Oct '25 – Feb '26 BTC drawdowns):\n * - 50% hedge in bear cuts loss by ~25 ret pts vs 30%\n * - 10% hedge in bull saves ~7 ret pts vs 30% drag in chop\n *\n * Setting HEDGE_RATIO env var bypasses the table — useful for sweeps.\n */\nexport function hedgeRatioFor(marketTrend: number | undefined): number {\n if (process.env.HEDGE_RATIO !== undefined && Number.isFinite(Number(process.env.HEDGE_RATIO))) {\n return Number(process.env.HEDGE_RATIO);\n }\n if (marketTrend === undefined || !Number.isFinite(marketTrend)) {\n return HEDGE_RATIO_DEFAULT;\n }\n if (marketTrend <= -0.05) return 0.70; // strong bear (~ -1%/day sustained)\n if (marketTrend <= -0.025) return 0.50; // confirmed bear\n if (marketTrend >= 0.025) return 0.10; // strong bull — minimize drag\n return HEDGE_RATIO_DEFAULT; // chop / neutral\n}\n\n/** Minimum number of open buy fills before hedge activates. */\nconst MIN_FILLS_TO_HEDGE = 3;\n\n/** Don't adjust hedge unless size differs by more than this fraction. */\nconst ADJUSTMENT_THRESHOLD = 0.10;\n\nexport interface HedgePosition {\n token: string;\n /** Short entry price (average, updates on adjustments). */\n entryPrice: number;\n /** Short quantity in token units. */\n quantity: number;\n /** Timestamp of last adjustment. */\n lastAdjustedAt: number;\n /** Cumulative realized PnL from hedge adjustments. */\n realizedPnl: number;\n}\n\nexport interface HedgeState {\n positions: HedgePosition[];\n /** Total realized PnL across all hedge positions (including closed). */\n totalRealizedPnl: number;\n /** Today's realized PnL (resets daily). */\n todayRealizedPnl: number;\n lastDailyReset: number;\n}\n\nexport interface OpenFillExposure {\n token: string;\n totalQuantity: number;\n totalNotional: number;\n avgEntryPrice: number;\n fillCount: number;\n}\n\nexport interface HedgeTickResult {\n /** Number of hedge adjustments made this tick. */\n adjustments: number;\n /** Unrealized PnL across all active hedge positions. */\n unrealizedPnl: number;\n /** Total realized PnL (cumulative). */\n totalRealizedPnl: number;\n}\n\nexport class GridHedgeManager {\n private state: HedgeState | null = null;\n private statePath: string;\n\n constructor(stateDir?: string) {\n this.statePath = gridStatePath('hedge.json', stateDir);\n }\n\n async load(now: number = Date.now()): Promise<HedgeState> {\n if (this.state) return this.state;\n try {\n const raw = await readFile(this.statePath, 'utf-8');\n this.state = JSON.parse(raw) as HedgeState;\n } catch {\n this.state = {\n positions: [],\n totalRealizedPnl: 0,\n todayRealizedPnl: 0,\n lastDailyReset: now,\n };\n }\n\n // Reset daily PnL at UTC midnight (uses `now` so backtester can drive it)\n const todayMidnight = new Date(now);\n todayMidnight.setUTCHours(0, 0, 0, 0);\n if (this.state.lastDailyReset < todayMidnight.getTime()) {\n this.state.todayRealizedPnl = 0;\n this.state.lastDailyReset = now;\n }\n\n return this.state;\n }\n\n async save(): Promise<void> {\n if (!this.state) return;\n await mkdir(dirname(this.statePath), { recursive: true });\n const tmp = `${this.statePath}.tmp.${process.pid}`;\n await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf-8');\n const { rename } = await import('node:fs/promises');\n await rename(tmp, this.statePath);\n }\n\n /**\n * Run one hedge tick. Call after grid tick with current prices and open fill data.\n *\n * @param openFills - Per-token open fill exposure from the grid portfolio\n * @param prices - Current mark prices per token\n * @param now - injected clock (backtester drives this)\n * @param marketTrend - recent market trend (e.g. BTC's 56h trend) used by\n * `hedgeRatioFor()` to scale hedge size by regime. Pass\n * undefined to use the static default.\n * @param paused - when true, force desired hedge to zero for all tokens so\n * the close-path realizes any unrealized PnL into the\n * ledger. The loop passes `state.paused` so a soft-pause\n * grid doesn't hold paper-gain on the hedge that erodes\n * when the underlying mean-reverts toward the resume\n * threshold.\n */\n async tick(\n openFills: OpenFillExposure[],\n prices: Record<string, number>,\n now: number = Date.now(),\n marketTrend?: number,\n paused: boolean = false,\n ): Promise<HedgeTickResult> {\n const state = await this.load(now);\n let adjustments = 0;\n let unrealizedPnl = 0;\n\n // Resolve the active hedge ratio once per tick so all per-token sizing\n // and event logging use the same value.\n const activeRatio = hedgeRatioFor(marketTrend);\n\n for (const fill of openFills) {\n const price = prices[fill.token];\n if (!price || price <= 0) continue;\n\n // When the grid is soft-paused, force zero target. The existing close\n // branch below crystallizes unrealized PnL into the ledger — preserving\n // the protection value the hedge accrued during the drawdown instead\n // of giving it back when the underlying recovers toward unpause.\n const desiredShortQty = paused\n ? 0\n : fill.fillCount >= MIN_FILLS_TO_HEDGE\n ? fill.totalQuantity * activeRatio\n : 0;\n\n const existing = state.positions.find(p => p.token === fill.token);\n\n if (desiredShortQty <= 0) {\n // Close hedge if one exists\n if (existing && existing.quantity > 0) {\n const closePnl = (existing.entryPrice - price) * existing.quantity;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n existing.realizedPnl += closePnl;\n console.error(chalk.yellow(\n ` [hedge] CLOSE ${fill.token} short ${existing.quantity.toFixed(6)} @ $${price.toFixed(2)} ` +\n `PnL: $${closePnl.toFixed(2)}`\n ));\n existing.quantity = 0;\n existing.entryPrice = 0;\n adjustments++;\n }\n continue;\n }\n\n if (!existing) {\n // Open new hedge\n state.positions.push({\n token: fill.token,\n entryPrice: price,\n quantity: desiredShortQty,\n lastAdjustedAt: Date.now(),\n realizedPnl: 0,\n });\n console.error(chalk.magenta(\n ` [hedge] OPEN ${fill.token} short ${desiredShortQty.toFixed(6)} @ $${price.toFixed(2)} ` +\n `(${(activeRatio * 100).toFixed(0)}% of ${fill.fillCount} open fills)`\n ));\n adjustments++;\n } else if (existing.quantity > 0) {\n // Check if adjustment needed\n const diff = Math.abs(desiredShortQty - existing.quantity) / existing.quantity;\n if (diff > ADJUSTMENT_THRESHOLD) {\n if (desiredShortQty > existing.quantity) {\n // Increase hedge — add to short\n const addQty = desiredShortQty - existing.quantity;\n const newAvgEntry = (existing.entryPrice * existing.quantity + price * addQty) / desiredShortQty;\n existing.entryPrice = newAvgEntry;\n existing.quantity = desiredShortQty;\n existing.lastAdjustedAt = Date.now();\n console.error(chalk.magenta(\n ` [hedge] INCREASE ${fill.token} short to ${desiredShortQty.toFixed(6)} @ avg $${newAvgEntry.toFixed(2)}`\n ));\n adjustments++;\n } else {\n // Decrease hedge — partially close short\n const closeQty = existing.quantity - desiredShortQty;\n const closePnl = (existing.entryPrice - price) * closeQty;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n existing.realizedPnl += closePnl;\n existing.quantity = desiredShortQty;\n existing.lastAdjustedAt = Date.now();\n console.error(chalk.magenta(\n ` [hedge] DECREASE ${fill.token} short to ${desiredShortQty.toFixed(6)}, ` +\n `closed ${closeQty.toFixed(6)} PnL: $${closePnl.toFixed(2)}`\n ));\n adjustments++;\n }\n }\n\n // Compute unrealized PnL on current hedge\n const uPnl = (existing.entryPrice - price) * existing.quantity;\n unrealizedPnl += uPnl;\n } else {\n // Hedge was closed but fills are back — reopen\n existing.entryPrice = price;\n existing.quantity = desiredShortQty;\n existing.lastAdjustedAt = Date.now();\n console.error(chalk.magenta(\n ` [hedge] REOPEN ${fill.token} short ${desiredShortQty.toFixed(6)} @ $${price.toFixed(2)}`\n ));\n adjustments++;\n }\n }\n\n // Close hedges for tokens no longer in the fill list\n for (const pos of state.positions) {\n if (pos.quantity <= 0) continue;\n if (!openFills.find(f => f.token === pos.token)) {\n const price = prices[pos.token];\n if (price) {\n const closePnl = (pos.entryPrice - price) * pos.quantity;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n pos.realizedPnl += closePnl;\n console.error(chalk.yellow(\n ` [hedge] CLOSE orphaned ${pos.token} short, PnL: $${closePnl.toFixed(2)}`\n ));\n pos.quantity = 0;\n adjustments++;\n }\n }\n }\n\n await this.save();\n\n return {\n adjustments,\n unrealizedPnl,\n totalRealizedPnl: state.totalRealizedPnl,\n };\n }\n\n /**\n * Close every active hedge position in the ledger at the provided mark\n * prices, accumulating realized PnL using the same `(entry - price) * qty`\n * formula `tick()` uses on its auto-close path. Positions whose token is\n * missing from `prices` are left untouched and reported in `skipped`.\n *\n * Bookkeeping-only — this manager does not place perp orders; the actual\n * HL position (if any) must be closed externally. Use this to zero the\n * ledger as part of `sherwood grid flatten`.\n */\n async flatten(prices: Record<string, number>, now: number = Date.now()): Promise<{\n closed: Array<{ token: string; quantity: number; realizedPnl: number }>;\n skipped: string[];\n totalRealizedPnl: number;\n }> {\n const state = await this.load(now);\n const closed: Array<{ token: string; quantity: number; realizedPnl: number }> = [];\n const skipped: string[] = [];\n\n for (const pos of state.positions) {\n if (pos.quantity <= 0) continue;\n const price = prices[pos.token];\n if (!price || price <= 0) {\n skipped.push(pos.token);\n continue;\n }\n const closePnl = (pos.entryPrice - price) * pos.quantity;\n state.totalRealizedPnl += closePnl;\n state.todayRealizedPnl += closePnl;\n pos.realizedPnl += closePnl;\n closed.push({ token: pos.token, quantity: pos.quantity, realizedPnl: closePnl });\n pos.quantity = 0;\n pos.entryPrice = 0;\n pos.lastAdjustedAt = now;\n }\n\n await this.save();\n return { closed, skipped, totalRealizedPnl: state.totalRealizedPnl };\n }\n\n /** Get current hedge status for display. */\n getStatus(): { positions: HedgePosition[]; totalRealizedPnl: number; todayRealizedPnl: number } | null {\n if (!this.state) return null;\n return {\n positions: this.state.positions.filter(p => p.quantity > 0),\n totalRealizedPnl: this.state.totalRealizedPnl,\n todayRealizedPnl: this.state.todayRealizedPnl,\n };\n }\n}\n","/**\n * GridExecutor — bridges GridManager output to real Hyperliquid orders.\n *\n * The strategy contract owns USDC on HyperCore margin. The keeper (proposer EOA)\n * calls strategy.updateParams() with batch order data each tick. The CLI uses\n * the HL SDK directly via hlPlaceLimitOrder / hlCancelAllOrders for the simpler\n * deployment path (off-chain orders against the keeper's HyperCore account).\n */\n\nimport chalk from 'chalk';\nimport { hlPlaceLimitOrder, hlCancelAllOrders, resolveHLCoin } from '../lib/hyperliquid-executor.js';\nimport type { GridOrderPlan } from './manager.js';\n\nexport interface GridExecutorConfig {\n /** Hyperliquid asset index per token (e.g. bitcoin → 3). */\n assetIndices: Record<string, number>;\n}\n\nexport class GridExecutor {\n private cfg: GridExecutorConfig;\n\n constructor(cfg: GridExecutorConfig) {\n this.cfg = cfg;\n }\n\n /**\n * Execute the order plan against Hyperliquid.\n * Cancels stale orders for rebalanced tokens, then places new orders.\n */\n async execute(plan: GridOrderPlan): Promise<{ placed: number; cancelled: number; errors: string[] }> {\n const errors: string[] = [];\n let cancelled = 0;\n let placed = 0;\n\n for (const token of plan.assetsToCancel) {\n const coin = resolveHLCoin(token);\n if (!coin) {\n errors.push(`No HL ticker for ${token}`);\n continue;\n }\n try {\n await hlCancelAllOrders(coin);\n cancelled++;\n console.error(chalk.dim(` [grid-exec] Cancelled all orders for ${coin}`));\n } catch (e) {\n errors.push(`Cancel ${coin} failed: ${(e as Error).message}`);\n }\n }\n\n for (const order of plan.ordersToPlace) {\n const coin = resolveHLCoin(order.token);\n if (!coin) {\n errors.push(`No HL ticker for ${order.token}`);\n continue;\n }\n try {\n const res = await hlPlaceLimitOrder(coin, order.isBuy, order.quantity, order.price);\n if (res.success) {\n placed++;\n } else {\n errors.push(`Place ${coin} ${order.isBuy ? 'buy' : 'sell'} @${order.price}: ${res.error}`);\n }\n } catch (e) {\n errors.push(`Place ${coin} threw: ${(e as Error).message}`);\n }\n }\n\n return { placed, cancelled, errors };\n }\n}\n","/**\n * OnchainGridExecutor — calls HyperliquidGridStrategy.updateParams() on\n * HyperEVM via viem so grid orders execute against the strategy contract's\n * HyperCore account (which holds vault USDC).\n *\n * Persists per-token nonces + placed-CLOID tracking to disk so a restart\n * can correctly cancel the orders left on-chain by the prior process.\n */\n\nimport chalk from 'chalk';\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { encodeAbiParameters, parseUnits, type Address, type Hex } from 'viem';\nimport { getPublicClient, writeContractWithRetry } from '../lib/client.js';\nimport { hlGetMeta, resolveHLCoin, type HLAssetMeta } from '../lib/hyperliquid-executor.js';\nimport { gridCloid } from './cloid.js';\nimport { gridStatePath } from './paths.js';\nimport { HYPERLIQUID_GRID_STRATEGY_ABI } from './strategy-abi.js';\nimport type { GridOrderPlan } from './manager.js';\n\nconst UINT64_MAX = 18446744073709551615n;\n\nexport interface OnchainGridExecutorConfig {\n strategyAddress: Address;\n /** Hyperliquid asset index per token (e.g. bitcoin → 3). */\n assetIndices: Record<string, number>;\n /** Override directory for persisted state. Defaults to ~/.sherwood/grid. */\n stateDir?: string;\n}\n\ninterface PersistedState {\n /** Per-token nonce — increments on cancel/rebuild. */\n nonces: Record<string, number>;\n /** Per-token CLOIDs of the orders currently live on HyperCore. Stored as decimal strings (BigInt). */\n placedCloids: Record<string, string[]>;\n}\n\ninterface EncodedOrder {\n assetIndex: number;\n isBuy: boolean;\n limitPx: bigint;\n sz: bigint;\n cloid: bigint;\n}\n\nconst ACTION_PLACE_GRID = 1;\nconst ACTION_CANCEL_ALL = 2;\nconst ACTION_CANCEL_AND_PLACE = 3;\n\nfunction chunkArray<T>(arr: T[], size: number): T[][] {\n if (size <= 0) throw new Error(`chunk size must be > 0 (got ${size})`);\n if (arr.length === 0) return [];\n const out: T[][] = [];\n for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));\n return out;\n}\n\nconst GRID_ORDER_COMPONENTS = [\n { name: 'assetIndex', type: 'uint32' },\n { name: 'isBuy', type: 'bool' },\n { name: 'limitPx', type: 'uint64' },\n { name: 'sz', type: 'uint64' },\n { name: 'cloid', type: 'uint128' },\n] as const;\n\nexport class OnchainGridExecutor {\n private cfg: OnchainGridExecutorConfig;\n private nonces: Map<string, number> = new Map();\n private placedCloids: Map<string, bigint[]> = new Map();\n private meta: Map<string, HLAssetMeta> | null = null;\n private busy = false;\n /** On-chain `maxOrdersPerTick`; cached at load(). Used to chunk batches so\n * the strategy never reverts with TooManyOrders(actual, max). */\n private maxOrdersPerTick: number | null = null;\n private statePath: string;\n\n constructor(cfg: OnchainGridExecutorConfig) {\n this.cfg = cfg;\n this.statePath = gridStatePath('onchain-state.json', cfg.stateDir);\n }\n\n /** Read the strategy's per-call order cap and cache it. */\n private async fetchMaxOrdersPerTick(): Promise<number> {\n if (this.maxOrdersPerTick !== null) return this.maxOrdersPerTick;\n const pub = getPublicClient();\n const value = await pub.readContract({\n address: this.cfg.strategyAddress,\n abi: HYPERLIQUID_GRID_STRATEGY_ABI,\n functionName: 'maxOrdersPerTick',\n });\n this.maxOrdersPerTick = Number(value);\n return this.maxOrdersPerTick;\n }\n\n /**\n * Read persisted state from disk — does NOT touch the network. Use this\n * when you only need `nonces` + `placedCloids` (e.g. for `flattenAll`'s\n * cancel-only path). Idempotent: callers may invoke it repeatedly; each\n * call re-reads the file and clobbers in-memory maps with disk state.\n */\n private async loadFromDisk(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, 'utf-8');\n const state = JSON.parse(raw) as PersistedState;\n this.nonces.clear();\n this.placedCloids.clear();\n for (const [tok, n] of Object.entries(state.nonces)) this.nonces.set(tok, n);\n for (const [tok, cloids] of Object.entries(state.placedCloids)) {\n this.placedCloids.set(tok, cloids.map((s) => BigInt(s)));\n }\n console.error(chalk.dim(` [grid-onchain] Loaded state: ${this.nonces.size} tokens`));\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n // First run — fine\n } else {\n // Corrupt JSON or other read error — start fresh. On-chain state is the\n // source of truth; at worst we orphan one cycle of orders until HL\n // expires them via TIF.\n console.error(\n chalk.yellow(\n ` [grid-onchain] Failed to load state (${(e as Error).message}) — starting fresh. Existing on-chain orders may be orphaned.`,\n ),\n );\n }\n }\n }\n\n /** Load persisted state + chain meta. Call once before the first execute(). */\n async load(): Promise<void> {\n await this.loadFromDisk();\n if (!this.meta) this.meta = await hlGetMeta();\n await this.fetchMaxOrdersPerTick();\n }\n\n /**\n * Atomic save: write to .tmp, then POSIX-rename. A crash mid-write leaves\n * either the old file intact or the new file fully written — never a\n * partial JSON that would crash load() on restart.\n */\n private async save(): Promise<void> {\n const state: PersistedState = {\n nonces: Object.fromEntries(this.nonces),\n placedCloids: Object.fromEntries(\n [...this.placedCloids].map(([tok, cloids]) => [tok, cloids.map((c) => c.toString())]),\n ),\n };\n await mkdir(dirname(this.statePath), { recursive: true });\n const tmp = this.statePath + '.tmp';\n await writeFile(tmp, JSON.stringify(state, null, 2));\n await rename(tmp, this.statePath);\n }\n\n /**\n * Execute the order plan: cancel stale orders for rebalanced tokens, then\n * place new orders. Each (token) is one tx. Persists state after each tx\n * so a crash mid-execution still leaves a recoverable on-disk record.\n *\n * Concurrency-guarded: a second concurrent call returns immediately rather\n * than racing tx submission against another in-flight execute().\n */\n async execute(plan: GridOrderPlan): Promise<{ placed: number; cancelled: number; txs: Hex[]; errors: string[] }> {\n if (this.busy) {\n return { placed: 0, cancelled: 0, txs: [], errors: ['execute() already in flight — skipping'] };\n }\n this.busy = true;\n try {\n if (!this.meta) await this.load();\n\n const errors: string[] = [];\n const txs: Hex[] = [];\n let placed = 0;\n let cancelled = 0;\n\n const ordersByToken = new Map<string, GridOrderPlan['ordersToPlace']>();\n for (const o of plan.ordersToPlace) {\n if (!ordersByToken.has(o.token)) ordersByToken.set(o.token, []);\n ordersByToken.get(o.token)!.push(o);\n }\n const cancelSet = new Set(plan.assetsToCancel);\n const allTokens = new Set([...ordersByToken.keys(), ...cancelSet]);\n\n for (const token of allTokens) {\n const assetIndex = this.cfg.assetIndices[token];\n if (assetIndex === undefined) {\n errors.push(`No asset index for ${token}`);\n continue;\n }\n const coin = resolveHLCoin(token);\n if (!coin) {\n errors.push(`No HL ticker for ${token}`);\n continue;\n }\n const meta = this.meta!.get(coin);\n if (!meta) {\n errors.push(`No HL meta for ${coin} (run \\`sherwood grid status\\` to refresh)`);\n continue;\n }\n\n const wantCancel = cancelSet.has(token);\n const orders = ordersByToken.get(token) ?? [];\n const wantPlace = orders.length > 0;\n\n try {\n if (wantCancel && wantPlace) {\n const txArr = await this.cancelAndPlace(token, assetIndex, orders, meta);\n txs.push(...txArr);\n cancelled += 1;\n placed += orders.length;\n } else if (wantCancel) {\n const tx = await this.cancelAll(token, assetIndex);\n txs.push(tx);\n cancelled += 1;\n } else if (wantPlace) {\n const txArr = await this.placeGrid(token, assetIndex, orders, meta);\n txs.push(...txArr);\n placed += orders.length;\n }\n await this.save();\n } catch (e) {\n errors.push(`${token}: ${(e as Error).message}`);\n }\n }\n\n return { placed, cancelled, txs, errors };\n } finally {\n this.busy = false;\n }\n }\n\n private currentNonce(token: string): number {\n return this.nonces.get(token) ?? 0;\n }\n\n private bumpNonce(token: string): number {\n const next = this.currentNonce(token) + 1;\n this.nonces.set(token, next);\n return next;\n }\n\n /**\n * Pure encoding — does NOT mutate placedCloids. Caller commits CLOIDs\n * only after the on-chain tx confirms successfully.\n *\n * Uses viem's `parseUnits` for decimal scaling instead of float math so\n * high-szDecimals tokens (BTC=5, ETH=4) keep full precision on small sizes.\n */\n private encodeOrders(\n assetIndex: number,\n orders: GridOrderPlan['ordersToPlace'],\n meta: HLAssetMeta,\n nonce: number,\n ): { encoded: EncodedOrder[]; cloids: bigint[] } {\n const cloids: bigint[] = [];\n const encoded = orders.map((o, i) => {\n const cloid = gridCloid(this.cfg.strategyAddress, assetIndex, o.isBuy, i, nonce);\n cloids.push(cloid);\n // parseUnits uses string scaling — no float-rounding precision loss.\n const limitPx = parseUnits(o.price.toFixed(meta.pxDecimals), meta.pxDecimals);\n const sz = parseUnits(o.quantity.toFixed(meta.szDecimals), meta.szDecimals);\n // Defensive uint64 bound check — parseUnits returns uint256 but the\n // strategy contract reads uint64.\n if (limitPx > UINT64_MAX || sz > UINT64_MAX) {\n throw new Error(\n `Order exceeds uint64: token=${o.token} px=${limitPx} sz=${sz}`,\n );\n }\n return { assetIndex, isBuy: o.isBuy, limitPx, sz, cloid };\n });\n return { encoded, cloids };\n }\n\n /**\n * Place orders, chunking into batches of ≤ maxOrdersPerTick per tx.\n * Each chunk uses its own nonce so CLOIDs stay unique across chunks.\n * placedCloids is committed once after the last chunk lands; if any\n * chunk reverts, the partial cloids stay tracked via the per-chunk save.\n */\n private async placeGrid(\n token: string,\n assetIndex: number,\n orders: GridOrderPlan['ordersToPlace'],\n meta: HLAssetMeta,\n ): Promise<Hex[]> {\n const max = await this.fetchMaxOrdersPerTick();\n const chunks = chunkArray(orders, max);\n const txs: Hex[] = [];\n const allCloids: bigint[] = [...(this.placedCloids.get(token) ?? [])];\n for (const chunk of chunks) {\n const nonce = this.bumpNonce(token);\n const { encoded, cloids } = this.encodeOrders(assetIndex, chunk, meta, nonce);\n const data = encodeAbiParameters(\n [{ type: 'uint8' }, { type: 'tuple[]', components: [...GRID_ORDER_COMPONENTS] }],\n [ACTION_PLACE_GRID, encoded],\n );\n const tx = await this.send(data); // throws if reverts\n txs.push(tx);\n allCloids.push(...cloids);\n this.placedCloids.set(token, allCloids); // commit incrementally so cancel-on-restart sees what landed\n await this.save();\n }\n return txs;\n }\n\n private async cancelAll(token: string, assetIndex: number): Promise<Hex> {\n const cloids = this.placedCloids.get(token) ?? [];\n if (cloids.length === 0) {\n // Nothing tracked — nothing to cancel. Still bump nonce for consistency.\n this.bumpNonce(token);\n return '0x' as Hex;\n }\n const data = encodeAbiParameters(\n [{ type: 'uint8' }, { type: 'uint32' }, { type: 'uint128[]' }],\n [ACTION_CANCEL_ALL, assetIndex, cloids],\n );\n const tx = await this.send(data); // throws if reverts\n this.placedCloids.set(token, []); // commit only on success\n this.bumpNonce(token);\n return tx;\n }\n\n /**\n * Atomic cancel-old + place-new on rebalance. When `orders` exceeds\n * maxOrdersPerTick, the first chunk uses ACTION_CANCEL_AND_PLACE (so the\n * old orders are cleared in the same tx as the first wave of new orders);\n * subsequent chunks use ACTION_PLACE_GRID. Atomicity holds for chunk #1;\n * after that there's a brief window where some new orders are live before\n * the rest are placed — acceptable for a 60s rebuild cycle.\n */\n private async cancelAndPlace(\n token: string,\n assetIndex: number,\n orders: GridOrderPlan['ordersToPlace'],\n meta: HLAssetMeta,\n ): Promise<Hex[]> {\n const max = await this.fetchMaxOrdersPerTick();\n const chunks = chunkArray(orders, max);\n const oldCloids = this.placedCloids.get(token) ?? [];\n const txs: Hex[] = [];\n const allNewCloids: bigint[] = [];\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i]!;\n const newNonce = this.bumpNonce(token);\n const { encoded, cloids } = this.encodeOrders(assetIndex, chunk, meta, newNonce);\n let data: Hex;\n if (i === 0) {\n // First chunk swaps old → new in one tx.\n data = encodeAbiParameters(\n [\n { type: 'uint8' },\n { type: 'uint32' },\n { type: 'uint128[]' },\n { type: 'tuple[]', components: [...GRID_ORDER_COMPONENTS] },\n ],\n [ACTION_CANCEL_AND_PLACE, assetIndex, oldCloids, encoded],\n );\n } else {\n data = encodeAbiParameters(\n [{ type: 'uint8' }, { type: 'tuple[]', components: [...GRID_ORDER_COMPONENTS] }],\n [ACTION_PLACE_GRID, encoded],\n );\n }\n const tx = await this.send(data); // throws if reverts\n txs.push(tx);\n allNewCloids.push(...cloids);\n // After chunk #0 the old cloids are already cancelled on-chain — record\n // only the new cloids that have landed so far.\n this.placedCloids.set(token, [...allNewCloids]);\n await this.save();\n }\n return txs;\n }\n\n /**\n * Cancel every tracked CLOID across all configured tokens. Used by\n * `sherwood grid flatten` to wind the strategy down to a no-orders state\n * without placing anything new.\n *\n * Per-token errors are captured and returned rather than thrown — partial\n * progress is the expected outcome when one token reverts (e.g. nonce\n * desync after a manual on-chain action). Each successful cancel saves\n * before moving on, so a crash mid-flatten leaves a consistent on-disk\n * record of which tokens still hold cloids.\n */\n async flattenAll(): Promise<{ txs: Hex[]; cancelled: string[]; skipped: string[]; errors: string[] }> {\n if (this.busy) {\n return { txs: [], cancelled: [], skipped: [], errors: ['flattenAll() called while another execute()/flattenAll() is in flight'] };\n }\n this.busy = true;\n try {\n // Disk-only load — flatten must succeed even when chain meta / RPC are\n // unhealthy. The actual send() call below still needs RPC, but the init\n // path no longer aborts on a flaky HL HTTP endpoint or strategy read.\n await this.loadFromDisk();\n\n const txs: Hex[] = [];\n const cancelled: string[] = [];\n const skipped: string[] = [];\n const errors: string[] = [];\n\n // cancelAll is the single source of truth for the empty-cloid path:\n // it returns '0x' (no tx) and bumps nonce when there's nothing to\n // cancel. We use that return value to drive the skip set rather than\n // pre-filtering — keeps both call sites consistent.\n for (const [token, assetIndex] of Object.entries(this.cfg.assetIndices)) {\n try {\n const tx = await this.cancelAll(token, assetIndex);\n if (tx === '0x') {\n skipped.push(token);\n } else {\n txs.push(tx);\n cancelled.push(token);\n }\n await this.save();\n } catch (e) {\n errors.push(`${token}: ${(e as Error).message}`);\n }\n }\n\n return { txs, cancelled, skipped, errors };\n } finally {\n this.busy = false;\n }\n }\n\n /**\n * Submit and wait for receipt. Throwing here surfaces to the per-token\n * try/catch in execute(), recording the error and skipping the save() so\n * placedCloids never reflects orders that didn't land.\n */\n private async send(data: Hex): Promise<Hex> {\n const tx = await writeContractWithRetry({\n address: this.cfg.strategyAddress,\n abi: HYPERLIQUID_GRID_STRATEGY_ABI,\n functionName: 'updateParams',\n args: [data],\n });\n const pub = getPublicClient();\n const receipt = await pub.waitForTransactionReceipt({ hash: tx, timeout: 30_000 });\n if (receipt.status !== 'success') {\n throw new Error(`Tx ${tx} reverted on-chain`);\n }\n console.error(chalk.dim(` [grid-onchain] tx ${tx.slice(0, 10)}... confirmed`));\n return tx;\n }\n}\n","/**\n * Deterministic CLOID generator for grid orders.\n *\n * CLOID = uint128 = keccak256(strategy, assetIndex, isBuy, levelIndex, nonce)[0:16]\n *\n * Including the strategy address namespaces CLOIDs per-deployment so two\n * grid strategies running on the same HL account can't collide.\n *\n * The nonce is per-grid-rebuild — increments when a token's grid is\n * rebuilt/shifted, making prior CLOIDs stale (so `cancel-all` for a token\n * uses the OLD nonce's CLOIDs).\n */\n\nimport { keccak256, encodeAbiParameters, type Address } from 'viem';\n\nexport function gridCloid(\n strategy: Address,\n assetIndex: number,\n isBuy: boolean,\n levelIndex: number,\n nonce: number,\n): bigint {\n const hash = keccak256(\n encodeAbiParameters(\n [\n { type: 'address' },\n { type: 'uint32' },\n { type: 'bool' },\n { type: 'uint32' },\n { type: 'uint32' },\n ],\n [strategy, assetIndex, isBuy, levelIndex, nonce],\n ),\n );\n // Take the high 16 bytes as uint128.\n // keccak256 already returns `0x${string}` — no cast needed.\n const top16 = hash.slice(0, 2 + 32); // '0x' + 32 hex chars = 16 bytes\n return BigInt(top16);\n}\n","/**\n * Grid backtester — replays historical Hyperliquid 1-minute bars through\n * the existing GridManager and reports PnL, fills, drawdown.\n *\n * Uses Approach 2 from the design spec: a separate orchestrator that\n * reuses GridManager via injected dependencies (candle fetcher, fill\n * detectors, in-memory portfolio). Live mode is untouched.\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { homedir } from 'node:os';\nimport { createHash } from 'node:crypto';\nimport { GridManager, type CandleFetcher } from './manager.js';\nimport { BacktestPortfolio } from './backtest-portfolio.js';\nimport { HistoricalDataLoader, type Bar1m, type AtrPoint } from './historical-data-loader.js';\nimport { type GridConfig } from './config.js';\nimport { BacktestHedgeManager } from './backtest-hedge.js';\n\nconst DEFAULT_OUT_DIR = join(homedir(), '.sherwood', 'grid', 'backtests');\n\nexport interface BacktestOpts {\n fromMs: number;\n toMs: number;\n capital: number;\n config: GridConfig;\n /** Equity-curve snapshot cadence in simulated minutes. Default 60. */\n snapshotEveryMinutes?: number;\n /** When true, re-enables the manager's chalk console.error logs. */\n verbose?: boolean;\n /** When true, skips cache for fetch. */\n noCache?: boolean;\n /** Override the default JSON output path. */\n outPath?: string;\n /** Inject for tests — defaults to a real HistoricalDataLoader. */\n loader?: HistoricalDataLoader;\n /** Trading fee in basis points per fill. Default 5 (typical maker). */\n feeBps?: number;\n /** Simulate the GridHedgeManager. Default true (matches live grid). */\n hedge?: boolean;\n}\n\nexport interface EquityPoint {\n t: number;\n totalAllocation: number;\n totalPnl: number;\n totalRoundTrips: number;\n openFillCount: number;\n paused: boolean;\n}\n\nexport interface BacktestResult {\n runId: string;\n startedAt: number;\n finishedAt: number;\n durationMs: number;\n window: {\n fromMs: number;\n toMs: number;\n fromIso: string;\n toIso: string;\n days: number;\n };\n config: GridConfig;\n capital: {\n initialUsd: number;\n finalUsd: number;\n pnlUsd: number; // NET of fees\n pnlPct: number; // NET of fees\n grossPnlUsd: number; // before fees (= old pnlUsd value)\n };\n fees: {\n bps: number;\n totalUsd: number;\n perFill: number; // avg fee per fill in USD (across tokens, weighted)\n };\n hedge: {\n enabled: boolean;\n realizedPnlUsd: number;\n unrealizedPnlUsd: number; // at end of run\n adjustments: number; // total hedge adjustments across the run\n finalOpenPositions: number; // count of open shorts at end\n };\n liquidations: {\n /** Per-token liquidation events. */\n events: Array<{\n token: string;\n timestamp: number;\n tokenAllocation: number;\n unrealizedPnlAtLiquidation: number;\n thresholdUsd: number;\n }>;\n /** When all configured tokens are liquidated, the run terminates here. Null if not all liquidated. */\n haltedAt: number | null;\n };\n totals: {\n roundTrips: number;\n fills: number;\n rebuilds: number;\n pausedSteps: number;\n skippedSteps: number;\n totalSteps: number;\n };\n perToken: Array<{\n token: string;\n allocation: { initial: number; final: number };\n roundTrips: number;\n fills: number;\n pnlUsd: number;\n rebuilds: number;\n }>;\n drawdown: {\n maxUsd: number;\n maxPct: number;\n peakAt: number;\n troughAt: number;\n };\n equityCurve: EquityPoint[];\n}\n\n/** Compute a deterministic 8-char hash from window+config for run ID. */\nexport function shortHash(input: { fromMs: number; toMs: number; config: GridConfig }): string {\n const h = createHash('sha256').update(JSON.stringify(input)).digest('hex');\n return h.slice(0, 8);\n}\n\n/** Compute peak-to-trough drawdown from an equity curve. */\nexport function computeDrawdown(curve: EquityPoint[]): BacktestResult['drawdown'] {\n if (curve.length === 0) {\n return { maxUsd: 0, maxPct: 0, peakAt: 0, troughAt: 0 };\n }\n const equityAt = (p: EquityPoint) => p.totalAllocation + p.totalPnl;\n let peak = equityAt(curve[0]!);\n let peakAt = curve[0]!.t;\n let maxDrop = 0;\n let dropPeakAt = peakAt;\n let dropTroughAt = peakAt;\n for (const point of curve) {\n const eq = equityAt(point);\n if (eq > peak) {\n peak = eq;\n peakAt = point.t;\n }\n const drop = peak - eq;\n if (drop > maxDrop) {\n maxDrop = drop;\n dropPeakAt = peakAt;\n dropTroughAt = point.t;\n }\n }\n const peakPoint = curve.find(p => p.t === dropPeakAt);\n const peakValue = peakPoint ? equityAt(peakPoint) : 0;\n return {\n maxUsd: maxDrop,\n maxPct: peakValue > 0 ? maxDrop / peakValue : 0,\n peakAt: dropPeakAt,\n troughAt: dropTroughAt,\n };\n}\n\nfunction isoToYmdHms(ms: number): string {\n const d = new Date(ms);\n const pad = (n: number) => n.toString().padStart(2, '0');\n return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}-${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`;\n}\n\nexport function makeRunId(fromMs: number, toMs: number, config: GridConfig): string {\n return `bt-${isoToYmdHms(Date.now())}-${shortHash({ fromMs, toMs, config })}`;\n}\n\n/**\n * Run a backtest. Returns the structured result; also writes JSON to disk\n * unless outPath is the empty string ''.\n */\nexport async function runBacktest(opts: BacktestOpts): Promise<BacktestResult> {\n const startedAt = Date.now();\n\n // Validation\n if (opts.fromMs >= opts.toMs) throw new Error('--from must be before --to');\n const FIFTY_SIX_HOURS = 56 * 60 * 60 * 1000;\n if (opts.toMs - opts.fromMs < FIFTY_SIX_HOURS) {\n throw new Error('window too short — need ≥ 56h for ATR(14) warmup');\n }\n const splitSum = Object.values(opts.config.tokenSplit).reduce((a, b) => a + b, 0);\n if (Math.abs(splitSum - 1.0) > 1e-6) {\n throw new Error(`tokenSplit must sum to 1.0, got ${splitSum.toFixed(6)}`);\n }\n\n const loader = opts.loader ?? new HistoricalDataLoader({ noCache: opts.noCache });\n const snapshotEvery = opts.snapshotEveryMinutes ?? 60;\n\n // Load all token series in parallel\n const seriesByToken: Record<string, { minutes: Bar1m[]; fourHour: Bar1m[]; atrSeries: AtrPoint[] }> = {};\n await Promise.all(opts.config.tokens.map(async token => {\n seriesByToken[token] = await loader.load(token, opts.fromMs, opts.toMs);\n }));\n\n // Build unified timeline: minutes present in ALL token series\n const minuteSets = opts.config.tokens.map(t => new Set(seriesByToken[t]!.minutes.map(b => b.t)));\n const masterMinutes = seriesByToken[opts.config.tokens[0]!]!.minutes;\n const sharedTimestamps: number[] = [];\n let skippedSteps = 0;\n for (const bar of masterMinutes) {\n if (bar.t < opts.fromMs || bar.t >= opts.toMs) continue;\n if (minuteSets.every(s => s.has(bar.t))) {\n sharedTimestamps.push(bar.t);\n } else {\n skippedSteps++;\n }\n }\n\n if (sharedTimestamps.length === 0) {\n throw new Error('no overlapping bars across requested tokens');\n }\n\n // Index lookup: token → timestamp → bar\n const barIndex: Record<string, Map<number, Bar1m>> = {};\n for (const token of opts.config.tokens) {\n const m = new Map<number, Bar1m>();\n for (const bar of seriesByToken[token]!.minutes) m.set(bar.t, bar);\n barIndex[token] = m;\n }\n\n // Backtest clock injection\n let currentT = sharedTimestamps[0]!;\n const nowProvider = () => currentT;\n\n // Candle fetcher: returns 4h bars whose close ts ≤ currentT (point-in-time correct)\n const candleFetcher: CandleFetcher = async (tokenId, interval, lookbackMs) => {\n if (interval !== '4h') return null;\n const series = seriesByToken[tokenId];\n if (!series) return null;\n const cutoff = currentT - lookbackMs;\n return series.fourHour\n .filter(b => b.t <= currentT && b.t >= cutoff)\n .map(b => ({\n timestamp: b.t,\n open: b.o,\n high: b.h,\n low: b.l,\n close: b.c,\n volume: b.v,\n }));\n };\n\n // Construct manager with default close-only detectors. HLC fills are\n // implemented via TWO-PASS TICK: each step calls manager.tick twice\n // — once with bar.low (triggers buys), once with bar.high (triggers\n // sells + closes opens). Default close-only detector then fires at\n // the right times. No per-token detector context required.\n const portfolio = new BacktestPortfolio(nowProvider);\n const manager = new GridManager(opts.config, candleFetcher, undefined, undefined, portfolio, nowProvider);\n\n // Initialize portfolio with starting capital\n await manager.init(opts.capital);\n\n // Snapshot initial per-token allocation. Used only for fee notional\n // approximation (notionalPerFillByToken). Allocation compounding is now\n // live — grid.allocation += profit each step, matching live-mode behavior.\n // (Fee approx slightly understates fees as allocation compounds upward;\n // acceptable for v1 and can be refined later.)\n const initialAllocations: Record<string, number> = {};\n {\n const initState = portfolio.getState();\n if (initState) {\n for (const grid of initState.grids) {\n initialAllocations[grid.token] = grid.allocation;\n }\n }\n }\n\n // Pre-compute per-token notional-per-fill (used for running fee accrual)\n const feeBps = opts.feeBps ?? 5;\n const notionalPerFillByToken: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n const tokenInitial = initialAllocations[token] ?? 0;\n notionalPerFillByToken[token] = (tokenInitial * opts.config.leverage) / opts.config.levelsPerSide;\n }\n\n // Running fee accumulators (kept in sync with equity curve)\n const feesByToken: Record<string, number> = {};\n for (const token of opts.config.tokens) feesByToken[token] = 0;\n const lastSeenFills: Record<string, number> = {};\n for (const token of opts.config.tokens) lastSeenFills[token] = 0;\n\n const hedgeEnabled = opts.hedge ?? true;\n const hedge = new BacktestHedgeManager(nowProvider);\n let hedgeAdjustments = 0;\n let hedgeRealized = 0;\n let hedgeUnrealized = 0;\n\n // Track rebuild count via portfolio state (manager updates grid.stats.lastRebalanceAt)\n let totalRebuilds = 0;\n const lastRebalanceAt: Record<string, number> = {};\n for (const t of opts.config.tokens) lastRebalanceAt[t] = 0;\n\n // Liquidation tracking. A token is liquidated when its unrealized PnL\n // exceeds the calibrated maintenance threshold; once liquidated, the\n // token's grid is frozen (existing opens cleared as realized losses, no\n // new fills allowed). When all tokens are liquidated the run halts.\n const liquidatedTokens = new Set<string>();\n const liquidationEvents: BacktestResult['liquidations']['events'] = [];\n let haltedAt: number | null = null;\n\n // Equity curve\n const equityCurve: EquityPoint[] = [];\n let pausedSteps = 0;\n\n // Silence manager's chalk logs unless verbose\n const originalConsoleError = console.error;\n if (!opts.verbose) {\n console.error = () => {};\n }\n\n try {\n let cycleCount = 0;\n const totalSteps = sharedTimestamps.length;\n const decileSize = Math.max(1, Math.floor(totalSteps / 10));\n\n for (const t of sharedTimestamps) {\n currentT = t;\n\n // Per-token pass order inferred from bar color (option B):\n // green (close >= open): price went low → high → buy fills (Pass 1=low),\n // then close-outs may fire on the way up (Pass 2=high) — same-bar\n // round trip is realistic.\n // red (close < open): price went high → low → close-outs fire first\n // (Pass 1=high) on pre-existing opens. New buys from Pass 2=low can't\n // close this bar because low < target — no same-bar round trip.\n // Doji (close == open) treated as green.\n const passAPrices: Record<string, number> = {};\n const passBPrices: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n const bar = barIndex[token]!.get(t)!;\n const isGreen = bar.c >= bar.o;\n passAPrices[token] = isGreen ? bar.l : bar.h;\n passBPrices[token] = isGreen ? bar.h : bar.l;\n }\n\n const r1 = await manager.tick(passAPrices);\n const r2 = await manager.tick(passBPrices);\n\n // Detect rebuilds — manager updates grid.stats.lastRebalanceAt\n const stateAfter = portfolio.getState();\n if (stateAfter) {\n for (const grid of stateAfter.grids) {\n if (grid.stats.lastRebalanceAt > lastRebalanceAt[grid.token]!) {\n totalRebuilds++;\n lastRebalanceAt[grid.token] = grid.stats.lastRebalanceAt;\n }\n }\n }\n\n if (r1.paused || r2.paused) pausedSteps++;\n\n // Hedge tick: uses bar.close prices and the manager's open-fill exposure.\n if (hedgeEnabled) {\n const hedgePrices: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n const bar = barIndex[token]!.get(t)!;\n hedgePrices[token] = bar.c;\n }\n const exposure = manager.getOpenFillExposure();\n const marketTrend = manager.getMarketTrend();\n const hedgeResult = await hedge.tick(exposure, hedgePrices, t, marketTrend, stateAfter?.paused ?? false);\n hedgeAdjustments += hedgeResult.adjustments;\n hedgeRealized = hedgeResult.totalRealizedPnl;\n hedgeUnrealized = hedgeResult.unrealizedPnl;\n }\n\n // Accrue per-step fees: any new fills this step pay notionalPerFill × bps / 10_000\n if (stateAfter) {\n for (const grid of stateAfter.grids) {\n const newFills = grid.stats.totalFills - lastSeenFills[grid.token]!;\n if (newFills > 0) {\n feesByToken[grid.token]! += newFills * (notionalPerFillByToken[grid.token] ?? 0) * feeBps / 10_000;\n lastSeenFills[grid.token] = grid.stats.totalFills;\n }\n }\n }\n\n // Liquidation check: per token, sum unrealized PnL on its open fills\n // and compare against the calibrated threshold.\n // Threshold is in the backtester's overstated unrealized-PnL units (see\n // the leverage double-count caveat).\n const stateLiq = portfolio.getState();\n if (stateLiq && haltedAt === null) {\n const lev = opts.config.leverage;\n const maint = opts.config.maintenanceMarginPct;\n // Now that the manager's PnL formula no longer double-counts leverage,\n // unrealized in this loop is the REAL dollar PnL. Threshold drops\n // by a factor of leverage vs. the previous (overstated) calibration:\n // real-world liquidation at (1/lev - maint) adverse move →\n // unrealized loss = allocation - allocation × lev × maint\n // = allocation × (1 - lev × maint).\n const liquidationCoefficient = 1 - lev * maint;\n for (const grid of stateLiq.grids) {\n if (liquidatedTokens.has(grid.token)) continue;\n const close = barIndex[grid.token]?.get(t)?.c;\n if (close === undefined) continue;\n let unrealized = 0;\n for (const f of grid.openFills) {\n if (f.closed) continue;\n unrealized += (close - f.buyPrice) * f.quantity;\n }\n const tokenAlloc = initialAllocations[grid.token] ?? 0;\n const threshold = -tokenAlloc * liquidationCoefficient;\n if (tokenAlloc > 0 && unrealized <= threshold) {\n // Realize the loss and freeze the grid for this token.\n grid.stats.totalPnlUsd += unrealized;\n grid.stats.todayPnlUsd += unrealized;\n grid.allocation += unrealized; // bookkeeping; allocation now near-zero\n for (const f of grid.openFills) {\n if (!f.closed) {\n f.closed = true;\n f.closedAt = t;\n f.pnlUsd = (close - f.buyPrice) * f.quantity;\n }\n }\n // Drop the level grid so manager doesn't fire new fills\n grid.levels = [];\n liquidatedTokens.add(grid.token);\n liquidationEvents.push({\n token: grid.token,\n timestamp: t,\n tokenAllocation: tokenAlloc,\n unrealizedPnlAtLiquidation: unrealized,\n thresholdUsd: threshold,\n });\n // Stderr notice (always, not gated on verbose — this is a serious event)\n process.stderr.write(\n ` [backtest] LIQUIDATED ${grid.token} at t=${new Date(t).toISOString()}: unrealized=$${unrealized.toFixed(0)} (threshold=$${threshold.toFixed(0)})\\n`\n );\n }\n }\n // If all configured tokens are liquidated, halt the run\n if (liquidatedTokens.size === opts.config.tokens.length) {\n haltedAt = t;\n process.stderr.write(` [backtest] All tokens liquidated; halting run at t=${new Date(t).toISOString()}\\n`);\n }\n }\n\n if (haltedAt !== null) {\n // Capture a final snapshot at halt, then break\n const sFinal = portfolio.getState();\n if (sFinal) {\n const aggFinal = portfolio.aggregateStats(sFinal);\n const ofcFinal = sFinal.grids.reduce((sum, g) => sum + g.openFills.filter(f => !f.closed).length, 0);\n const runningFeesFinal = Object.values(feesByToken).reduce((a, b) => a + b, 0);\n equityCurve.push({\n t,\n totalAllocation: sFinal.totalAllocation,\n totalPnl: aggFinal.totalPnlUsd - runningFeesFinal + hedgeRealized + hedgeUnrealized,\n totalRoundTrips: aggFinal.totalRoundTrips,\n openFillCount: ofcFinal,\n paused: sFinal.paused,\n });\n }\n break;\n }\n\n // Snapshot\n cycleCount++;\n if (cycleCount % snapshotEvery === 0 || cycleCount === totalSteps) {\n const s = portfolio.getState();\n if (s) {\n const agg = portfolio.aggregateStats(s);\n const openFillCount = s.grids.reduce(\n (sum, g) => sum + g.openFills.filter(f => !f.closed).length,\n 0,\n );\n // Mark open positions to market at the current bar's close.\n // Without this, drawdown is always 0 because the grid only books\n // realized PnL on profitable closes — open underwater buys never\n // show up in equity.\n let unrealizedPnl = 0;\n for (const grid of s.grids) {\n const close = barIndex[grid.token]?.get(t)?.c;\n if (close === undefined) continue;\n for (const f of grid.openFills) {\n if (f.closed) continue;\n // quantity already leveraged — see manager.simulateFills note.\n unrealizedPnl += (close - f.buyPrice) * f.quantity;\n }\n }\n const runningFees = Object.values(feesByToken).reduce((a, b) => a + b, 0);\n equityCurve.push({\n t,\n totalAllocation: s.totalAllocation,\n totalPnl: agg.totalPnlUsd + unrealizedPnl - runningFees + hedgeRealized + hedgeUnrealized,\n totalRoundTrips: agg.totalRoundTrips,\n openFillCount,\n paused: s.paused,\n });\n }\n }\n\n // Progress (10% increments)\n if (cycleCount % decileSize === 0) {\n if (opts.verbose) {\n originalConsoleError(` [backtest] ${Math.round((cycleCount / totalSteps) * 100)}% step ${cycleCount}/${totalSteps}`);\n } else {\n process.stderr.write(` [backtest] ${Math.round((cycleCount / totalSteps) * 100)}% step ${cycleCount}/${totalSteps}\\n`);\n }\n }\n }\n } finally {\n console.error = originalConsoleError;\n }\n\n // Build result\n const finalState = portfolio.getState()!;\n const agg = portfolio.aggregateStats(finalState);\n\n const finishedAt = Date.now();\n const runId = makeRunId(opts.fromMs, opts.toMs, opts.config);\n\n const initialPerToken: Record<string, number> = {};\n for (const token of opts.config.tokens) {\n initialPerToken[token] = opts.capital * (opts.config.tokenSplit[token] ?? 0);\n }\n\n // Fee totals from running accumulators (co-evolves with equity curve)\n const totalFeesUsd = Object.values(feesByToken).reduce((a, b) => a + b, 0);\n const totalFills = finalState.grids.reduce((s, g) => s + g.stats.totalFills, 0);\n const avgFeePerFill = totalFills > 0 ? totalFeesUsd / totalFills : 0;\n\n const grossPnl = agg.totalPnlUsd;\n const netPnl = grossPnl - totalFeesUsd;\n\n const hedgeStatus = hedgeEnabled ? hedge.getStatus() : null;\n const hedgePnl = hedgeRealized + hedgeUnrealized;\n const finalNetPnl = netPnl + hedgePnl;\n\n // Per-token rebuild count not preserved separately; total in totals.rebuilds.\n const perToken = finalState.grids.map(g => ({\n token: g.token,\n allocation: { initial: initialPerToken[g.token] ?? 0, final: g.allocation },\n roundTrips: g.stats.totalRoundTrips,\n fills: g.stats.totalFills,\n pnlUsd: g.stats.totalPnlUsd,\n rebuilds: 0,\n }));\n\n const result: BacktestResult = {\n runId,\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n window: {\n fromMs: opts.fromMs,\n toMs: opts.toMs,\n fromIso: new Date(opts.fromMs).toISOString(),\n toIso: new Date(opts.toMs).toISOString(),\n days: (opts.toMs - opts.fromMs) / (24 * 60 * 60 * 1000),\n },\n config: opts.config,\n capital: {\n initialUsd: opts.capital,\n finalUsd: opts.capital + finalNetPnl,\n pnlUsd: finalNetPnl,\n pnlPct: finalNetPnl / opts.capital,\n grossPnlUsd: grossPnl,\n },\n fees: {\n bps: feeBps,\n totalUsd: totalFeesUsd,\n perFill: avgFeePerFill,\n },\n hedge: {\n enabled: hedgeEnabled,\n realizedPnlUsd: hedgeRealized,\n unrealizedPnlUsd: hedgeUnrealized,\n adjustments: hedgeAdjustments,\n finalOpenPositions: hedgeStatus ? hedgeStatus.positions.length : 0,\n },\n liquidations: {\n events: liquidationEvents,\n haltedAt,\n },\n totals: {\n roundTrips: agg.totalRoundTrips,\n fills: finalState.grids.reduce((s, g) => s + g.stats.totalFills, 0),\n rebuilds: totalRebuilds,\n pausedSteps,\n skippedSteps,\n totalSteps: sharedTimestamps.length,\n },\n perToken,\n drawdown: computeDrawdown(equityCurve),\n equityCurve,\n };\n\n // Write JSON output (skip if outPath is empty string)\n if (opts.outPath !== '') {\n const outPath = opts.outPath ?? join(DEFAULT_OUT_DIR, `${runId}.json`);\n await mkdir(dirname(outPath), { recursive: true });\n await writeFile(outPath, JSON.stringify(result, null, 2), 'utf-8');\n }\n\n return result;\n}\n","/**\n * In-memory portfolio for backtest replays.\n *\n * Subclasses GridPortfolio to inherit the live state-shape semantics\n * (initialize, getState, checkPauseThreshold, aggregateStats) while\n * overriding load/save to skip disk I/O and resetDailyStats to use a\n * backtest clock instead of Date.now().\n */\n\nimport { GridPortfolio } from './portfolio.js';\nimport type { GridPortfolioState } from './config.js';\n\nexport class BacktestPortfolio extends GridPortfolio {\n private nowProvider: () => number;\n private inMemoryState: GridPortfolioState | null = null;\n\n constructor(nowProvider: () => number) {\n super();\n this.nowProvider = nowProvider;\n }\n\n /** Override: never read from disk. Returns the in-memory state. */\n override async load(): Promise<GridPortfolioState | null> {\n return this.inMemoryState;\n }\n\n /** Override: never write to disk. Stores the state in memory. */\n override async save(state: GridPortfolioState): Promise<void> {\n this.inMemoryState = state;\n }\n\n /** Override: read in-memory state instead of parent's private field. */\n override getState(): GridPortfolioState | null {\n return this.inMemoryState;\n }\n\n /** Override: use the injected clock instead of Date.now(). */\n override resetDailyStats(state: GridPortfolioState): boolean {\n return super.resetDailyStats(state, this.nowProvider());\n }\n}\n","/**\n * Historical data loader for the grid backtester.\n *\n * Fetches and caches 1-minute and 4-hour candles from Binance's /api/v3/klines\n * endpoint. Pre-computes ATR(14) for the 4-hour series.\n * Cache lives at ~/.sherwood/grid/backtest-cache/.\n */\n\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { TOKEN_TO_COIN } from '../providers/data/hyperliquid.js';\nimport { calculateATR } from '../agent/technical.js';\n\nconst BINANCE_BASE = 'https://api.binance.com/api/v3/klines';\nconst DEFAULT_CACHE_DIR = join(homedir(), '.sherwood', 'grid', 'backtest-cache');\n\nexport interface Bar1m {\n t: number; // open timestamp ms\n o: number;\n h: number;\n l: number;\n c: number;\n v: number;\n}\n\nexport interface AtrPoint {\n ts: number; // 4h bar close timestamp\n atr: number;\n}\n\nexport interface LoadedSeries {\n minutes: Bar1m[];\n fourHour: Bar1m[];\n atrSeries: AtrPoint[];\n}\n\nexport interface HistoricalDataLoaderOpts {\n cacheDir?: string;\n noCache?: boolean;\n /** Injectable for tests. Default: global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nconst FOUR_HOURS_MS = 4 * 60 * 60 * 1000;\nconst ONE_MIN_MS = 60 * 1000;\nconst ATR_PERIOD = 14;\nconst ATR_WARMUP_MS = ATR_PERIOD * FOUR_HOURS_MS;\nconst MAX_BARS_PER_REQUEST = 1000;\n\n/** Maps HL coin symbol → Binance USDT-spot symbol. */\nconst COIN_TO_BINANCE_SYMBOL: Record<string, string> = {\n BTC: 'BTCUSDT',\n ETH: 'ETHUSDT',\n SOL: 'SOLUSDT',\n ARB: 'ARBUSDT',\n LINK: 'LINKUSDT',\n AAVE: 'AAVEUSDT',\n UNI: 'UNIUSDT',\n DOGE: 'DOGEUSDT',\n};\n\nexport class HistoricalDataLoader {\n private cacheDir: string;\n private noCache: boolean;\n private fetchImpl: typeof fetch;\n\n constructor(opts: HistoricalDataLoaderOpts = {}) {\n this.cacheDir = opts.cacheDir ?? DEFAULT_CACHE_DIR;\n this.noCache = opts.noCache ?? false;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n /**\n * Load 1-minute bars and an aligned ATR(14) series for `coinTokenId`\n * (CoinGecko ID; resolved internally to HL coin symbol).\n *\n * The 4-hour series is fetched with ATR_WARMUP_MS extra prefix so ATR\n * is well-defined at fromMs.\n */\n async load(coinTokenId: string, fromMs: number, toMs: number): Promise<LoadedSeries> {\n const coin = TOKEN_TO_COIN[coinTokenId];\n if (!coin) throw new Error(`Unknown token: ${coinTokenId}`);\n\n const minutes = await this.loadInterval(coin, '1m', fromMs, toMs);\n if (minutes.length === 0) {\n throw new Error(`no data for ${coinTokenId} in window — check symbol mapping or date range`);\n }\n\n const fourHour = await this.loadInterval(coin, '4h', fromMs - ATR_WARMUP_MS, toMs);\n const atrSeries = computeAtrSeries(fourHour);\n\n return { minutes, fourHour, atrSeries };\n }\n\n /** Fetch + cache one interval. Public for unit testing. */\n async loadInterval(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n ): Promise<Bar1m[]> {\n if (!this.noCache) {\n const cached = await this.tryReadCache(coin, interval, fromMs, toMs);\n if (cached) return cached;\n }\n\n const fresh = await this.fetchPaginated(coin, interval, fromMs, toMs);\n if (!this.noCache && fresh.length > 0) {\n await this.writeCache(coin, interval, fromMs, toMs, fresh);\n }\n return fresh;\n }\n\n private async tryReadCache(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n ): Promise<Bar1m[] | null> {\n const path = this.cachePath(coin, interval, fromMs, toMs);\n try {\n const raw = await readFile(path, 'utf-8');\n const parsed = JSON.parse(raw) as { bars: Bar1m[] };\n if (!Array.isArray(parsed.bars)) return null;\n return parsed.bars;\n } catch {\n return null;\n }\n }\n\n private async writeCache(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n bars: Bar1m[],\n ): Promise<void> {\n await mkdir(this.cacheDir, { recursive: true });\n const path = this.cachePath(coin, interval, fromMs, toMs);\n const body = JSON.stringify({\n coin,\n interval,\n fetchedAt: Date.now(),\n bars,\n });\n await writeFile(path, body, 'utf-8');\n }\n\n private cachePath(coin: string, interval: '1m' | '4h', fromMs: number, toMs: number): string {\n return join(this.cacheDir, `${coin}-${interval}-${fromMs}-${toMs}.json`);\n }\n\n /** Paginate Binance klines until we cover [fromMs, toMs]. Dedup on merge. */\n private async fetchPaginated(\n coin: string,\n interval: '1m' | '4h',\n fromMs: number,\n toMs: number,\n ): Promise<Bar1m[]> {\n const intervalMs = interval === '1m' ? ONE_MIN_MS : FOUR_HOURS_MS;\n const pageSpanMs = MAX_BARS_PER_REQUEST * intervalMs;\n const seen = new Set<number>();\n const all: Bar1m[] = [];\n\n let cursor = fromMs;\n while (cursor < toMs) {\n const pageEnd = Math.min(cursor + pageSpanMs, toMs);\n const page = await this.fetchPageWithRetry(coin, interval, cursor, pageEnd);\n if (page.length === 0) break;\n\n for (const bar of page) {\n if (!seen.has(bar.t)) {\n seen.add(bar.t);\n all.push(bar);\n }\n }\n // Advance cursor to one interval past the last bar to avoid re-fetching\n const last = page[page.length - 1]!;\n const next = last.t + intervalMs;\n if (next <= cursor) break; // safety: HL returned older bars than requested\n cursor = next;\n }\n\n all.sort((a, b) => a.t - b.t);\n return all;\n }\n\n private async fetchPageWithRetry(\n coin: string,\n interval: '1m' | '4h',\n startTime: number,\n endTime: number,\n ): Promise<Bar1m[]> {\n const delays = [1000, 2000, 4000];\n let lastErr: Error | null = null;\n for (let attempt = 0; attempt < delays.length + 1; attempt++) {\n try {\n return await this.fetchPage(coin, interval, startTime, endTime);\n } catch (err) {\n lastErr = err as Error;\n if (attempt < delays.length) {\n await sleep(delays[attempt]!);\n }\n }\n }\n throw lastErr ?? new Error('fetchPage failed');\n }\n\n private async fetchPage(\n coin: string,\n interval: '1m' | '4h',\n startTime: number,\n endTime: number,\n ): Promise<Bar1m[]> {\n const symbol = COIN_TO_BINANCE_SYMBOL[coin];\n if (!symbol) throw new Error(`No Binance symbol for coin: ${coin}`);\n\n const url = `${BINANCE_BASE}?symbol=${symbol}&interval=${interval}` +\n `&startTime=${startTime}&endTime=${endTime}&limit=${MAX_BARS_PER_REQUEST}`;\n const res = await this.fetchImpl(url);\n if (!res.ok) throw new Error(`Binance ${res.status}: ${await res.text()}`);\n\n const raw = await res.json() as Array<[\n number, string, string, string, string, string, ...unknown[]\n ]>;\n if (!Array.isArray(raw)) return [];\n\n return raw.map(c => ({\n t: c[0],\n o: Number(c[1]),\n h: Number(c[2]),\n l: Number(c[3]),\n c: Number(c[4]),\n v: Number(c[5]),\n })).filter(b =>\n Number.isFinite(b.o) && Number.isFinite(b.h) && Number.isFinite(b.l) && Number.isFinite(b.c)\n );\n }\n}\n\nfunction computeAtrSeries(fourHourBars: Bar1m[]): AtrPoint[] {\n if (fourHourBars.length < ATR_PERIOD) return [];\n\n const candles = fourHourBars.map(b => ({\n timestamp: b.t,\n open: b.o,\n high: b.h,\n low: b.l,\n close: b.c,\n volume: b.v,\n }));\n\n const atrArr = calculateATR(candles, ATR_PERIOD);\n const out: AtrPoint[] = [];\n for (let i = 0; i < atrArr.length; i++) {\n if (Number.isFinite(atrArr[i]!)) {\n out.push({ ts: fourHourBars[i]!.t, atr: atrArr[i]! });\n }\n }\n return out;\n}\n\n/** Lookup ATR at backtest time `t`. Binary-search; returns last value with ts ≤ t.\n * Returns null if t is before the first available ATR (warmup not satisfied). */\nexport function lookupAtr(series: AtrPoint[], t: number): number | null {\n if (series.length === 0 || t < series[0]!.ts) return null;\n let lo = 0, hi = series.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (series[mid]!.ts <= t) lo = mid; else hi = mid - 1;\n }\n return series[lo]!.atr;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","/**\n * In-memory hedge manager for backtest replays.\n *\n * Subclasses GridHedgeManager so the live tick() logic is reused verbatim;\n * only state I/O and the clock are redirected — load() returns an in-memory\n * state initialized with a backtest-driven `lastDailyReset`, and save() is\n * a no-op.\n */\n\nimport { GridHedgeManager, type HedgeState } from './hedge.js';\n\nexport class BacktestHedgeManager extends GridHedgeManager {\n private nowProvider: () => number;\n private inMemoryState: HedgeState | null = null;\n\n constructor(nowProvider: () => number) {\n super();\n this.nowProvider = nowProvider;\n }\n\n override async load(_now?: number): Promise<HedgeState> {\n if (this.inMemoryState) {\n // Manual daily-reset using injected clock\n const now = this.nowProvider();\n const todayMidnight = new Date(now);\n todayMidnight.setUTCHours(0, 0, 0, 0);\n if (this.inMemoryState.lastDailyReset < todayMidnight.getTime()) {\n this.inMemoryState.todayRealizedPnl = 0;\n this.inMemoryState.lastDailyReset = now;\n }\n // Keep parent's `state` field in sync so getStatus() works.\n (this as unknown as { state: HedgeState | null }).state = this.inMemoryState;\n return this.inMemoryState;\n }\n const now = this.nowProvider();\n this.inMemoryState = {\n positions: [],\n totalRealizedPnl: 0,\n todayRealizedPnl: 0,\n lastDailyReset: now,\n };\n (this as unknown as { state: HedgeState | null }).state = this.inMemoryState;\n return this.inMemoryState;\n }\n\n override async save(): Promise<void> {\n // no-op: state stays in memory\n }\n}\n","/**\n * Parameter sweep for the grid backtester.\n *\n * Runs runBacktest over a Cartesian product of parameter values, sharing\n * one HistoricalDataLoader so the data is fetched once. Useful for\n * comparing leverage / level count / ATR multiplier / drift trade-offs\n * over the same window.\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { createHash } from 'node:crypto';\nimport { runBacktest, type BacktestResult } from './backtest.js';\nimport { HistoricalDataLoader } from './historical-data-loader.js';\nimport { DEFAULT_GRID_CONFIG, type GridConfig } from './config.js';\n\nconst DEFAULT_SWEEP_DIR = join(homedir(), '.sherwood', 'grid', 'sweeps');\n\nexport type SweepableField = 'leverage' | 'levelsPerSide' | 'atrMultiplier' | 'rebalanceDriftPct';\n\nexport interface SweepOpts {\n fromMs: number;\n toMs: number;\n capital: number;\n tokens: string[];\n /** Optional explicit token weights (must sum to 1.0). Defaults to equal weight. */\n tokenSplit?: Record<string, number>;\n /** Base config; sweep params override per run. tokenSplit auto-computed. */\n baseConfig?: Partial<GridConfig>;\n /** Map of sweepable field name → list of values to try. Empty list means use base value. */\n sweep: Partial<Record<SweepableField, number[]>>;\n /** Trading fee bps. Default 5. */\n feeBps?: number;\n /** Output dir for sweep result + per-run files. */\n outDir?: string;\n /** Skip cache for HL fetches. */\n noCache?: boolean;\n /** Print progress per run. Default true. */\n verbose?: boolean;\n}\n\nexport interface SweepRunSummary {\n index: number;\n config: Partial<Record<SweepableField, number>>;\n runId: string;\n resultPath: string;\n capital: { initialUsd: number; finalUsd: number; pnlUsd: number; pnlPct: number; grossPnlUsd: number };\n fees: { bps: number; totalUsd: number };\n totals: { roundTrips: number; fills: number; pausedSteps: number };\n drawdown: { maxUsd: number; maxPct: number };\n /** Net PnL pct divided by max(abs(drawdown pct), 1). Higher = better risk-adjusted. */\n riskAdjusted: number;\n /** True if no full liquidation halt occurred. Per-token liquidations still count as survived if not all tokens died. */\n survived: boolean;\n durationMs: number;\n}\n\nexport interface SweepResult {\n sweepId: string;\n startedAt: number;\n finishedAt: number;\n durationMs: number;\n window: { fromMs: number; toMs: number; days: number };\n tokens: string[];\n capital: number;\n feeBps: number;\n /** Cartesian-product run summaries, sorted by riskAdjusted desc. */\n runs: SweepRunSummary[];\n}\n\n/** Build the Cartesian product of parameter combinations. */\nexport function expandSweep(\n sweep: Partial<Record<SweepableField, number[]>>,\n base: Pick<GridConfig, 'leverage' | 'levelsPerSide' | 'atrMultiplier' | 'rebalanceDriftPct'>,\n): Array<Record<SweepableField, number>> {\n const fields: SweepableField[] = ['leverage', 'levelsPerSide', 'atrMultiplier', 'rebalanceDriftPct'];\n const valueLists: Record<SweepableField, number[]> = {\n leverage: sweep.leverage && sweep.leverage.length > 0 ? sweep.leverage : [base.leverage],\n levelsPerSide: sweep.levelsPerSide && sweep.levelsPerSide.length > 0 ? sweep.levelsPerSide : [base.levelsPerSide],\n atrMultiplier: sweep.atrMultiplier && sweep.atrMultiplier.length > 0 ? sweep.atrMultiplier : [base.atrMultiplier],\n rebalanceDriftPct: sweep.rebalanceDriftPct && sweep.rebalanceDriftPct.length > 0 ? sweep.rebalanceDriftPct : [base.rebalanceDriftPct],\n };\n let combos: Array<Record<SweepableField, number>> = [{} as Record<SweepableField, number>];\n for (const field of fields) {\n const next: Array<Record<SweepableField, number>> = [];\n for (const combo of combos) {\n for (const value of valueLists[field]) {\n next.push({ ...combo, [field]: value });\n }\n }\n combos = next;\n }\n return combos;\n}\n\nfunction makeSweepId(opts: SweepOpts): string {\n const d = new Date();\n const pad = (n: number) => n.toString().padStart(2, '0');\n const stamp = `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}-${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`;\n const hash = createHash('sha256').update(JSON.stringify({\n fromMs: opts.fromMs, toMs: opts.toMs, sweep: opts.sweep, tokens: opts.tokens,\n })).digest('hex').slice(0, 8);\n return `sw-${stamp}-${hash}`;\n}\n\nexport async function runSweep(opts: SweepOpts): Promise<SweepResult> {\n const startedAt = Date.now();\n const sweepId = makeSweepId(opts);\n const outDir = opts.outDir ?? DEFAULT_SWEEP_DIR;\n const sweepDir = join(outDir, sweepId);\n\n // Build tokenSplit (explicit or equal-weight)\n let tokenSplit: Record<string, number>;\n if (opts.tokenSplit) {\n tokenSplit = opts.tokenSplit;\n } else {\n const weight = 1 / opts.tokens.length;\n tokenSplit = {};\n for (const t of opts.tokens) tokenSplit[t] = weight;\n }\n\n // Base config\n const base: GridConfig = {\n ...DEFAULT_GRID_CONFIG,\n ...opts.baseConfig,\n tokens: opts.tokens,\n tokenSplit,\n };\n\n const combos = expandSweep(opts.sweep, base);\n if (combos.length === 0) throw new Error('sweep produced no combinations');\n\n // Share one loader (shared cache)\n const loader = new HistoricalDataLoader({ noCache: opts.noCache });\n\n if (opts.verbose !== false) {\n process.stderr.write(` [sweep] ${sweepId}: running ${combos.length} backtests…\\n`);\n }\n\n await mkdir(sweepDir, { recursive: true });\n\n const runs: SweepRunSummary[] = [];\n for (let i = 0; i < combos.length; i++) {\n const combo = combos[i]!;\n const config: GridConfig = { ...base, ...combo };\n const runOutPath = join(sweepDir, `run-${i.toString().padStart(3, '0')}.json`);\n\n if (opts.verbose !== false) {\n process.stderr.write(` [sweep] [${i + 1}/${combos.length}] ${JSON.stringify(combo)}\\n`);\n }\n\n const result: BacktestResult = await runBacktest({\n fromMs: opts.fromMs,\n toMs: opts.toMs,\n capital: opts.capital,\n config,\n loader,\n noCache: opts.noCache,\n feeBps: opts.feeBps,\n outPath: runOutPath,\n });\n\n const ddPct = Math.abs(result.drawdown.maxPct * 100);\n const pnlPct = result.capital.pnlPct * 100;\n const riskAdjusted = pnlPct / Math.max(ddPct, 1);\n const survived = result.liquidations.haltedAt === null;\n\n runs.push({\n index: i,\n config: combo,\n runId: result.runId,\n resultPath: runOutPath,\n capital: result.capital,\n fees: { bps: result.fees.bps, totalUsd: result.fees.totalUsd },\n totals: {\n roundTrips: result.totals.roundTrips,\n fills: result.totals.fills,\n pausedSteps: result.totals.pausedSteps,\n },\n drawdown: result.drawdown,\n riskAdjusted,\n survived,\n durationMs: result.durationMs,\n });\n }\n\n runs.sort((a, b) => {\n // Survivors first\n if (a.survived !== b.survived) return a.survived ? -1 : 1;\n // Then by risk-adjusted desc\n return b.riskAdjusted - a.riskAdjusted;\n });\n\n const finishedAt = Date.now();\n const sweep: SweepResult = {\n sweepId,\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n window: {\n fromMs: opts.fromMs,\n toMs: opts.toMs,\n days: (opts.toMs - opts.fromMs) / (24 * 60 * 60 * 1000),\n },\n tokens: opts.tokens,\n capital: opts.capital,\n feeBps: opts.feeBps ?? 5,\n runs,\n };\n\n const sweepJsonPath = join(sweepDir, 'sweep.json');\n await writeFile(sweepJsonPath, JSON.stringify(sweep, null, 2), 'utf-8');\n\n return sweep;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,UAAU,kBAAkB;AAErC,SAAS,qBAAqB;AAQ9B,SAAS,SAAS,cAAc;AAChC,SAAS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O,EAAE,CAAC,CAAC;AACrC,UAAQ,IAAI,iBAAiBA,QAAM,KAAK,OAAO,CAAC,WAAW,OAAO,GAAG;AACrE,UAAQ,IAAI,iBAAiB,YAAYA,QAAM,MAAM,SAAS,IAAIA,QAAM,IAAI,SAAS,CAAC,EAAE;AACxF,UAAQ,IAAI,iBAAiB,OAAO,aAAaA,QAAM,MAAM,YAAY,IAAIA,QAAM,IAAI,SAAS,CAAC,EAAE;AACnG,UAAQ,IAAI,iBAAiB,OAAO,WAAWA,QAAM,IAAI,SAAS,CAAC,EAAE;AACrE,UAAQ,IAAI,iBAAiB,UAAU,SAASA,QAAM,IAAI,SAAS,CAAC,EAAE;AACtE,UAAQ,IAAI,iBAAiB,iBAAiB,IAAIA,QAAM,MAAM,oBAAoB,IAAIA,QAAM,IAAI,SAAS,CAAC,EAAE;AAC5G,UAAQ,IAAI,iBAAiB,gBAAgB,IAAIA,QAAM,MAAM,oBAAoB,IAAIA,QAAM,IAAI,SAAS,CAAC,EAAE;AAG3G,QAAM,eAAe,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC;AAChF,MAAI,aAAa,SAAS,GAAG;AAC3B,YAAQ,IAAI;AACZ,YAAQ,IAAIA,QAAM,KAAK,eAAe,CAAC;AACvC,eAAW,CAAC,KAAK,GAAG,KAAK,cAAc;AACrC,cAAQ,IAAI,OAAO,GAAG,KAAKA,QAAM,KAAK,GAAG,CAAC,EAAE;AAAA,IAC9C;AAAA,EACF;AAEA,UAAQ,IAAI;AACZ,UAAQ,IAAIA,QAAM,IAAI,wCAAwC,CAAC;AAC/D,UAAQ,IAAI;AACd,CAAC;AAEH,QAAQ,MAAM;","names":["parseUnits","formatUnits","isAddress","chalk","ora","formatUnits","isAddress","encodeAbiParameters","input","SYNDICATE_VAULT_ABI","ERC20_ABI","getAddress","ERC20_ABI","SYNDICATE_VAULT_ABI","getAddress","getAddress","SYNDICATE_VAULT_ABI","getAddress","SYNDICATE_VAULT_ABI","encodeFunctionData","getAddress","isAddress","ZERO_VALUE","encodeFunctionData","ZERO_ADDRESS","isAddress","getAddress","strategy","encodeFunctionData","encodeFunctionData","getAddress","ZERO_VALUE","getAddress","encodeFunctionData","encodeFunctionData","getAddress","ZERO_ADDRESS","ZERO_VALUE","getAddress","encodeFunctionData","encodeFunctionData","getAddress","ZERO_ADDRESS","registry","getAddress","encodeFunctionData","encodeAbiParameters","encodeFunctionData","getAddress","ZERO_ADDRESS","ZERO_BYTES32","getAddress","encodeFunctionData","encodeAbiParameters","encodeFunctionData","getAddress","ZERO_VALUE","registry","encodeFunctionData","getAddress","getAddress","encodeAbiParameters","encodeFunctionData","encodeAbiParameters","encodeFunctionData","encodeAbiParameters","encodeFunctionData","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","INIT_PARAMS_TYPES","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","maxUint256","INIT_PARAMS_TYPES","buildInitData","encodeAbiParameters","buildExecuteCalls","maxUint256","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","buildInitData","encodeAbiParameters","buildExecuteCalls","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","maxUint256","buildInitData","encodeAbiParameters","buildExecuteCalls","maxUint256","encodeFunctionData","buildSettleCalls","encodeAbiParameters","encodeFunctionData","maxUint256","buildInitData","encodeAbiParameters","buildExecuteCalls","maxUint256","encodeFunctionData","buildSettleCalls","concat","ZERO","encodeAbiParameters","encoded","buildInitData","buildExecuteCalls","buildSettleCalls","strategy","unavailable","isAddress","performanceFeeBps","formatUnits","parseDuration","strategyDuration","executeCalls","settleCalls","metadataURI","pinJSON","propose","getActiveSyndicates","data","formatUnits","isAddress","parseUnits","chalk","ora","program","ora","chalk","formatUnits","getEasScanUrl","parseUnits","isAddress","keccak256","getChainContracts","parseUnits","formatUnits","isAddress","chalk","ora","encodeFunctionData","parseUnits","parseUnits","encodeFunctionData","program","isAddress","chalk","ora","parseUnits","formatUnits","chalk","ora","IDENTITY_REGISTRY_ABI","program","chalk","ora","registry","isAddress","encodeFunctionData","chalk","ora","readFileSync","decodeFunctionData","encodeFunctionData","chalk","erc20Abi","chalk","MOONWELL_CTOKEN_ABI","MOONWELL_COMPTROLLER_ABI","SWAP_ROUTER_SINGLE_ABI","labeledAddr","decodeFunctionData","input","encodeFunctionData","getAccount","G","chalk","W","DIM","BOLD","LABEL","SEP","readFileSync","program","isAddress","strategy","metadataURI","spinner","ora","encodeFunctionData","resolve","chalk","ora","G","chalk","W","DIM","BOLD","LABEL","SEP","ora","program","chalk","ora","formatUnits","isAddress","parseUnits","G","chalk","W","DIM","BOLD","LABEL","SEP","GUARDIAN_REGISTRY_ABI","ERC20_ABI","ora","program","isAddress","formatUnits","parseUnits","chalk","createInterface","chalk","mkdir","dirname","chalk","resolve","chalk","readFile","writeFile","mkdir","dirname","chalk","readFile","mkdir","dirname","writeFile","rename","chalk","chalk","chalk","mkdir","readFile","rename","writeFile","dirname","encodeAbiParameters","parseUnits","keccak256","encodeAbiParameters","strategy","size","readFile","chalk","mkdir","dirname","writeFile","rename","parseUnits","encodeAbiParameters","chalk","resolve","mkdir","dirname","stats","writeFile","mkdir","join","dirname","homedir","readFile","writeFile","mkdir","join","homedir","join","homedir","readFile","mkdir","writeFile","resolve","now","join","homedir","input","agg","mkdir","dirname","writeFile","writeFile","mkdir","join","homedir","createHash","join","homedir","base","createHash","mkdir","writeFile","DIM","chalk","G","BOLD","W","SEP","program","createInterface","require","G","chalk","W","DIM","BOLD","LABEL","SEP","isAddress","spinner","ora","chainId","refParam","getActiveSyndicates","AGENT_REGISTRY","registry","syndicate","referrerAgentId","parseUnits","formatUnits"]}
|