<!-- 0Gkit docs — CLI reference
     Source: https://docs.0gkit.com/cli
     LLM-friendly Markdown twin of the page. -->

# CLI reference

The `0g` command line (`@foundryprotocol/0gkit-cli`) is the universal,
language-agnostic surface for 0G. Every command mirrors a primitive package;
`--json` makes it scriptable from any language.

```bash
# Install globally (exposes the `0g` binary):
npm install -g @foundryprotocol/0gkit-cli
0g doctor

# Or run one-off via npx (note the full scope — `npx 0g` resolves to an
# unrelated package on npm):
npx @foundryprotocol/0gkit-cli doctor
```

## Global flags

These apply to every command and are inherited by subcommands.

| Flag                   | Env                 | Default    | Meaning                                                        |
| ---------------------- | ------------------- | ---------- | -------------------------------------------------------------- |
| `--network <name>`     | `ZEROG_NETWORK`     | `galileo`  | `aristotle` \| `galileo` \| `local`.                           |
| `--rpc <url>`          | `ZEROG_RPC_URL`     | preset RPC | Override the network RPC URL.                                  |
| `--private-key <hex>`  | `ZEROG_PRIVATE_KEY` | _(none)_   | Signer key (funds storage tx).                                 |
| `--json`               | —                   | off        | Machine-readable JSON output.                                  |
| `--foundry`            | —                   | off        | Force-show the optional Foundry plugin namespace.              |
| `--copy-issue-context` | —                   | off        | On error, also print a redacted markdown report to **stderr**. |
| `--version`            | —                   | —          | Prints the installed CLI version.                              |

Precedence: **flag > env > preset default**. Additional env vars:
`ZEROG_BROKER_KEY`, `ZEROG_PROVIDER` (for `infer`).

## Output & exit codes

- Human mode: pretty lines; errors print `✗ <message>` then `→ <hint>`.
- `--json` mode: success is `{ "ok": true, ... }`; failure is
  `{ "ok": false, "error": { "code", "message", "hint" } }`.
- **Exit code `0`** on success. **Exit code `1`** when a command throws
  (any `ZeroGError`), when `0g doctor` has a failing required check, or when
  `0g attest verify` does not verify.

## Debugging: `--copy-issue-context`

Any `0g` command accepts `--copy-issue-context`. When the command throws a `ZeroGError`, the normal error output still goes to stdout; in addition, a markdown report is written to **stderr**, suitable for pasting straight into a new GitHub issue.

The report contains:

- Error `code`, `message`, `hint`, and `helpUrl`.
- The CLI invocation, with `--private-key` redacted and URL userinfo stripped from `--rpc`.
- Node.js version, OS, and a timestamp.
- Versions of all installed `@foundryprotocol/0gkit-*` packages.
- The top 10 frames of the stack.

```bash
# Run normally — error to stdout, report to stderr.
0g storage put ./big.bin --copy-issue-context

# Capture only the report:
0g storage put ./big.bin --copy-issue-context 2> issue.md
```

## `0g init [name]`

Scaffold a runnable, testnet-default project. Defaults the directory name to
`0g-app`. Writes `package.json`, `.env.example`, `index.mjs`, `README.md`,
`.gitignore`. **Errors** (`ConfigError`) if the target directory exists and is
non-empty.

```bash
0g init my-app
cd my-app && npm install
0g doctor
npm start
```

## `0g doctor`

Preflight every 0G surface for the selected network. Checks, in order:

1. **rpc** (required) — RPC reachable and reports the preset's chain id.
2. **signer** (soft) — key present and the address is funded (read-only is
   valid; absence is not a failure).
3. **storage-indexer** (soft) — indexer endpoint reachable (HTTP < 500).
4. **da-encoder** (soft) — DA encoder reachable (falls back to local mode).
5. **faucet** (informational) — faucet guidance for the network.

Exit `1` only if a **required** check fails (i.e. RPC).

```bash
0g doctor --network galileo
0g doctor --json | jq '.checks[] | select(.ok==false)'
```

### `0g doctor --fix`

Pass `--fix` to apply the **safe** auto-fixes `doctor` can make without touching
the network or installing anything (advisory-only by design — Decision D85):

- Regenerates a missing `.env` / `.env.example` from your `define0GConfig`.
- Prints the exact command to bump a stale package pin (it never edits your
  `package.json` for you).

```bash
0g doctor --fix
# ✓ wrote .env.example from 0g.config.ts
# → stale pin: run `npm i @foundryprotocol/0gkit-cli@latest`
```

`--fix` never installs dependencies, never sends a transaction, and never mutates
network state — it only writes local `.env*` files and prints next steps.

## `0g dev`

Spin up a **local 0G stack** (chain + storage + compute + DA) for offline
development — no testnet funds, no RPC latency.

| Subcommand         | What                                              |
| ------------------ | ------------------------------------------------- |
| `0g dev` / `start` | Start the local devnet (default subcommand).      |
| `0g dev stop`      | Stop the running devnet.                          |
| `0g dev status`    | Inspect the running devnet (ports, pids, health). |
| `0g dev reset`     | Stop the devnet **and wipe** its state directory. |

Common `start` flags: `--port-chain <n>` (default `8545`), `--port-da <n>`
(default `5680`), `--mnemonic <phrase>`, `--state-dir <path>` (default
`~/.0g-dev`), `--detach` (exit once services are up — for tests/CI).

```bash
0g dev --detach                       # start in the background
0g test --local                       # run conformance against it (see below)
0g dev status
0g dev reset                          # tear down + wipe state
```

## `0g test`

Run the **offline conformance suites** — storage / DA / and other primitive
round-trips — to prove your install and config work before you ship. Lazy-loads
[`@foundryprotocol/0gkit-testing`](/packages/0gkit-testing) so it never bloats
cold-start (Decision D39).

| Flag             | Meaning                                                                   |
| ---------------- | ------------------------------------------------------------------------- |
| `--suite <list>` | Comma-separated subset, e.g. `--suite=storage,da` (default: all).         |
| `--galileo`      | Run against the live galileo testnet (**default**).                       |
| `--local`        | Run against the running `0g dev` stack (`http://127.0.0.1:8545`).         |
| `--kits`         | Also run each applied kit's conformance check (reads `.0gkit/kits.json`). |

```bash
0g test                       # all suites, galileo
0g test --suite=storage,da    # just these two
0g test --local --kits        # local stack + every applied kit's check
0g test --json | jq '.ok'
```

Exit `1` if any suite fails — wire it as a CI gate before deploy.

## `0g chain`

Native-chain helpers.

| Subcommand                   | What                                                      |
| ---------------------------- | --------------------------------------------------------- |
| `0g chain faucet <address>`  | Request testnet funds (galileo points at the web faucet). |
| `0g chain balance <address>` | Native 0G balance (prints `0G` and wei).                  |
| `0g chain tx <hash>`         | Wait for a tx receipt + explorer link.                    |

```bash
0g chain balance 0xYourAddress --network aristotle
0g chain tx 0xYourTxHash --json
0g chain faucet 0xNew --network galileo   # → https://faucet.0g.ai
```

## `0g storage`

0G Storage. Networks restricted to `aristotle` | `galileo` (a `ConfigError`
otherwise).

| Subcommand                    | What                                                                 |
| ----------------------------- | -------------------------------------------------------------------- |
| `0g storage put <file>`       | Upload a file's bytes; prints `root` + `tx`. **Needs a signer key.** |
| `0g storage get <root> [out]` | Download by root; writes to `[out]` or prints byte count.            |
| `0g storage exists <root>`    | `true` if the root is retrievable.                                   |

```bash
export ZEROG_PRIVATE_KEY=0x...   # funds the upload tx
ROOT=$(0g storage put model.bin --network galileo --json | jq -r .root)
0g storage get "$ROOT" ./out.bin
0g storage exists "$ROOT" --json
```

## `0g infer`

Run a chat completion against a 0G compute provider. Requires a broker key
(`ZEROG_BROKER_KEY`, falling back to `ZEROG_PRIVATE_KEY` / `--private-key`)
and a provider (`--provider` or `ZEROG_PROVIDER`).

| Flag                   | Meaning                                 |
| ---------------------- | --------------------------------------- |
| `-m, --message <text>` | Prompt text (default: read stdin).      |
| `--provider <address>` | 0G inference provider (or env).         |
| `--model <name>`       | Model id (provider default if omitted). |
| `--temperature <n>`    | Sampling temperature.                   |

```bash
export ZEROG_BROKER_KEY=0x... ZEROG_PROVIDER=0xPROVIDER
0g infer -m "Summarize 0G in one line" --network galileo
echo "What is 0G DA?" | 0g infer --json | jq -r .output
```

## `0g da`

0G Data Availability.

| Subcommand                     | What                                                     |
| ------------------------------ | -------------------------------------------------------- |
| `0g da publish <file>`         | Publish a blob (`-` = stdin); local-digest mode off-net. |
| `0g da verify <file> <digest>` | Local integrity check: recompute the digest and compare. |

```bash
0g da publish payload.json --network galileo --json | jq -r .digest
echo '{"a":1}' | 0g da publish - --json
0g da verify payload.json 0xDIGEST   # prints MATCH / MISMATCH
```

## `0g attest`

TEE attestation. Operates on a `SignedEnvelope` JSON file
(`{ envelope, digest, signature }`).

| Subcommand                                   | What                                                                                               |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `0g attest verify <file> --signer <address>` | Verify digest integrity **and** signer identity. `--signer` is required. Exit `1` if not verified. |
| `0g attest report <file>`                    | Human-readable summary of the signed envelope.                                                     |

```bash
0g attest verify signed.json --signer 0xCoordinator
0g attest report signed.json --json
```

## `0g contracts`

Generate a **typed TypeScript client** from a contract ABI — either an off-chain
Foundry artifact or a verified ABI fetched from the chain explorer.

| Subcommand                      | What                                                                                                                       |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `0g contracts generate`         | Codegen from a local Foundry artifact JSON. `--abi <path>` + `--out <dir>` required; `--name` overrides the contract name. |
| `0g contracts import [address]` | Fetch a **verified** ABI from the explorer (or `--abi <path>`) → codegen. `--out` defaults to `./0gkit/contracts`.         |
| `0g contracts list`             | List the bundled standard 0G contracts and their pinned addresses.                                                         |
| `0g contracts info <name>`      | Show the ABI summary for a bundled standard contract.                                                                      |

`import` fetches the ABI from 0G ChainScan's Etherscan-compatible `/open/api`
(keyless; set `OG_EXPLORER_API_KEY` only for rate-limit relief). **`--name` is
required when importing by address** — the explorer's `getabi` carries no
contract name. An unverified contract, an HTTP error, or a malformed payload
throws a `ConfigError` pointing you at `--abi <path>.json` — it **never**
fabricates an ABI.

```bash
# From a verified on-chain contract (galileo default):
0g contracts import 0xAbc…DEF --name MyToken
# → wrote ./0gkit/contracts/MyToken.ts

# From a local Foundry artifact:
0g contracts generate --abi ./out/MyToken.sol/MyToken.json --out ./src/contracts

0g contracts list --json
```

The generated client is fully typed and wraps `@foundryprotocol/0gkit-contracts`
— see the [contracts package docs](/packages/0gkit-contracts).

## `0g cost`

Cost forecasting across 0G primitives. Two modes — synthesise estimates from
flags, or aggregate _real_ per-op costs from a [Jaeger](https://www.jaegertracing.io/) trace
emitted by `@foundryprotocol/0gkit-observability`.

| Subcommand                                                               | What                                                                                                       |
| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `0g cost forecast --storage <bytes...> --compute <spec...> --da <bytes>` | Sum hypothetical estimates across one or more ops. Pass any combination of the three primitives.           |
| `0g cost forecast --from-jaeger <trace.json>`                            | Aggregate **real** per-op gas + fee totals from a Jaeger v1 trace dump. Mutually exclusive with the above. |

```bash
# Hypothetical: forecast a workload before you run it
0g cost forecast \
  --storage 1024,4096 \
  --compute "summarise|llama-3-8b|512" \
  --da 2048 \
  --json

# Real: replay an existing trace through the cost calculator
0g cost forecast --from-jaeger ./trace.json --json
```

`--from-jaeger` scans every span carrying the `0gkit.op` attribute (emitted
automatically by [`@foundryprotocol/0gkit-observability`](/packages/0gkit-observability)),
groups by op, and sums `0gkit.fee_native` + `0gkit.gas_native`. Dry-run spans
(`0gkit.dry_run=true`) and errored spans (any `0gkit.error_code` tag) are
counted but excluded from totals — they did not spend on-chain resources.

The JSON envelope from `--from-jaeger`:

```json
{
  "ok": true,
  "source": "jaeger",
  "file": "trace.json",
  "spansScanned": 42,
  "spansAttributed": 18,
  "spansSkipped": 2,
  "byOp": {
    "storage.upload": {
      "count": 3,
      "totalGas": "240000",
      "totalFeeWei": "3000000000",
      "totalSizeBytes": 12288
    },
    "compute.inference": {
      "count": 12,
      "totalGas": "0",
      "totalFeeWei": "6000000000",
      "totalInputTokens": 2400,
      "totalOutputTokens": 6144
    },
    "da.publish": {
      "count": 3,
      "totalGas": "0",
      "totalFeeWei": "1536000000",
      "totalSizeBytes": 1536
    }
  },
  "totalGas": "240000",
  "totalFeeWei": "10536000000"
}
```

Download a trace dump from the Jaeger UI (Trace → ⋮ → Download JSON) or hit
the query API directly (`/api/traces/<id>`). The same parser works against any
OTLP collector that exports the Jaeger JSON format.

Pass `-` as the file path to read a Jaeger envelope from stdin — pipes
cleanly from `0g traces inspect <id> --json` (see below).

## `0g estimate`

Quick per-op cost estimates for a **concrete** input (a real file, a prompt, a
byte size). Where `0g cost forecast` sums hypothetical or trace-aggregated
workloads, `estimate` answers "what will _this one_ op cost?"

| Subcommand                   | What                                                                                                                                      |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `0g estimate storage <file>` | Estimate the cost to upload `<file>` to 0G Storage.                                                                                       |
| `0g estimate compute`        | Estimate a chat completion. `-p, --prompt <text>`, `--model <name>`, `--max-output <n>` (default 512).                                    |
| `0g estimate da [file]`      | Estimate a 0G DA publish. `[file]` or `--bytes <n>`.                                                                                      |
| `0g estimate contracts`      | Estimate gas + fee for a contract write. Required: `--abi <path>`, `--address <0x>`, `--method <name>`; optional `--args '<json array>'`. |

```bash
0g estimate storage ./model.bin --json
0g estimate compute -p "Summarize 0G" --model llama-3.1-8b --max-output 256
0g estimate da --bytes 4096
```

## `0g traces`

Inspect local 0gkit trace JSONL files written by the `OGKIT_TRACE_DIR`
opt-in mirror in `@foundryprotocol/0gkit-observability`. Off by default;
when the env var is set, every instrumented span is written to
`<dir>/<YYYY-MM-DD>-<traceId>.jsonl` in addition to your configured OTel
exporter. Pure local sink — no network, no extra infra.

| Subcommand                  | What it does                                                        |
| --------------------------- | ------------------------------------------------------------------- |
| `0g traces list [--last N]` | Show trace files newest-first with span count + fee total + top op. |
| `0g traces inspect <id>`    | Pretty-print every span in a trace (op, fee, gas, attributes).      |

### Quickstart

```bash
# In the process that runs your 0gkit code:
export OGKIT_TRACE_DIR=.0gkit/traces

# After requests have run:
0g traces list --last 5
0g traces inspect <traceId>

# Replay one local trace as a cost forecast:
0g traces inspect <traceId> --json | 0g cost forecast --from-jaeger -
```

Both subcommands accept `--dir <path>` to override `OGKIT_TRACE_DIR` for a
one-off look at a directory copied from a teammate. `--json` is supported
on both for piping into other tooling.

## `0g kits`

Compose your app from **kits** — overlays that drop in a portable `lib/`,
per-base `adapters/`, and (for React bases) a `ui/` tier, deduping dependencies
as they apply. See the [kits guide](/kits) and
[authoring guide](/kits/authoring).

| Subcommand           | What                                                               |
| -------------------- | ------------------------------------------------------------------ |
| `0g add <kit...>`    | Apply one or more kits to the current project.                     |
| `0g kits list`       | List kits compatible with the detected (or `--base`) project base. |
| `0g kits info <kit>` | Show a kit's description, tiers, deps, and env.                    |

`0g add` flags: `--base <name>` (force the base: `react-app` \| `mcp-agent` \|
`node` \| …), `--pm <pnpm|npm|yarn>` (which package manager appears in the
printed install hint), `--dry-run` (preview what would be written, touch
nothing). Kits are fetched from the template registry via `giget` at apply-time.

```bash
0g kits list --base react-app
0g kits info agent-memory
0g add agent-memory live-feed        # applies both (composed deps resolved first)
0g add ai-oracle --dry-run           # preview only
```

## `0g jobs`

Inspect `@foundryprotocol/0gkit-jobs` queues.

| Subcommand            | What                                      |
| --------------------- | ----------------------------------------- |
| `0g jobs status <id>` | Print the `JobRecord` for a given job id. |

Flags: `--backend <memory|sqlite>` (default `sqlite`), `--path <path>` (sqlite
file, default `./.jobs.db`).

```bash
0g jobs status job_abc123 --backend sqlite --path ./.jobs.db --json
```

## `0g mcp init <agent>`

Wire the 0gkit tool set into your AI editor. Writes the MCP server config for the
given agent — one of `cursor`, `claude`, `windsurf`, `codex`. In a kitted
`mcp-agent` project it also surfaces your applied kits' tools.

| Flag       | Meaning                                                      |
| ---------- | ------------------------------------------------------------ |
| `--global` | Install to the agent's user-level config (default: project). |

```bash
0g mcp init cursor            # writes project-level MCP config
0g mcp init claude --global   # user-level config
# → restart the agent to pick up the 0gkit tools
```

Writes editor config only — it never mutates network state. See the
[MCP guide](/mcp).

## `0g foundry …` (opt-in, hidden)

The optional Foundry plugin namespace. Hidden unless `@foundryprotocol/mcp`
is installed or you pass `--foundry`. Absent by default — the neutrality
boundary stays green by construction.

## Scripting from any language

`--json` is stable and meaningful exit codes make `0g` a clean subprocess:

```bash
# Python
import json, subprocess
r = subprocess.run(["0g","storage","exists",root,"--json"],
                    capture_output=True, text=True)
print(json.loads(r.stdout)["exists"])
```

## Related

[storage](/packages/storage) · [compute](/packages/compute) ·
[da](/packages/da) · [attestation](/packages/attestation) · [MCP
guide](/mcp) (the same surface for agents).
