import { Command } from "commander"; import { Commands } from "./commands.js"; import fs from "fs"; import { createRequire } from "module"; import chalk from "chalk"; import { stdin as input, stdout } from "node:process"; import { createInterface } from "readline/promises"; import { unitsToAmount, isP2pUri, ServiceStatusNumber, ServiceRestartParams, } from "@oceanprotocol/lib"; import { parseComputeInput, toBoolean } from "./helpers.js"; import { getCurrentNodeUrl, getCurrentEnvId, hasNode, nodeChainIds, setCurrentNodeUrl, setCurrentEnvId, clearCurrentEnvId, startP2P, validateNode, } from "./nodeConnection.js"; import { buildParamsFromFlags, hasSearchFlags, SearchFlags, } from "./searchResourcesHelpers.js"; import { interactiveResourceSearch } from "./searchResourcesFlow.js"; import { loadRegistry, getActiveChainId, getSigner, parseRpcEnv, getDefaultChainId, setDefaultChainId, resolveDefaultChain, hasChain, listChains, addChain, removeChain, } from "./rpcRegistry.js"; // Commands usable before any Ocean Node is selected. Everything else is refused by the // preAction gate below until `setNode` succeeds. Canonical names only — aliases // (useNode, currentNode, h) resolve to these. const NODE_FREE_COMMANDS = new Set([ "setNode", "setNodeEnv", "getNode", "help", // A network-wide DHT search — a natural way to *find* a node to select, so it must work // before `setNode` picks one. "searchComputeResources", // Chain/RPC management is independent of the node and must work before one is chosen. "addChain", "removeChain", "listChains", "setChain", "getChain", ]); // Topic grouping for the help listing. Purely presentational: it only changes how the command // list is printed (`help`, bare `--help`, and the no-arg startup banner), never behavior. Names // are canonical (aliases are looked up and shown from each command). `assertHelpGroupsCoverAll` // keeps this in lockstep with the registered commands, so adding a command without grouping it // fails at startup rather than dropping it silently from help. interface HelpSubgroup { subheading: string; commands: string[]; } interface HelpGroup { heading: string; commands?: string[]; subgroups?: HelpSubgroup[]; } const HELP_GROUPS: HelpGroup[] = [ { heading: "Node & session", commands: ["setNode", "setNodeEnv", "getNode", "help"], }, { heading: "Discover compute providers", commands: ["searchComputeResources", "getComputeEnvironments"], }, { heading: "Chains & RPC", commands: [ "addChain", "removeChain", "listChains", "setChain", "getChain", ], }, { heading: "Assets — publish, edit, consume", commands: ["publish", "publishAlgo", "editAsset", "allowAlgo", "getDDO", "download"], }, { heading: "Compute", subgroups: [ { subheading: "Jobs (C2D)", commands: [ "startCompute", "startFreeCompute", "getJobStatus", "computeStreamableLogs", "downloadJobResults", "stopCompute", ], }, { subheading: "Services on demand", commands: [ "getServiceTemplates", "startService", "getServiceStatus", "getServices", "serviceLogs", "extendService", "restartService", "stopService", ], }, ], }, { heading: "Tokens & auth", commands: ["mintOcean", "generateAuthToken", "invalidateAuthToken"], }, { heading: "Escrow payments", commands: [ "depositEscrow", "getUserFundsEscrow", "withdrawFromEscrow", "authorizeEscrow", "getAuthorizationsEscrow", ], }, { heading: "Access lists", commands: [ "createAccessList", "addToAccessList", "checkAccessList", "removeFromAccessList", ], }, { heading: "Persistent storage (buckets)", commands: [ "createBucket", "addFileToBucket", "listBuckets", "listFilesInBucket", "getFileObject", "deleteFile", ], }, { heading: "Admin", commands: ["downloadNodeLogs"] }, ]; // Every command name mentioned across all groups/subgroups, in listing order. function groupedCommandNames(): string[] { const names: string[] = []; for (const g of HELP_GROUPS) { for (const n of g.commands ?? []) names.push(n); for (const s of g.subgroups ?? []) names.push(...s.commands); } return names; } // Fail fast if the groups drift from the registered commands: a command in no group (would // vanish from help), one grouped twice, or a group naming a command that no longer exists. function assertHelpGroupsCoverAll(program: Command): void { const grouped = groupedCommandNames(); const dupes = [...new Set(grouped.filter((n, i) => grouped.indexOf(n) !== i))]; const registered = program.commands.map((c) => c.name()); const missing = registered.filter((n) => !grouped.includes(n)); const unknown = grouped.filter((n) => !registered.includes(n)); const problems: string[] = []; if (dupes.length) problems.push(`listed in more than one group: ${dupes.join(", ")}`); if (missing.length) problems.push(`not in any help group: ${missing.join(", ")}`); if (unknown.length) problems.push(`grouped but not registered: ${unknown.join(", ")}`); if (problems.length) { throw new Error(`Help groups out of sync — ${problems.join("; ")}`); } } // Render the topic-grouped command listing used by `help` and the startup banner. export function formatGroupedHelp(program: Command): string { const byName = new Map(program.commands.map((c) => [c.name(), c] as const)); const line = (name: string): string => { const cmd = byName.get(name); const aliases = cmd?.aliases() ?? []; const label = aliases.length ? `${name} (${aliases.join(", ")})` : name; const desc = cmd?.description() ?? ""; const gap = label.length < 38 ? " ".repeat(38 - label.length) : " "; return ` ${label}${gap}${desc}`; }; const out: string[] = [chalk.bold(`Ocean CLI v${pkg.version} — commands`), ""]; for (const group of HELP_GROUPS) { out.push(chalk.cyan.bold(group.heading)); for (const n of group.commands ?? []) out.push(line(n)); for (const sub of group.subgroups ?? []) { out.push(chalk.cyan(` ${sub.subheading}:`)); for (const n of sub.commands) out.push(line(n)); } out.push(""); } out.push( chalk.gray( "Both positional args and named options work for every command. Add -h/--help after a command for its options, e.g. publish --help", ), ); return out.join("\n"); } // Single source of truth for the CLI version: read it from package.json instead // of hardcoding, so it can't drift. `../package.json` resolves from both src/ // (dev via tsx) and dist/ (published), since both sit one level below the root. const pkg = createRequire(import.meta.url)("../package.json"); // Parse a CLI JSON array-of-strings option (e.g. --cmd '["python","app.py"]'). // Returns the array, or throws with a clear message for the action to surface. function parseJsonStringArray(name: string, value: string): string[] { let parsed: unknown; try { parsed = JSON.parse(value); } catch { throw new Error(`${name} must be a JSON array, e.g. '["a","b"]'`); } if (!Array.isArray(parsed) || !parsed.every((x) => typeof x === "string")) { throw new Error(`${name} must be a JSON array of strings`); } return parsed as string[]; } // Parse a comma-separated port list, validating each is an integer 1-65535. function parsePorts(value: string): number[] { return value .split(",") .map((p) => p.trim()) .filter(Boolean) .map((p) => { const n = parseInt(p, 10); if (!Number.isInteger(n) || n < 1 || n > 65535) { throw new Error(`Invalid port "${p}" (must be an integer 1-65535)`); } return n; }); } // Commander collector for a repeatable `--resource name:amount` option. function collectResource(value: string, previous: string[]): string[] { return previous.concat([value]); } // Run the interactive resource-search wizard, but only when we have a TTY — a wizard with // no stdin would hang. In a non-interactive context, tell the user to pass filter flags. async function runResourceWizard(chainId: number) { if (!input.isTTY) { throw new Error( "searchComputeResources needs either filter flags (e.g. --cpu 4 --paid) or an " + "interactive terminal for the wizard. Run with --help to see the flags.", ); } return interactiveResourceSearch(chainId); } // Thin wrapper over the RPC registry: seed it from the `RPC` env, resolve the single // active (default) chain, and return that chain's memoized signer. For legacy // single-URL users the chainId is still discovered by probing getNetwork() and nothing // about their behavior changes; multi-URL/JSON-map users get a FallbackProvider. async function initializeSigner() { loadRegistry(); // Lenient: the real default when there is one, else any registered chain purely to // obtain a signer for chain-agnostic commands (plan §"Default chain" step 4). const chainId = await getActiveChainId(); const signer = await getSigner(chainId); return { signer, chainId }; } // Resolve the chain for a chain-explicit command (category c): the `--chainId` flag → // the default chain → a clear error. Validates the flag is a registered positive integer. function resolveChainId(flag?: string | number): number { if (flag !== undefined && flag !== null && `${flag}`.trim() !== "") { const id = Number(flag); if (!Number.isInteger(id) || id <= 0) { throw new Error(`Invalid --chainId "${flag}": must be a positive integer.`); } if (!hasChain(id)) { throw new Error( `Chain ${id} is not configured. Configured chains: ${ listChains() .map((c) => c.chainId) .join(", ") || "none" }. Add it with 'addChain '.`, ); } return id; } const def = getDefaultChainId(); if (def !== undefined) return def; throw new Error( `No chain specified and no default chain is set. Pass --chainId , or run 'setChain '. Configured chains: ${ listChains() .map((c) => c.chainId) .join(", ") || "none" }.`, ); } // Route a chain-explicit command's Commands instance onto the resolved chain. Returns the // resolved chainId, or null (already logged) when resolution/switch fails so the action bails. async function routeExplicit( commands: Commands, flag?: string | number, ): Promise { try { const target = resolveChainId(flag); await commands.useChain(target); return target; } catch (e) { console.error(chalk.red((e as Error).message)); return null; } } export async function createCLI() { // A pure help/version invocation must work with no configuration at all (a // globally installed binary is expected to answer `--help`/`--version` // without credentials). Detect it from argv and skip both env validation and // the P2P bootstrap in that case; every real command still validates below. const argv = process.argv.slice(2); const isHelpOrVersion = argv.includes("--help") || argv.includes("-h") || argv.includes("--version") || argv.includes("-V") || argv[0] === "help" || argv[0] === "h"; if (!isHelpOrVersion) { if (!process.env.MNEMONIC && !process.env.PRIVATE_KEY) { console.error( chalk.red("Have you forgot to set MNEMONIC or PRIVATE_KEY?"), ); process.exit(1); } if (!process.env.RPC) { console.error(chalk.red("Have you forgot to set env RPC?")); process.exit(1); } // Validate the RPC shape (single URL or JSON map keyed by chainId) up front, so a // malformed value fails fast with a clear, example-bearing message instead of deep // inside the first command. Pure parse — no providers built, no network touched. try { parseRpcEnv(process.env.RPC); } catch (e) { console.error(chalk.red((e as Error).message)); process.exit(1); } } // NODE_URL is optional: without it the CLI still starts, but only the commands in // NODE_FREE_COMMANDS are accepted until `setNode` picks a node (see the gate below). if (!isHelpOrVersion) { if (process.env.DISABLE_P2P === "true" && isP2pUri(getCurrentNodeUrl())) { console.error( chalk.red( "NODE_URL is a P2P URI but DISABLE_P2P=true — no command could reach it.", ), ); process.exit(1); } // Eager, non-blocking: libp2p warms up (bootstrap dials + DHT) while the user reads // the prompt, so a later switch to a P2P node doesn't pay that cost interactively. // // Only in loop mode. A one-shot run has no "later command" to warm up for, and // starting a libp2p node it never uses would just delay its exit — the process // cannot end until the node is up and stopped again. One-shot runs that *do* target // a P2P node still get it: validateNode() -> ensureP2PReady() starts it on demand. if (process.env.AVOID_LOOP_RUN !== "true") { startP2P(process.env.NODE_URL); } if (hasNode()) { // Confirms the startup node is reachable before the user types anything. For a // P2P node the status call dials the peer, which is what the old wait-for-peer // polling loop used to do. const status = await validateNode(getCurrentNodeUrl()); if (status) { console.log( chalk.green( `Using node ${getCurrentNodeUrl()} (version ${status.version})`, ), ); } else { console.error( chalk.red( `Node ${getCurrentNodeUrl()} is not reachable. Commands may fail.`, ), ); } } else { console.log( chalk.yellow( "No Ocean Node configured. Run `setNode ` to choose one — " + `only ${[...NODE_FREE_COMMANDS].join(", ")} are available until then.`, ), ); } } const program = new Command(); program .name("ocean-cli") .description("CLI tool to interact with Ocean Protocol") .version(pkg.version) .helpOption("-h, --help", "Display help for command"); // Every command except the node-free ones needs an Ocean Node. A single preAction // hook on the root program runs before *any* subcommand action, so this covers both // the REPL loop and one-shot mode without touching 40 action bodies. // // A plain Error (not a CommanderError) is thrown on purpose: in loop mode index.ts // reports it in red and keeps the REPL alive; in one-shot mode main() reports it and // exits 1, so scripts see a non-zero status. program.hook("preAction", (_thisCommand, actionCommand) => { // actionCommand.name() is the canonical name, so aliases resolve for free. if (!hasNode() && !NODE_FREE_COMMANDS.has(actionCommand.name())) { throw new Error( `No Ocean Node set. Run \`setNode \` first ` + `(available now: ${[...NODE_FREE_COMMANDS].join(", ")}).`, ); } }); // Custom help command to support legacy "h" invocation. Prints the topic-grouped listing. program .command("help") .alias("h") .description("Display help for all commands") .action(() => { console.log(formatGroupedHelp(program)); }); // setNode command. The switch itself never touches the RPC/signer: choosing a node is // independent of them and must work even when the RPC is slow or wrong. The RPC is // consulted only afterwards, under a timeout, to warn about a chain mismatch. program .command("setNode") .alias("useNode") .description( "Sets / switches the Ocean Node used by subsequent commands, without restarting", ) .argument("", "HTTP(S) URL, peer id or full multiaddr of the node") .option("-n, --node ", "Ocean Node to use") .action(async (nodeUrl, options) => { const target = options.node || nodeUrl; const previous = getCurrentNodeUrl(); if (target === previous) { console.log(chalk.green(`Node ${target} is already the active one.`)); return; } const status = await validateNode(target); if (!status) { console.error( chalk.red( previous ? `Cannot reach ${target}. Keeping current node: ${previous}` : `Cannot reach ${target}. Still no node set.`, ), ); return; } setCurrentNodeUrl(target); // The node changed (equal targets returned early above), so any env remembered by // setNodeEnv belonged to the previous node and no longer applies. clearCurrentEnvId(); console.log( chalk.green(`Using node: ${target} (version ${status.version})`), ); // chainId comes from RPC, not from the node, so the two can disagree. The switch // is already committed at this point, so this is a courtesy warning only — bound // it so an unresponsive RPC cannot leave the command hanging. const chainIds = nodeChainIds(status); if (chainIds.length > 0) { let timer: NodeJS.Timeout | undefined; try { const { chainId } = await Promise.race([ initializeSigner(), new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error("RPC timeout")), 5000); }), ]); if (!chainIds.includes(String(chainId))) { console.log( chalk.yellow( `Warning: this node serves chain(s) ${chainIds.join(", ")} but RPC is on chain ${chainId}. Commands may fail.`, ), ); } } catch { // A bad/slow RPC must not make a successful node switch look like a failure. } finally { // Leaving the loser pending would keep the event loop alive for 5s. clearTimeout(timer); } } }); // setNodeEnv command: paste a search result's "node|env" token to select BOTH the Ocean Node // and the compute environment for subsequent compute commands in one step. Mirrors setNode // (validate then switch the node) and additionally remembers the env id. program .command("setNodeEnv") .alias("useNodeEnv") .description( "Select both an Ocean Node and a compute environment from a search result's 'node|env' token", ) .argument( "", "A 'node|env' token from a searchComputeResources result (node URL/peer id, a '|', then the env id)", ) .action(async (nodeEnv) => { // Tolerate a pasted "Node+env: |" line, not just the bare token. const raw = nodeEnv.replace(/^\s*Node\+env:\s*/i, "").trim(); const sep = raw.indexOf("|"); if (sep <= 0 || sep === raw.length - 1) { console.error( chalk.red( "Expected a 'node|env' token (node, a '|', then the compute env id), e.g. 16Uiu2…|0xabc…-0xdef…", ), ); return; } const target = raw.slice(0, sep).trim(); const envId = raw.slice(sep + 1).trim(); const status = await validateNode(target); if (!status) { const previous = getCurrentNodeUrl(); console.error( chalk.red( previous ? `Cannot reach ${target}. Keeping current node: ${previous} (env unchanged)` : `Cannot reach ${target}. Still no node set.`, ), ); return; } setCurrentNodeUrl(target); setCurrentEnvId(envId); console.log( chalk.green( `Using node: ${target} (version ${status.version})\nUsing compute env: ${envId}`, ), ); console.log( chalk.yellow( "startCompute / startFreeCompute will use this env by default (override with --env).", ), ); }); // getNode command program .command("getNode") .alias("currentNode") .description("Shows the Ocean Node currently in use") .action(async () => { const current = getCurrentNodeUrl(); if (!current) { console.log( chalk.yellow( "No Ocean Node set. Run `setNode ` to pick one.", ), ); return; } console.log(`Current Ocean Node: ${current}`); const envId = getCurrentEnvId(); if (envId) { console.log(`Selected compute env: ${envId}`); } // Best effort: a node that is down must not fail the command. const status = await validateNode(current); if (status) { const nodeChains = nodeChainIds(status); console.log( `Version: ${status.version}, chain(s): ${nodeChains.join(", ") || "none"}`, ); // Cross-reference the node's served chains with the RPC registry, surfacing any // chain the node serves but for which no RPC is configured (commands would fail). try { loadRegistry(); const missing = nodeChains.filter((c) => !hasChain(Number(c))); const configured = nodeChains.filter((c) => hasChain(Number(c))); if (configured.length) { console.log( chalk.green(` RPC configured for chain(s): ${configured.join(", ")}`), ); } if (missing.length) { console.log( chalk.yellow( ` No RPC configured for node chain(s): ${missing.join( ", ", )} — add one with 'addChain '.`, ), ); } } catch { // RPC not configured / unavailable — the node info above is still useful. } } else { console.log(chalk.yellow("Node is not reachable right now.")); } }); // --------------------------------------------------------------------------- // Chain / RPC management (node-free — see NODE_FREE_COMMANDS). Implemented directly // here, mirroring setNode/getNode: the registry is the single source of truth and no // signer/Commands instance is needed. Errors are plain Error so the gate/REPL render // them in red and stay alive. // --------------------------------------------------------------------------- const configuredChainList = (): string => listChains() .map((c) => c.chainId) .join(", ") || "none"; program .command("addChain") .alias("addRpc") .description( "Register an RPC chain at runtime (verifies each URL serves the chain; persists)", ) .argument("", "Chain id the URL(s) serve") .argument("[rpcUrl...]", "One or more RPC URLs for that chain") .option("-c, --chainId ", "Chain id the URL(s) serve") .option("-u, --url ", "One or more RPC URLs for that chain") .action(async (chainIdArg, rpcUrlArgs, options) => { loadRegistry(); const id = Number(options.chainId || chainIdArg); const urls: string[] = options.url && options.url.length ? options.url : rpcUrlArgs; if (!Number.isInteger(id) || id <= 0) { console.error(chalk.red(`Invalid chainId "${chainIdArg}".`)); return; } if (!urls || urls.length === 0) { console.error(chalk.red("At least one RPC URL is required.")); return; } try { await addChain(id, urls); console.log( chalk.green( `Chain ${id} registered with ${urls.length} URL(s). Configured chains: ${configuredChainList()}.`, ), ); } catch (e) { console.error(chalk.red((e as Error).message)); } }); program .command("removeChain") .alias("removeRpc") .description("Unregister an RPC chain (persists)") .argument("", "Chain id to remove") .option("-c, --chainId ", "Chain id to remove") .action(async (chainIdArg, options) => { loadRegistry(); const id = Number(options.chainId || chainIdArg); if (!Number.isInteger(id) || id <= 0) { console.error(chalk.red(`Invalid chainId "${chainIdArg}".`)); return; } try { removeChain(id); console.log( chalk.green( `Chain ${id} removed. Configured chains: ${configuredChainList()}.`, ), ); } catch (e) { console.error(chalk.red((e as Error).message)); } }); program .command("listChains") .alias("getRpcs") .alias("chains") .description("List configured RPC chains, their URLs, and the default") .action(async () => { loadRegistry(); // A legacy single-URL RPC isn't registered until its chainId is probed; do that // (best effort) so it shows up here without needing to run a signing command first. await getActiveChainId().catch(() => undefined); const chains = listChains(); if (chains.length === 0) { console.log(chalk.yellow("No RPC chains configured.")); return; } // Best-effort: cross-reference the node's served chains, if a node is set. let nodeChains: number[] = []; const current = getCurrentNodeUrl(); if (current) { const status = await validateNode(current); if (status) nodeChains = nodeChainIds(status).map((c) => Number(c)); } const def = resolveDefaultChain(nodeChains); console.log(chalk.bold("Configured RPC chains:")); for (const { chainId, urls } of chains) { const marks: string[] = []; if (chainId === def) marks.push(chalk.green("default")); if (nodeChains.includes(chainId)) marks.push("served by node"); const suffix = marks.length ? ` [${marks.join(", ")}]` : ""; console.log(` ${chainId}${suffix}`); for (const u of urls) console.log(` ${u}`); } const nodeMissing = nodeChains.filter((c) => !hasChain(c)); if (nodeMissing.length) { console.log( chalk.yellow( `Node serves chain(s) with no configured RPC: ${nodeMissing.join(", ")}.`, ), ); } if (def === undefined) { console.log( chalk.yellow( "No default chain set — chain-explicit commands need --chainId. Set one with 'setChain '.", ), ); } }); program .command("setChain") .alias("useChain") .description("Set the default (active) chain (must be registered; persists)") .argument("", "Chain id to make default") .option("-c, --chainId ", "Chain id to make default") .action(async (chainIdArg, options) => { loadRegistry(); const id = Number(options.chainId || chainIdArg); if (!Number.isInteger(id) || id <= 0) { console.error(chalk.red(`Invalid chainId "${chainIdArg}".`)); return; } try { setDefaultChainId(id); console.log(chalk.green(`Default chain is now ${id}.`)); } catch (e) { console.error(chalk.red((e as Error).message)); } }); program .command("getChain") .alias("currentChain") .description("Show the current default (active) chain") .action(async () => { loadRegistry(); await getActiveChainId().catch(() => undefined); const def = getDefaultChainId(); if (def !== undefined) { console.log(`Default chain: ${def}`); } else { console.log( chalk.yellow( `No default chain set. Configured chains: ${configuredChainList()}. Set one with 'setChain '.`, ), ); } }); // getDDO command program .command("getDDO") .description("Gets DDO for an asset using the asset did") .argument("", "The asset DID") .option("-d, --did ", "The asset DID") .action(async (did, options) => { const assetDid = options.did || did; if (!assetDid) { console.error(chalk.red("DID is required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.getDDO([null, assetDid]); }); // publish command program .command("publish") .description("Publishes a new asset with access service or compute service") .argument("", "Path to metadata file") .option("-f, --file ", "Path to metadata file") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) .action(async (metadataFile, options) => { const file = options.file || metadataFile; if (!file) { console.error(chalk.red("Metadata file is required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.publish([null, file, options.encrypt.toString()]); }); // publishAlgo command program .command("publishAlgo") .description("Publishes a new algorithm") .argument("", "Path to metadata file") .option("-f, --file ", "Path to metadata file") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) .action(async (metadataFile, options) => { const file = options.file || metadataFile; if (!file) { console.error(chalk.red("Metadata file is required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.publishAlgo([null, file, options.encrypt.toString()]); }); // editAsset command (alias "edit" for backwards compatibility) program .command("editAsset") .alias("edit") .description("Updates DDO using the metadata items in the file") .argument("", "Dataset DID") .argument("", "Updated metadata file") .option("-d, --did ", "Dataset DID") .option("-f, --file ", "Updated metadata file") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) .action(async (datasetDid, metadataFile, options) => { const dsDid = options.did || datasetDid; const file = options.file || metadataFile; if (!dsDid || !file) { console.error(chalk.red("Dataset DID and metadata file are required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.editAsset([null, dsDid, file, options.encrypt.toString()]); }); // download command program .command("download") .description("Downloads an asset into specified folder") .argument("", "The asset DID") .argument("[folder]", "Destination folder", ".") .argument("[serviceId]", "Service ID (optional)") .option("-d, --did ", "The asset DID") .option("-f, --folder [folder]", "Destination folder", ".") .option("-s, --service ", "Service ID") .action(async (did, folder, serviceId, options) => { const assetDid = options.did || did; const destFolder = options.folder || folder || "."; const svcId = options.service || serviceId; if (!assetDid) { console.error(chalk.red("DID is required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.download([null, assetDid, destFolder, svcId]); }); // allowAlgo command program .command("allowAlgo") .description("Approves an algorithm to run on a dataset") .argument("", "Dataset DID") .argument("", "Algorithm DID") .option("-d, --dataset ", "Dataset DID") .option("-a, --algo ", "Algorithm DID") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) .action(async (datasetDid, algoDid, options) => { const dsDid = options.dataset || datasetDid; const aDid = options.algo || algoDid; if (!dsDid || !aDid) { console.error(chalk.red("Dataset DID and Algorithm DID are required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.allowAlgo([null, dsDid, aDid, options.encrypt.toString()]); }); // startCompute command program .command("startCompute") .description("Starts a compute job") .argument( "", 'Dataset DIDs (comma-separated), an empty array for none, OR a JSON ComputeAsset object/array with a fileObject (raw datasets, no DID). Mixed input must be valid JSON, e.g. \'["did:op:abc",{"fileObject":{...}}]\'', ) .argument( "", "Algorithm DID, OR a JSON ComputeAlgorithm object with a fileObject and meta (raw algorithm, no DID)", ) .argument( "[computeEnvId]", "Compute environment ID (optional if one was selected via setNodeEnv). If omitted, pass the later values (maxJobDuration, paymentToken, resources, ...) as named options rather than positionally, since they would otherwise fill this slot.", ) .argument("[maxJobDuration]", "maxJobDuration for compute job") .argument("[paymentToken]", "Payment token for compute") .argument("[resources]", "Resources of compute environment stringified") .argument( "[output]", "Output backend to save job results to. Supported types include S3, FTP, URL, Arweave, etc. Defaults to node local disk if omitted.", ) .argument( "[serviceIds]", "Service IDs (comma-separated; positional mapping with datasetDIDs)", ) .argument("[algoServiceId]", "Algorithm Service ID (optional)") .option( "-d, --datasets ", "Dataset DIDs (comma-separated), an empty array for none, OR a JSON ComputeAsset object/array with a fileObject (raw datasets, no DID)", ) .option( "-a, --algo ", "Algorithm DID, OR a JSON ComputeAlgorithm object with a fileObject and meta (raw algorithm, no DID)", ) .option("-e, --env ", "Compute environment ID") .option("--maxJobDuration ", "Compute maxJobDuration") .option("-t, --token ", "Compute payment token") .option( "-s, --services [serviceIds]", "Service IDs (comma-separated; positional mapping with datasetDIDs)", ) .option( "-x, --algo-service [algoServiceId]", "Algorithm Service ID (optional)", ) .option("--resources ", "Compute resources") .option( "--accept [boolean]", "Auto-confirm payment for compute job (true/false)", toBoolean, ) .option( "--chainId ", "Payment/escrow chain for the job (defaults to the active chain). Each dataset/algorithm is still ordered on its own DDO chain.", ) .option( "-o, --output [output]", "Output backend to save job results to. Supported types include S3, FTP, URL, Arweave, etc. Defaults to node local disk if omitted.", ) .action( async ( datasetDids, algoDid, computeEnvId, maxJobDuration, paymentToken, resources, output, serviceIds, algoServiceId, options, ) => { const dsDids = options.datasets || datasetDids; const aDid = options.algo || algoDid; // Fall back to the env remembered by setNodeEnv when none is given explicitly. const envId = options.env || computeEnvId || getCurrentEnvId(); const jobDuration = options.maxJobDuration || maxJobDuration; const token = options.token || paymentToken; const res = options.resources || resources; const outputLocation = options.output || output; const svcIds = options.services ?? serviceIds ?? ""; const algoSvcId = options.algoService ?? algoServiceId ?? ""; // A compute env id is never a bare number, so a numeric positional here almost // always means the user omitted the env (relying on setNodeEnv) and let the next // value — maxJobDuration — shift up into this slot. Catch that early with an // actionable message instead of failing later with a misleading env error. if (!options.env && computeEnvId && /^\d+$/.test(computeEnvId.trim())) { console.error( chalk.red( `"${computeEnvId}" looks like maxJobDuration, not a compute environment ID. ` + "If you meant to use the env selected via setNodeEnv, pass the remaining values as named options " + "(--maxJobDuration, --token, --resources). Otherwise provide the environment ID explicitly (--env ).", ), ); return; } if (!dsDids || !aDid || !envId || !jobDuration || !token || !res) { console.error(chalk.red("Missing required arguments")); // process.exit(1); return; } // Count datasets with the same tokenizer the resolver uses. Splitting // the raw string on "," breaks every JSON form (a single // '[{"fileObject":{...}}]' contains commas), which made this check // reject valid input. const dsCount = parseComputeInput(dsDids).length; // Empty entries are kept: they are positional placeholders, so // `svc0,,svc2` is three slots, not two. const svArr = svcIds ? svcIds.split(",").map((s) => s.trim()) : undefined; // Optional check: serviceIds must match length if provided if (svArr && svArr.length !== dsCount) { console.error( chalk.red( `Length mismatch: datasets=${dsCount} vs serviceIds=${svArr.length}. ` + "If serviceIds is provided, it must match the dataset count (positional 1–1).", ), ); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); // Payment/escrow chain (category d): `--chainId` → default → error. Independent // of where the assets live — each asset is ordered on its own DDO chain inside // the compute methods. let paymentChainId: number; try { paymentChainId = resolveChainId(options.chainId); } catch (e) { console.error(chalk.red((e as Error).message)); return; } const initArgs = [ null, dsDids, aDid, envId, jobDuration, token, res, outputLocation, svcIds, algoSvcId, ]; console.log("initArgs:", initArgs); const initResp = await commands.initializeCompute( initArgs, paymentChainId, ); if (!initResp) { console.error(chalk.red("Initialization failed. Aborting.")); return; } console.log(chalk.yellow("\n--- Payment Details ---")); console.log(JSON.stringify(initResp, null, 2)); // The payment token lives on the payment chain, which may differ from the active // chain — read its decimals with that chain's signer, not the default one. const paymentSigner = await commands.signerFor(paymentChainId); const amount = await unitsToAmount( paymentSigner, initResp.payment.token, initResp.payment.amount.toString(), ); const proceed = options.accept; if (!proceed) { if (!process.stdin.isTTY) { console.error( chalk.red( 'Cannot prompt for confirmation (non-TTY). Use "--accept true" to skip.', ), ); process.exit(1); } const rl = createInterface({ input, output: stdout }); const confirmation = await rl.question( `\nProceed with payment for starting compute job at price ${amount} in tokens from address ${initResp.payment.token}? (y/n): `, ); rl.close(); if ( confirmation.toLowerCase() !== "y" && confirmation.toLowerCase() !== "yes" ) { console.log(chalk.red("Compute job canceled by user.")); return; } } else { console.log(chalk.cyan("Auto-confirm enabled with --yes flag.")); } const computeArgs = [ null, dsDids, aDid, envId, JSON.stringify(initResp), jobDuration, token, res, outputLocation, svcIds, algoSvcId, ]; const started = await commands.computeStart(computeArgs, paymentChainId); if (started) { console.log(chalk.green("Compute job started successfully.")); } }, ); // startFreeCompute command program .command("startFreeCompute") .description("Starts a FREE compute job") .argument( "", 'Dataset DIDs (comma-separated), an empty array for none, OR a JSON ComputeAsset object/array with a fileObject (raw datasets, no DID). Mixed input must be valid JSON, e.g. \'["did:op:abc",{"fileObject":{...}}]\'', ) .argument( "", "Algorithm DID, OR a JSON ComputeAlgorithm object with a fileObject and meta (raw algorithm, no DID)", ) .argument( "[computeEnvId]", "Compute environment ID (optional if one was selected via setNodeEnv)", ) .argument( "[output]", "Output backend to save job results to. Supported types include S3, FTP, URL, Arweave, etc. Defaults to node local disk if omitted.", ) .argument( "[serviceIds]", "Service IDs (comma-separated; positional mapping with datasetDIDs)", ) .argument("[algoServiceId]", "Algorithm Service ID (optional)") .option( "-d, --datasets ", "Dataset DIDs (comma-separated), an empty array for none, OR a JSON ComputeAsset object/array with a fileObject (raw datasets, no DID)", ) .option( "-a, --algo ", "Algorithm DID, OR a JSON ComputeAlgorithm object with a fileObject and meta (raw algorithm, no DID)", ) .option("-e, --env ", "Compute environment ID") .option( "-o, --output [output]", "Output backend to save job results to. Supported types include S3, FTP, URL, Arweave, etc. Defaults to node local disk if omitted.", ) .option( "-s, --services [serviceIds]", "Service IDs (comma-separated; positional mapping with datasetDIDs)", ) .option( "-x, --algo-service [algoServiceId]", "Algorithm Service ID (optional)", ) .option( "--chainId ", "Chain to sign the free compute request on (defaults to the active chain). A free env does no ordering or payment.", ) .action( async ( datasetDids, algoDid, computeEnvId, output, serviceIds, algoServiceId, options, ) => { const dsDids = options.datasets || datasetDids; const aDid = options.algo || algoDid; // Fall back to the env remembered by setNodeEnv when none is given explicitly. const envId = options.env || computeEnvId || getCurrentEnvId(); const outputLocation = options.output || output; const svcIds = options.services ?? serviceIds ?? ""; const algoSvcId = options.algoService ?? algoServiceId ?? ""; if (!dsDids || !aDid || !envId) { console.error(chalk.red("Missing required arguments")); // process.exit(1); return; } // Count datasets with the same tokenizer the resolver uses. Splitting // the raw string on "," breaks every JSON form (a single // '[{"fileObject":{...}}]' contains commas), which made this check // reject valid input. const dsCount = parseComputeInput(dsDids).length; // Empty entries are kept: they are positional placeholders, so // `svc0,,svc2` is three slots, not two. const svArr = svcIds ? svcIds.split(",").map((s) => s.trim()) : undefined; // Optional check: serviceIds must match length if provided if (svArr && svArr.length !== dsCount) { console.error( chalk.red( `Length mismatch: datasets=${dsCount} vs serviceIds=${svArr.length}. ` + "If serviceIds is provided, it must match the dataset count (positional 1–1).", ), ); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); // Free compute is single-chain signing only (no ordering/escrow): route the // signer onto `--chainId` → default, exactly like a category (c) command. if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.freeComputeStart([ null, dsDids, aDid, envId, outputLocation, svcIds, algoSvcId, ]); }, ); // getComputeEnvironments command program .command("getComputeEnvironments") .alias("getC2DEnvs") .argument( "[node]", "Optional Ocean Node URL or peer id to query (defaults to NODE_URL)", ) .option("-n, --node ", "Ocean Node URL or peer id to query") .description("Gets the existing compute environments") .action(async (node, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.getComputeEnvironments(options.node || node); }); // computeStreamableLogs command program .command("computeStreamableLogs") .description("Gets the existing compute streamable logs") .argument("", "Job ID") .option("-j, --job ", "Job ID") .action(async (jobId, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); const args = jobId || options.job; await commands.computeStreamableLogs([args]); }); // stopCompute command program .command("stopCompute") .description("Stops a compute job") .argument("", "Dataset DID") .argument("", "Job ID") .argument("", "Agreement ID") .option("-d, --dataset ", "Dataset DID") .option("-j, --job ", "Job ID") .option("-a, --agreement [agreementId]", "Agreement ID") .action(async (datasetDid, jobId, agreementId, options) => { const dsDid = options.dataset || datasetDid; const jId = options.job || jobId; const agrId = options.agreement || agreementId; if (!dsDid || !jId) { console.error(chalk.red("Dataset DID and Job ID are required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); const args = [null, dsDid, jId]; if (agrId) args.push(agrId); await commands.computeStop(args); }); // getJobStatus command program .command("getJobStatus") .description("Displays the compute job status") .argument("", "Dataset DID") .argument("", "Job ID") .argument("[agreementId]", "Agreement ID") .option("-d, --dataset ", "Dataset DID") .option("-j, --job ", "Job ID") .option("-a, --agreement [agreementId]", "Agreement ID") .action(async (datasetDid, jobId, agreementId, options) => { const dsDid = options.dataset || datasetDid; const jId = options.job || jobId; const agrId = options.agreement || agreementId; if (!dsDid || !jId) { console.error(chalk.red("Dataset DID and Job ID are required")); // process.exit(1); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); const args = [null, dsDid, jId]; if (agrId) args.push(agrId); await commands.getJobStatus(args); }); // downloadJobResults command program .command("downloadJobResults") .description("Downloads compute job results") .argument("", "Job ID") .argument("", "Result index", parseInt) .argument("[destinationFolder]", "Destination folder", ".") .action(async (jobId, resultIndex, destinationFolder) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.downloadJobResults([ null, jobId, resultIndex, destinationFolder, ]); }); // ========================================================================= // Service-on-Demand commands // ========================================================================= // getServiceTemplates command program .command("getServiceTemplates") .alias("serviceTemplates") .description( "Lists the node's Service-on-Demand templates and compatible environments", ) .argument( "[node]", "Optional Ocean Node URL or peer id to query (defaults to NODE_URL)", ) .option("-n, --node ", "Ocean Node URL or peer id to query") .action(async (node, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.getServiceTemplates(options.node || node); }); // startService command program .command("startService") .description( "Starts an on-demand service (long-running container) on a compute environment, paid via escrow", ) .argument( "", "Compute environment ID (must have services enabled)", ) .argument("", "Requested duration in seconds", parseInt) .argument("", "Payment token address") .option( "--template ", "Start from an operator-published template", ) .option( "-i, --image ", "Container image (alternative to --template)", ) .option( "--tag ", "Image tag (mutually exclusive with --checksum/--dockerfile)", ) .option("--checksum ", "Image digest, e.g. sha256:<64 hex>") .option( "--dockerfile ", "Path to a local Dockerfile (node must allow image builds)", ) .option( "--additional-docker-files ", "Path to JSON file of {filename: content} used with --dockerfile", ) .option( "--cmd ", 'Docker CMD override as JSON array, e.g. \'["python","app.py"]\'', ) .option("--entrypoint ", "Docker ENTRYPOINT override as JSON array") .option( "-p, --ports ", "Comma-separated container ports to expose, e.g. 8888,8080", ) .option( "-r, --resources ", 'Stringified JSON [{"id":"cpu","amount":1},...]; defaults to template requirements', ) .option( "-u, --user-data ", "JSON object of container env vars (encrypted to the node; never logged)", ) .option( "--user-data-file ", "Path to JSON file with container env vars", ) .option( "--accept [boolean]", "Auto-confirm payment (true/false)", toBoolean, ) .option( "--wait [boolean]", "Poll until Running or failure (default true)", toBoolean, true, ) .option( "--timeout ", "Max seconds to wait for Running (default 600)", parseInt, ) .option( "--chainId ", "Payment/escrow chain (default: active chain); must be one the env prices on", ) .action(async (computeEnvId, duration, paymentToken, options) => { const envId = options.env || computeEnvId; const token = paymentToken; if (!envId || !duration || !token) { console.error( chalk.red( "Missing required arguments: ", ), ); return; } if (!Number.isInteger(duration) || duration <= 0) { console.error( chalk.red("Duration must be a positive integer number of seconds."), ); return; } if (options.template && options.image) { console.error( chalk.red("Provide either --template or --image, not both."), ); return; } let ports: number[] | undefined; let cmd: string[] | undefined; let entrypoint: string[] | undefined; try { if (options.ports) ports = parsePorts(options.ports); if (options.cmd) cmd = parseJsonStringArray("--cmd", options.cmd); if (options.entrypoint) entrypoint = parseJsonStringArray("--entrypoint", options.entrypoint); } catch (e) { console.error(chalk.red((e as Error).message)); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); // Services are single-chain: --chainId (→ default) is the payment/escrow chain, and // must be registered here; startService additionally checks it is one the env prices on. if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.startService({ envId, duration, paymentToken: token, templateId: options.template, image: options.image, tag: options.tag, checksum: options.checksum, dockerfilePath: options.dockerfile, additionalDockerFilesPath: options.additionalDockerFiles, cmd, entrypoint, ports, resources: options.resources, userDataInline: options.userData, userDataFilePath: options.userDataFile, accept: options.accept, wait: options.wait, timeout: options.timeout, }); }); // getServiceStatus command (caller-owned, full detail) program .command("getServiceStatus") .alias("myServices") .description("Shows status + endpoints of YOUR on-demand service(s)") .argument("[serviceId]", "Service ID; omit to list all your services") .option("-s, --service ", "Service ID") .option("-v, --verbose [boolean]", "Dump full job objects", toBoolean) .action(async (serviceId, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.getServiceStatus( options.service || serviceId, options.verbose, ); }); // getServices command (SERVICES_LIST — node-wide, all owners) program .command("getServices") .alias("listServices") .description( "Lists on-demand services across ALL owners on the node (docker spec hidden)", ) .argument( "[node]", "Optional Ocean Node URL or peer id to query (defaults to NODE_URL)", ) .option("-n, --node ", "Ocean Node URL or peer id to query") .option( "--status ", "Filter by a single service status number (e.g. 40 for Running)", parseInt, ) .option( "--include-all [boolean]", "Include all statuses, not just active reservations", toBoolean, ) .option( "--from ", "Only services created at/after this time (ISO string or Unix timestamp)", ) .option("-v, --verbose [boolean]", "Dump full job objects", toBoolean) .action(async (node, options) => { if ( options.status !== undefined && ServiceStatusNumber[options.status] === undefined ) { console.error( chalk.red( `Unknown --status ${options.status}. Valid values: 10,11,12,13,14,15,20,30,40,50,70,75,99`, ), ); return; } const filters: { status?: number; includeAllStatuses?: boolean; fromTimestamp?: string; } = {}; if (options.status !== undefined) filters.status = options.status; if (options.includeAll !== undefined) filters.includeAllStatuses = options.includeAll; if (options.from !== undefined) filters.fromTimestamp = options.from; const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.getServices( options.node || node, filters, options.verbose, ); }); // serviceLogs command (streamable logs) program .command("serviceLogs") .alias("computeServiceLogs") .description("Streams live logs from an on-demand service's container") .argument("", "Service ID") .option("-s, --service ", "Service ID") .option( "--since ", "Only logs since this time — Unix seconds or a relative duration like 30s / 2h", ) .action(async (serviceId, options) => { const id = options.service || serviceId; if (!id) { console.error(chalk.red("Missing required argument: ")); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.serviceLogs(id, options.since); }); // extendService command program .command("extendService") .description( "Extends a running on-demand service's expiry (paid via escrow)", ) .argument("", "Service ID") .argument( "", "Additional duration in seconds", parseInt, ) .argument( "[paymentToken]", "Payment token (defaults to the token used at start)", ) .option("-s, --service ", "Service ID") .option( "--duration ", "Additional duration in seconds", parseInt, ) .option("-t, --token [paymentToken]", "Payment token") .option( "--accept [boolean]", "Auto-confirm payment (true/false)", toBoolean, ) .option("--chainId ", "Payment/escrow chain (default: active chain)") .action(async (serviceId, additionalDuration, paymentToken, options) => { const id = options.service || serviceId; const addl = options.duration || additionalDuration; const token = options.token || paymentToken; if (!id || !addl) { console.error( chalk.red( "Missing required arguments: ", ), ); return; } if (!Number.isInteger(addl) || addl <= 0) { console.error( chalk.red( "additionalDuration must be a positive integer number of seconds.", ), ); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.extendService(id, addl, token, options.accept); }); // restartService command program .command("restartService") .description( "Restarts a running service (same ports & expiry; no extra charge). " + "With no container-spec flags the container bounces unchanged (REUSE); " + "supplying any image-spec flag (--image/--tag/--checksum/--dockerfile/" + "--additional-docker-files) rebuilds it on the new spec (RESPEC, #2119)", ) .argument("", "Service ID") .option( "-u, --user-data ", "REPLACE stored container env vars (JSON object)", ) .option( "--user-data-file ", "Path to JSON file with replacement env vars", ) .option( "--cmd ", "REPLACE stored Docker CMD as JSON array (#2114); empty array clears it", ) .option( "--entrypoint ", "REPLACE stored Docker ENTRYPOINT as JSON array (#2114)", ) .option( "--image ", "RESPEC: rebuild on this container image (#2119)", ) .option("--tag ", "RESPEC: rebuild on this image tag (#2119)") .option("--checksum ", "RESPEC: image digest/checksum (#2119)") .option( "--dockerfile ", "RESPEC: dockerfile contents to build from (#2119)", ) .option( "--additional-docker-files ", "RESPEC: extra build files as a JSON object { path: contents } (#2119)", ) .option( "--wait [boolean]", "Poll until Running (default true)", toBoolean, true, ) .option( "--timeout ", "Max seconds to wait (default 600)", parseInt, ) .action(async (serviceId, options) => { if (!serviceId) { console.error(chalk.red("Missing required argument: ")); return; } const params: ServiceRestartParams = {}; try { if (options.userData) { const parsed = JSON.parse(options.userData); if ( typeof parsed !== "object" || parsed === null || Array.isArray(parsed) ) { throw new Error("--user-data must be a JSON object"); } params.userData = parsed; } else if (options.userDataFile) { const parsed = JSON.parse( fs.readFileSync(options.userDataFile, "utf8"), ); if ( typeof parsed !== "object" || parsed === null || Array.isArray(parsed) ) { throw new Error("--user-data-file must contain a JSON object"); } params.userData = parsed; } if (options.cmd !== undefined) params.dockerCmd = parseJsonStringArray("--cmd", options.cmd); if (options.entrypoint !== undefined) params.dockerEntrypoint = parseJsonStringArray( "--entrypoint", options.entrypoint, ); if (options.image !== undefined) params.image = options.image; if (options.tag !== undefined) params.tag = options.tag; if (options.checksum !== undefined) params.checksum = options.checksum; if (options.dockerfile !== undefined) params.dockerfile = options.dockerfile; if (options.additionalDockerFiles !== undefined) { const parsed = JSON.parse(options.additionalDockerFiles); if ( typeof parsed !== "object" || parsed === null || Array.isArray(parsed) ) { throw new Error("--additional-docker-files must be a JSON object"); } params.additionalDockerFiles = parsed; } } catch (e) { console.error(chalk.red((e as Error).message)); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.restartService( serviceId, Object.keys(params).length > 0 ? params : undefined, options.wait, options.timeout, ); }); // stopService command program .command("stopService") .description("Stops an on-demand service and releases its resources") .argument("", "Service ID") .option("-s, --service ", "Service ID") .action(async (serviceId, options) => { const id = options.service || serviceId; if (!id) { console.error(chalk.red("Missing required argument: ")); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.stopService(id); }); // mintOcean command program .command("mintOcean") .description("Mints Ocean tokens") .option( "-t, --token ", "Ocean token address (overrides the chain's configured address; required on chains with no bundled Ocean token)", ) .option("--chainId ", "Chain to mint on (default: active chain)") .action(async (options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.mintOceanTokens(options.token); }); // Generate new auth token program .command("generateAuthToken") .description("Generate new auth token") .action(async () => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.generateAuthToken(); }); // Invalidate auth token program .command("invalidateAuthToken") .description("Invalidate auth token") .argument("", "Auth token") .option("-t, --token ", "Auth token") .action(async (token, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.invalidateAuthToken([token || options.token]); }); // Escrow deposit command program .command("depositEscrow") .description("Deposit tokens into the escrow contract") .argument("", "Address of the token to deposit") .argument("", "Amount of tokens to deposit") .option("-t, --token ", "Address of the token to deposit") .option("-a, --amount ", "Amount of tokens to deposit") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, amount, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); const target = await routeExplicit(commands, options.chainId); if (target === null) return; const tokenAddress = options.token || token; const amountToDeposit = options.amount || amount; const success = await commands.depositToEscrow( commands.signer, tokenAddress, amountToDeposit, target, ); if (!success) { console.log(chalk.red("Deposit failed")); return; } console.log(chalk.green("Deposit successful")); }); // Check escrow deposited balance program .command("getUserFundsEscrow") .description("Get deposited token amount in escrow for user") .argument("", "Address of the token to check") .option("-t, --token ", "Address of the token to check") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.getEscrowBalance(token || options.token); }); // Withdraw from escrow program .command("withdrawFromEscrow") .description("Withdraw tokens from escrow") .argument("", "Address of the token to check") .argument("", "Amount of tokens to withdraw") .option("-t, --token ", "Address of the token to check") .option("-a, --amount ", "Amount of tokens to withdraw") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, amount, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.withdrawFromEscrow(token || options.token, amount); }); // Escrow authorization command program .command("authorizeEscrow") .description("Authorize a payee to lock and claim funds from escrow") .argument("", "Address of the token to authorize") .argument("", "Address of the payee to authorize") .argument("", "Maximum amount that can be locked by payee") .argument("", "Maximum lock duration in seconds") .argument("", "Maximum number of locks allowed") .option("-t, --token ", "Address of the token to authorize") .option("-p, --payee ", "Address of the payee to authorize") .option( "-m, --maxLockedAmount ", "Maximum amount that can be locked by payee", ) .option( "-s, --maxLockSeconds ", "Maximum lock duration in seconds", ) .option( "-c, --maxLockCounts ", "Maximum number of locks allowed", ) .option("--chainId ", "Escrow chain (default: active chain)") .action( async ( token, payee, maxLockedAmount, maxLockSeconds, maxLockCounts, options, ) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; const tokenAddress = options.token || token; const payeeAddress = options.payee || payee; const maxLockedAmountValue = options.maxLockedAmount || maxLockedAmount; const maxLockSecondsValue = options.maxLockSeconds || maxLockSeconds; const maxLockCountsValue = options.maxLockCounts || maxLockCounts; const success = await commands.authorizeEscrowPayee( tokenAddress, payeeAddress, maxLockedAmountValue, maxLockSecondsValue, maxLockCountsValue, ); if (!success) { console.log(chalk.red("Authorization failed")); return; } console.log(chalk.green("Authorization successful")); }, ); program .command("getAuthorizationsEscrow") .description("Get authorizations for escrow") .argument("", "Address of the token to check") .argument("", "Address of the payee to check") .option("-t, --token ", "Address of the token to check") .option("-p, --payee ", "Address of the payee to check") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, payee, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.getAuthorizationsEscrow( token || options.token, payee || options.payee, ); }); program .command("createAccessList") .description("Create a new access list contract") .argument("", "Name for the access list") .argument("", "Symbol for the access list") .argument( "[initialUsers]", "Comma-separated list of initial user addresses", "", ) .argument( "[transferable]", "Whether tokens are transferable (true/false)", "false", ) .option("-n, --name ", "Name for the access list") .option("-s, --symbol ", "Symbol for the access list") .option( "-u, --initial-users [initialUsers]", "Comma-separated list of initial user addresses", "", ) .option( "-t, --transferable [transferable]", "Whether tokens are transferable (true/false)", "false", ) .option("--chainId ", "Chain to deploy on (default: active chain)") .action(async (name, symbol, initialUsers, transferable, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.createAccessList([ options.name || name, options.symbol || symbol, options.transferable || transferable, options.initialUsers || initialUsers, ]); }); program .command("addToAccessList") .description("Add user(s) to an access list") .argument("", "Address of the access list contract") .argument("", "Comma-separated list of user addresses to add") .option( "-a, --address ", "Address of the access list contract", ) .option( "-u, --users ", "Comma-separated list of user addresses to add", ) .option("--chainId ", "Access-list chain (default: active chain)") .action(async (accessListAddress, users, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.addToAccessList([ options.address || accessListAddress, options.users || users, ]); }); program .command("checkAccessList") .description("Check if user(s) are on an access list") .argument("", "Address of the access list contract") .argument("", "Comma-separated list of user addresses to check") .option( "-a, --address ", "Address of the access list contract", ) .option( "-u, --users ", "Comma-separated list of user addresses to check", ) .option("--chainId ", "Access-list chain (default: active chain)") .action(async (accessListAddress, users, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.checkAccessList([ options.address || accessListAddress, options.users || users, ]); }); program .command("removeFromAccessList") .description("Remove user(s) from an access list") .argument("", "Address of the access list contract") .argument("", "Comma-separated list of user addresses to remove") .option( "-a, --address ", "Address of the access list contract", ) .option( "-u, --users ", "Comma-separated list of user addresses to remove", ) .option("--chainId ", "Access-list chain (default: active chain)") .action(async (accessListAddress, users, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.removeFromAccessList([ options.address || accessListAddress, options.users || users, ]); }); program .command("downloadNodeLogs") .description("Download logs from a node as an admin") .argument("", "Output directory to save the logs") .argument( "[last]", "Period of time to get logs from now (in hours). Use either last or from-to", ) .argument("[from]", "Start time (epoch ms) to get logs from") .argument("[to]", "End time (epoch ms) to get logs to") .argument( "[maxLogs]", "Maximum number of logs to retrieve (default: 100, max: 1000)", ) .option("-o, --output ", "Output directory to save the logs") .option( "-l, --last [last]", "Period of time to get logs from now (in hours)", ) .option("-f, --from [from]", "Start time (epoch ms) to get logs from") .option("-t, --to [to]", "End time (epoch ms) to get logs to") .option( "-m, --maxLogs [maxLogs]", "Maximum number of logs to retrieve (default: 100, max: 1000)", ) .action(async (output, last, from, to, options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.downloadNodeLogs([ options.output || output, options.last || last, options.from || from, options.to || to, options.maxLogs, ]); }); program .command("createBucket") .description( "Create a new persistent-storage bucket. Pass an access list to gate it; omit for owner-only access (chain inferred from RPC)", ) .argument( "[accessListAddress]", "Access list contract address (0x…); omit for owner-only access", ) .action(async (accessListAddress) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.createBucket([null, accessListAddress]); }); program .command("addFileToBucket") .description("Upload a local file into a bucket") .argument("", "Bucket id") .argument("", "Path to local file") .argument( "[fileName]", "Name under which to store the file (defaults to basename)", ) .action(async (bucketId, filePath, fileName) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.addFileToBucket([null, bucketId, filePath, fileName]); }); program .command("listBuckets") .description("List buckets owned by an address (defaults to signer)") .option("-o, --owner
", "Owner address") .action(async (options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.listBuckets([null, options.owner]); }); program .command("listFilesInBucket") .description("List files in a bucket") .argument("", "Bucket id") .action(async (bucketId) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.listFilesInBucket([null, bucketId]); }); program .command("getFileObject") .description("Get the file-object descriptor for a file in a bucket") .argument("", "Bucket id") .argument("", "File name") .action(async (bucketId, fileName) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.getFileObject([null, bucketId, fileName]); }); program .command("deleteFile") .description("Delete a file from a bucket") .argument("", "Bucket id") .argument("", "File name") .action(async (bucketId, fileName) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.deleteFile([null, bucketId, fileName]); }); program .command("searchComputeResources") .alias("findComputeNodes") .description( "Search the network for compute providers that can run a job with the resources you need. " + "Runs an interactive wizard when no filter flags are given, otherwise uses the flags.", ) .option("--cpu ", "CPU cores needed") .option("--ram ", "RAM needed") .option("--disk ", "Disk needed") .option("--gpu ", "GPU devices needed") .option("--gpu-model ", "GPU kind/description to match (e.g. A100)") .option( "--resource ", "Arbitrary resource (e.g. fpga:2); repeatable", collectResource, [] as string[], ) .option("--free", "Search only free compute environments") .option("--paid", "Search only paid compute environments") .option("--both", "Search both free and paid (default)") .option( "--chain ", "Chain(s) to price against, comma-separated (defaults to the RPC chain)", ) .option( "--token ", "Restrict to payment-token address(es), comma-separated; applied to every --chain", ) .option("--max-price ", "Drop paid results costing more than this (human units)") .option("--duration ", "Assumed job duration for the cost estimate") .option( "--order-by ", "Order results: price | freeCapacity | resources | leastBusy", ) .action(async (options) => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); const flags = options as SearchFlags; const params = hasSearchFlags(flags) ? buildParamsFromFlags(flags, chainId) : await runResourceWizard(chainId); await commands.searchComputeResources(params); }); // Every registered command must belong to exactly one help group (see HELP_GROUPS). assertHelpGroupsCoverAll(program); return program; }