Skip to content
midnight-dapp:state-management logo

midnight-dapp:state-management

Use when reading public ledger state, implementing reactive UI that updates with chain state, caching state for performance, or understanding public vs private state in Midnight DApps.

SKILL.md

Full skill instructions

State Management

Read, sync, and cache contract state in Midnight DApps with proper handling of the dual-state model.

When to Use

  • Reading public ledger state from deployed contracts
  • Implementing reactive UI that updates with chain state
  • Caching state for performance optimization
  • Understanding when to use public vs private state
  • Syncing state across multiple components

Key Concepts

Dual-State Model

Midnight contracts have two types of state:

State TypeStorage LocationAccess MethodVisibility
Public Ledger StateOn-chain (indexer)contract.state.*Anyone can read
Private Local StateBrowser (LevelDB)WitnessContext.privateStateOnly local user

This is fundamentally different from Ethereum where all state is public on-chain.

State Access Patterns

// Public state - anyone can read
const totalSupply = await contract.state.total_supply();
const balance = await contract.state.balances.get(address);

// Private state - accessed only in witnesses
const witnesses = {
  get_secret: ({ privateState }) => privateState.secretKey,
};

Chain Synchronization

State on-chain can change from other transactions. DApps must handle:

  1. Initial Load - Fetch current state when component mounts
  2. Polling - Periodically check for updates
  3. WebSocket - Subscribe to real-time updates
  4. Optimistic Updates - Update UI before confirmation

References

DocumentDescription
contract-state.mdReading public and private contract state
chain-sync.mdSynchronization patterns and subscriptions
privacy-aware-caching.mdSafe caching strategies for Midnight
web3-comparison.mdEthereum state patterns vs Midnight

Examples

ExampleDescription
use-contract-state/React hook for reading contract state
state-sync-provider/Context provider for state synchronization
cache-manager/Privacy-aware caching utilities

Quick Start

1. Read Simple State Values

// After contract deployment, read public state
const contract = await deployedContract();

// Simple value
const totalSupply: bigint = await contract.state.total_supply();

// Map lookup
const balance: bigint | undefined = await contract.state.balances.get(userAddress);

// Set membership
const isMember: boolean = await contract.state.members.has(userAddress);

2. Create a State Hook

function useContractState<T>(
  contract: Contract,
  accessor: (state: ContractState) => Promise<T>
) {
  const [value, setValue] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;

    async function fetchState() {
      setLoading(true);
      const result = await accessor(contract.state);
      if (!cancelled) {
        setValue(result);
        setLoading(false);
      }
    }

    fetchState();
    return () => { cancelled = true; };
  }, [contract, accessor]);

  return { value, loading };
}

3. Subscribe to Updates

// Poll for state changes
useEffect(() => {
  const interval = setInterval(async () => {
    const newBalance = await contract.state.balances.get(address);
    setBalance(newBalance);
  }, 5000); // Poll every 5 seconds

  return () => clearInterval(interval);
}, [contract, address]);

Common Patterns

Type-Safe State Reading

interface ContractState {
  total_supply(): Promise<bigint>;
  balances: {
    get(address: string): Promise<bigint | undefined>;
  };
  members: {
    has(address: string): Promise<boolean>;
  };
}

// The compiler generates these types from your Compact contract

Error Handling

async function safeStateRead<T>(
  accessor: () => Promise<T>,
  fallback: T
): Promise<T> {
  try {
    return await accessor();
  } catch (error) {
    console.error('State read failed:', error);
    return fallback;
  }
}

const balance = await safeStateRead(
  () => contract.state.balances.get(address),
  0n
);

Optimistic Updates

// Update UI immediately, then sync with chain
const [balance, setBalance] = useState<bigint>(0n);

async function transfer(to: string, amount: bigint) {
  // Optimistic update
  setBalance(prev => prev - amount);

  try {
    await contract.callTx.transfer(to, amount, witnesses);
    // State will sync on next poll
  } catch (error) {
    // Revert optimistic update
    setBalance(prev => prev + amount);
    throw error;
  }
}

Related Skills

  • wallet-integration - Required for setting up providers
  • proof-handling - Witness implementation that accesses private state
  • transaction-flows - Submitting state-changing transactions
  • error-handling - Handling state read errors

Related Commands

  • /​dapp-check - Validates provider configuration
  • /​dapp-debug state - Debug state synchronization issues

More DevOps & CI/CD skills

Project scaffolding, deployment configuration, and CI/CD setup for Google ADK agents.

6K 472.6K
View

Set up tracing, logging, and monitoring for deployed ADK agents across Cloud Trace, BigQuery, and third-party platforms.

6K 472.6K
View

Enterprise Azure infrastructure architect generating Bicep or Terraform from workload descriptions.

1.5K 454.3K
View
azure-kubernetes logo
DevOps & CI/CD

azure-kubernetes

Plan and configure production-ready Azure Kubernetes Service clusters with Day-0 and Day-1 best practices.

1.5K 447.1K
View

Raw mechanical interfaces fusing Swiss typographic print with military terminal aesthetics. Rigid grids, extreme type scale contrast, utilitarian color, analog degradation effects. For data-heavy dashboards, portfolios, or editorial sites that need to feel like declassified blueprints.

92.7K 354.9K
View
just-scrape logo
DevOps & CI/CD

just-scrape

Web search, scraping, extraction, crawling, and monitoring via ScrapeGraph AI CLI.

69 245K
View

Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting.

462 159.7K
View

Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends.

462 159.1K
View
deploy-to-vercel logo
DevOps & CI/CD

deploy-to-vercel

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

31.9K 146.6K
View
programmatic-seo logo
DevOps & CI/CD

programmatic-seo

Build SEO-optimized pages at scale using templates, data, and proven playbook patterns.

53.3K 140.1K
View

Design and build isolated, reusable Convex backend components with clear boundaries and app-facing wrappers.

63 123.5K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View

Coding & apps AI tools

Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View
I
Coding & apps

Imagica

Build a no-code AI app in minutes.

Freemium
View
E
Coding & apps

Emergent.sh

An IDE for code migration from legacy to modern frameworks through coding agents.

Freemium
View
Wonder Dynamics logo
Coding & apps

Wonder Dynamics

Automate CGI animation in live-action scenes

Paid
View
M
Coding & apps

Mixo

Launch a website in seconds with AI.

Paid
View
AI Code Convert logo
Coding & apps

AI Code Convert

Streamline Your Coding Experience with AI Code Helper

Free
View