/midnight-skills:1am-walletfrom midnight-skills
Integrates the 1AM browser wallet for dust-free contract deployment and transaction flow on Midnight Network. Handles wallet detection, connection, provider wiring, ZK proving, and private state management for Midnight dApps.
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.
Scope
This skill covers detecting, connecting, and wiring the 1AM browser extension (window.midnight['1am']) into a frontend dApp. The wallet proves and balances transactions through the DApp Connector API. 1AM has advertised DUST fee sponsorship through its ProofStation; confirm the current policy with 1AM after the Ledger 9 DUST reset. This skill is generic: replace every YourContract / yourCircuit / your-contract placeholder with your actual contract name and circuit IDs.
Ledger 9 (Nov 2026). Targets Midnight.js 5.0.2, DApp Connector API 4.1.0,
ledger-v91.0.2,compact-runtime0.21.0, Compact 0.36.1 (pragma language_version >= 0.28.0).setNetworkIdis gone, theoffset: nullindexer patch is no longer needed, and the hand-rolled proof/wallet/midnight providers are replaced by@midnightntwrk/midnight-js-dapp-connector-proof-provider. The session code in §3 is the same filetemplates/locker-dappships, and that template type-checks and passesnext build. Make sure users run a Ledger 9 build of the 1AM extension.
Suggested file layout (adapt to your project):
src/lib/midnight.ts → wallet session and provider wiring (canonical source: references/midnight-session.md)src/lib/encryption.ts → optional payload encryption derived from wallet signaturesrc/hooks/useContract.ts → app logic and state orchestrationsrc/contexts/WalletContext.tsx → wallet connection stateShared references: references/midnight-session.md, references/gotchas.md, references/versions.json
The Ledger 9.1 set (checked against npm and the support matrix on 21 Nov 2026):
npm install \
@midnight-ntwrk/[email protected] \
@midnight-ntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected] \
@midnightntwrk/[email protected]
compact-runtime / compact-js stay on the @midnight-ntwrk scope (the compiler's output imports @midnight-ntwrk/compact-runtime). Everything else is @midnightntwrk. Removed: @midnight-ntwrk/midnight-js-network-id, @midnight-ntwrk/ledger-v8, and the obsolete @midnight-ntwrk/ledger.
Vite requires these plugins for WASM and top-level await (the Compact SDK uses both):
npm install -D vite-plugin-wasm vite-plugin-top-level-await
For Next.js, see §12 — webpack config is required instead.
Full content: references/wallet-detection-connection.md. It covers detecting the 1AM extension, connecting, and handling network/authorization errors. Open it when you reach this step.
createConnectedSession)Full content: references/session-setup.md. It covers the full createConnectedSession implementation and provider wiring. Open it when you reach this step.
Earlier versions of this skill wrapped indexerPublicDataProvider to dodge an offset: null GraphQL bug on the hosted indexers. Delete that wrapper. Indexer 4.4.101 answers no-offset queries with the latest state (verified against Preview), and Midnight.js 5 sends a nullable offset itself. Use indexerPublicDataProvider(network.indexer) as in §3.
Reading state changed shape in 5.x. Decode the era-tagged bytes with your own runtime:
import { ContractState } from '@midnight-ntwrk/compact-runtime';
const read = await session.providers.publicDataProvider.queryContractState(contractAddress);
const state = read ? yourLedger(read.contractState.deserialize({ v9: ContractState }).data) : null;
Indexer endpoints: preview is https://indexer.preview.midnight.network/api/v4/graphql; preprod/mainnet are Blockfrost (?project_id=<token>). In a browser dApp, take the endpoints from the wallet (dappConnectorNetwork) rather than hardcoding them.
PrivateStateProvider is per-contract in Midnight.js 5 (provider.forContract(address).get/set). The old in-memory object with setContractAddress() no longer satisfies the interface. Use levelPrivateStateProvider, which uses IndexedDB in the browser:
levelPrivateStateProvider({
accountId: unshieldedAddress, // scope the store per wallet account
privateStoragePasswordProvider: async () => password, // ≥16 chars, 3 character classes
});
The template uses a random password kept in localStorage, which is demo-grade. Production apps should ask the user or derive the password from wallet-held material. Use one database per browser tab.
Replace YourContract, your-contract, and yourCircuit with your actual names. Type the providers to your contract; no as any needed.
import type { ProvableCircuitId } from '@midnight-ntwrk/compact-js';
import { deployContract, findDeployedContract } from '@midnightntwrk/midnight-js-contracts';
import type { MidnightProviders } from '@midnightntwrk/midnight-js-types';
import { CompiledYourContract, type YourContract, type YourPrivateState } from '../contract/src/index';
const PRIVATE_STATE_ID = 'yourPrivateState';
type YourProviders = MidnightProviders<ProvableCircuitId<YourContract>, typeof PRIVATE_STATE_ID, YourPrivateState>;
const providersFor = (s: ConnectedSession) => s.providers as unknown as YourProviders;
export async function deploy(session: ConnectedSession, initialPrivateState: YourPrivateState) {
const deployed = await deployContract(providersFor(session), {
compiledContract: CompiledYourContract,
privateStateId: PRIVATE_STATE_ID,
initialPrivateState,
// args: [...] for constructor parameters
});
return deployed.deployTxData.public.contractAddress;
}
export async function callYourCircuit(session: ConnectedSession, contractAddress: string, ...args: any[]) {
const contract = await findDeployedContract(providersFor(session), {
compiledContract: CompiledYourContract,
contractAddress,
privateStateId: PRIVATE_STATE_ID,
});
return contract.callTx.yourCircuit(...args);
}
CompiledYourContract is built in contract/src/index.ts with CompiledContract from @midnight-ntwrk/compact-js. Keep node:path out of the browser bundle (see references/midnight-session.md).
deployContract / callTx wait for the transaction to be indexed and store private state for you. If you need the address immediately and want to show progress while the indexer catches up, use the non-blocking path in §8.
dApp builds unproven tx (Midnight.js)
↓
proofProvider.proveTx() → wallet getProvingProvider() → ZK proofs
↓
walletProvider.balanceTx() → api.balanceUnsealedTransaction() → wallet adds inputs + DUST fees
↓
midnightProvider.submitTx() → api.submitTransaction() → Midnight chain
balanceUnsealedTransaction (option payFees, default true) is where fees are paid: from the user's DUST, or by 1AM's sponsorship where 1AM offers it. Never skip it. The connector takes no TTL, so the wallet chooses the expiry of the intents it adds, and providers.config.ttlSeconds doesn't apply to them. Wallet errors carry a connector code (Rejected, InsufficientFunds (new in 4.1.0), Disconnected, …). deployContract / callTx wrap them in ProviderFailedError, which drops that code.
Use these when you need the contract address before the transaction is indexed, or want to drive your own progress UI. submitTxAsync does not persist private state or the signing key. You must do that yourself, or later calls won't find them. Type-checked against Midnight.js 5.0.2:
import { sampleSigningKey } from '@midnight-ntwrk/compact-runtime';
import { createUnprovenDeployTx, submitTxAsync, submitCallTxAsync } from '@midnightntwrk/midnight-js-contracts';
export async function deployNonBlocking(session: ConnectedSession, initialPrivateState: YourPrivateState) {
const providers = providersFor(session);
const deployTxData = await createUnprovenDeployTx(providers, {
compiledContract: CompiledYourContract,
initialPrivateState,
signingKey: sampleSigningKey(), // contract maintenance authority key
});
const contractAddress = deployTxData.public.contractAddress; // known before submission
const txId = await submitTxAsync(providers, { unprovenTx: deployTxData.private.unprovenTx });
// submitTxAsync does NOT store these — do it yourself:
await providers.privateStateProvider.forContract(contractAddress).set(PRIVATE_STATE_ID, initialPrivateState);
await providers.privateStateProvider.setSigningKey(contractAddress, deployTxData.private.signingKey);
return { contractAddress, finalized: providers.publicDataProvider.watchForTxData(txId) };
}
export async function callNonBlocking(session: ConnectedSession, contractAddress: string, ...args: any[]) {
const providers = providersFor(session);
const { txId } = await submitCallTxAsync(providers, {
compiledContract: CompiledYourContract,
contractAddress,
circuitId: 'yourCircuit',
args,
privateStateId: PRIVATE_STATE_ID,
});
return providers.publicDataProvider.watchForTxData(txId); // resolves once indexed
}
Midnight.js 5 has watchers, so hand-rolled polling loops are rarely needed:
import { ContractState } from '@midnight-ntwrk/compact-runtime';
// Wait for a newly deployed contract to be indexed
await session.providers.publicDataProvider.watchForDeployTxData(contractAddress);
// Wait for a submitted transaction
await session.providers.publicDataProvider.watchForTxData(txId);
// Poll until a predicate on the decoded ledger holds
export async function waitForLedger<T>(
session: ConnectedSession,
contractAddress: string,
readLedger: (data: ReturnType<typeof ContractState.deserialize>['data']) => T,
done: (ledger: T) => boolean,
pollIntervalMs = 2000,
maxAttempts = 60,
): Promise<T> {
for (let i = 0; i < maxAttempts; i++) {
const read = await session.providers.publicDataProvider.queryContractState(contractAddress);
if (read) {
const ledger = readLedger(read.contractState.deserialize({ v9: ContractState }).data);
if (done(ledger)) return ledger;
}
await new Promise((r) => setTimeout(r, pollIntervalMs));
}
throw new Error(`State did not reach the expected value after ${(maxAttempts * pollIntervalMs) / 1000}s`);
}
This is a minimal template. Replace YourState, yourLedger, and circuit names with your contract's actual shape.
// hooks/useContract.ts
import { useCallback, useEffect, useState } from 'react';
import { useWallet } from '../contexts/WalletContext';
import { ContractState } from '@midnight-ntwrk/compact-runtime';
import { callNonBlocking, waitForLedger } from '../lib/midnight';
export function useContract(contractAddress: string | null) {
const { session } = useWallet();
const [contractState, setContractState] = useState<YourState | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fetchState = useCallback(async () => {
if (!session || !contractAddress) return;
const read = await session.providers.publicDataProvider.queryContractState(contractAddress);
// Midnight.js 5 returns era-tagged bytes. Decode with YOUR compact-runtime copy, then pass
// .data (a ChargedState) to ledger() — passing the ContractState itself fails with
// "expected instance of ChargedState".
if (read) setContractState(yourLedger(read.contractState.deserialize({ v9: ContractState }).data));
}, [session, contractAddress]);
useEffect(() => { fetchState(); }, [fetchState]);
const callSomeCircuit = useCallback(async (...args: any[]) => {
if (!session || !contractAddress) return;
setIsLoading(true);
setError(null);
try {
const snapshotBefore = contractState?.someField;
await callNonBlocking(session, contractAddress, ...args); // resolves once indexed
await waitForLedger(session, contractAddress, yourLedger, (l) => l.someField !== snapshotBefore);
// Optimistic local update (optional — feels instant)
setContractState(prev => prev ? { ...prev /* apply expected delta */ } : prev);
await fetchState(); // reconcile with chain
} catch (e: any) {
setError(e.message);
} finally {
setIsLoading(false);
}
}, [session, contractAddress, contractState, fetchState]);
return { contractState, isLoading, error, callSomeCircuit, refreshState: fetchState };
}
Key design points:
fetchState() returns.fetchState() after the optimistic update to sync with the true indexed state.Full content: references/payload-encryption.md. It covers optional encryption of payloads before they go on-chain. Open it when you reach this step.
The SDK uses isomorphic-ws, async WebAssembly, and top-level await — none of which work out of the box in Next.js. Required steps:
1. Create a WebSocket shim (Next.js bundles a broken isomorphic-ws for browser targets):
// lib/isomorphic-ws-fix.mjs
export default globalThis.WebSocket;
export const WebSocket = globalThis.WebSocket;
2. Configure next.config.mjs:
// next.config.mjs
const nextConfig = {
webpack(config) {
config.resolve.alias['isomorphic-ws'] = new URL('./lib/isomorphic-ws-fix.mjs', import.meta.url).pathname;
config.resolve.fallback = { fs: false, net: false, tls: false, child_process: false };
config.experiments = { asyncWebAssembly: true, topLevelAwait: true };
return config;
},
};
export default nextConfig;
3. Webpack, not Turbopack. Next 15 builds with webpack by default (next dev, next build). On Next 16, add --webpack. The flag doesn't exist in Next 15.5 and makes the command fail there. You cannot use custom webpack experiments and Turbopack together.
4. Never prerender the wallet UI. level resolves to a native module on the server, so load the client component from a 'use client' page with dynamic(() => import('./YourClient'), { ssr: false }). Otherwise next build fails with No native build was found … classic-level.
TypeScript — no as any needed with Midnight.js 5. Type the compiled contract (CompiledContract.make<Contract<YourPrivateState>>(...)) and narrow the session's providers to MidnightProviders<ProvableCircuitId<YourContract>, Id, YourPrivateState> (see §6). The old casts hid real argument-shape bugs.
Compiled contracts produce assets that must be served over HTTP with CORS enabled. The FetchZkConfigProvider fetches them at runtime.
your-server.com/<zk-path>/
compiler/
contract-manifest.json # integrity manifest — REQUIRED by FetchZkConfigProvider (compactc ≥0.33)
contract-info.json # declares runtime-version
keys/
circuitName.prover # 2–10 MB each
circuitName.verifier # ~2 KB each
zkir/
circuitName.bzkir # ZKIR v3
Without compiler/, every contract operation fails with EraMismatchError: artifact-era-undeclared.
Required header: Access-Control-Allow-Origin: *
For local Vite development, sync assets into public/ with an npm script:
{
"scripts": {
"sync:zk": "mkdir -p public/zk/your-contract && cp -r contracts/managed/your-contract/compiler contracts/managed/your-contract/keys contracts/managed/your-contract/zkir public/zk/your-contract/"
}
}
Before debugging any provider error, open the asset URLs directly in the browser. A 404 or CORS failure here surfaces as a cryptic SDK error. Run sync:zk before npm run dev — Vite only serves files present in public/ at startup.
The 1AM wallet calls ProofStation internally via balanceUnsealedTransaction. You typically don't need to call it directly. Reference only:
| Endpoint | Method | Description |
|---|---|---|
/health | GET | Server health + upstream status |
/prove | POST | Generate ZK proof |
/verify | POST | Verify a ZK proof |
/prove-and-balance | POST | Prove + balance in one call |
/balance | POST | Balance a pre-proven tx |
/check | POST | Check a proof preimage |
/wallet-status | GET | Sponsorship wallet DUST balance |
(Endpoint list as reported by the preview server's own 404 hint on 21 Nov 2026; /health responded. 1AM's sponsorship policy after the Ledger 9 DUST reset is not something this skill can verify; check 1AM's docs.)
Base URLs:
https://api-preview.1am.xyzhttps://api-preprod.1am.xyzhttps://api.1am.xyzAuth: X-API-Key: pk_live_xxx (only needed for direct calls — prefer routing through api.balanceUnsealedTransaction).
| Network | Use for | Indexer | RPC |
|---|---|---|---|
preview | Active development | indexer.preview.midnight.network/api/v4/graphql | rpc.preview.midnight.network |
preprod | Pre-release testing | Blockfrost midnight-preprod.blockfrost.io/api/v0?project_id=… | Blockfrost rpc.midnight-preprod.blockfrost.io |
mainnet | Production | Blockfrost midnight-mainnet.blockfrost.io/api/v0?project_id=… | Blockfrost rpc.midnight-mainnet.blockfrost.io |
The old indexer.preprod/mainnet.midnight.network hosts return 410 (retired 9 Oct 2026). Preview relaunched as a new chain on 7 Nov 2026: old contract addresses and balances are gone, so redeploy, re-request tNIGHT and re-register DUST. Preprod upgraded in place on 9 Nov 2026 (non-cNIGHT DUST registrations cleared). Use preview during development, and always take endpoints from the wallet (dappConnectorNetwork(api)); never hardcode them.
window.midnight['1am'] (InitialAPI)| Method | Returns | Notes |
|---|---|---|
connect(networkId) | ConnectedAPI | 'preview' | 'preprod' | 'mainnet' |
name | string | '1AM' |
apiVersion | string | Connector spec version the wallet implements ('4.1.0' for current wallets); check it at runtime |
| Method | Returns | Notes |
|---|---|---|
getConfiguration() | { networkId, indexerUri, indexerWsUri, proverServerUri?, substrateNodeUri } | Source of truth for URLs; dappConnectorNetwork(api) wraps it |
getShieldedAddresses() | { shieldedAddress, shieldedCoinPublicKey, shieldedEncryptionPublicKey } | |
getUnshieldedAddress() | { unshieldedAddress } | |
getDustAddress() | { dustAddress } | |
getShieldedBalances() | Record<string, bigint> | |
getUnshieldedBalances() | Record<string, bigint> | |
getDustBalance() | { balance, cap } | |
getProvingProvider(zkConfigProvider) | ProvingProvider | Pass your FetchZkConfigProvider |
balanceUnsealedTransaction(hex, { payFees? }) | { tx: string } | Adds inputs + DUST fees — never skip |
submitTransaction(hex) | void | Midnight.js reads the tx id from the transaction itself |
signData(data, { encoding, keyType: 'unshielded' }) | { scheme?, data, signature, verifyingKey } | 4.1.0 adds ECDSA (ecdsa_secp256k1_sha256) alongside schnorr_bip340 |
makeTransfer(outputs, { payFees? }) | { tx } | Token transfer |
getTxHistory(page, size) / hintUsage(methods) | Optional helpers |
Errors carry a code from ErrorCodes: InternalError, Rejected, InvalidRequest, PermissionRejected, Disconnected, InsufficientFunds (new in 4.1.0).
| Pitfall | Fix |
|---|---|
Missing padStart(2, '0') in toHex | Single-digit hex bytes corrupt the transaction. Always use it. |
Importing setNetworkId / midnight-js-network-id | Removed in Midnight.js 5. The network id lives in providers.config, from dappConnectorNetwork(api). |
0x prefix not stripped in fromHex | The wallet may return hex with or without 0x. The fromHex helper above handles both. |
deployContract() feels slow | It waits for indexing. For immediate feedback use the non-blocking path in §8, and remember to store private state + signing key yourself. |
Hand-rolled proveTx / balanceTx / submitTx objects | Midnight.js 5 providers are era-aware (supportedEras). Use dappConnectorProofProvider / dappConnectorWalletProviders. |
| Coin public key bytes all wrong / zero | The connector returns Bech32m. Use coinPublicKeyToBytes(key, networkId) from §3, not a hex parser. |
EraMismatchError: artifact-era-undeclared | Serve compiler/ with your ZK assets (§13). |
ledger() fails on queryContractState result | 5.x returns era-tagged bytes: yourLedger(read.contractState.deserialize({ v9: ContractState }).data). |
| Reading state immediately after deploy | The indexer is not synchronous with chain finality. Always poll — never read state right after submit. |
| ZK assets 404 | Run sync:zk (copies compiler/, keys/, zkir/) before npm run dev. Vite only serves files that exist in public/ at startup. |
| Reusing old contract address after recompile | Any contract change, including moving from compiler 0.31 to 0.36.x, regenerates verifier keys. Redeploy. Preview addresses from before 7 Nov 2026 are gone. |
| Circuit too small on preview | Preview ProofStation requires minimum circuit size k≥6. If you see prove: no SRS params for k=6, add dummy ledger fields to increase circuit size as a workaround. |
| Hardcoding indexer/RPC URLs | Always read URLs from getConfiguration(). Users may be on a different network than you expect. |
Next.js: isomorphic-ws / WASM / top-level await errors | See §12 for the required webpack config, WebSocket shim, and Turbopack disable instructions. |
| TypeScript errors on SDK call sites | Type the compiled contract and narrow providers (§6) instead of casting. The errors usually point at real argument-shape bugs. |
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub kali-decoder/midnight-skills --plugin midnight-skills43 skills in this plugin
/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.
/Other plugins' skills for the same job