/midnight-skills:compactfrom midnight-skills
Write, reason about, and debug Compact smart contracts for the Midnight blockchain. Covers syntax, ledger state, witnesses, circuits, ZK patterns, data types, standard library, security, and privacy-preserving patterns.
Ships in midnight-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Versions: every pin in this skill comes from
references/versions.json, the repo's single source of truth (checked in CI). Resolve the current set at use time withreferences/volatile.md. Never install@latest.
Compact is Midnight's smart contract language. It looks like TypeScript but compiles to zero-knowledge circuits. The compiler handles all cryptographic machinery — you write business logic.
Toolchain (Ledger 9.1, Nov 2026): Compact toolchain 0.36.1, language version 0.28.0,
@midnight-ntwrk/compact-runtime0.21.0. Install withcompact update 0.36.1and compile withcompact compile +0.36.1 ...so the compiler always matches the runtime you pinned. Every full example in this skill compiles with 0.36.1. Output built with 0.31.x / ZKIR v2 must be recompiled, and recompiling changes the verifier keys (redeploy, or replace keys through the maintenance authority).
Primary references:
compact-book.vercel.app — structured example-driven reference (your best source)docs.midnight.network/compact — official spec and the standard-library exports pagedocs.midnight.network/relnotes/compact/toolchain-0.36.0 — language 0.28.0 changesThree non-negotiables before writing anything:
1. A circuit is a constraint system, not a function.
It declares relationships that MUST hold. The proof proves they held.
2. The ledger is public. Everything in `export ledger` is plaintext on-chain.
Private data lives in witnesses. It never touches the chain.
3. `disclose()` is a compile-time annotation, not encryption.
It tells the compiler "I am intentionally making this public."
The compiler prevents accidental disclosure. No runtime cost.
The two worlds:
| World | Where | Who sees it | Updated by |
|---|---|---|---|
export ledger | Every network node | Everyone | ZK proof |
witness (private) | User's local storage | Only the owner | Never (stays local) |
Every Compact contract has four mandatory pieces + one optional:
pragma language_version >= 0.28.0; // 1. Language version
import CompactStandardLibrary; // optional, needed for hashing, Merkle, etc.
export ledger counter: Uint<64>; // 2. Public state (on-chain, readable by all)
witness callerSecret(): Bytes<32>; // 3. Private input (body lives in TypeScript)
constructor() { // 5. OPTIONAL: runs once on deployment
counter = 0;
}
export circuit increment(): [] { // 4. Logic (compiles to ZK circuit)
counter = disclose((counter + 1) as Uint<64>);
}
| Piece | Keyword | Purpose |
|---|---|---|
| Public state | export ledger | On-chain, readable by all |
| Private inputs | witness | Callbacks the DApp provides (body in TypeScript) |
| Logic | export circuit | Compiles to ZK circuits |
| Initialization | constructor | Runs once on deploy |
| Organization | module / import | Namespace and file management |
| Type | Range/Size | Notes |
|---|---|---|
Boolean | true / false | No truthy/falsy coercion |
Field | 0 to prime field order | Only == and != — no <, > |
Uint<n> | n-bit unsigned, wraps on overflow | Uint<8> = 0..255 |
Uint<0..n> | Bounded integer, 0 to n-1 | Supports <, >. Cast can fail at runtime |
Bytes<n> | Exactly n bytes | Use pad(n, str) for fixed-length from strings |
Opaque<"string"> | Foreign JS data | Circuits see only hash, not contents. Not hidden on-chain |
Critical: Use Field only for equality checks. Use Uint<0..n> whenever you need ordering (<, <=, >, >=).
// Tuple
const pair: [Field, Boolean] = [42, true];
const first = pair[0];
// Vector (homogeneous, fixed-length)
const v: Vector<4, Uint<8>> = [1, 2, 3, 4];
// Struct (nominal typing — shape isn't enough, name matters)
struct Point { x: Uint<32>, y: Uint<32> }
const p = Point { x: 10, y: 20 };
// Enum (first variant = default)
enum State { VACANT, OCCUPIED }
type Hash = Bytes<32>; // structural alias — fully interchangeable
new type UserId = Bytes<32>; // nominal alias — requires explicit cast
Every type has a zero default: false, 0, n zero bytes, first enum variant. Access with default<T>().
disclose()ledger val: Field; // private to contract, not exported
export ledger cnt: Counter; // readable from TypeScript/DApp
sealed ledger config: Uint<32>; // write-once (only in constructor)
export sealed ledger mapping: Map<Boolean, Field>;
disclose() RuleIf data flows from a witness to a ledger write (or circuit return), it must be wrapped in disclose(). The compiler tracks witness taint through every operation and will error if untainted disclosure reaches the ledger.
// ❌ COMPILER ERROR — undisclosed witness data reaching ledger
export circuit record(): [] {
stored = getSecret();
}
// ✅ CORRECT — explicitly disclosed
export circuit record(): [] {
stored = disclose(getSecret());
}
disclose() is not encryption. It is a compile-time signal. The disclosed value is plaintext on-chain.
| Use case | Type |
|---|---|
| Single mutable value | ledger f: T (Cell) |
| Monotonically growing counter | Counter (use .increment(n)) |
| Membership tracking (reveals which) | Set<T> |
| Per-key storage | Map<K, V> |
| Ordered queue | List<T> |
| Anonymous membership proofs (current root) | MerkleTree<n, T> |
| Anonymous membership proofs (past roots) | HistoricMerkleTree<n, T> |
| Block time, tokens, contract address | Kernel |
// Exported = callable from DApp
export circuit post(msg: Opaque<"string">): [] {
message = disclose(msg);
}
// Pure = no ledger access, no side effects
pure circuit publicKey(sk: Bytes<32>, seq: Bytes<32>): Bytes<32> {
return persistentHash<Vector<3, Bytes<32>>>([pad(32, "domain:"), seq, sk]);
}
// Internal (no export keyword) — not callable from DApp
circuit hashTokenData(owner: Bytes<32>, meta: Bytes<32>): Bytes<32> {
return persistentHash<Vector<2, Bytes<32>>>([owner, meta]);
}
[] as return type = no return value (procedure-style)assert(condition, "message") = runtime guard, transaction fails if condition is falseassert — witnesses are untrustedA witness declares a private input callback. The signature is in Compact, the body is in TypeScript.
// Compact side — declaration only
witness callerAddress(): Bytes<32>;
witness findMerklePath(leaf: Bytes<32>): MerkleTreePath<10, Bytes<32>>;
// TypeScript side — implementation
function callerAddress(context: WitnessContext): Uint8Array {
return context.coinPublicKey; // or wallet-derived address
}
function findMerklePath(
context: WitnessContext,
leaf: Uint8Array,
): MerkleTreePath<Uint8Array> {
return context.ledger.items.findPathForLeaf(leaf)!;
}
Witness data never touches the chain. Only the ZK proof that the circuit ran correctly goes on-chain.
Full content: references/standard-library.md. It covers key standard-library functions with signatures and usage. Open it when you reach this step.
The official security docs are "coming soon." Use these patterns from the compact-book.
| Operation | What it reveals |
|---|---|
ledger.insert(v) | The value v |
ledger.lookup(k) | Key k and the returned value |
set.member(f(x)) | f(x), not x |
merkleTree.insert(v) | Does NOT reveal v |
| Circuit arguments | All of them |
witness return values | Nothing (stays local) |
export ledger balanceCommitments: Map<Bytes<32>, Bytes<32>>;
export circuit commitBalance(value: Uint<64>): [] {
const nonce = freshNonce();
const commitment = persistentCommit<Uint<64>>(value, nonce);
balanceCommitments.insert(disclose(callerAddress()), disclose(commitment));
}
Nonce reuse = privacy catastrophe. Two commitments with same nonce + value are identical on-chain. Always fresh nonce.
witness secretKey(): Bytes<32>;
export ledger organizer: Bytes<32>;
constructor() {
organizer = disclose(publicKey(secretKey()));
}
export circuit adminAction(): [] {
assert(organizer == publicKey(secretKey()), "not authorized");
// ... do the thing
}
pure circuit publicKey(sk: Bytes<32>): Bytes<32> {
return persistentHash<Vector<2, Bytes<32>>>(
[pad(32, "myapp:admin:v1"), sk]
);
}
Domain separator is critical. Same secret key → different public keys for different purposes. Never reuse a public key across domains.
Set<T> reveals which commitment was checked. MerkleTree<n, T> only reveals that some value was proven.
export ledger allowlist: MerkleTree<16, Bytes<32>>;
witness findPath(leaf: Bytes<32>): MerkleTreePath<16, Bytes<32>>;
export circuit addToAllowlist(commitment: Bytes<32>): [] {
allowlist.insert(disclose(commitment)); // insert still requires disclose
}
export circuit proveAllowlisted(): [] {
const sk = secretKey();
const leaf = publicKey(sk);
const path = findPath(leaf);
assert(
allowlist.checkRoot(merkleTreePathRoot<16, Bytes<32>>(path)),
"not in allowlist"
);
// proof: caller is in the allowlist. Nothing else revealed.
}
Depth guide: each level adds ~1 to circuit depth. 16–20 is typical. Use minimum depth needed.
export ledger commitments: HistoricMerkleTree<16, Bytes<32>>;
export ledger nullifiers: Set<Bytes<32>>;
export circuit spend(): [] {
const sk = secretKey();
const commitment = makeCommitment(sk);
const path = findCommitmentPath(commitment);
// 1. Prove membership
assert(
commitments.checkRoot(merkleTreePathRoot<16, Bytes<32>>(path)),
"not in commitments tree"
);
// 2. Prevent reuse
const nul = makeNullifier(sk);
assert(!nullifiers.member(nul), "already spent");
nullifiers.insert(disclose(nul));
}
// CRITICAL: commitment and nullifier MUST use different domain separators
pure circuit makeCommitment(sk: Bytes<32>): Bytes<32> {
return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:commit:v1"), sk]);
}
pure circuit makeNullifier(sk: Bytes<32>): Bytes<32> {
return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:nullifier:v1"), sk]);
}
Use HistoricMerkleTree only when proofs must verify against past roots (i.e., items may be added after the proof was computed). Otherwise use plain MerkleTree.
Full content: references/contract-examples.md. It covers complete, annotated example contracts. Open it when you reach this step.
# Install and pin the Ledger 9.1 toolchain
compact update 0.36.1
compact compile +0.36.1 --version # 0.36.1
compact compile +0.36.1 --language-version # 0.28.0
# Compile a contract (--skip-zk skips key generation for fast iteration)
compact compile +0.36.1 contracts/your-contract.compact contracts/managed/your-contract
# Output structure
contracts/managed/your-contract/
compiler/
contract-info.json # declares runtime-version
contract-manifest.json # integrity manifest (verified by FetchZkConfigProvider)
contract/ # generated JS + .d.ts (imports @midnight-ntwrk/compact-runtime)
keys/
circuitName.prover # 2–10 MB
circuitName.verifier # ~2 KB
zkir/
circuitName.bzkir # ZKIR v3
When serving artifacts to a browser, copy compiler/ along with keys/ and zkir/. Without it Midnight.js 5 refuses the bundle (EraMismatchError). In compact-runtime 0.21, circuits and initialState are async, and witnesses receive WitnessContext<Ledger, PrivateState>.
TypeScript bindings are also generated — import the Contract object from the managed output folder.
Circuit size on preview: ProofStation requires minimum circuit size (k ≥ 6). Error: prove: no SRS params for k=6 means the circuit is too small. Pad with additional dummy ledger fields to increase size.
Disclosure mistakes:
disclose() → compiler error (good, caught early)export circuit without disclose() → compiler errordisclose() encrypts data → it doesn't, it's plaintextType mistakes:
Field when you need <, > → use Uint<0..n> insteadas Uint<0..n> cast at runtime → can fail if value is out of range (transaction error, not compile error)type Hash = Bytes<32> (structural, interchangeable) with new type UserId = Bytes<32> (nominal, requires cast)Privacy mistakes:
persistentHash for small value spaces (brute-forcible) → use persistentCommit with fresh nonceSet<T> when you need anonymity → Set.member(v) reveals v. Use MerkleTree insteadtransientHash for ledger storage → transient values don't survive contract upgradesexport ledger → privacy leakLedger mistakes:
assert on witness outputs → witnesses are untrusted, validate themconstructor that should be in circuits → constructor runs once and is doneHistoricMerkleTree unnecessarily → adds storage cost; use MerkleTree unless past roots are neededexport on internal helper circuits → exposes surface area unnecessarily| Keyword | Purpose |
|---|---|
pragma language_version >= n | Declare minimum language version |
import ModuleName | Import a module |
export ledger f: T | Public on-chain state field |
sealed ledger f: T | Write-once state (constructor only) |
witness f(): T | Private input callback (body in TypeScript) |
export circuit f(): T | Callable ZK circuit |
pure circuit f(): T | Pure function (no ledger access) |
constructor() | Runs once on deployment |
disclose(v) | Mark intentional public disclosure |
assert(cond, msg) | Runtime guard (tx fails if false) |
default<T>() | Zero/empty value for type T |
pad(n, str) | Create Bytes<n> from string |
some<T>(v) / none<T>() | Maybe/Option constructors |
new type A = B | Nominal type alias |
type A = B | Structural type alias |
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub kali-decoder/midnight-skills --plugin midnight-skills43 skills in this plugin
/1am-walletIntegrate the 1AM wallet for dust-free contract deployment and transaction flow on Midnight Network. Use this skill whenever a user is building a Midnight Network dApp, connecting to the 1AM browser extension, deploying or calling a Compact contract, handling ZK proving, setting up providers, or asking about dust-free transaction flow. Also use it for indexer patching, private state providers, payload encryption, or any question involving window.midnight['1am']./android-example-votingBuild a voting/poll dApp on Midnight Network using the Kuira Android SDK — Compact smart contract with create/cast/close circuits, passkey-derived identity, embedded wallet, Compose UI, reactive ledger reads via observeLedger(), and on-device ZK proving. Use when building a poll or voting dApp targeting Android./Other plugins' skills for the same job