惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Martin Fowler
Martin Fowler
P
Palo Alto Networks Blog
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
博客园_首页
量子位
小众软件
小众软件
F
Full Disclosure
Vercel News
Vercel News
爱范儿
爱范儿
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
博客园 - 聂微东
V
V2EX
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
L
Lohrmann on Cybersecurity
H
Hacker News: Front Page
Spread Privacy
Spread Privacy
AI
AI
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CERT Recently Published Vulnerability Notes
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recorded Future
Recorded Future
L
LINUX DO - 热门话题
Microsoft Azure Blog
Microsoft Azure Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Latest news
Latest news
W
WeLiveSecurity
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 司徒正美
博客园 - 叶小钗
T
Threat Research - Cisco Blogs
P
Privacy International News Feed
O
OpenAI News
Help Net Security
Help Net Security
aimingoo的专栏
aimingoo的专栏
宝玉的分享
宝玉的分享
博客园 - Franky

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to build an unshielded token smart contract and UI on Midnight network
Kevin Oh · 2026-05-07 · via DEV Community

This tutorial will cover how to write an unshielded token contract on the Midnight network and integrate it with a UI built with Vite. Before we begin let's quickly go over the differences between unshielded and shielded tokens on Midnight network.

Shielded vs Unshielded tokens

Midnight network provides both unshielded and shielded tokens out of the box. The difference between the two is visibility. Unshielded tokens are fully visible and shielded tokens are fully private with selective visibility.

Use unshielded tokens in cases where public visibility is important to you. Think public treasuries, charities, or foundations where you want to give anyone the ability to see how funds are being used.

Use shielded tokens when user privacy is important to you. Think payrolls, voting, or trading, where users don't want anyone to be able to see their transactions.

Note that when we are talking about unshielded and shielded tokens these are not like ERC-20 tokens that you may be used to from Ethereum. Unshielded and shielded tokens are based on the UTXO model. ERC-20 tokens are based on the account model.

Prerequisites

Unshielded token smart contract

We will use native circuits provided by the CompactStandardLibrary such as mintUnshieldedToken, sendUnshielded, and receiveUnshielded. Listed below are the circuit definitions for each of them.

mintUnshieldedToken(
  domainSep: Bytes<32>,
  value: Uint<64>,
  recipient: Either<ContractAddress, UserAddress>
): Bytes<32>;

sendUnshielded(
  color: Bytes<32>,
  amount: Uint<128>, 
  recipient: Either<ContractAddress, UserAddress>
): [];

receiveUnshielded(
  color: Bytes<32>,
  amount: Uint<128>
): [];

Enter fullscreen mode Exit fullscreen mode

mintUnshieldedToken takes a domain separator, amount, and a recipient address. It returns a color or sometimes called a token type which is derived from the domain separator and uniquely identifies the token in the contract. This means that a single contract has the ability to mint and manage multiple tokens using the color or token type as a unique identifier. The domain separator must be 32 bytes so you may have to pad it or shorten it to meet the size requirement.

sendUnshielded takes a color, amount, and a recipient. This circuit sends the token amount from the contract to the recipient. Which token it sends is identified by the given color.

receiveUnshielded takes a color and amount. This circuit sends the token amount from the caller to the contract. Which token it sends is identified by the given color.

You may have noticed that none of these circuits transfer tokens from user to user. sendUnshielded, and receiveUnshielded are only used if and only if the token contract itself is the sender or recipient of a transfer of tokens. Transactions are built and signed directly by the client for any transfers where the token contract is not the sender or recipient.

Now that we understand how mintUnshielded, sendUnshielded, and receiveUnshielded library circuits work we can start writing the smart contract. The smart contract will define circuits for minting tokens to a user, and depositing and withdrawing tokens from the smart contract.

Let's start with the constructor:

export ledger domainSep: Bytes<32>;

constructor() {
    domainSep = "aaaaAAAAaaaaAAAAaaaaAAAAaaaaAAAA";
}

Enter fullscreen mode Exit fullscreen mode

We only need to do one thing in the constructor which is to setup the domain separator. The domain separator is static because this smart contract will only manage one token.

Implement the mint circuit:

export circuit mint(value: Uint<64>, recipient: UserAddress): [] {
    mintUnshieldedToken(
        domainSep, 
        disclose(value), 
        disclose(right<ContractAddress, UserAddress>(disclose(recipient)))
    );
}

Enter fullscreen mode Exit fullscreen mode

Implement the withdraw circuit:

export circuit sendToken(amount: Uint<128>, recipient: UserAddress): [] {
    const color = tokenType(domainSep, kernel.self());
    sendUnshielded(
        color, 
        disclose(amount), 
        disclose(right<ContractAddress, UserAddress>(disclose(recipient))));
}

Enter fullscreen mode Exit fullscreen mode

Derive the color using the tokenType function from the CompactStandardLibrary.

Implement the deposit circuit:

export circuit receiveToken(amount: Uint<128>): [] {
    const color = tokenType(domainSep, kernel.self());
    receiveUnshielded(color, disclose(amount));
}

Enter fullscreen mode Exit fullscreen mode

For reference here is the entire smart contract:

pragma language_version >= 0.16;

import CompactStandardLibrary;

export ledger domainSep: Bytes<32>;

constructor() {
    domainSep = "aaaaAAAAaaaaAAAAaaaaAAAAaaaaAAAA";
}

export circuit mint(value: Uint<64>, recipient: UserAddress): [] {
    mintUnshieldedToken(
        domainSep, 
        disclose(value), 
        disclose(right<ContractAddress, UserAddress>(disclose(recipient)))
    );
}

export circuit sendToken(amount: Uint<128>, recipient: UserAddress): [] {
    const color = tokenType(domainSep, kernel.self());
    sendUnshielded(
        color, 
        disclose(amount), 
        disclose(right<ContractAddress, UserAddress>(disclose(recipient)))
    );
}

export circuit receiveToken(amount: Uint<128>): [] {
    const color = tokenType(domainSep, kernel.self());
    receiveUnshielded(color, disclose(amount));
}

Enter fullscreen mode Exit fullscreen mode

Compile the smart contract with the command:

compact compile path/to/unshielded.compact compiled/

Enter fullscreen mode Exit fullscreen mode

The compact CLI will take a path to your smart contract and output the artifacts to compiled/ folder.

I will not be showing how to deploy the smart contract in this tutorial as that would double the tutorial length. All the scripts I used to deploy will be in the source code linked below.

Now that the smart contract is completed we can move on to the frontend.

Frontend

Create a Vite project using React as the framework. Copy the compiled/ folder to public/ and also 'src/'.

We need to define some contract primitives at lib/contract.ts that we will use later on to interact with the smart contract.

import {
  CompiledContract,
  ProvableCircuitId,
} from "@midnight-ntwrk/compact-js";
import * as CompiledOutput from "../compiled/contract";
import type { MidnightProviders } from "@midnight-ntwrk/midnight-js/types";

export const contractAddress = "";
export const unshieldedContract =
  CompiledContract.make<CompiledOutput.Contract>(
    "unshielded-token",
    CompiledOutput.Contract,
  ).pipe(
    CompiledContract.withVacantWitnesses,
    CompiledContract.withCompiledFileAssets("./compiled"),
  );
export type DemoContract = CompiledOutput.Contract<undefined>;
export type DemoCircuits = ProvableCircuitId<DemoContract>;
export type DemoProviders = MidnightProviders<DemoCircuits>;

Enter fullscreen mode Exit fullscreen mode

Replace the contractAddress string with the address you received after deploying the smart contract.

Create lib/address.ts which holds a helper function used to convert from human readable addresses to a smart contract accepted byte array.

import {
  MidnightBech32m,
  UnshieldedAddress,
} from "@midnight-ntwrk/wallet-sdk-address-format";

export function convertBech32ToUserAddress(b32: string, networkId: string) {
  const parsed = MidnightBech32m.parse(b32 ?? "").decode(
    UnshieldedAddress,
    networkId,
  );
  const userAddress = new Uint8Array(parsed.data);
  return userAddress;
}

Enter fullscreen mode Exit fullscreen mode

Create lib/wallet.ts which will hold a helper function to locate the injected wallet.

import type { InitialAPI } from "@midnight-ntwrk/dapp-connector-api";

export function findInitialAPIs(): InitialAPI[] {
  const midnight = window.midnight;
  if (!midnight) return [];

  const apis: InitialAPI[] = [];
  for (const key of Object.keys(midnight)) {
    const candidate = midnight[key];
    if (
      candidate &&
      typeof candidate === "object" &&
      typeof candidate.name === "string" &&
      typeof candidate.icon === "string" &&
      typeof candidate.apiVersion === "string" &&
      typeof candidate.connect === "function"
    ) {
      apis.push(candidate as InitialAPI);
    }
  }
  return apis;
}

Enter fullscreen mode Exit fullscreen mode

Create lib/walletAdapter.ts. This provides a helper function to build out walletProvider and midnightProvider. walletProvider is responsible for creating balanced and proven transactions and midnightProvider submits them to the network.

import {
  type UnboundTransaction,
  type WalletProvider,
} from "@midnight-ntwrk/midnight-js/types";
import {
  Binding,
  type CoinPublicKey,
  type EncPublicKey,
  type FinalizedTransaction,
  Proof,
  SignatureEnabled,
  Transaction,
} from "@midnight-ntwrk/ledger-v8";
import type { ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api";

export type ShieldedAddress = {
  shieldedAddress: string;
  shieldedCoinPublicKey: string;
  shieldedEncryptionPublicKey: string;
};

export function uint8ArrayToHex(bytes: Uint8Array): string {
  return Array.from(bytes)
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
}

export function hexToUint8Array(hex: string): Uint8Array {
  const cleaned = hex.replace(/^0x/, "");
  const matches = cleaned.match(/.{1,2}/g);
  if (!matches) return new Uint8Array();
  return new Uint8Array(matches.map((byte) => parseInt(byte, 16)));
}

export function createWalletProvidersFromConnectedAPI(
  connectedAPI: ConnectedAPI,
  shieldedAddress: ShieldedAddress,
) {
  const walletProvider: WalletProvider = {
    getCoinPublicKey(): CoinPublicKey {
      return shieldedAddress.shieldedCoinPublicKey;
    },
    getEncryptionPublicKey(): EncPublicKey {
      return shieldedAddress.shieldedEncryptionPublicKey;
    },
    async balanceTx(tx: UnboundTransaction): Promise<FinalizedTransaction> {
      try {
        const serialized = tx.serialize();
        const serializedStr = uint8ArrayToHex(serialized);
        const result =
          await connectedAPI.balanceUnsealedTransaction(serializedStr);
        const resultBytes = hexToUint8Array(result.tx);
        const deserializedTx = Transaction.deserialize(
          "signature",
          "proof",
          "binding",
          resultBytes,
        ) as Transaction<SignatureEnabled, Proof, Binding>;
        return deserializedTx;
      } catch (error) {
        console.error(
          "[WalletAdapter] balanceTx: Error during transaction balancing:",
          error,
        );
        throw error;
      }
    },
  };

  const midnightProvider = {
    async submitTx(tx: FinalizedTransaction): Promise<string> {
      try {
        const serialized = tx.serialize();
        const serializedStr = uint8ArrayToHex(serialized);
        await connectedAPI.submitTransaction(serializedStr);
        const txId = tx.identifiers()[0];
        return txId;
      } catch (error) {
        console.error(
          "[WalletAdapter] submitTx: Error during transaction submission:",
          error,
        );
        throw error;
      }
    },
  };

  return { walletProvider, midnightProvider };
}

Enter fullscreen mode Exit fullscreen mode

Create lib/providers.ts. The function buildProvidersFromConnectedAPI will build out the rest of the providers needed to interact with the Midnight network.

import { levelPrivateStateProvider } from "@midnight-ntwrk/midnight-js-level-private-state-provider";
import { indexerPublicDataProvider } from "@midnight-ntwrk/midnight-js-indexer-public-data-provider";
import { FetchZkConfigProvider } from "@midnight-ntwrk/midnight-js-fetch-zk-config-provider";
import { httpClientProofProvider } from "@midnight-ntwrk/midnight-js-http-client-proof-provider";
import type { ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api";

import {
  createWalletProvidersFromConnectedAPI,
  type ShieldedAddress,
} from "./walletAdapter";
import {
  contractAddress,
  type DemoCircuits,
  type DemoProviders,
} from "./contract";

export const networkId = "undeployed";

export async function buildProvidersFromConnectedAPI(
  connectedAPI: ConnectedAPI,
): Promise<DemoProviders> {
  const zkConfigHttpBase = window.location.origin + "/compiled/";
  console.log("zkConfigHttpBase", zkConfigHttpBase);
  const zkConfigProvider = new FetchZkConfigProvider<DemoCircuits>(
    zkConfigHttpBase,
    fetch.bind(window),
  );

  const config = await connectedAPI.getConfiguration();
  console.log("config", config);
  const publicDataProvider = indexerPublicDataProvider(
    config.indexerUri,
    config.indexerWsUri,
  );

  const proofProvider = httpClientProofProvider(
    config.proverServerUri!,
    zkConfigProvider,
  );

  const shieldedAddress: ShieldedAddress =
    await connectedAPI.getShieldedAddresses();

  const { walletProvider, midnightProvider } =
    createWalletProvidersFromConnectedAPI(connectedAPI, shieldedAddress);

  const accountId = (await connectedAPI.getUnshieldedAddress())
    .unshieldedAddress;

  const privateStateProvider = levelPrivateStateProvider({
    privateStateStoreName: "unshielded-private-state",
    privateStoragePasswordProvider: () => "DEVelopmentdevelopment111%",
    accountId,
  });

  return {
    privateStateProvider,
    publicDataProvider,
    zkConfigProvider,
    proofProvider,
    walletProvider,
    midnightProvider,
  };
}

Enter fullscreen mode Exit fullscreen mode

Change the networkId to whichever network your contract is deployed on.

Create hooks/useDeployedContract.ts. This will find the deployed contract for us and provide the API to call circuits on our smart contract.

import { useQuery } from "@tanstack/react-query";
import {
  contractAddress,
  unshieldedContract,
  type DemoProviders,
} from "../lib/contract";
import { findDeployedContract } from "@midnight-ntwrk/midnight-js/contracts";

export const useDeployedContract = (providers: DemoProviders) => {
  const q = useQuery({
    queryKey: ["deployedContract"],
    queryFn: getDeployedContract,
    enabled: providers != null,
  });

  async function getDeployedContract() {
    const found = await findDeployedContract(providers!, {
      compiledContract: unshieldedContract,
      contractAddress,
    });
    return found;
  }

  return q;
};

Enter fullscreen mode Exit fullscreen mode

Define a custom hook in hooks/useWallet.ts. This will provide a convienient hook to get the providers and wallet API.

import { useState } from "react";
import { findInitialAPIs } from "../lib/wallet";
import { buildProvidersFromConnectedAPI, networkId } from "../lib/providers";
import type { DemoProviders } from "../lib/contract";
import type { ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api";

export const useWallet = () => {
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const [walletAddress, setWalletAddress] = useState<string | null>(null);
  const [providers, setProviders] = useState<DemoProviders | null>(null);
  const [connectedApi, setConnectedApi] = useState<ConnectedAPI | null>(null);

  const handleConnect = async () => {
    let isConnected = false;
    let address = null;

    try {
      const wallet = findInitialAPIs()[0];
      const connectedApi = await wallet.connect(networkId);
      setConnectedApi(connectedApi);
      const addresses = await connectedApi.getShieldedAddresses();
      address = addresses.shieldedAddress;
      const serviceUriConfig = await connectedApi.getConfiguration();
      console.log("Service URI Config:", serviceUriConfig);
      const connectionStatus = await connectedApi.getConnectionStatus();
      if (connectionStatus) {
        isConnected = true;
        console.log("Connected to the wallet:", address);
      }

      const demoCircuitsMidnightProviders =
        await buildProvidersFromConnectedAPI(connectedApi);
      setProviders(demoCircuitsMidnightProviders);
    } catch (error) {
      console.log("An error occurred:", error);
    }

    setIsConnected(isConnected);
    setWalletAddress(address);
  };

  const handleDisconnect = () => {
    setWalletAddress(null);
    setIsConnected(false);
  };

  return {
    handleConnect,
    handleDisconnect,
    isConnected,
    walletAddress,
    providers,
    connectedApi,
  };
};

Enter fullscreen mode Exit fullscreen mode

Let's define an async function called mintToken that takes an amount and recipient and calls the mint function on our smart contract.

async function mintToken({
  amount,
  recipient,
}: {
  amount: number;
  recipient: string;
}) {}

Enter fullscreen mode Exit fullscreen mode

Inside, before we can call the smart contract we have to set the network ID:

const networkId = (await connectedAPI!.getConfiguration()).networkId;

setNetworkId(networkId);

Enter fullscreen mode Exit fullscreen mode

Convert the human readable recipient string into 32 bytes. The helper function used here can be found in the source code.

const userAddress = convertBech32ToUserAddress(recipient!, networkId);

Enter fullscreen mode Exit fullscreen mode

Call the mint circuit on the smart contract passing in the amount and userAddress we just created:

const callTxData = await foundContract!.callTx.mint(BigInt(amount), {
  bytes: userAddress,
});

Enter fullscreen mode Exit fullscreen mode

Here is the complete mintToken function:

async function mintToken({
  amount,
  recipient,
}: {
  amount: number;
  recipient: string;
}) {
  const networkId = (await connectedAPI!.getConfiguration()).networkId;
  setNetworkId(networkId);
  const userAddress = convertBech32ToUserAddress(recipient!, networkId);
  const callTxData = await foundContract!.callTx.mint(BigInt(amount), {
    bytes: userAddress,
  });
}

Enter fullscreen mode Exit fullscreen mode

Wrap the mintToken function we just wrote inside of a custom hook for easy reuse:

import { useMutation } from "@tanstack/react-query";
import { type DemoContract } from "../lib/contract";
import { type FoundContract } from "@midnight-ntwrk/midnight-js/contracts";
import { setNetworkId } from "@midnight-ntwrk/midnight-js/network-id";
import { convertBech32ToUserAddress } from "../lib/address";
import type { ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api";

export const useMintToken = (
  foundContract: FoundContract<DemoContract>,
  connectedAPI: ConnectedAPI,
) => {
  const m = useMutation({
    mutationFn: mintToken,
  });

  async function mintToken({
    amount,
    recipient,
  }: {
    amount: number;
    recipient: string;
  }) {
    const networkId = (await connectedAPI!.getConfiguration()).networkId;
    setNetworkId(networkId);
    const userAddress = convertBech32ToUserAddress(recipient!, networkId);
    const callTxData = await foundContract!.callTx.mint(BigInt(amount), {
      bytes: userAddress,
    });

  }

  return m;
};

Enter fullscreen mode Exit fullscreen mode

Here is depositToken function which will call the receiveToken circuit on the smart contract.

import { useMutation } from "@tanstack/react-query";
import { type DemoContract } from "../lib/contract";
import { type FoundContract } from "@midnight-ntwrk/midnight-js/contracts";
import { setNetworkId } from "@midnight-ntwrk/midnight-js/network-id";
import type { ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api";

export const useDepositToken = (
  foundContract: FoundContract<DemoContract>,
  connectedAPI: ConnectedAPI,
) => {
  const m = useMutation({
    mutationFn: depositToken,
  });

  async function depositToken(amount: number) {
    const networkId = (await connectedAPI!.getConfiguration()).networkId;
    setNetworkId(networkId);
    const callTxData = await foundContract!.callTx.receiveToken(BigInt(amount));
  }

  return m;
};

Enter fullscreen mode Exit fullscreen mode

Here is withdrawToken function which will call the sendToken circuit on the smart contract.

import { useMutation } from "@tanstack/react-query";
import { type DemoContract } from "../lib/contract";
import { type FoundContract } from "@midnight-ntwrk/midnight-js/contracts";
import { setNetworkId } from "@midnight-ntwrk/midnight-js/network-id";
import { convertBech32ToUserAddress } from "../lib/address";
import type { ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api";

export const useWithdrawToken = (
  foundContract: FoundContract<DemoContract>,
  connectedAPI: ConnectedAPI,
) => {
  const m = useMutation({
    mutationFn: withdrawToken,
  });

  async function withdrawToken({
    amount,
    recipient,
  }: {
    amount: number;
    recipient: string;
  }) {
    const networkId = (await connectedAPI!.getConfiguration()).networkId;
    setNetworkId(networkId);
    const userAddress = convertBech32ToUserAddress(recipient, networkId);
    const callTxData = await foundContract!.callTx.sendToken(BigInt(amount), {
      bytes: userAddress,
    });
  }

  return m;
};

Enter fullscreen mode Exit fullscreen mode

We need to get the balances of unshielded tokens that the wallet holds. Luckily the ConnectedAPI type provides this as a function.

import { useQuery } from "@tanstack/react-query";
import { setNetworkId } from "@midnight-ntwrk/midnight-js/network-id";
import type { ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api";

export const useFetchBalance = (connectedAPI: ConnectedAPI) => {
  const q = useQuery({
    queryKey: ["getBalance", connectedAPI],
    queryFn: getBalance,
    enabled: connectedAPI != null,
  });

  async function getBalance() {
    const networkId = (await connectedAPI!.getConfiguration()).networkId;
    setNetworkId(networkId);
    const data = await connectedAPI?.getUnshieldedBalances();
    return data;
  }

  return q;
};

Enter fullscreen mode Exit fullscreen mode

Those are all the functions needed to interact with our deployed smart contract. The rest of the code needed for buttons and input fields is linked in the full source code below.

Source code

References