NIGHTGATE on Midnight

NIGHTGATE is the OData V4 API for the Midnight blockchain, built on SAP CAP. A crawler indexes blocks from a Midnight node into CAP entities. A wallet stack in worker threads submits transactions: NIGHT and custom-token transfers, Compact contract deploys and calls, document anchoring, zero-knowledge attestations that prove a claim without revealing the value. No GraphQL, no SDK on the client.

It runs hosted at api.odatano.dev, or self-hosted from the container image or a clone of the repository. It runs on Midnight ledger 9 networks. The client side is @odatano/nightgate-tx on npm.

Services

ServicePathWhat
NightgateService/odata/v4/midnightchain data, wallet sessions, token, contract, attestation and agent-grant actions
NightgateIndexerService/odata/v4/midnight-indexersync state, health, reorg history, metrics, crawler control
NightgateAnalyticsService/odata/v4/midnight-analyticsaggregate counts
NightgateAdminService/odata/v4/midnight-adminsessions, contract registration, sponsor policy, diagnostics
NightgateVerifyService/odata/v4/midnight-verifystate verification without login, when NIGHTGATE_PUBLIC_VERIFY=true

The hosted API serves the same paths.

Write actions are async. They return { jobId, status }; read the result with GET …/getJobStatus(jobId='…',waitMs=20000), which holds until the job settles or the time is up. A job result names txId, the ledger identifier, and txHash, the hash explorers show. Jobs survive restarts: idempotency keys, leased execution, chainStatus confirmed from the indexer. Write actions answer 503 with Retry-After while the wallet runtime is down.

Reads count in the rate class query, 600 per minute per caller. A $batch carries at most 20 requests. A block height arrives as text, like every 64-bit integer.

What it does

  • Block indexing: live and catch-up crawler with reorg detection. Blocks, Transactions, ContractActions, UnshieldedUtxos and NightBalances fill from the node. Rows carry their chain position (blockHeight, indexInBlock): sort by it, it is indexed.
  • Wallet sessions: connectWallet (viewing key, read only) and connectWalletForSigning (BIP39 mnemonic, Lace-compatible derivation). Secrets are AES-256-GCM encrypted at rest. deriveWalletInfo creates a wallet without Lace.
  • Tokens: sendToken moves NIGHT or a custom token (tokenType). getWalletBalance and estimateSendTokenFee run before you spend.
  • Compact contracts: deployContract, submitContractCall, submitContractCallBatch with up to 8 calls in one transaction. Admins register contract artifacts at runtime.
  • Proving: in-process WASM by default, no proof server. NIGHTGATE_PROOF_SERVER_URL switches to a proof server.
  • Fee sponsoring: sponsorSessionId on every submit action; the caller needs neither NIGHT nor DUST. A sponsor policy limits contracts, circuits and token types; a grant sets the deploys and maintenance updates it may have paid.
  • Document anchoring: anchorDocument and verifyDocument put a hash on chain; storage stays with the caller. prepareDocumentProof turns canonical JSON into a content root with per-field paths, 16 or 32 slots.
  • Field proofs: proveFieldPredicate (value at most or at least a threshold), proveFieldEquality, proveFieldMembership, and proveClaims with up to 8 claims in one transaction. Values stay hidden. A threshold is a decimal string.
  • Cross-document proofs: proveDocumentIntegrity and proveDocumentDiff compare two anchored documents.
  • Crawler-free verification: verifyAttestation, verifyPredicate and verifyDisclosure read live contract state from the indexer and name the block they read. The verify service serves all three without login.
  • Disclosure: grantDisclosure and revokeDisclosure record on chain who may read a document at which level. grantDisclosureToHolders and claimDisclosure do the same for the holders of a token.
  • Agent grants: createAgentGrant issues an ngat_… token with action allow list, budgets, pinned session and sponsor. attestAgentOutput anchors agent-output provenance.
  • Local building: @odatano/nightgate-tx builds, proves and signs with your own key; sponsorFinalized and sponsorUnbound pay and submit.
  • Browser: connectContract in @odatano/nightgate-tx/calls plus /zk-config and /contract-manifest for wallet-driven Lace dApps.
  • Operations: liveness and readiness without login, Prometheus metrics for the operator, crawler pause, resume and reindex, offline start when the node is unreachable.

Architecture

Main thread                       Worker thread
┌────────────────────┐            ┌────────────────────────┐
│ Crawler            │            │ Wallet SDK             │
│ - BlockProcessor   │            │ - facade.start (sync)  │
│ - reorg detection  │            │ - transferTransaction  │
└────────┬───────────┘            │ - finalize (ZK prove)  │
         ▼  atomic writes         │ - deployContract       │
┌────────────────────┐            │ - submitContractCall   │
│ CAP DB             │◄─state-save┤ - private-state-rpc    │
└────────┬───────────┘            └────────────────────────┘
         ▼  OData V4
5 services on /odata/v4/midnight{,-indexer,-analytics,-admin,-verify}

The wallet SDK lives in a worker thread because its sync saturates the microtask queue. The CAP request pipeline stays responsive.

Run it

Container

docker run -d --init -p 127.0.0.1:4004:4004 \
  -e ENCRYPTION_KEY=$(openssl rand -hex 32) \
  -e NIGHTGATE_HTTP_PASSWORD=change-me \
  -e NIGHTGATE_NODE_URL='ws://<node-host>:9944' \
  -e NIGHTGATE_INDEXER_HTTP_URL='http://<indexer-host>:8088/api/v4/graphql' \
  -v nightgate-data:/data \
  ghcr.io/odatano/nightgate:latest

The image defaults to mainnet and always checks credentials (HTTP basic auth). Every network but preview needs its own node and indexer in NIGHTGATE_NODE_URL and NIGHTGATE_INDEXER_HTTP_URL; NIGHTGATE_NETWORK=preview alone is enough, it has public endpoints built in. The database lives in the volume, SQLite by default; NIGHTGATE_DB_URL=postgres://… switches to PostgreSQL. Mainnet submission stays off until NIGHTGATE_ALLOW_MAINNET_SUBMISSION=true.

From a clone

git clone https://github.com/ODATANO/NIGHTGATE && cd NIGHTGATE
npm ci
npm run deploy
npm run dev            # cds watch with a 12 GB heap
# .env in the repository root
NIGHTGATE_NETWORK=preprod
NIGHTGATE_NODE_URL=ws://<node-host>:9944
NIGHTGATE_INDEXER_HTTP_URL=http://<indexer-host>:8088/api/v4/graphql
ENCRYPTION_KEY=<output of openssl rand -hex 32>

Needs Node.js 22.12 or newer. Started this way the server checks no credentials, so it listens on 127.0.0.1 only. npm run serve:sync serves long wallet syncs from the file database.

Stack

LayerTech
NetworkMidnight mainnet, preprod, preview, stagenet; undeployed for a local stack
Chain accessSubstrate RPC over WebSocket, GraphQL indexer
BackendSAP CAP 10, Node.js, TypeScript; midnight-js in worker_threads
DatabaseSQLite with one instance, or PostgreSQL
Auth@odatano/cap-auth: basic auth, agent-token lane, public verify lane

On GitHub

The repo holds the detail this page leaves out. github.com/ODATANO/NIGHTGATE

Built on NIGHTGATE: NIGHTPASS, the EU battery passport with three disclosure levels.