Skip to content

Latest commit

 

History

History
487 lines (391 loc) · 26.1 KB

JSON_CONTRACT.md

File metadata and controls

487 lines (391 loc) · 26.1 KB

JSON Contract

What mn (midnight-wallet-cli) and midnight-wallet-mcp promise to never break, in exchange for integrators getting a stable surface to build on.

This document is the line we will not cross without a major version bump. Every shape here is what --json mode emits today and what every consumer should be able to rely on tomorrow.

The non-JSON (human-formatted) stderr output is decorative and may change freely. The contract is JSON only.

Stability rules

  1. Additive only. New fields may appear at any version. Existing field names, types, and locations stay frozen.
  2. No renames. If a field needs a different name, both names exist side by side until the next major bump.
  3. No removals. A field that ever shipped stays.
  4. No type changes. A string stays a string; a number stays a number.
  5. No nesting changes. A field at the top level stays at the top level. Nested forms that integrators depend on (see balance.balances.NIGHT) stay nested.

If we must make a breaking change, it's a major version bump and an explicit BREAKING CHANGES section in the changelog naming every field involved.

Surfaces under contract

Network names

"undeployed" | "preprod" | "preview" | "mainnet"

These values are stable. Adding a new network is additive. Renaming or removing one is a major bump.

Address formats

Bech32m, network-tagged in the HRP:

  • Unshielded: mn_addr_<network>1...
  • Shielded: mn_shield-addr_<network>1...

On mainnet the HRP has no network segment: mn_addr1... and mn_shield-addr1....

The HRP encoding is stable. Tools may rely on mn_addr_<network> as a parseable network indicator, and on a missing segment meaning mainnet.

Wallet file (~/.midnight/wallets/<name>.json)

Path, schema, and permissions are stable:

  • Path: ~/.midnight/wallets/<name>.json (per OS user)
  • Permissions: 0600 on file, 0700 on directory
  • Required fields: addresses, createdAt, and the secrets: sealed (the seed, and the mnemonic when there is one, encrypted under mn's passphrase; every wallet mn writes is sealed). A plain-text file an older mn wrote has seed (and mnemonic) instead of sealed; mn still reads it and midnight wallet protect seals it.
  • Optional: shieldedAddresses
  • addresses and shieldedAddresses are objects keyed by network name

Swap offer file (swap make, experimental)

What a maker hands a taker: JSON, written 0600. The transaction's bytes are the truth; a taker refuses a file that says otherwise.

  • kind: "midnight-swap-offer"
  • version: 1 for an offer anyone can take; 2 for one made for one wallet (swap make --for). An mn that reads neither refuses the file as NOT_AN_OFFER.
  • network, id (the sha256 of the transaction, 64 hex), terms (give and want, each { token, amount }, the amount a decimal string in the token's smallest unit), expiresAt (ISO 8601), tx (the sealed transaction, hex)
  • for (version 2 only): the shielded address of the wallet the offer is made for. Its transaction pays terms.give to that address and shows anyone only terms.want; that wallet reads its coin with its keys when it takes the offer, and any other wallet's take is OFFER_NOT_FOR_THIS_WALLET.

Config file (~/.midnight/config.json)

Valid keys:

  • network (canonical)
  • proof-server
  • node
  • indexer-ws
  • wallet
  • blockfrost-project-id (kept per network under networks.<name>; config get returns it masked, e.g. nightpreprod…ab12 (preprod), never in full)
  • account-artifacts (where mn grant gets the account contract's proving artefacts: an absolute folder or an http(s) URL; one for every network; MN_ACCOUNT_ARTIFACTS wins over it)

Aliases (transparently resolved to a canonical key):

  • network-id → network (added 2026-04-27 for midnight-expert compatibility)

Exit codes

Code Meaning
0 Success
1 Unknown error
2 Invalid arguments
3 Wallet not found
4 Network error
5 Insufficient balance / DUST_REQUIRED
6 TX_REJECTED / STALE_UTXO / PROOF_TIMEOUT
7 Cancelled

The numeric codes and the error code strings are stable. Each package defines its error codes (its <package>.codes.ts), and the table below is generated from them.

Error code strings

Stable identifiers used in error messages and structured error objects, with the exit code each ends the CLI with:

Code Exit Meaning
INVALID_ARGS 2 Missing/invalid argument.
WALLET_NOT_FOUND 3 Named wallet doesn't exist on disk.
WALLET_ADDRESS_MISMATCH 2 A wallet file's saved addresses are not the ones its seed derives: the file was edited or mixed with another wallet's. Nothing was sent.
NETWORK_ERROR 4 Indexer/node/proof-server connection refused or DNS failure.
SYNC_TIMEOUT 4 Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync.
WALLET_BEHIND_FORK 4 A transaction can't be built yet: one of the wallet's three wallets (shielded, unshielded, Dust) hasn't synced past the chain's fork to ledger 9, and the wallet acts at the lowest of their versions.
INSUFFICIENT_BALANCE 5 Wallet doesn't have enough NIGHT to cover the requested amount.
TX_REJECTED 6 Chain rejected the submitted transaction (catch-all when no more specific code applies).
STALE_UTXO 6 UTXO was already spent on-chain (substrate "error code 115").
STALE_CACHE 6 Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed).
PROOF_TIMEOUT 6 ZK proof generation didn't finish within the deadline.
PROOF_FAILURE 6 Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server.
NOT_A_PROOF_SERVER 4 The proof server URL answers, but not as a proof server: its /version gives no version (another service on that port, a proxy that answers everything).
INVALID_DUST_PROOF 6 Chain rejected the dust spend proof as malformed (substrate "Custom error 170"). Stale commitment tree.
CONTRACT_STATE_UNREADABLE 1 A contract's state on chain can't be decoded by this mn's ledger: the state the chain holds is at fault, not the user's setup. The message names the contract and includes what the ledger said.
FEE_TOO_LOW 6 The node refused the fee as too low even after mn priced it again with its largest margin (8 blocks of rising prices): prices are climbing faster than that, as when blocks are full one after another.
FEE_REPRICED 6 mn serve's node refused a transaction's fee as too low; mn serve now prices fees with more margin. The transaction keeps its old fee.
DUST_DOUBLE_SPENT 6 Another transaction from the same wallet spent the Dust coin this one pays with first (node error 196, DustDoubleSpend): two payments from one wallet at once. mn builds a transfer or a contract call again by itself, at most twice; mn serve answers it to the dApp to balance again.
TX_INVALIDATED 6 The node accepted the transaction into its pool, then dropped it as invalid while building a block ("Transaction is invalid and was rejected by the node", no error code): another transaction from the same wallet, sent at the same time (another mn, script or machine with the same seed), spent the same Dust or coin and went in first. mn builds a transfer or a contract call again by itself, at most twice; mn serve answers it to the dApp to balance again.
DUST_REQUIRED 5 Wallet has NIGHT but not enough DUST for the fee.
DUST_GENERATING 5 A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust.
CHAIN_CLOCK_BEHIND 4 The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold.
UNSUPPORTED_LEDGER 4 The chain is still on ledger 8; mn supports ledger 9 only.
NO_TEST_CONFIG 1 No dapp.test.json in the folder the test command ran in.
LOCAL_STACK_UNREACHABLE 4 No ledger-9 stack answers at the configured endpoints.
AMBIGUOUS_LOCAL_STACKS 4 Several local Midnight stacks are running and no endpoints are configured, so mn won't guess.
UNSUPPORTED_NODE 1 Node.js is older than 22 (22.18 for mn grant).
NO_NODE_RUNTIME 1 Contract scripts run under Node.js, and none was found on PATH.
CONTRACT_NOT_COMPILED 1 No compiled contract was found where the command looked (managed//compiler/contract-info.json).
CONTRACT_INFO_INVALID 1 A compiled contract's contract-info.json is not what the Compact compiler writes (not JSON, or its circuits or witnesses missing or malformed).
CONTRACT_STATE_BUSY 1 A contract's private-state store stayed in use by another process (another mn running a call of the same contract) for the 3 minutes a call waits for it. The message names the contract and, when it is an mn, its pid and command.
CONTRACT_ASSERTION_FAILED 2 A Compact assert in the circuit called (or in the constructor, for a deploy) failed while the contract ran on this machine, before anything was proven or sent. The message names the contract, the circuit and the assert's own text (e.g. "Still locked").
WITNESSES_NOT_FOUND 1 The contract declares witnesses and the dApp has no compiled witnesses module (dist/witnesses.js or one of the other places the message lists).
NO_ACCOUNT 1 A grant command (midnight_grant_* tool) was called for a wallet that has no account on this network.
CONTRACT_NOT_FOUND 2 No contract is deployed at the address on this network.
ACCOUNT_KEYS_UNAVAILABLE 1 A proving key of the account contract couldn't be had: the installed account build's keys are not published (HTTP 404), or fetching them failed. Nothing was submitted.
WRONG_PASSPHRASE 2 MN_PASSPHRASE is not the passphrase mn's secrets were encrypted with, or a sealed file was changed.
PASSPHRASE_REQUIRED 2 A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: MN_PASSPHRASE is unset and there is no terminal to ask at (the MCP server has none).
BLOCKFROST_PROJECT_ID_REQUIRED 4 The network (preprod or mainnet) is served by Blockfrost and no project id is set for it.
BLOCKFROST_PROJECT_ID_REJECTED 4 Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network.
BLOCKFROST_LIMIT_REACHED 4 Blockfrost's plan limit or rate limit.
ENDPOINT_SHUT_DOWN 4 An endpoint set by flag or config was shut down by its operator (the old preprod indexer, mainnet's old Midnight-hosted indexer and node).
MAINNET_REFUSED 2 The command is refused on mainnet before anything runs: an airdrop (mainnet has no faucet), a test suite (it deploys throwaway contracts), or mn grant (its account build has been tested on a local network only).
MIXED_SDK_LAYOUT 1 mn's packages were installed without the engine's shrinkwrap (bun's installer): the engine's SDK tree isn't the one it was tested with.
NO_STATE_ROOT 1 The host gave mn no place to keep its state (a program's createHost without paths).
NO_PAYER 1 A command that submits a transaction was called without a payer.
SERVE_PORT_IN_USE 1 The port mn serve was to use is taken by a process that can't serve this command (another program, or an mn serve for another network, chain or wallet).
APPROVAL_UNAVAILABLE 1 A request to mn serve needed approval and nobody could be asked: the serve has no terminal and was not started to approve it without asking.
COMMAND_FAILED 1 A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result.
NOT_AN_OFFER 2 The bytes given as a swap offer are not one.
TERMS_MISMATCH 2 A swap offer's own terms differ from the agreed ones.
OFFER_EXPIRED 2 A swap offer is past the expiry its maker set.
OFFER_TAKEN 2 A swap offer's coins are already spent: it was taken, or its maker cancelled it, first (also when the node refuses a take or a cancel for that).
OFFER_NOT_FOR_THIS_WALLET 2 A swap offer was made for another wallet (swap make --for): what it gives is paid to that wallet alone, so this one can't take it. Nothing was sent.
OFFER_COINS_IN_USE 2 A spend would use coins an open swap offer of this wallet's holds, cancelling it.
OFFER_RECORD_UNREADABLE 1 mn's record of a wallet's open swap offers (~/.midnight/swap-offers/<network>/<address>.json) can't be read: not JSON, or not the shape mn writes.
CANCELLED 7 Operation was aborted (SIGINT, or the MCP call was cancelled).
UNKNOWN 1 Error didn't match any known classifier.

Hooks and parsers may rely on substring matching against these.

Command JSON shapes (--json)

Each entry shows the canonical shape. Fields marked alias are backward-compatibility mirrors of another field in the same object.

Every result may carry warnings: an array of strings, the notices the command would print on stderr without --json (for example that Dust on a hosted network was read in WASM, without the native sidecar, and why; or that a contract's private-state store was moved), without colour or indent, in the order they were given. It is present only when there is at least one, and only on a result, not on an error. MCP tool results carry it the same way.

mn balance <address> --json

{
  "address": "mn_addr_undeployed1...",
  "network": "undeployed",
  "balances": { "NIGHT": "1000.000000" },
  "NIGHT": "1000.000000",   // alias of balances.NIGHT (added 2026-04-27)
  "utxoCount": 1,
  "txCount": 2
}

mn balance --wallet <name> --json

{
  "address": "mn_addr_undeployed1...",
  "shieldedAddress": "mn_shield-addr_undeployed1...",
  "network": "undeployed",
  "unshielded": { "NIGHT": "1000.000000", "utxoCount": 1 },
  "shielded": {
    "NIGHT": "10.000000",
    "availableCoins": 1,
    "pendingCoins": 0,
    "tokens": {}               // other shielded tokens: raw token type → amount in its smallest unit, as a string
  },
  "shieldedSynced": true       // false: the shielded balance was not read (preview, preprod and mainnet without --force-shielded), so shielded.NIGHT is not a confirmed zero
}

mn transfer <to> <amount> --json

{
  "txHash": "00ab...",
  "amount": "100",                         // NIGHT, as a string; with --token, the token's smallest unit
  "token": "ab12...",                      // with --shielded --token only: the token's raw type (64 hex)
  "recipient": "mn_addr_undeployed1...",
  "network": "undeployed",
  "type": "shielded",                      // with --shielded only
  "receipt": {                             // see "Receipts" below
    "kind": "regular", "hash": "00ab...", "identifiers": ["..."], "result": "SUCCESS",
    "fee": "0.548120", "feeSpecks": "548120000000000",
    "blockHeight": 1234, "blockHash": "...", "blockTime": "2026-11-11T10:00:00.000Z"
  }
}

With several recipients, amount is their total and recipient gives way to recipients: [{ "recipient": "mn_addr_...", "amount": "10" }, ...], in order. selfTransfer: true (with a note) marks a payment to the sending wallet itself.

mn airdrop <amount> --json

{
  "txHash": "00ef...",
  "amount": "50000",
  "recipient": "mn_addr_undeployed1...",
  "network": "undeployed",
  "receipt": { /* see "Receipts" below */ },
  "dustRegistered": false      // unshielded airdrop, when it could be read: false means run mn dust register before the wallet pays a fee
}

With --shielded, recipient is the shielded address, shieldedAddress repeats it (alias, its older name), and type is "shielded".

Receipts

A command that submits a transaction (transfer, airdrop, dust register, contract deploy and call, the grant and swap commands) returns its txHash, the transaction's identifier (66 hex characters, the one mn tx status takes; since 0.6.0 for contract deploy and call too, which gave the 64-hex hash before), and waits up to 60 s for the indexer to list it. receipt is then the transaction as mn tx status gives it: kind, hash, identifiers (regular transactions), result (SUCCESS, PARTIAL_SUCCESS or FAILURE), segments (a partial success), fee (DUST, exact) and feeSpecks, blockHeight, blockHash and blockTime. When the indexer has not listed it, receipt is null and receiptMissing says why; check later with mn tx status <txHash>.

mn info --wallet <name> --json

{
  "addresses": {
    "mainnet": "mn_addr1...",
    "preprod": "mn_addr_preprod1...",
    "preview": "mn_addr_preview1...",
    "undeployed": "mn_addr_undeployed1..."
  },
  "shieldedAddresses": { /* same shape, mn_shield-addr_<net>1... (mn_shield-addr1... on mainnet) */ },
  "activeNetwork": "undeployed",
  "activeAddress": "mn_addr_undeployed1...",
  "createdAt": "2026-03-26T05:27:33.721Z",
  "file": "/Users/<user>/.midnight/wallets/<name>.json"
}

mn dust status --wallet <name> --json

{
  "subcommand": "status",
  "registered": true,
  "registeredUtxos": 1,
  "unregisteredUtxos": 0,
  "dustBalance": "1050.675442999999998",
  "dustAvailable": true,
  "eventsApplied": 19,
  "ownedUtxos": 1,
  "cached": true,
  "network": "undeployed"
}

dustBalance is DUST as a decimal string (6 to 15 places), never specks. Not registered, it is { subcommand, registered: false, registeredUtxos, unregisteredUtxos, network }.

mn dust register --wallet <name> --json

{
  "subcommand": "register",
  "network": "undeployed",
  "dustBalance": "0.000000",   // DUST once registered, as status gives it
  "dustNeeds": {               // what the Dust is ready for, and when
    "generatedPerSecond": "0.000123",                  // DUST its registered NIGHT generates a second
    "transfer": { "dust": "0.650000", "waitSeconds": 180 },        // waitSeconds: 0 has it now; null not within a day
    "counterDeploy": { "dust": "1.240000", "waitSeconds": 600 }    // a guide: contract deploy --dry-run prices yours
  },
  "txHash": "00ab...",         // only when a registration was submitted; absent when the wallet had Dust already
  "receipt": { /* see Receipts */ }
}

Without --json, stdout is dust=<DUST> and, when a registration was submitted, tx_hash=<txHash>, one per line.

mn contract inspect --json

{
  "name": "counter",
  "compilerVersion": "0.36.0",
  "languageVersion": "0.28.0",
  "runtimeVersion": "0.21.0",   // must be the compact-runtime mn bundles (0.21.0), or a deploy or call is refused
  "managedDir": "/path/to/managed/counter",
  "siblings": [],            // names of other contracts in the same managed/ dir; empty for single-contract projects
  "circuits": [{ "name": "increment", "pure": false, "proof": true, "arguments": [], "returnType": "void" }],
  "witnesses": []
}

mn contract deploy --json

{
  "subcommand": "deploy",
  "contractName": "counter",
  "address": "9b3e083bf850ca17983d34110337d384d2dc626da8223c3fb2dbd3f8a2df35a3",
  "network": "preprod",
  "txHash": "00b1...",                 // the deploy's transaction's identifier (66 hex, as every command gives it; its hash is receipt.hash); absent when the payer gave none
  "receipt": { /* see "Receipts" above */ },
  // The deploy's price, worked out after the wallet synced and before anything was proven; absent when the mn serve that paid gave none.
  "cost": {
    "fee": "1.075820342856952",        // expected fee at the chain's fee prices then, DUST
    "committed": "1.2310452531272",    // Dust the wallet commits to it: the fee with marginBlocks of rising prices, all of it burned
    "have": "5.000000",                // Dust the wallet held
    "covers": true,                    // whether have covers committed
    "waitSeconds": 0,                  // how long its registered NIGHT takes to generate the rest; null when not within a day
    "marginBlocks": 3
  }
}

mn contract deploy --dry-run --json

Prices the deploy and stops: nothing is proven or sent, and there is no address, txHash or receipt. mn contract call --dry-run --json is the same for a call, with circuit and address.

{
  "subcommand": "deploy",
  "contractName": "counter",
  "network": "undeployed",
  "dryRun": true,
  "cost": { "fee": "1.075820342856952", "committed": "1.2310452531272", "have": "0.388954231668571", "covers": false, "waitSeconds": 102, "marginBlocks": 3 }
}

mn contract call --json

{
  "subcommand": "call",
  "contractName": "counter",
  "circuit": "increment",
  "address": "9b3e083bf850ca17983d34110337d384d2dc626da8223c3fb2dbd3f8a2df35a3",
  "network": "preprod",
  "status": "success",
  "txHash": "00c2...",
  "receipt": { /* see "Receipts" above */ },
  // As deploy's; a call's proofs are priced at the ledger's estimate, so a few percent off (a counter's increment: about 3% over).
  "cost": { "fee": "0.201842057142821", "committed": "0.230964870646751", "have": "0.827836439768184", "covers": true, "waitSeconds": 0, "marginBlocks": 3 },
  // Only when the arguments held {"@coin": ...} shorthands: each fresh coin's nonce, by which the contract may name it later.
  "freshCoins": [{ "argument": "coin", "nonce": "3f2a..." }],
  // Only when the call gave the contract coins: recorded in its private state under mnHeldCoins, for a witness to spend.
  "heldCoins": [{ "argument": "coin", "commitment": "9c41...", "mtIndex": "17" }]
}

warnings (see above) carries a note when --args gave an argument the circuit keeps private, which belongs in --args-file or --args -.

mn contract state --json

{
  "subcommand": "state",
  "address": "9b3e083bf850ca17983d34110337d384d2dc626da8223c3fb2dbd3f8a2df35a3",
  "network": "preprod",
  "fields": { "round": "1", "owner": "511eff…" },     // scalars as strings (BigInt-safe)
  "maps":   { "providers": { "size": 1 } }            // maps by entry count, a number (null when unreadable)
}

mn test create --json

{
  "subcommand": "create",
  "contractName": "counter",
  "suiteName": "cli-default",
  "strategy": "cli",                                  // "cli" or "ui"
  "written": [
    "/path/to/dapp.test.json",
    "/path/to/tests/suites/cli-default/suite.json",
    "/path/to/tests/suites/cli-default/actions.json",
    "/path/to/tests/suites/cli-default/assertions.json"
  ]
}

mn localnet logs --json

{
  "subcommand": "logs",
  "tail": 200,
  "lines": ["…"]
}

mn wallet list --json

Per packages/wallet/src/commands/wallet.ts, list of wallet names, addresses, networks, with the active wallet marked. Shape stable.

mn config get <key>

Plain stdout: the raw value as a string, no JSON wrapper. With --json: {"action": "get", "key": "...", "value": "..."} (config set and config unset answer the same shape with "action": "set" / "unset"). mn config get with no key: one key value line per key; with --json, {"action": "get", "values": {"network": "...", ...}} (and "network" with --network, which lists only the keys a network scopes). The Blockfrost project id is masked in both.

MCP tool names

Every tool name shipped in src/mcp-server.ts is stable, except the eight midnight_grant_* tools and the five midnight_swap_* tools, which are experimental: their names, parameters and results can change in any release until they are declared stable here. Current 44 tools:

# Wallet management
midnight_wallet_generate      midnight_wallet_list
midnight_wallet_use           midnight_wallet_info
midnight_wallet_remove

# Balance & info
midnight_info                 midnight_balance
midnight_address              midnight_genesis_address
midnight_inspect_cost

# Transactions
midnight_airdrop              midnight_transfer
midnight_dust_register        midnight_dust_status
midnight_tx_status

# Consent
midnight_confirm_operation

# Configuration
midnight_config_get           midnight_config_set
midnight_config_unset         midnight_cache_clear

# Local network
midnight_localnet_up          midnight_localnet_stop
midnight_localnet_down        midnight_localnet_status
midnight_localnet_clean       midnight_localnet_logs

# Contracts
midnight_contract_inspect     midnight_contract_state
midnight_contract_deploy      midnight_contract_call

# Test framework
midnight_test_create

# Swaps (experimental)
midnight_swap_make            midnight_swap_inspect
midnight_swap_take            midnight_swap_cancel
midnight_swap_list

# Grants (experimental)
midnight_grant_status         midnight_grant_list
midnight_grant_request        midnight_grant_deploy
midnight_grant_deposit        midnight_grant_issue
midnight_grant_revoke         midnight_grant_revoke_all

Tool parameter names are also stable (the experimental tools excepted). A new optional parameter is additive; renaming or removing one is a major bump.

MCP response envelope

Every MCP tool response — success, error, or pending-confirmation token — carries a _serverVersion field with the server's package.json version. Use it to detect a stale server (CLI on disk says X, responses still say Y means the user's MCP client is talking to a long-lived process from an older install). Underscore prefix marks it as metadata, distinct from tool-shape data fields.

// success:
{ "subcommand": "deploy", "address": "9b3e…", "_serverVersion": "0.6.0" }
// error:
{ "error": true, "code": "DUST_REQUIRED", "message": "…", "_serverVersion": "0.6.0" }
// pending-token:
{ "pending": true, "token": "uuid", "description": "…", "tool": "midnight_transfer", "expiresAt": "2026-11-11T10:05:00.000Z", "nextStep": "…", "_serverVersion": "0.6.0" }

Compatibility aliases (additive shims)

Additions made on our side so existing integrations keep working without touching their code:

Surface Canonical Alias Added For
Config key network network-id 2026-04-27 midnight-expert setup-test-wallets
Balance JSON balances.NIGHT top-level NIGHT 2026-04-27 midnight-expert session-start-health

If you're an integrator and you depend on a shape we haven't documented here yet, open an issue. We'd rather codify it now than discover it broken in your release later.