/midnight-skills:example-zk-loan-applicationfrom midnight-skills
Builds a zero-knowledge loan dApp on Midnight Network with private credit scoring inside Compact circuits, Schnorr attestation, and optional Next.js frontend.
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.
A privacy-preserving loan dApp where applicants prove eligibility inside a ZK circuit without revealing credit score, income, or tenure on-chain. A trusted attestation provider signs credit data off-chain; the contract verifies the Schnorr signature in-circuit and writes only the loan outcome (status + authorized amount) to the ledger.
What this skill produces:
contract/ — schnorr.compact + zkloan-credit-scorer.compact, witnesses, compile scriptszkloan-credit-scorer-attestation-api/ — REST server that Schnorr-signs credit profileszkloan-credit-scorer-cli/ — deploy, register providers, request/respond to loans (headless wallet)app/loan/ (optional) — Next.js + 1AM wallet UI (copy patterns from templates/leaderboard-dapp/)lib/zkloan.ts — deploy, requestLoan, respondToLoan, admin calls, ledger decodelib/midnight.ts — wallet session + patched indexer provider (copy from references/midnight-session.md)public/zk/zkloan/ — ZK proving assets synced from contract buildShared references (canonical provider + troubleshooting — do not duplicate in prompts):
references/midnight-session.md — createConnectedSession, indexer patch, deploy/call helpersreferences/gotchas.md — Ledger 9 errors (version mismatch, EraMismatchError, Blockfrost 410/403), ZK asset pathsreferences/versions.json — the Ledger 9.1 pin setPrimary references:
example-leaderboard-dapp/ / templates/leaderboard-dapp/ — Next.js + 1AM, low-level deploy/call, indexer readsexample-locker-dapp/ — witness private state, createUnprovenDeployTx + submitTxAsyncexample-counter/ — headless CLI wallet, monorepo workspaces, vitest contract testscompact/ — disclose(), witnesses, persistentHash, Map, Set, new type, pure circuitssecurity/ — never trust ownPublicKey() for caller identity; witness-derived keysindexer/ — read public loan ledger without walletKey architecture notes:
ownPublicKey() for auth — it is prover-supplied and bypassable; derive identity from getUserSecret() witness + PIN via deriveUserPublicKey / deriveAdminPublicKeytransientHash(userPubKeyBytes) inside evaluateApplicantrequestLoan may return Proposed when amount exceeds tier max — user calls respondToLoan to accept/declinechangePin + onGoingPinMigration ledger mapcreateUnprovenDeployTx + submitTxAsync — not deployContract() (hangs on preprod)@midnightntwrk/wallet-sdk-shielded (Iterator helpers on Map.values())When helping the user, follow this sequence:
package.json workspaces: contract, attestation-api, clischnorr.compact + zkloan-credit-scorer.compact) + witnessesuserSecretKey + contract address in private stateregisterProvider(providerId, providerPk) on-chainrequestLoan(amount, secretPin)Proposed, call respondToLoan(loanId, secretPin, accept)loans nested map (public)zkloan-credit-scorer/
├── package.json # workspaces + pinned Midnight.js 5.0.2 / ledger-v9 1.0.2
├── .nvmrc # 22
├── contract/
│ ├── package.json
│ └── src/
│ ├── schnorr.compact
│ ├── zkloan-credit-scorer.compact
│ ├── witnesses.ts
│ ├── index.ts
│ └── managed/zkloan-credit-scorer/ # compiler output (gitignored)
├── zkloan-credit-scorer-attestation-api/
│ └── src/ # Express/Fastify REST — sign credit profiles
├── zkloan-credit-scorer-cli/
│ └── src/ # deploy, register-provider, request-loan, admin
└── zkloan-dapp/ # optional Next.js frontend
├── lib/midnight.ts # copy from templates/leaderboard-dapp
├── lib/zkloan.ts
├── app/loan/LoanClient.tsx
├── contract/ # symlink or workspace import from ../contract
├── scripts/sync-zk-assets.mjs
└── public/zk/zkloan/
Root package.json engines: "node": ">=22.0.0". Workspaces pin @midnight-ntwrk/compact-runtime: 0.21.0, @midnight-ntwrk/compact-js: 3.0.2, @midnightntwrk/midnight-js-*: 5.0.2, @midnightntwrk/ledger-v9: 1.0.2, Wallet SDK 2.0.1 (wallet-sdk-facade 5.0.1) for the CLI. Remove midnight-js-network-id (no setNetworkId in Midnight.js 5).
contract/src/schnorr.compact)Verifies Jubjub Schnorr signatures inside the circuit. It was written as a polyfill while the standard library had no Schnorr verifier.
Ledger 9 update: the 0.36.1 standard library now has a native verifier. This compiles:
export circuit check(msg: Vector<4, Field>, sig: JubjubSchnorrSignature, pk: JubjubPoint): [] {
ok = disclose(jubjubSchnorrVerify<4>(msg, sig, pk)); // Boolean; rejects the identity pk (since 0.35)
}
Migrating isn't a drop-in swap. The polyfill computes its own transientHash challenge (schnorrChallenge), and the native circuit may hash differently, so signatures produced by the attestation API for the polyfill may not verify natively. Move the signer and the circuit together, then redeploy. Until then, the polyfill still works.
module schnorr {
import CompactStandardLibrary;
export struct SchnorrSignature { announcement: JubjubPoint; response: Field; }
witness getSchnorrReduction(challengeHash: Field): [Field, Uint<248>];
export circuit schnorrVerify<#n>(msg: Vector<n, Field>, signature: SchnorrSignature, pk: JubjubPoint): [] { /* ... */ }
export pure circuit schnorrChallenge(...): Field { /* transientHash challenge */ }
}
JubjubPoint equality: compare jubjubPointX() / jubjubPointY() — struct == is reference equality and always fails for fresh points.
contract/src/zkloan-credit-scorer.compact)pragma language_version >= 0.28.0;
import CompactStandardLibrary;
import "schnorr" prefix Schnorr_;
export enum LoanStatus { Approved, Rejected, Proposed, NotAccepted }
export struct LoanApplication { authorizedAmount: Uint<16>; status: LoanStatus; }
export new type UserSecretKey = Bytes<32>;
export new type UserPublicKey = Bytes<32>;
export new type AdminPublicKey = Bytes<32>;
export ledger blacklist: Set<UserPublicKey>;
export ledger loans: Map<Bytes<32>, Map<Uint<16>, LoanApplication>>;
export ledger onGoingPinMigration: Map<Bytes<32>, Uint<16>>;
export ledger contractAdmin: AdminPublicKey;
export ledger providers: Map<Uint<16>, JubjubPoint>;
witness getAttestedScoringWitness(): [Applicant, Schnorr_SchnorrSignature, Uint<16>];
witness getUserSecret(): UserSecretKey;
export pure circuit deriveUserPublicKey(sk: UserSecretKey, pin: Uint<16>): UserPublicKey { /* persistentHash domain "zkloan:user:pk:v1" */ }
export pure circuit deriveAdminPublicKey(sk: UserSecretKey): AdminPublicKey { /* "zkloan:admin:pk:v1" */ }
export circuit requestLoan(amountRequested: Uint<16>, secretPin: Uint<16>): [] { /* ... */ }
export circuit respondToLoan(loanId: Uint<16>, secretPin: Uint<16>, accept: Boolean): [] { /* ... */ }
export circuit changePin(oldPin: Uint<16>, newPin: Uint<16>): [] { /* batched migration, 5 per tx */ }
// Admin (all guard with deriveAdminPublicKey(getUserSecret()) == contractAdmin)
export circuit blacklistUser(account: UserPublicKey): [] { /* ... */ }
export circuit registerProvider(providerId: Uint<16>, providerPk: JubjubPoint): [] { /* ... */ }
export circuit rotateAdmin(newAdmin: AdminPublicKey): [] { /* ... */ }
Privacy boundary:
| Data | Visibility |
|---|---|
| Credit score, income, tenure | Private (witness) |
| Attestation signature | Private (ZK input) |
| User secret + PIN | Private (witness / circuit input) |
Derived UserPublicKey (loan map key) | Public (ledger) |
| Loan status + authorized amount | Public (ledger) |
contractAdmin, providers, blacklist | Public (ledger) |
Compile:
cd contract
npm run compact # → src/managed/zkloan-credit-scorer/
npm run build
cd ..
For browser UI also run npm run sync:assets (copies keys/zkir → public/zk/zkloan/).
contract/src/witnesses.ts:
export type ZKLoanCreditScorerPrivateState = {
creditScore: bigint;
monthlyIncome: bigint;
monthsAsCustomer: bigint;
attestationSignature: SchnorrSignature;
attestationProviderId: bigint;
userSecretKey: Uint8Array; // 32 bytes — authoritative caller identity
};
export const witnesses = {
getAttestedScoringWitness: (ctx) => [ctx.privateState, [profile, sig, providerId]],
getSchnorrReduction: (ctx, challengeHash) => [ctx.privateState, [q, r]], // challenge / 2^248
getUserSecret: (ctx) => [ctx.privateState, ctx.privateState.userSecretKey],
};
Before requestLoan, TypeScript must:
userSecretKey is 32 bytes (persist in localStorage or CLI keystore)Trusted off-chain signer. Flow:
sequenceDiagram
participant User
participant API as Attestation API
participant Wallet as 1AM / CLI
participant Chain as Midnight Network
User->>API: POST /attest { creditScore, income, tenure, userPubKeyHash }
API->>API: Schnorr-sign msg = [score, income, tenure, userPubKeyHash]
API-->>User: { signature, providerId }
User->>Wallet: requestLoan(amount, pin) + private state with attestation
Wallet->>Chain: ZK tx — evaluateApplicant verifies signature in-circuit
Chain-->>User: Loan Proposed / Approved / Rejected on ledger
Implementation checklist:
pureCircuits.schnorrChallenge (same hash as in-circuit){ announcement, response } + providerIdregisterProvider(providerId, providerPk) on-chain before any loan succeedstransientHash(deriveUserPublicKey(secret, pin)) — same hash the circuit usesExample endpoint shape:
// POST /attest
// body: { creditScore, monthlyIncome, monthsAsCustomer, userPubKeyHash: string }
// response: { providerId, signature: { announcement: { x, y }, response } }
Run locally (default port e.g. 3001):
cd zkloan-credit-scorer-attestation-api
npm run dev
Mirror example-counter/ CLI patterns:
| Command | Purpose |
|---|---|
deploy | createUnprovenDeployTx → stores deployer as admin via constructor |
register-provider <id> | Admin: on-chain provider pubkey from attestation API |
request-loan <amount> <pin> | Fetch attestation → set private state → requestLoan |
respond-loan <id> <pin> accept|decline | Accept or decline Proposed loan |
list-loans | Indexer read of public loans map for derived user key |
change-pin <old> <new> | Repeat until onGoingPinMigration cleared |
blacklist-user <userPk> | Admin governance |
Use @midnightntwrk/wallet-sdk-facade + level private state provider. Point at local proof server + preprod indexer from wallet config or .env.
lib/zkloan.ts — same low-level pattern as templates/leaderboard-dapp/lib/leaderboard.ts:
| Function | Purpose |
|---|---|
getOrCreateUserSecret() | Persist 32-byte secret in localStorage |
deriveUserPublicKey(session, pin) | Call exported pure circuit off-chain |
fetchAttestation(apiUrl, profile, userPubKeyHash) | POST to attestation API |
deployZkLoan(session) | Deploy + seed private state with secret |
registerProvider(session, addr, id, pk) | Admin circuit call |
requestLoan(session, addr, amount, pin, profile) | Attest → update private state → requestLoan |
respondToLoan(session, addr, loanId, pin, accept) | Accept/decline proposed amount |
fetchLoanState(queryUrl, addr, userPkBytes) | Indexer poll + decode nested loans map |
import { createUnprovenDeployTx, submitCallTxAsync, submitTxAsync } from '@midnightntwrk/midnight-js-contracts';
import { ContractState } from '@midnight-ntwrk/compact-runtime';
import { CompiledZKLoanContract, Contract, ledger } from '../contract/src/index';
export const ZK_PATH = '/zk/zkloan';
const PRIVATE_STATE_ID = 'zkloanPrivateState';
export async function requestLoan(session, contractAddress, amount, pin, attestation) {
await session.providers.privateStateProvider.set(PRIVATE_STATE_ID, {
...attestation,
userSecretKey: getOrCreateUserSecret(),
});
await submitCallTxAsync(session.providers, {
compiledContract: CompiledZKLoanContract,
contractAddress,
circuitId: 'requestLoan',
args: [BigInt(amount), BigInt(pin)],
privateStateId: PRIVATE_STATE_ID,
});
}
ZK asset path: /zk/zkloan (synced to public/zk/zkloan/).
Copy structure from templates/leaderboard-dapp/app/leaderboard/LeaderboardClient.tsx:
detectWallet() → wallet.connect('preprod') → createConnectedSession(api, ZK_PATH)localStoragerequestLoanProposed, buttons to accept max eligible amount or declinechangePin repeatedly until migration complete)Indexer reads work without wallet for public loan records — only writes need connection + attestation.
# Terminal 1 — proof server
docker run -d -p 6300:6300 midnightntwrk/proof-server:9.0.2 midnight-proof-server -v
# Terminal 2 — attestation API
cd zkloan-credit-scorer-attestation-api && npm run dev
# Terminal 3 — CLI or Next.js UI
cd zkloan-credit-scorer-cli # or zkloan-dapp/
npm install
cd ../contract && npm run compact && npm run build && cd ..
npm run sync:assets # UI only
npm run deploy # CLI
npm run register-provider 1
npm run request-loan 5000 1234
Wallet: a Ledger 9 build of 1AM on Preprod (or Preview), proof server http://localhost:6300, tNIGHT from the faucet registered for DUST. Preprod cleared non-cNIGHT DUST registrations on 9 Nov 2026, so register again. Headless CLI endpoints for Preprod are Blockfrost and need BLOCKFROST_PROJECT_ID.
| Component | Version |
|---|---|
| Node.js | ≥ 22 (required for shielded wallet SDK) |
Compact toolchain, runtime, ledger-v9, Midnight.js, Wallet SDK, proof server | The Ledger 9.1 set in references/versions.json (resolve with references/volatile.md) |
| Contract pragma | pragma language_version >= 0.28.0; (the old <= 0.23 upper bound would block the current toolchain) |
| Docker | For local proof server |
node --version # v22+
compact update 0.36.1
compact compile +0.36.1 --version
docker run -d -p 6300:6300 midnightntwrk/proof-server:9.0.2 midnight-proof-server -v
ownPublicKey() for blacklist, admin, or user identity checksdisclose() marks witness values safe to cross into ledger reads; credit fields never get disclosedUserPublicKey, not wallet addressespersistentHash preimages affect derived keysrotateAdmin + re-register providernpm run compact && npm run sync:assetslocalStoragegetConfiguration()references/versions.json; cross-check support matrix# Contract only
cd contract && npm install && npm run compact && npm run build
# Full monorepo (from root)
npm install
npm run validate:registry # if added to workspace scripts
cd contract && npm run test:compile
# Optional browser UI (after adding zkloan-dapp from leaderboard template)
cd zkloan-dapp
npm install && npm run compact && npm run sync:assets && npm run dev
Open http://localhost:3000 → Connect 1AM → Deploy → Register provider → Request loan → View outcome on-chain.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
midnight-network, zero-knowledge, compact, schnorr, loan-dapp, attestation
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./ankr-midnightIntegrate Ankr as a Midnight Network RPC provider for testnet and mainnet. Covers creating an Ankr project, copying HTTPS/WSS endpoints with API key, wiring the node URL into midnight-js / multinetwork configs, and calling Midnight JSON-RPC methods (midnight_*, system_*, chain_*, state_*). Use when the user asks about Ankr + Midnight, Ankr.js for Midnight, Ankr RPC endpoint, or replacing public Midnight RPC with Ankr.
/compactWrite, reason about, and debug Compact smart contracts for the Midnight blockchain. Use this skill whenever a user asks about Compact syntax, ledger state, witnesses, circuits, disclosure, ZK patterns, data types, standard library functions, security patterns, nullifier design, Merkle trees, or anything related to writing .compact files. Also trigger for questions about compiling contracts, debugging circuit errors, choosing between ledger ADTs, and implementing privacy-preserving patterns like commitments, hash-based auth, and anonymous membership proofs./compact-language-engineeringBuild and maintain language tooling for Midnight's Compact language (parsers, grammars, syntax highlighters, formatters, linters, language servers, IntelliJ/Grammar-Kit plugins, tree-sitter grammars) without changing what the language accepts. Use this skill when a user asks to write or fix a Compact grammar, port the grammar to tree-sitter, Grammar-Kit, JFlex, ANTLR, Lezer, or TextMate, check operator precedence or associativity, track down parser ambiguities or nullable and left-recursive rules, generate parser regression tests, compare a third-party parser against the compiler, or build an LSP or editor extension for `.compact` files. Also use it for questions like "what tokens does Compact have", "is `/` or unary minus valid Compact", "why does my highlighter break on block comments", "tree-sitter-compact rejects valid code", or "how does the Nite language server get its diagnostics".
/dust-gas-sponsorshipLet one wallet pay Midnight transaction fees for another wallet's transaction, so users with zero DUST can transact from their first click. Use whenever a dApp onboards new users, offers a free tier, or covers usage for its users: the two-sided sponsorship flow (user proves and binds, sponsor adds DUST and submits), the sponsor service and its acceptance policy, sponsor economics and monitoring, and the hosted alternatives (NIGHTGATE, Capacity Exchange).Other plugins' skills for the same job