DEV Community

Kevin Oh
Kevin Oh

Posted on

How to build an unshielded token smart contract and UI on Midnight network

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

Top comments (0)