/midnight-skills:token-transfersfrom midnight-skills
Explains Midnight Network's dual token systems: shielded/unshielded NIGHT ledger transfers via Zswap, and ERC-20-style contract tokens (FungibleToken) in Compact. Covers balance queries, DUST mechanics, and the Either<ZswapCoinPublicKey, ContractAddress> recipient pattern.
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.
Midnight has two distinct token systems that operate independently: ledger tokens (NIGHT, UTXO-based, native to the chain) and contract tokens (account-based, ERC-20-style, implemented in Compact). They work differently, transfer differently, and serve different purposes.
Primary references:
docs.midnight.network/concepts/ledgers — ledger vs contract token modeldocs.midnight.network/concepts/utxo — UTXO mechanics and nullifier setdocs.midnight.network/concepts/dust-architecture — DUST generation lifecycledocs.midnight.network/concepts/zswap — atomic swap and shielded transfer protocolgithub.com/OpenZeppelin/compact-contracts — reference FungibleToken implementation| Ledger Tokens (NIGHT) | Contract Tokens | |
|---|---|---|
| Where they live | Chain ledger, UTXO-based | Inside a Compact contract, account-based |
| Transfer mechanism | Zswap (ZK atomic swap) | Circuit call (transfer, mint, burn) |
| Privacy | Shielded or unshielded at UTXO level | Private state (balances can be private) |
| Fee resource | NIGHT generates DUST (transaction fees) | No fee role — just application logic |
| Wallet SDK method | facade.transferTransaction(...) (Wallet SDK 2.x) | contract.callTx.transfer(to, amount) |
| Who manages it | Protocol + wallet SDK | Your Compact contract |
| Analogy | Native ETH / BTC | ERC-20 |
Decision rule: If you are moving NIGHT tokens (the chain's native token), use the wallet SDK transfer. If you are building an application token (governance, game currency, stablecoin, NFT), implement it in Compact using the account/map model.
Every NIGHT UTXO is either shielded (private, hidden from observers) or unshielded (public, visible on-chain).
| Shielded | Unshielded | |
|---|---|---|
| Address prefix | mn_shield1... | mn_addr_preprod1... / mn_addr1... |
| Amount visible | No | Yes |
| Sender/receiver visible | No | Yes |
| DUST generation | Yes (via Zswap registration) | Yes (via registration table) |
| Faucet/bridge sends to | No | Yes — always unshielded first |
| Required for | Privacy-sensitive transfers | Interop, faucet, bridge, contracts |
Critical: Faucets and bridges always send to the unshielded address. Never give a shielded address to a faucet.
import * as Rx from 'rxjs';
const state = await Rx.firstValueFrom(
wallet.state().pipe(Rx.filter((s: any) => s.isSynced)),
);
// Unshielded address — use for faucets, bridges, contract interactions
const unshieldedAddress = state.unshielded.address;
// → "mn_addr_preprod1qxy..."
// Shielded coin public key — used as recipient in Zswap transfers
const shieldedCoinPublicKey = state.shielded.coinPublicKey.toHexString();
// → "0x3a7f..."
// DUST address — for DUST registration queries
const dustAddress = state.dust.address;
Use facade.transferTransaction(...) (Wallet SDK 2.0.1; the 1.x makeTransfer is gone from the facade). The wallet selects UTXOs, proves, and pays the DUST fee; unshielded inputs must be signed before finalizing. Type-checked against @midnightntwrk/wallet-sdk-facade 5.0.1:
import { unshieldedToken } from '@midnightntwrk/ledger-v9';
import { MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk-address-format';
import { createKeystore } from '@midnightntwrk/wallet-sdk-unshielded-wallet';
// facade: WalletFacade from WalletFacade.init (see midnight-js skill), seeds: WalletSeeds
const keystore = createKeystore({ kind: 'schnorr', secret: seeds.unshielded }, networkId);
const signSegment = (payload: Uint8Array) => Promise.resolve(keystore.signData(payload));
const state = await facade.waitForSyncedState();
const nightTokenType = unshieldedToken().raw; // hex token type
console.log('NIGHT (Stars):', state.unshielded.balances[nightTokenType] ?? 0n); // 1 NIGHT = 1_000_000 Stars
// Recipients are parsed addresses, not strings
const to = MidnightBech32m.parse('mn_addr_preview1...').decode(UnshieldedAddress, networkId);
const recipe = await facade.transferTransaction(
[{ type: 'unshielded', outputs: [{ type: nightTokenType, receiverAddress: to, amount: 1_000_000n }] }],
{ ttl: new Date(Date.now() + 60 * 60 * 1000) },
);
const signed = await facade.signRecipe(recipe, signSegment); // signs the unshielded inputs
const txId = await facade.submitTransaction(await facade.finalizeRecipe(signed));
Put several outputs (and shielded + unshielded groups) in one call. They settle atomically:
const recipe = await facade.transferTransaction(
[
{
type: 'unshielded',
outputs: [
{ type: nightTokenType, receiverAddress: alice, amount: 500_000n },
{ type: nightTokenType, receiverAddress: bob, amount: 250_000n },
],
},
// { type: 'shielded', outputs: [{ type: tokenType, receiverAddress: shieldedAddr, amount }] },
],
{ ttl: new Date(Date.now() + 60 * 60 * 1000) },
);
In a browser dApp, ask the user's wallet instead: connectedAPI.makeTransfer(desiredOutputs, { payFees }) (DApp Connector 4.1.0). If the wallet can't cover it, the call rejects with error code InsufficientFunds.
You can also query the indexer directly for unshielded balances at a contract or address:
async function getUnshieldedBalance(
indexerUrl: string,
contractAddress: string,
): Promise<Map<string, bigint>> {
const res = await fetch(indexerUrl, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
query: `
query($address: HexEncoded!) {
contractAction(address: $address) {
... on ContractCall { unshieldedBalances { tokenType amount } }
... on ContractUpdate { unshieldedBalances { tokenType amount } }
}
}
`,
variables: { address: contractAddress },
}),
});
const payload = await res.json();
const balances: Array<{ tokenType: string; amount: string }> =
payload.data?.contractAction?.unshieldedBalances ?? [];
return new Map(balances.map(b => [b.tokenType, BigInt(b.amount)]));
}
DUST is the non-transferable fee resource generated by holding NIGHT. It is not a token you send — it is a capacity resource consumed automatically when you submit transactions.
NIGHT → generates → DUST → consumed by → transactions
(Solar Panel) (Electricity) (Appliances)
night_dust_ratio = 5_000_000_000)generation_decay_rate = 8267)NIGHT UTXO created
↓
Registration: DustRegistration links NIGHT public key → DUST public key
↓
DUST UTXO starts generating value (grows toward cap over ~1 week)
↓
Transaction submitted: DUST UTXO consumed → new DUST UTXO created (value - fees)
↓
NIGHT UTXO spent → DUST UTXO immediately begins decaying to zero
const state = await Rx.firstValueFrom(
wallet.state().pipe(Rx.filter((s: any) => s.isSynced)),
);
// Find unregistered NIGHT UTXOs
const unregistered = state.unshielded.availableCoins.filter(
(coin: any) => coin.meta?.registeredForDustGeneration !== true,
);
if (unregistered.length > 0) {
const recipe = await wallet.registerNightUtxosForDustGeneration(
unregistered,
unshieldedKeystore.getPublicKey(),
(payload: Uint8Array) => Promise.resolve(unshieldedKeystore.signData(payload)), // SignSegment returns a Promise
);
const finalized = await wallet.finalizeRecipe(recipe);
await wallet.submitTransaction(finalized);
}
// Wait for DUST to become available
await Rx.firstValueFrom(
wallet.state().pipe(
Rx.throttleTime(5_000),
Rx.filter((s: any) => s.isSynced),
Rx.filter((s) => s.dust.balance(new Date()) > 0n), // Wallet SDK 2.x
),
);
const state = await Rx.firstValueFrom(
wallet.state().pipe(Rx.filter((s: any) => s.isSynced)),
);
const dustBalance = state.dust.balance(new Date()); // Specks (Wallet SDK 2.x; `walletBalance` was 1.x)
const dustCoins = state.dust.availableCoins.length;
const dustPending = state.dust.pendingCoins.length;
console.log(`DUST: ${dustBalance.toLocaleString()} Specks`);
console.log(`Coins: ${dustCoins} available, ${dustPending} pending`);
pendingCoins > 0 && availableCoins === 0 → DUST is booked by a pending transaction. In Wallet SDK 2.x the facade releases those bookings itself when the node provably rejects the submission (TransactionInvalidError, pool refusal, …); otherwise they free when the TTL passes or on sync. Wait, or call facade.revertTransaction(tx) for a transaction you know is dead, instead of restarting the process (the 1.x workaround).
Generation parameters are unchanged (5 DUST/NIGHT cap, 10^15 Specks per DUST, ~1 week to cap, 3 h grace), but state was reset: mainnet replayed cNIGHT registrations to full cap; Preprod (9 Nov 2026) cleared registrations not backed by cNIGHT, so register again; Preview relaunched as a new chain (7 Nov 2026), so re-request tNIGHT and register.
1AM has advertised that its ProofStation sponsors fees for 1AM-wallet users on preview and mainnet, via balanceUnsealedTransaction. That is a third-party policy that may have changed with the Ledger 9 DUST reset, so check 1AM's docs before you skip DUST registration. Headless wallets and other wallets always pay from their own DUST.
Full content: references/contract-tokens.md. It covers the FungibleToken pattern: contract code, minting, transfers, and allowances. Open it when you reach this step.
import { findDeployedContract } from '@midnightntwrk/midnight-js-contracts';
const contract = await findDeployedContract(providers, {
contractAddress: '09dbe05f...',
compiledContract,
privateStateId: 'tokenState',
initialPrivateState: {},
});
// Transfer tokens
const result = await contract.callTx.transfer(recipientAddressBytes, 100n);
console.log('txId:', result.public.txId);
console.log('blockHeight:', result.public.blockHeight);
// Read balance (no transaction — direct state query)
import { ContractState } from '@midnight-ntwrk/compact-runtime';
import { YourToken } from './managed/your-token';
const stateRaw = await providers.publicDataProvider.queryContractState(contractAddress);
if (stateRaw) {
const ledgerState = YourToken.ledger(stateRaw.data);
const balance = ledgerState.balances.lookup(myAccountBytes); // from myAccount()
console.log('Balance:', balance);
}
Contract token balances live in export ledger — readable from the indexer like any other contract state:
import { ContractState } from '@midnight-ntwrk/compact-runtime';
async function getTokenBalance(
indexerUrl: string,
contractAddress: string,
holderAddress: Uint8Array,
ledgerFn: (data: any) => any,
): Promise<bigint> {
const res = await fetch(indexerUrl, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
query: `
query($address: HexEncoded!) {
contractAction(address: $address) { state }
}
`,
variables: { address: contractAddress },
}),
});
const payload = await res.json();
const stateHex = payload.data?.contractAction?.state;
if (!stateHex) return 0n;
const normalized = stateHex.startsWith('0x') ? stateHex.slice(2) : stateHex;
const bytes = new Uint8Array(normalized.length / 2);
for (let i = 0; i < normalized.length; i += 2) {
bytes[i / 2] = parseInt(normalized.slice(i, i + 2), 16);
}
const contractState = ContractState.deserialize(bytes);
const ledgerState = ledgerFn(contractState.data);
return ledgerState.balances.member(holderAddress)
? ledgerState.balances.lookup(holderAddress)
: 0n;
}
Zswap is Midnight's multi-asset atomic swap protocol built on ZK-SNARK proofs. It enables non-interactive atomic swaps with transaction merging.
As a DApp developer, you interact with Zswap indirectly:
facade.transferTransaction(...) — builds a transfer (shielded outputs go through Zswap)facade.initSwap(inputs, outputs, secrets, { ttl, payFees: false }) — builds a swap offer another party can complete and mergewalletProvider.balanceTx(tx) — the balancing step uses Zswap internally to add DUST fees and change outputsZswapChainState — returned by indexer queries, needed by some SDK provider methodsZswapSecretKeys — derived from HD wallet seed (Roles.Zswap), used by ShieldedWalletZswap itself has no "swap two contracts" call. Since Ledger 9, though, contracts can call each other (phase 1, unshielded only; see the compact skill). So a contract can now orchestrate unshielded token movements across contracts in one transaction. Shielded multi-party swaps still go through Zswap offers (initSwap + merging).
| Token | Unit | Conversion |
|---|---|---|
| NIGHT | Star | 1 NIGHT = 1,000,000 Stars |
| DUST | Speck | 1 DUST = 10^15 Specks |
| Contract tokens | Defined by decimals | Typically 18 decimals (1 token = 10^18 base units) |
Always use BigInt for amounts — NIGHT Stars and DUST Specks overflow JavaScript's number type at realistic balances.
const ONE_NIGHT = 1_000_000n; // Stars
const ONE_DUST = 1_000_000_000_000_000n; // Specks
const DUST_PER_NIGHT_MAX = 5_000_000_000n; // Specks per Star at full cap
Taking the caller's identity from a witness — witness callerAddress(): Bytes<32> used as the account to debit is forgeable. A witness is the caller's own TypeScript, so the returned value is chosen by whoever builds the transaction; nothing in the circuit binds it to a key. Any account can then be drained by anyone. Derive the account from a secret instead — accountOf(secretKey()) — so the circuit constrains it. The same applies to any authorisation check: compare derived identities, never a raw witness value.
Mint circuits with no authority check — export circuit mint(to, amount) with no assert lets anyone mint unlimited supply. Record an authority at construction and assert against it.
Passing a circuit parameter straight to a ledger op — parameters are witness values until disclosed, so balances.member(account) fails to compile with "potential witness-value disclosure must be declared but is not". Bind const a = disclose(account); first.
Sending to shielded address from faucet — faucets only support unshielded (mn_addr_preprod1...) addresses. Giving a shielded address gets zero tokens.
Spending NIGHT before DUST is available — spending a NIGHT UTXO causes its associated DUST to start decaying immediately. If you spend NIGHT before DUST reaches useful levels, you lose the generation time invested. Wait until DUST is available before spending NIGHT.
DUST booked after a failed transaction — Wallet SDK 2.x releases bookings for provably rejected submissions; others free at TTL or sync. Prefer waiting or facade.revertTransaction(tx) over restarting.
makeTransfer / walletBalance not found — Wallet SDK 1.x names. Use facade.transferTransaction(...) and state.dust.balance(time).
amount as JS number instead of BigInt — 1 NIGHT = 1,000,000 Stars. Realistic balances exceed Number.MAX_SAFE_INTEGER. Always use BigInt literals (1_000_000n).
balances.lookup(k) without balances.member(k) check — calling lookup on a key that doesn't exist in the Map is a runtime error in Compact. Always check member first.
Overflow on Uint<128> arithmetic — addition that exceeds 2^128 - 1 wraps silently or errors depending on context. Cast explicitly: (a + b) as Uint<128> and add assert guards.
unshieldedToken().raw varies by network — the hex token type identifier for NIGHT is network-specific. Always call unshieldedToken() at runtime; never hardcode the hex string.
OZ versions — the package is @openzeppelin/compact-contracts. Stable 0.4.0 targets Compact 0.31 / Ledger 8, while 0.5.0-alpha.2 targets Ledger 9 (language 0.28.0) and is unaudited. Import through ./node_modules/@openzeppelin/compact-contracts/token/FungibleToken (no src/). In 0.5, owners and accounts are Either<Bytes<32>, ContractAddress>, where account IDs come from a secret-key witness. The ZswapCoinPublicKey form is gone.
Contract tokens do not generate DUST — only NIGHT (the native ledger token) generates DUST. Your custom FungibleToken has no fee role.
What SKILL.md sets; muted values are Claude Code's defaults
43 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).npx claudepluginhub kali-decoder/midnight-skills --plugin midnight-skillsOther plugins' skills for the same job