Back to Browse

Use with your AI agent

  1. Install — run npx skills add Kali-Decoder/Midnight-skills --skill example-hello-world for this skill, or npx skills add Kali-Decoder/Midnight-skills for all
  2. Prompt — copy the example prompt and paste it into Cursor, Claude Code, or Codex
  3. Build — the agent loads this skill and scaffolds your Midnight work

Example Hello World

Full-Fledged TemplatesIntermediateReviewedUpdated 3 days agov1.0.0

Agent picks this when: Build a complete Midnight Network hello-world DApp from scratch using Compact smart contract, headless Node.js tests with vitest, and testkit-js FluentWalletBuilder.

Build a complete Midnight Network hello-world DApp from scratch with Compact, vitest, and FluentWalletBuilder.

Good for

  • Build a complete Midnight Network hello-world DApp from scratch using Compact smart contract, headless Node.js tests with vitest, and testkit-js FluentWalletBuilder.

Preview in agent

Suggested prompts

Build a complete Midnight Network hello-world DApp from scratch using Compact smart contract, headless Node.js tests with vitest, and testkit-js FluentWalletBuilder. Use the "hello-world" skill from MIDSKILLS. Follow Compact smart-contract best practices, wire wallet flows where needed, and explain each step as you implement. Target Midnight Preprod unless I specify otherwise.

Loaded skill example-hello-world

What the skill guides the agent to do:

  1. Build a complete Midnight Network hello-world DApp from scratch using Compact smart contract, headless Node.js tests with vitest, and testkit-js FluentWalletBuilder.

Illustrative — based on the skill's description, not recorded agent output.

Try it without installing: npx skills use Kali-Decoder/Midnight-skills@example-hello-world

What changed in v1.0.16

All registry changes

Updated since v1.0.14: +2 −161 lines.

Show diff
SKILL.md+2−161
@@ -342,172 +342,13 @@  ## 11) `src/test/hw.test.ts` -```typescript-import { describe, it, expect, beforeAll, afterAll } from 'vitest';-import { WebSocket } from 'ws';-import { deployContract, findDeployedContract } from '@midnightntwrk/midnight-js-contracts';-import { ContractState, type ContractAddress } from '@midnight-ntwrk/compact-runtime';-import pino from 'pino';--import { getConfig } from '../config.js';-import { MidnightWalletProvider, syncWallet } from '../wallet.js';-import { buildProviders, type HelloWorldProviders } from '../providers.js';-import {-  CompiledHelloWorldContract,-  ledger,-  zkConfigPath,-} from '../../contracts/index.js';-import type { EnvironmentConfiguration } from '@midnightntwrk/testkit-js';--// Required for GraphQL subscriptions in Node.js-globalThis.WebSocket = WebSocket as unknown as typeof globalThis.WebSocket;--process.on('unhandledRejection', (reason, promise) => {-  console.error('UNHANDLED REJECTION:', reason);-  console.error('Promise:', promise);-});--process.on('uncaughtException', (err) => {-  console.error('UNCAUGHT EXCEPTION:', err);-});--const ALICE_SEED =-  '0000000000000000000000000000000000000000000000000000000000000001';--const logger = pino({-  level: process.env['LOG_LEVEL'] ?? 'info',-  transport: { target: 'pino-pretty' },-});--describe('Hello World Contract', () => {-  let aliceWallet: MidnightWalletProvider;-  let aliceProviders: HelloWorldProviders;-  let contractAddress: ContractAddress;--  const config = getConfig();--  async function queryLedger(providers: HelloWorldProviders) {-    const read = await providers.publicDataProvider.queryContractState(contractAddress);-    expect(read).not.toBeNull();-    // Midnight.js 5: era-tagged bytes, decoded with this project's compact-runtime-    return ledger(read!.contractState.deserialize({ v9: ContractState }).data);-  }--  beforeAll(async () => {-    const envConfig: EnvironmentConfiguration = {-      walletNetworkId: config.networkId,-      networkId: config.networkId,-      indexer: config.indexer,-      indexerWS: config.indexerWS,-      node: config.node,-      nodeWS: config.nodeWS,-      faucet: config.faucet,-      proofServer: config.proofServer,-    };--    aliceWallet = await MidnightWalletProvider.build(logger, envConfig, ALICE_SEED);-    await aliceWallet.start();-    await syncWallet(logger, aliceWallet.wallet, 600_000);--    aliceProviders = buildProviders(aliceWallet, zkConfigPath, config);-    logger.info('Providers initialized. Ready to test!');-  });--  afterAll(async () => {-    if (aliceWallet) {-      logger.info('Stopping Alice wallet...');-      await aliceWallet.stop();-    }-  });--  it('Deploys the contract', async () => {-    logger.info('Creating private state...');--    const deployed = await deployContract(aliceProviders, {-      compiledContract: CompiledHelloWorldContract,-    });--    logger.info('Setting the contract address...');-    contractAddress = deployed.deployTxData.public.contractAddress;-    logger.info(`Contract deployed at: ${contractAddress}`);-    expect(contractAddress).toBeDefined();-    expect(contractAddress.length).toBeGreaterThan(0);--    const state = await queryLedger(aliceProviders);-    expect(state.message).toEqual('');-  });--  it('Stores Hello World!', async () => {-    const message = 'Hello World!';--    const hw = await findDeployedContract(aliceProviders, {-      compiledContract: CompiledHelloWorldContract,-      contractAddress,-    });-    await hw.callTx.storeMessage(message);--    const state = await queryLedger(aliceProviders);-    expect(state.message).toEqual(message);-  });-});-```+Full content: [references/hw-test.md](references/hw-test.md). It covers the full vitest suite that deploys and calls the contract on a local devnet. Open it when you reach this step.  ---  ## 12) `compose.yml` -```yaml-services:-  proof-server:-    image: 'midnightntwrk/proof-server:9.0.2'-    command: ['midnight-proof-server', '-v']-    ports:-      - '127.0.0.1:6300:6300'-    environment:-      RUST_BACKTRACE: 'full'-    healthcheck:-      test: ['CMD-SHELL', 'echo > /dev/tcp/127.0.0.1/6300']-      interval: 10s-      timeout: 5s-      retries: 20-      start_period: 10s--  indexer:-    image: 'midnightntwrk/indexer-standalone:4.4.101'-    ports:-      - '127.0.0.1:8088:8088'-    environment:-      RUST_LOG: 'indexer=info,chain_indexer=info,indexer_api=info,wallet_indexer=info,indexer_common=info,fastrace_opentelemetry=off,info'-      APP__INFRA__NODE__URL: 'ws://node:9944'-      APP__APPLICATION__NETWORK_ID: 'undeployed'-      APP__INFRA__STORAGE__PASSWORD: 'indexer'-      APP__INFRA__PUB_SUB__PASSWORD: 'indexer'-      APP__INFRA__LEDGER_STATE_STORAGE__PASSWORD: 'indexer'-      APP__INFRA__SECRET: '303132333435363738393031323334353637383930313233343536373839303132'-    healthcheck:-      test: ['CMD-SHELL', 'cat /var/run/indexer-standalone/running']-      interval: 10s-      timeout: 5s-      retries: 20-      start_period: 10s-    depends_on:-      node:-        condition: service_healthy--  node:-    image: 'midnightntwrk/midnight-node:2.1.101'-    ports:-      - '127.0.0.1:9944:9944'-    healthcheck:-      test: ['CMD', 'curl', '-f', 'http://localhost:9944/health']-      interval: 2s-      timeout: 5s-      retries: 20-      start_period: 5s-    environment:-      CFG_PRESET: 'dev'-      SIDECHAIN_BLOCK_BENEFICIARY: '04bcf7ad3be7a5c790460be82a713af570f22e0f801f6659ab8e84a52be6969e'-```+Full content: [references/compose.md](references/compose.md). It covers the local devnet `compose.yml` (node, indexer, proof server). Open it when you reach this step.  --- 
On this page · 15 sections
SKILL.md

Example Hello World DApp Skill

This skill generates a complete, runnable Midnight DApp. It covers every file in the project: the Compact contract, TypeScript utilities, test script, Docker configs, and package setup. All code matches the official midnightntwrk/example-hello-world reference implementation.

Primary references:

  • github.com/midnightntwrk/example-hello-world — official reference repo
  • docs.midnight.network/getting-started/hello-world — official hello-world guide
  • docs.midnight.network/relnotes/support-matrix — authoritative version compatibility matrix

Package versions below are a dated snapshot (May 2026). Resolve the current tested set from the support matrix before pinning — see references/volatile.md. Never install @latest.

Key architecture notes:

  • Uses @midnightntwrk/testkit-js 5.0.2 MidnightWalletProvider (built on FluentWalletBuilder) for an era-aware, Wallet SDK 2.x wallet
  • Uses @midnightntwrk/midnight-js-contracts deployContract and submitCallTx
  • Compact pragma is >= 0.28.0; toolchain, runtime and Ledger 9 packages are the set in references/versions.json
  • Indexer API paths use /api/v4/graphql for local devnet
  • MidnightWalletProvider class wraps WalletFacade to implement MidnightProvider and WalletProvider interfaces
  • syncWallet function provides detailed progress logging during wallet sync
  • Test uses static seed (ALICE_SEED) for reproducible testing
  • privateStateStoreName uses Date.now() for test isolation
  • NODE_OPTIONS='--experimental-vm-modules' required for vitest with ESM

1) Project Structure

hello-world-local/
├── contracts/
│   ├── hello-world.compact          # Compact smart contract (you create this)
│   ├── index.ts                     # Barrel file for compiled contract exports (create manually)
│   └── managed/
│       └── hello-world/             # Compiler output (auto-generated, do not edit)
│           ├── compiler/
│           ├── contract/
│           ├── keys/
│           └── zkir/
├── src/
│   ├── config.ts                    # Network configuration
│   ├── wallet.ts                    # MidnightWalletProvider + syncWallet
│   ├── providers.ts                 # HelloWorldProviders builder
│   └── test/
│       └── hw.test.ts               # vitest tests (deploy + storeMessage)
├── compose.yml                      # Docker: full local stack
├── package.json
├── tsconfig.json
└── vitest.config.ts

The contracts/managed/ directory is created by the Compact compiler — do not create or edit files inside it manually.


2) Prerequisites

# Node.js 22+ required
node --version

# Docker required (local stack)
docker --version

# Install Compact compiler
curl --proto '=https' --tlsv1.2 -sSf \
  https://github.com/midnightntwrk/compact/releases/latest/download/compact-installer.sh | sh
source $HOME/.local/bin/env
compact --version

3) package.json

{
  "name": "hello-world-local",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22.0.0"
  },
  "scripts": {
    "compile": "compact compile contracts/hello-world.compact managed/hello-world",
    "test": "NODE_OPTIONS='--experimental-vm-modules' vitest run",
    "test:local": "MIDNIGHT_NETWORK=local yarn test",
    "env:up": "docker compose up -d --wait",
    "env:down": "docker compose down",
    "validate": "yarn env:up && yarn test:local; yarn env:down"
  },
  "dependencies": {
    "@midnight-ntwrk/compact-runtime": "0.21.0",
    "@midnightntwrk/ledger-v9": "1.0.2",
    "@midnightntwrk/midnight-js-contracts": "5.0.2",
    "@midnightntwrk/midnight-js-http-client-proof-provider": "5.0.2",
    "@midnightntwrk/midnight-js-indexer-public-data-provider": "5.0.2",
    "@midnightntwrk/midnight-js-level-private-state-provider": "5.0.2",
    "@midnightntwrk/midnight-js-node-zk-config-provider": "5.0.2",
    "@midnightntwrk/midnight-js-types": "5.0.2",
    "@midnightntwrk/midnight-js-utils": "5.0.2",
    "@midnightntwrk/testkit-js": "5.0.2",
    "@midnightntwrk/wallet-sdk-facade": "5.0.1",
    "axios": "^1.15.0",
    "pino": "^9.0.0",
    "pino-pretty": "^13.0.0",
    "rxjs": "^7.8.2",
    "testcontainers": "^11.13.0",
    "ws": "^8.14.2"
  },
  "devDependencies": {
    "@midnightntwrk/midnight-js-compact": "5.0.2",
    "@types/node": "^22.0.0",
    "@types/ws": "^8.5.9",
    "typescript": "^5.7.0",
    "vitest": "^3.0.0"
  },
  "resolutions": {
    "@midnightntwrk/ledger-v9": "1.0.2",
    "@midnight-ntwrk/compact-runtime": "0.21.0"
  },
  "packageManager": "[email protected]"
}

4) tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "bundler",
    "lib": ["ES2022"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    "noEmit": true,
    "outDir": "dist",
    "rootDir": "."
  },
  "include": ["src/**/*.ts", "contract/**/*.ts"]
}

⚠️ "contract/**/*.ts" is singular — this matches the repo exactly and covers the compiler output path. Using "contracts/**/*.ts" (plural) will silently break TypeScript resolution of the compiled contract types.


5) vitest.config.ts

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    environment: 'node',
    globals: true,
    testTimeout: 10 * 60_000,
    hookTimeout: 15 * 60_000,
    include: ['src/**/*.test.ts'],
    reporters: ['default'],
    sequence: { concurrent: false },
  },
});

6) contracts/hello-world.compact

Create this file manually — the compiler output in managed/ is generated from it.

pragma language_version >= 0.28.0;

export ledger message: Opaque<"string">;

export circuit storeMessage(newMessage: Opaque<"string">): [] {
  message = disclose(newMessage);
}

Compile from the contracts/ directory:

cd contracts
compact compile hello-world.compact managed/hello-world
cd ..

Expected output:

Compiling 1 circuits:
  circuit "storeMessage" (k=6, rows=26)

This generates contracts/managed/hello-world/contract/index.js (and keys, zkir, compiler dirs). Always compile before running tests.


7) contracts/index.ts (barrel file — create manually)

Create this file manually — it imports from the compiled contract output. The compiled contract module must exist (from running compact compile) for the imports to resolve.

import { CompiledContract } from '@midnight-ntwrk/compact-js';   // not compact-runtime
import { fileURLToPath } from 'node:url';
import path from 'node:path';

export {
  Contract,
  ledger,
  pureCircuits,
  type Ledger,
  type ImpureCircuits,
  type PureCircuits,
} from './managed/hello-world/contract/index.js';
import { Contract } from './managed/hello-world/contract/index.js';

const currentDir = path.dirname(fileURLToPath(import.meta.url));
export const zkConfigPath = path.resolve(currentDir, 'managed', 'hello-world');

export type HelloWorldContract = Contract<undefined>;

export const CompiledHelloWorldContract = CompiledContract.make<HelloWorldContract>(
  'HelloWorldContract',
  Contract,
).pipe(
  CompiledContract.withVacantWitnesses,
  CompiledContract.withCompiledFileAssets(zkConfigPath),
);

8) src/config.ts

export type NetworkConfig = {
  networkId: string;
  indexer: string;
  indexerWS: string;
  node: string;
  nodeWS: string;
  proofServer: string;
  faucet: string;
};

export const LOCAL_CONFIG: NetworkConfig = {
  networkId: 'undeployed',
  indexer: 'http://127.0.0.1:8088/api/v4/graphql',
  indexerWS: 'ws://127.0.0.1:8088/api/v4/graphql/ws',
  node: 'http://127.0.0.1:9944',
  nodeWS: 'ws://127.0.0.1:9944',
  proofServer: 'http://127.0.0.1:6300',
  faucet: '',
};

export function getConfig(): NetworkConfig {
  const network = process.env['MIDNIGHT_NETWORK'] ?? 'local';
  if (network !== 'local') {
    throw new Error(
      `Unknown network: ${network}. This harness only supports 'local'.`,
    );
  }
  return LOCAL_CONFIG;
}

9) src/wallet.ts

testkit-js 5.x ships the wallet provider: MidnightWalletProvider.build(logger, env, seed) creates a Wallet SDK 2.x WalletFacade from the seed (via FluentWalletBuilder), and implements Midnight.js 5's era-aware WalletProvider + MidnightProvider (balancing, signing unshielded intents, submitting). Don't hand-roll one: the Ledger 8-era copy used wallet.start(zswapKeys, dustKey) and key-object balancing, which Wallet SDK 2.x no longer accepts.

import { MidnightWalletProvider } from '@midnightntwrk/testkit-js';
import type { WalletFacade, FacadeState } from '@midnightntwrk/wallet-sdk-facade';
import type { Logger } from 'pino';

export { MidnightWalletProvider };

export async function syncWallet(logger: Logger, wallet: WalletFacade, timeout = 300_000): Promise<FacadeState> {
  logger.info('Syncing wallet...');
  const timer = new Promise<never>((_, reject) =>
    setTimeout(() => reject(new Error(`Wallet sync timeout after ${timeout}ms`)), timeout),
  );
  const state = await Promise.race([wallet.waitForSyncedState(), timer]);
  logger.info(`Wallet synced (protocol version ${String(state.activeProtocolVersion)})`);
  return state;
}

10) src/providers.ts

import type { ProvableCircuitId } from '@midnight-ntwrk/compact-js';
import { type MidnightProviders } from '@midnightntwrk/midnight-js-types';
import { indexerPublicDataProvider } from '@midnightntwrk/midnight-js-indexer-public-data-provider';
import { httpClientProofProvider } from '@midnightntwrk/midnight-js-http-client-proof-provider';
import { NodeZkConfigProvider } from '@midnightntwrk/midnight-js-node-zk-config-provider';
import { levelPrivateStateProvider } from '@midnightntwrk/midnight-js-level-private-state-provider';
import type { HelloWorldContract } from '../contracts/index.js';
import { type MidnightWalletProvider } from './wallet.js';
import { type NetworkConfig } from './config.js';

export type HelloWorldCircuits = ProvableCircuitId<HelloWorldContract>;
export type HelloWorldProviders = MidnightProviders<HelloWorldCircuits, string, undefined>;

export function buildProviders(wallet: MidnightWalletProvider, zkConfigPath: string, config: NetworkConfig): HelloWorldProviders {
  const zkConfigProvider = new NodeZkConfigProvider<HelloWorldCircuits>(zkConfigPath);
  return {
    privateStateProvider: levelPrivateStateProvider({
      privateStateStoreName: `hello-world-${Date.now()}`,
      privateStoragePasswordProvider: () => 'xK9#mQ2$pL8@nR5!vW3*',
      accountId: wallet.unshieldedKeystore.getBech32Address().asString(),
    }),
    publicDataProvider: indexerPublicDataProvider({ queryURL: config.indexer, subscriptionURL: config.indexerWS }),
    zkConfigProvider,
    proofProvider: httpClientProofProvider({ url: config.proofServer, zkConfigProvider }),
    walletProvider: wallet,
    midnightProvider: wallet,
    config: { networkId: config.networkId, ttlSeconds: 3600 },   // replaces setNetworkId
  };
}

11) src/test/hw.test.ts

Full content: references/hw-test.md. It covers the full vitest suite that deploys and calls the contract on a local devnet. Open it when you reach this step.


12) compose.yml

Full content: references/compose.md. It covers the local devnet compose.yml (node, indexer, proof server). Open it when you reach this step.


13) First Run — Local Devnet

# 1. Install deps
yarn install

# 2. Compile contract (must run from contracts/ directory)
cd contracts
compact compile hello-world.compact managed/hello-world
cd ..

# 3. Start local stack
yarn env:up
# wait ~30 seconds for all services to become healthy

# 4. Run tests (new terminal)
yarn test:local

Expected output:

[12:46:12.694] INFO (22064): Wallet sync complete after 23 emissions
[12:46:12.703] INFO (22064): Providers initialized. Ready to test
[12:46:12.707] INFO (22064): Creating private state...
[12:46:32.347] INFO (22064): Setting the contract address...
[12:46:32.347] INFO (22064): Contract deployed at: bba6579743ae23b44301d4a9f8df30dbd5244d63a59d8fbc2c9fc7ea521a04f8
 ✓ src/test/hw.test.ts (2 tests) 39112ms
   ✓ Hello World Contract > Deploys the contract  19649ms
   ✓ Hello World Contract > Stores Hello World!   18184ms

14) Troubleshooting

ErrorCauseFix
compact: command not foundPATH not setsource $HOME/.local/bin/env
Cannot find module '../../contracts/...'Contract not compiled yetRun compact compile from contracts/ first
ETARGET No matching version foundVersion not in the tested setResolve current versions from the support matrix — see references/volatile.md. Do not install @latest.
ECONNREFUSED 127.0.0.1:6300Proof server not runningyarn env:up
NODE_OPTIONS error in testMissing experimental flagEnsure NODE_OPTIONS='--experimental-vm-modules' in test script
Wallet sync timeoutDocker services not healthyVerify yarn env:up finished — all 3 containers must be healthy
v4/graphql 404Old indexer URLLocal devnet uses /api/v4/graphql — correct in config.ts
FluentWalletBuilder is not a functionWrong testkit-js importImport from @midnightntwrk/testkit-js
levelPrivateStateProvider options errorMissing required fieldsMust pass privateStateStoreName, walletProvider, privateStoragePasswordProvider (strong password, min 16 chars, no sequential patterns), and accountId
TS: Cannot find module for contractsWrong tsconfig.json includeMust be "contract/**/*.ts" (singular), not "contracts/**/*.ts"
submitCallTx not foundWrong importImport from @midnightntwrk/midnight-js-contracts
Old contract address fails after recompileVerifier key changedRedeploy — compiled keys change when contract source changes

15) Adapting This Template

  1. Replace contracts/hello-world.compact with your contract
  2. Compile: cd contracts && compact compile your-contract.compact managed/your-contract
  3. Update contracts/index.ts:
    • Change import paths to ./managed/your-contract/contract/index.js
    • Update zkConfigPath to managed/your-contract
    • Update CompiledContract.make() name and Contract reference
  4. In src/providers.ts:
    • Update HelloWorldCircuits type to your circuit names
    • Update privateStateStoreName prefix to avoid LevelDB collisions
  5. In src/test/hw.test.ts:
    • Replace submitCallTx args with your circuit calls
    • Replace ledger() with your contract's ledger() function
    • If your contract has witnesses, add privateStateId + initialPrivateState to deployContract and type the providers with your private-state type
  6. Update src/config.ts if targeting non-local networks

Start in 2 steps

  1. 1. Install — one skill or the full set
  2. 2. Prompt — paste the example into your agent

Install all skills (recommended)

npx skills add Kali-Decoder/Midnight-skills

One command adds every Midnight skill to Cursor, Claude Code, and similar agents.

Install this skill only

npx skills add Kali-Decoder/Midnight-skills --skill example-hello-world

Installs only "example-hello-world" into every detected agent (Cursor, Claude Code, Codex, …).

Example agent prompt

Build a complete Midnight Network hello-world DApp from scratch using Compact smart contract, headless Node.js tests with vitest, and testkit-js FluentWalletBuilder. Use the "hello-world" skill from MIDSKILLS. Follow Compact smart-contract best practices, wire wallet flows where needed, and explain each step as you implement. Target Midnight Preprod unless I specify otherwise.

Paste into Cursor, Claude Code, or Codex after installing.

Author
Tusharpamnani
Category
Full-Fledged Templates
Difficulty
intermediate
Version
v1.0.0

Tags

Hello worldVitestTestkit

Files included

SKILL.md
Create Social CardLive HackathonsGallery
Mock Demo
Example Hello World