# Step by step tutorial on zksapp development

# zkApp Development Frameworks

Developers building zkApps in the Mina ecosystem can utilize two different frameworks, each designed to optimize different types of solutions. Explore the options below to find the best fit for your project.

# o1js

o1js is the framework for building zkApps on the Mina L1 and new infrastructure like rollups. It is TypeScript-based for ease of use, comes with built-in features, is highly extensible, and takes full advantage of Mina's unique protocol characteristics.

o1js is also the zkDSL used for:

* Writing general-purpose zk circuits.
    
* Constructing new primitives and data structures.
    

#### Considerations for Building zkApps with o1js on Mina L1:

* zkApps are subject to protocol throughput limitations.
    
* zkApps requiring support for multiple concurrent users must be designed to avoid race conditions:
    
    * If more than eight on-chain field elements are needed to manage state without shared access, the **Offchain Storage API** provides a solution.
        
    * If concurrent access to shared global state is necessary, **Protokit** allows building zkApp-chains (L2) with built-in support. Currently, there is no equivalent easy-to-use solution for shared state in o1js L1 contracts.
        

**o1js** is a **TypeScript library** designed for:

* Writing **general-purpose zero-knowledge (zk) programs**.
    
* Writing **zk smart contracts** for **Mina**.
    

#### Example Code

```plaintext
typescript
```

```plaintext
CopyEdit
```

```plaintext
import { Field, Poseidon } from 'o1js';
```

```plaintext
function knowsPreimage(preimage: Field) {
```

```plaintext
  let hash = Poseidon.hash([preimage]);
```

```plaintext
  hash.assertEquals(expectedHash);
```

```plaintext
}
```

```plaintext
const expectedHash =
```

```plaintext
  0x1d444102d9e8da6d566467defcc446e8c1c3a3616d059facadbfd674afbc37ecn;
```

This example demonstrates **zero-knowledge proof** (ZKP) capabilities, proving knowledge of a secret value without revealing it.

# Key Features of o1js

* **Provable Methods**: Includes operations like `Poseidon.hash()` and `Field.assertEquals()`, enabling zk proofs.
    
* **Zero-Knowledge Proofs**: Verification without revealing input values or execution traces.
    
* **Rich Built-in Operations**: Arithmetic, hashing, signatures, boolean operations, comparisons, and more.
    
* **Client-Side zkApps**: Smart contracts that run privately on users' devices.
    

#### Getting Started

* **Use zkApp CLI** for setup.
    
* Install via npm:
    

```plaintext
sh
```

```plaintext
CopyEdit
```

```plaintext
npm i o1js
```

* Compatible with **major web browsers** and **Node.js**.
    

### **Audits of o1js**

#### **Veridise External Audit (Q3 2024)**

* Security audit conducted by **Veridise**, a leading auditing company.
    
* **Duration**: **39 person-weeks** of in-depth review.
    
* **Outcome**: All **medium severity and higher** issues were identified and resolved.
    

#### **Internal Audit (Q1 2024)**

* Conducted by the **o1js team** in **March 2024**.
    
* **Duration**: **Two person-weeks** focused on core provable code.
    
* **Outcome**: Several issues were found and fixed.
    

# **o1js Basic Concepts**

o1js is a **TypeScript (TS) library** designed for:

* Writing **general-purpose zero knowledge (zk) programs**.
    
* Writing **zk smart contracts** for **Mina**.
    

### **Field**

Field elements are the fundamental data unit in **zero knowledge proof programming**. Each **field element** can store a number **up to almost 256 bits** in size, similar to **uint256 in Solidity**.

# Protokit

Protokit is a powerful framework for building **ZK appchains** and **smart contracts** that are user-facing, privacy-preserving, and interoperable. It provides a developer experience similar to Solidity dApps, making it easier for developers to integrate zero-knowledge proofs into blockchain solutions.

#### Features and Use Cases:

Protokit offers a full set of tools for:

* zkApps requiring **high throughput** or **multiple concurrent users**.
    
* zkApps needing **shared or global state access**.
    
* Developers familiar with execution environments like **EVM**.
    
* Those leveraging Protokit's **modular architecture** for enhanced flexibility.
    
    #### **First: A Note on Permissions**
    
    Permissions related to ZkApp upgrades are detailed in the **Permissions** article, which covers the security assumptions in more depth. This article focuses on how to perform the upgrade itself.
    
    #### **Second: A Note on Mina's Execution Model**
    
    On other blockchains, upgrading a smart contract may result in users unknowingly running a different program with the same function signature, leading to unsafe or unpredictable outcomes. Mina’s execution model is different.
    
    On Mina, users run their own program and upload the proof to the blockchain only for verification. Upgrading a ZkApp means **changing the verification key on-chain**. Proofs generated with an older prover function will become invalid, requiring users to download the new prover function to generate valid proofs.
    
    ### **Baseline ZkApp**
    
    Here’s an example of a basic **Add** smart contract in Mina:
    
    ```plaintext
    typescript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    import { Field, SmartContract, state, State, method } from 'o1js';
    ```
    
    ```plaintext
    export class Add extends SmartContract {
    ```
    
    ```plaintext
      @state(Field) num = State<Field>();
    ```
    
    ```plaintext
      init() {
    ```
    
    ```plaintext
        super.init();
    ```
    
    ```plaintext
        this.num.set(Field(1));
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
      @method async update() {
    ```
    
    ```plaintext
        const currentState = this.num.getAndRequireEquals();
    ```
    
    ```plaintext
        const newState = currentState.add(2);
    ```
    
    ```plaintext
        this.num.set(newState);
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    }
    ```
    
    This contract has the **verification key**:  
    `27729068461170601362912907281403262888852363473424470267835507636847418791713`
    
    ---
    
    # **Upgraded ZkApp**
    
    Here’s the upgraded version of the contract, which adds **4** instead of **2**:
    
    ```plaintext
    typescript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    import { Field, SmartContract, state, State, method } from 'o1js';
    ```
    
    ```plaintext
    export class AddV2 extends SmartContract {
    ```
    
    ```plaintext
      @state(Field) num = State<Field>();
    ```
    
    ```plaintext
      init() {
    ```
    
    ```plaintext
        super.init();
    ```
    
    ```plaintext
        this.num.set(Field(1));
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
      @method async update() {
    ```
    
    ```plaintext
        const currentState = this.num.getAndRequireEquals();
    ```
    
    ```plaintext
        const newState = currentState.add(4);
    ```
    
    ```plaintext
        this.num.set(newState);
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    }
    ```
    
    This upgraded contract has a new **verification key**:  
    `18150279532259194644722165513074833862035641840431153413486908511595437348455`
    
    ### **Upgrading a ZkApp**
    
    Upgrading a ZkApp by **signature** can be done if you control the private key of the ZkApp. This involves signing a transaction that upgrades the ZkApp with the corresponding private key.
    
    Let’s assume we have already deployed the **Add** contract and we possess the private key as **zkAppKey**. To upgrade the contract, you would sign the transaction with **zkAppKey** to authorize the change, such as updating the verification key or any other contract parameters.
    
    ### **Upgrading a ZkApp (Code Example)**
    
    To upgrade a ZkApp, you can follow these steps using the following code:
    
    ```plaintext
    typescript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    const verificationKey = (await AddV2.compile()).verificationKey;
    ```
    
    ```plaintext
    const contractAddress = zkAppKey.toPublicKey();
    ```
    
    ```plaintext
    const upgradeTx = await Mina.transaction({ sender, fee },
    ```
    
    ```plaintext
      async () => {
    ```
    
    ```plaintext
        const update = AccountUpdate.createSigned(contractAddress);
    ```
    
    ```plaintext
        update.account.verificationKey.set(verificationKey);
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    );
    ```
    
    ```plaintext
    await upgradeTx.sign([senderKey, zkAppKey]).prove();
    ```
    
    ```plaintext
    await upgradeTx.send();
    ```
    
    In this example:
    
    * The **verification key** for the upgraded contract (`AddV2`) is compiled.
        
    * The contract address is derived from the public key of the **zkAppKey**.
        
    * A transaction is created, which signs the update for the contract's verification key.
        
    * After signing with both the **senderKey** and **zkAppKey**, the transaction is proved and sent to the blockchain.
        
    
    Once the transaction is applied, the verification key for the ZkApp address will be updated from:  
    `27729068461170601362912907281403262888852363473424470267835507636847418791713`  
    to:  
    `18150279532259194644722165513074833862035641840431153413486908511595437348455`
    
    ### **Angular Integration Guide**
    
    #### **1\. Install a Wallet**
    
    To interact with zkApp transactions, you'll need a wallet that supports them. In this tutorial, we’ll use **Auro Wallet**.
    
    1. **Download Auro Wallet**: [Download Auro Wallet](https://www.aurowallet.com)
        
    2. **Add the Auro Wallet Browser Extension**: Install it in your browser.
        
    3. **Create a New Wallet**: Open the extension and follow the prompts to create a new wallet.
        
    4. **Switch to Devnet**:
        
        * Click "Mainnet" at the top of the extension view.
            
        * Select "Show Testnet" from the menu, then choose **Devnet**.
            
        * **Devnet** allows you to interact with a test version of the Mina network, so you won’t need real Mina for transaction fees.
            
    
    #### **2\. Fund Your Wallet**
    
    * Use the **Mina Faucet** to fund your wallet with test Mina.
        
    * Wait for one block (~3 minutes) for the balance to reflect on-chain.
        
    * Track your transaction status using **Minascan**.
        
    
    ### **Initialize the Project**
    
    \[if !supportLists\]1.      \[endif\]**Install the Angular CLI globally**:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    npm install -g @angular/cli
    ```
    
    \[if !supportLists\]2.      \[endif\]**Create a new Angular project**:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    ng new <project-name>
    ```
    
    2. * Select your preferred stylesheet format (CSS, SCSS, etc.).
            
        * For **Server-Side Rendering (SSR)** and **Static Site Generation (SSG/Prerendering)**, choose **Yes** if you plan to use these features.
            
    
    \[if !supportLists\]3.      \[endif\]**Install the** `o1js` **library**:
    
    3. * Navigate to your project directory:
            
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    cd <project-name>
    ```
    
    3. * Install the `o1js` library:
            
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    npm install o1js
    ```
    
    \[if !supportLists\]4.      \[endif\]**Start the local development server**:
    
    4. * Run the following command to start the server:
            
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    npm run start
    ```
    
    4. * This runs `ng serve`, and you can further configure it by modifying options in the `angular.json` file under the **serve** build target.
            
    
    # **Create the ZkApp Contract**
    
    \[if !supportLists\]1.      \[endif\]**Navigate out of the demo project directory** and install the **zkapp-cli** globally:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    cd ../
    ```
    
    ```plaintext
    npm install -g zkapp-cli
    ```
    
    \[if !supportLists\]2.      \[endif\]**Initialize a new zkApp project** with the CLI:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    zk project add
    ```
    
    2. * When prompted to create a UI project, select **none**.
            
    
    \[if !supportLists\]3.      \[endif\]**Change into the newly created add directory** and build the contract:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    cd add
    ```
    
    ```plaintext
    npm run build
    ```
    
    \[if !supportLists\]4.      \[endif\]**Deploying the Add contract**:
    
    4. * An instance of the default **Add** contract has already been deployed to **Devnet** at:  
            `B62qnTDEeYtBHBePA4yhCt4TCgDtA4L2CGvK7PirbJyX4pKH8bmtWe5`
            
        * You won’t need to deploy this contract again, but you will still need to include the contract code in your project to compile it into a **verification key** and **proving key**.
            
    
    \[if !supportLists\]5.      \[endif\]**Proving Key and Verification Key**:
    
    5. * The **proving key** enables users to generate proofs of valid contract execution locally in their browsers.
            
        * A user can execute the contract, create a proof using the proving key, and publish the proof on-chain to update the zkApp's state.
            
        * The **verification key** is stored on-chain, and the network will accept a transaction sent to the contract's address if it includes a proof generated by the proving key that matches the verification key on-chain.
            
    
    Your provided code is a solid setup for interacting with a deployed **Add** contract on Mina's Devnet using **Angular** and **o1js**. Here's a brief breakdown of the key parts of the code and how they work:
    
    ### Breakdown of the Code:
    
    \[if !supportLists\]1.      \[endif\]**Imports**:
    
    1. * You import `afterNextRender` from Angular's core and also import the necessary components to handle Mina operations (`Mina`, `PublicKey`, `fetchAccount`).
            
    
    \[if !supportLists\]2.      \[endif\]**Mina Network Setup**:
    
    2. * The `Mina.setActiveInstance()` function connects the Mina instance to the **Devnet** using the specified API URL (`https://api.minascan.io/node/devnet/v1/graphql`).
            
    
    \[if !supportLists\]3.      \[endif\]**ZkApp Address**:
    
    3. * The `zkAppAddress` points to the already deployed **Add contract** on Mina's **Devnet**. This contract is accessible at the provided address (`B62qnTDEeYtBHBePA4yhCt4TCgDtA4L2CGvK7PirbJyX4pKH8bmtWe5`).
            
    
    \[if !supportLists\]4.      \[endif\]**Contract Interaction**:
    
    4. * The code fetches the account for the contract using the `fetchAccount()` method.
            
        * It then creates a new instance of the `Add` contract using the public key of the **zkApp**.
            
    
    \[if !supportLists\]5.      \[endif\]**State Reading**:
    
    5. * The `console.log()` reads and logs the current state of the contract, specifically the `num` field from the `Add` contract.
            
    
    \[if !supportLists\]6.      \[endif\]**Wallet Interaction**:
    
    6. * It retrieves the injected Mina provider (`window.mina`), assuming the user has Auro Wallet installed.
            
        * It then retrieves the public key of the wallet via `mina.requestAccounts()` and logs it.
            
        * The `Add.compile()` function compiles the contract to generate the necessary verification keys and proving keys.
            
    
    \[if !supportLists\]7.      \[endif\]**Transaction Creation**:
    
    7. * A Mina transaction is created, and the `update()` method from the `Add` contract is called.
            
        * The transaction is then proved and sent via the Mina provider to the network. Afterward, a link to the transaction is logged on the console.
            
    
    \[if !supportLists\]8.      \[endif\]**Error Handling**:
    
    8. * Multiple error cases are handled, including:
            
            * Missing Auro Wallet installation
                
            * Missing wallet creation
                
            * User rejecting wallet permissions
                
            * General unknown errors
                
    
    ### Key Functional Flow:
    
    1. **Setup**: Initializes the contract address and connects to the Devnet Mina network.
        
    2. **State Reading**: Fetches the state of the deployed **Add contract**.
        
    3. **Wallet Interaction**: Fetches the wallet’s public key from the Mina provider (Auro Wallet), compiles the contract, and sends the transaction.
        
    4. **Transaction Creation**: The transaction is sent and a link to the Mina scan page for the transaction is displayed.
        
    
    ### Improvements & Suggestions:
    
    * **Error Handling**: The error handling is well-structured. You might want to add more specific handling for other types of errors that could occur during the transaction (e.g., network issues).
        
    * **Async Execution**: Consider adding loading indicators or UI changes while the asynchronous operations (contract interaction, wallet connection, etc.) are happening to improve user experience.
        
    
    ### Things to Test:
    
    * Make sure Auro Wallet is installed and active in the browser.
        
    * Ensure the wallet is properly configured and connected to **Devnet**.
        
    * Check that the contract interaction successfully updates the state on the **Add contract** and sends the transaction to the Mina network.
        
    
    This is a great setup for an Angular-based Mina app with zkApps! Let me know if you need more assistance with this integration.
    
    ### Overview of What the Code Does:
    
    \[if !supportLists\]1.      \[endif\]**Connects to the Devnet**:
    
    1. * The code connects the Mina instance to the **Devnet node** using the Mina API URL. This ensures that any transactions made are broadcasted to the **Devnet** network rather than the main network, allowing you to interact with the test environment.
            
    
    \[if !supportLists\]2.      \[endif\]**Requests User Address from the Wallet**:
    
    2. * The code fetches the user's address by requesting it from the wallet's injected **mina provider** (`window.mina`). This provider is automatically injected into the browser context by the wallet (like Auro Wallet), making it accessible to the app.
            
    
    \[if !supportLists\]3.      \[endif\]**Compiles the zkApp**:
    
    3. * The `Add` zkApp contract is compiled using `Add.compile()`. This step generates and caches the **proving key**, which is necessary for generating proofs. These proofs will allow users to submit a valid transaction to the Mina network.
            
    
    \[if !supportLists\]4.      \[endif\]**Creates the zkApp Transaction**:
    
    4. * The code creates a **transaction** that calls the `update()` method of the `Add` contract. The transaction will update the state of the contract (in this case, incrementing the number).
            
    
    \[if !supportLists\]5.      \[endif\]**Proves the Transaction**:
    
    5. * The transaction is **proved** using the cached proving key that o1js holds internally. The proof ensures that the transaction is valid according to the contract's logic.
            
    
    \[if !supportLists\]6.      \[endif\]**Prompts User to Broadcast**:
    
    6. * After proving the transaction, the wallet prompts the user to approve and broadcast the transaction to the network. This step requires user interaction with the wallet (Auro Wallet in this case) to confirm and send the transaction.
            
    
    ### How to Run the Application:
    
    \[if !supportLists\]1.      \[endif\]**Start the Local Development Server**:
    
    1. * Run the following command in the terminal to start the local development server:
            
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    npm run start
    ```
    
    This command will execute `ng serve`, which compiles and serves the Angular application.
    
    \[if !supportLists\]2.      \[endif\]**Open the Browser Console**:
    
    2. * After the server starts, open your browser and navigate to the application (usually accessible at `http://localhost:4200`).
            
        * Open the **browser console** (right-click -&gt; Inspect -&gt; Console) to see the log outputs.
            
    
    \[if !supportLists\]3.      \[endif\]**Approve Connection in Auro Wallet**:
    
    3. * Once the app requests the wallet connection, Auro Wallet will display a prompt in the browser asking the user for permission to connect.
            
        * **Approve the connection request** in Auro Wallet. This grants the app access to your Mina address and allows the app to interact with the Mina network.
            
    
    ### After Approving:
    
    * Once the connection is approved, the app will proceed with compiling the zkApp, creating a transaction, proving it, and then prompting you to broadcast it to the network.
        
    * You will see a transaction hash in the console with a link to view the transaction on **MinaScan** for Devnet.
        
    
    To resolve the **DataCloneError** and enable the use of `SharedArrayBuffer` in your Angular application while running `ng serve`, you'll need to set the necessary HTTP headers for **Cross-Origin-Opener-Policy (COOP)** and **Cross-Origin-Embedder-Policy (COEP)**.
    
    ### Steps to Configure SharedArrayBuffer Headers in Angular:
    
    \[if !supportLists\]1.      \[endif\]**Open your** `angular.json` **file**:
    
    1. * Navigate to your project’s root directory and open the `angular.json` file.
            
    
    \[if !supportLists\]2.      \[endif\]**Locate the** `serve` **configuration**:
    
    2. * In the `angular.json` file, look for the `serve` configuration under the project settings. It will look like this:
            
    
    ```plaintext
    json
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    "projects": {
    ```
    
    ```plaintext
      "<your-project-name>": {
    ```
    
    ```plaintext
        "architect": {
    ```
    
    ```plaintext
          "serve": {
    ```
    
    ```plaintext
            "builder": "@angular-devkit/build-angular:dev-server",
    ```
    
    ```plaintext
            "options": {
    ```
    
    ```plaintext
              "proxyConfig": "proxy.conf.json"
    ```
    
    ```plaintext
            },
    ```
    
    ```plaintext
            "configurations": {
    ```
    
    ```plaintext
              "development": {
    ```
    
    ```plaintext
                // custom configurations here
    ```
    
    ```plaintext
              }
    ```
    
    ```plaintext
            }
    ```
    
    ```plaintext
          }
    ```
    
    ```plaintext
        }
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    }
    ```
    
    \[if !supportLists\]3.      \[endif\]**Add the headers configuration**:
    
    3. * Under the `options` section, add custom headers that enable **SharedArrayBuffer**. These headers are required for the WASM workers used in `o1js` for zkApp proof compilation.
            
    
    You need to configure `Cross-Origin-Opener-Policy` (COOP) and `Cross-Origin-Embedder-Policy` (COEP) to the following:
    
    ```plaintext
    json
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    "options": {
    ```
    
    ```plaintext
      "headers": {
    ```
    
    ```plaintext
        "Cross-Origin-Opener-Policy": "same-origin",
    ```
    
    ```plaintext
        "Cross-Origin-Embedder-Policy": "require-corp"
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    }
    ```
    
    This should look like:
    
    ```plaintext
    json
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    "projects": {
    ```
    
    ```plaintext
      "angular-o1js-demo": {
    ```
    
    ```plaintext
        "architect": {
    ```
    
    ```plaintext
          "serve": {
    ```
    
    ```plaintext
            "builder": "@angular-devkit/build-angular:dev-server",
    ```
    
    ```plaintext
            "options": {
    ```
    
    ```plaintext
              "headers": {
    ```
    
    ```plaintext
                "Cross-Origin-Opener-Policy": "same-origin",
    ```
    
    ```plaintext
                "Cross-Origin-Embedder-Policy": "require-corp"
    ```
    
    ```plaintext
              }
    ```
    
    ```plaintext
            },
    ```
    
    ```plaintext
            "configurations": {
    ```
    
    ```plaintext
              "development": {
    ```
    
    ```plaintext
                // custom configurations here
    ```
    
    ```plaintext
              }
    ```
    
    ```plaintext
            }
    ```
    
    ```plaintext
          }
    ```
    
    ```plaintext
        }
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    }
    ```
    
    \[if !supportLists\]4.      \[endif\]**Restart the development server**:
    
    4. * After saving the changes to the `angular.json` file, stop the running `ng serve` process and start it again using:
            
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    npm run start
    ```
    
    ### Explanation of the Headers:
    
    \[if !supportLists\]·         \[endif\]**Cross-Origin-Opener-Policy (COOP)**: This header ensures that only same-origin resources can interact with your application’s JavaScript context. This prevents malicious cross-origin resources from accessing shared memory in the browser.
    
    \[if !supportLists\]·         \[endif\]**Cross-Origin-Embedder-Policy (COEP)**: This header ensures that resources embedded in your page (like scripts or iframes) must either come from the same origin or include the appropriate permissions (`Cross-Origin-Resource-Policy: cross-origin`). This is required to allow the `SharedArrayBuffer` object to work correctly.
    
    ### Result:
    
    * With these headers configured, the error related to `SharedArrayBuffer` should no longer occur, and you should be able to compile and execute zkApp contracts using WASM workers for proof generation.
        
    * Restart the server with npm run start and view the application in the browser again - the SharedArrayBuffer error should be gone!
        
    
    ## **Loading o1js**[**​**](https://docs.minaprotocol.com/zkapps/front-end-integration-guides/angular#loading-o1js)
    
    * We still have another error: `Uncaught ReferenceError: __async is not defined`.
        
    * This one comes from the way Angular bundles dependencies internally. We'll address it by supplying our own custom webpack config which will exclude o1js from the bundle generated by Angular. Then we'll copy o1js into our static assets directory so it's served with the app and use import maps to import o1js directly.
        
    
    # zkApp Developer Tutorials
    
    The **zkApp Developer Tutorials** provide hands-on guides to walk you through use cases that help you achieve specific goals with zkApps. These tutorials are aimed at helping developers build decentralized applications on the Mina blockchain using zkApps.
    
    **o1js** (formerly known as SnarkyJS) is a TypeScript library designed for writing general-purpose zk (zero-knowledge) programs and zk smart contracts for the Mina Protocol. It simplifies the process of creating and deploying zkApps on the Mina blockchain.
    
    To connect with other developers who are building zkApps using o1js, you can join the **#zkapps-developers** channel on the **Mina Protocol Discord**. This is a great way to share knowledge, ask questions, and collaborate with other developers in the community.
    
    **Prerequisites** for the zkApp developer tutorials:
    
    * **zkApp CLI**: This command-line tool is essential for creating, managing, and deploying zkApps. It's important to have the latest version installed to ensure compatibility with the tutorials.
        
    * **o1js**: This TypeScript library is used to write zk smart contracts for the Mina blockchain. o1js is automatically included when you create a project using the zkApp CLI, so you don’t need to manually install it for basic usage.
        
    * **Other dependencies**: Depending on the specific tutorial you're following, there may be additional dependencies that are required. These will be noted in the individual tutorial instructions.
        
    
    To install the zkApp CLI, run the following command:
    
    ```plaintext
    ·         bash
    ```
    
    ```plaintext
    ·         CopyEdit
    ```
    
    ```plaintext
    ·         $ npm install -g zkapp-cli
    ```
    
    \[if !supportLists\]·         \[endif\]To confirm the installation was successful, check the version with:
    
    ```plaintext
    ·         bash
    ```
    
    ```plaintext
    ·         CopyEdit
    ```
    
    ```plaintext
    ·         $ zk –version
    ```
    
    To use the zkApp CLI and o1js, ensure your environment meets the following dependencies:
    
    * **NodeJS v18 and later**
        
    * **NPM v10 and later**
        
    * **Git v2 and later**
        
    
    To install or upgrade these dependencies, use a package manager appropriate for your operating system:
    
    * **MacOS**: Homebrew
        
    * **Windows**: Chocolatey
        
    * **Linux**: apt, yum, and others (you may need to use NodeSource for the latest Node.js version)
        
    
    You can verify your installed versions using the following commands:
    
    bash
    
    CopyEdit
    
    npm -v
    
    node -v
    
    git -v
    
    **Tips for following zkApp developer tutorials:**
    
    * **Source Code**: You can find the full source code for the tutorials in the examples/zkapps/ directory on GitHub. This can be helpful if you need to refer to the code directly or download it for your project.
        
    * **Support the Community**: While you're on GitHub, don’t forget to give the /docs2 repository a star. This will help other zk developers discover resources to build their own zkApps.
        
    * **Avoid Copying Errors**: To avoid copying line numbers or command prompts when copying code, use the "copy code to clipboard" button. This button appears at the top right of the snippet box when you hover over it. It ensures that you're only copying the actual code, without any extra annotations.
        
    
    **Useful Resources for zkApp Development:**
    
    1. **API Reference Docs**: Once you're comfortable with the basics, the o1js Reference docs provide detailed information about all the available methods, properties, and interfaces. It's a comprehensive guide to the o1js library.
        
    2. **o1Labs Blog**: For updates and further reading about o1js and zkApps, visit the [o1Labs Blog](https://www.o1labs.org/blog/). You can also explore specific topics, including o1js updates, via the [o1js-specific blog feed](https://www.o1labs.org/blog?topics=o1js).
        
    3. **Step-by-Step zkApp Explainer Videos**: If you're new to zkApp development, the Mina Foundation YouTube channel offers helpful [explainer videos](https://www.youtube.com/c/MinaProtocol). Each video is linked to corresponding tutorials, providing a guided path to learning. Don't forget to **Subscribe** to get notified about new videos!
        
    
    # **Tutorial 1: Hello World - Introduction to zkApps with o1js**
    
    This tutorial is designed to introduce you to o1js, zkApps, and the basics of programming with zero-knowledge proofs (zkPs). By the end of this hands-on tutorial, you will have learned to build and interact with a simple zkApp smart contract.
    
    ### What You Will Learn:
    
    \[if !supportLists\]1.      \[endif\]**Write a Basic Smart Contract**:
    
    1. * Create a smart contract that stores a number as an on-chain state.
            
        * Implement logic that allows you to replace the number with its square. For example:
            
            * 3 → 9 → 81 → 6561, and so on.
                
    
    \[if !supportLists\]2.      \[endif\]**Create a Project with zkApp CLI**:
    
    2. * Use the zkApp CLI to set up your project structure.
            
    
    \[if !supportLists\]3.      \[endif\]**Write the Smart Contract Code**:
    
    3. * Implement the contract logic in TypeScript using o1js.
            
    
    \[if !supportLists\]4.      \[endif\]**Interact with the Contract Locally**:
    
    4. * Use a simulated local Mina blockchain to deploy and interact with your smart contract.
            
    
    This tutorial covers everything from setting up your development environment to running a zkApp contract. It’s a great starting point for anyone new to zkApps and zero-knowledge programming!
    
    Later tutorials introduce more concepts and patterns.
    
    The full source code for this tutorial is provided in the [examples/zkapps/01-hello-world](https://github.com/o1-labs/docs2/tree/main/examples/zkapps/01-hello-world) directory on GitHub. While you're there, give the `/docs2` repository a star so that other zk developers can learn to build a zkApp!
    
    ### Prerequisites
    
    Before starting with the Hello World tutorial, make sure your development environment is ready. This includes having the necessary tools installed, especially the zkApp CLI.
    
    #### Steps to Prepare:
    
    \[if !supportLists\]1.      \[endif\]**Install the zkApp CLI**: Make sure the `zkapp-cli` is installed globally on your system by running the following command:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    $ npm install -g zkapp-cli
    ```
    
    \[if !supportLists\]2.      \[endif\]**Create or Change to a Directory**: Create a new directory or navigate to an existing directory where you have write access.
    
    \[if !supportLists\]3.      \[endif\]**Create a New Project**: Once you’re in the desired directory, you can create a new project using the `zk project` command:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    $ zk project 01-hello-world
    ```
    
    \[if !supportLists\]4.      \[endif\]**Scaffold the Project**: The `zk project` command allows you to scaffold both the project structure and a UI for your project. For this tutorial, when prompted to create a UI, select **none**.
    
    With the tools installed and the project created, you're ready to begin building your zkApp!
    
    ### Project Setup Completion
    
    After running the `zk project` command and selecting **none** for the UI, the project setup process completes with the following steps:
    
    * **Accompanying UI**: No UI is created as you selected **none**.
        
    * **Git Initialization**: The project initializes a Git repository with the first commit.
        
    * **Dependency Setup**: The project installs dependencies (e.g., Prettier, ESLint, Jest).
        
    * **Contract Build**: The contract is compiled as part of the setup process.
        
    * **Project Naming**: The project name is set.
        
    
    #### Next Steps:
    
    \[if !supportLists\]1.      \[endif\]**Navigate to the Project Directory**: Change into the `01-hello-world` project directory:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    cd 01-hello-world
    ```
    
    \[if !supportLists\]2.      \[endif\]**Add Remote Git Repository**: Add your remote repository URL to the project:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    git remote add origin <your-repo-url>
    ```
    
    \[if !supportLists\]3.      \[endif\]**Push to Remote Repository**: Push the changes to your Git remote repository:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    git push -u origin main
    ```
    
    The project is now ready with the initial setup. You can begin writing your zkApp smart contract code.
    
    To navigate into the `01-hello-world` directory and list its contents, run the following commands:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    $ cd 01-hello-world
    ```
    
    ```plaintext
    $ ls
    ```
    
    This will change your current directory to `01-hello-world` and display the files and directories contained within it.
    
    ### File Setup for the "Hello World" Tutorial
    
    After setting up the project, you need to prepare the project files by removing the default files and creating the necessary ones for this tutorial. Here are the steps:
    
    #### 1\. **Remove Default Files**:
    
    The default project includes some sample files that you no longer need for this tutorial. Run these commands to delete them:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    rm src/Add.ts
    ```
    
    ```plaintext
    rm src/Add.test.ts
    ```
    
    ```plaintext
    rm src/interact.ts
    ```
    
    #### 2\. **Create New Files**:
    
    Use the following commands to create new files for your project:
    
    \[if !supportLists\]·         \[endif\]**Create the contract file** (Square.ts):
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    zk file src/Square
    ```
    
    \[if !supportLists\]·         \[endif\]**Create the main script file** (main.ts) for interacting with the smart contract:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    touch src/main.ts
    ```
    
    The `zk file` command creates both the contract file `src/Square.ts` and a corresponding test file `src/Square.test.ts`. However, since the tutorial does not include writing tests, you will not need to focus on the test file for now.
    
    #### 3\. **Next Steps**:
    
    Now you're ready to proceed with coding your zkApp contract. The next steps will involve writing the logic for the smart contract in `src/Square.ts` and using the `src/main.ts` file to interact with it.
    
    ### Project Preparation and File Setup
    
    After cleaning up the default files, here’s how to proceed with the necessary setup for your project.
    
    #### 1\. **Delete Old Files**:
    
    The default files provided by the zkApp CLI are not needed for this tutorial, so you’ll remove them:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    rm src/Add.ts
    ```
    
    ```plaintext
    rm src/Add.test.ts
    ```
    
    ```plaintext
    rm src/interact.ts
    ```
    
    #### 2\. **Create New Files**:
    
    Use the following commands to create the necessary files for this tutorial:
    
    \[if !supportLists\]·         \[endif\]**Create the Square contract file**:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    zk file src/Square
    ```
    
    This will create the `src/Square.ts` contract file and a corresponding test file (`src/Square.test.ts`).
    
    \[if !supportLists\]·         \[endif\]**Create the main script file** (main.ts) for interacting with the smart contract:
    
    ```plaintext
    bash
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    touch src/main.ts
    ```
    
    #### 3\. **Modify the** `src/index.ts` **File**:
    
    Open the `src/index.ts` file in a text editor and change it to:
    
    ```plaintext
    typescript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    import { Square } from './Square.js';
    ```
    
    ```plaintext
    export { Square };
    ```
    
    This change makes the `Square` contract available for consumption from outside the smart contract project, such as from a UI or other modules.
    
    Now your project is prepared, and you can begin writing the smart contract code and interacting with it through the `src/main.ts` file. In the next tutorial steps, you'll start defining the logic of the `Square` contract.
    
    ### Writing the `Square` zkApp Smart Contract
    
    In this part of the tutorial, you’ll write the smart contract code in the `src/Square.ts` file. This contract will store a number as its on-chain state and allow this number to be replaced by its square, for example: 3 → 9 → 81 → 6561, and so on.
    
    Here’s an example of what the code in `src/Square.ts` might look like:
    
    ```plaintext
    typescript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    import { Field, SmartContract, state, State, method } from 'o1js';
    ```
    
    ```plaintext
    export class Square extends SmartContract {
    ```
    
    ```plaintext
      // Define a state variable to hold the current number
    ```
    
    ```plaintext
      @state(Field) num = State<Field>();
    ```
    
    ```plaintext
      // The initialization function sets the initial value of the number to 1
    ```
    
    ```plaintext
      init() {
    ```
    
    ```plaintext
        super.init();
    ```
    
    ```plaintext
        this.num.set(Field(1)); // Start with the number 1
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
      // Method to square the current number and store the new value
    ```
    
    ```plaintext
      @method async update() {
    ```
    
    ```plaintext
        const currentState = this.num.getAndRequireEquals(); // Get the current number
    ```
    
    ```plaintext
        const newState = currentState.square(); // Square the current number
    ```
    
    ```plaintext
        this.num.set(newState); // Set the new squared value as the new state
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    }
    ```
    
    ### Explanation of the Code:
    
    \[if !supportLists\]1.      \[endif\]**Imports**:
    
    1. * The `Field` module represents the type for numbers on the Mina blockchain.
            
        * The `SmartContract`, `state`, `State`, and `method` modules are imported to help define the contract's logic and state.
            
    
    \[if !supportLists\]2.      \[endif\]**Contract Definition**:
    
    2. * The `Square` class extends `SmartContract` which enables us to define the contract's state and methods.
            
    
    \[if !supportLists\]3.      \[endif\]**State**:
    
    3. * The contract has a state variable called `num`, which holds a `Field` type (a number). This is where the on-chain state is stored.
            
    
    \[if !supportLists\]4.      \[endif\]**Init Method**:
    
    4. * The `init()` method sets up the initial state of the contract. In this case, we start by setting `num` to `1`.
            
    
    \[if !supportLists\]5.      \[endif\]**Update Method**:
    
    5. * The `update()` method squares the current value of `num` and sets it as the new value of `num`.
            
        * `getAndRequireEquals()` is used to get the current state and ensure it matches the expected value.
            
        * `square()` is a method provided by the Mina protocol to square the `Field` type.
            
    
    ### Testing and Interacting with the Contract
    
    Once you've written this code, you can compile and deploy the smart contract, and interact with it using the `src/main.ts` file. Each time you call `update()`, it will square the value of `num`.
    
    ### **Copy the example**[**​**](https://docs.minaprotocol.com/zkapps/tutorials/hello-world#copy-the-example)
    
    This tutorial describes each part of the completed code in the [Square.ts](https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/Square.ts) example file.
    
    \[if !supportLists\]1.      \[endif\]First, open the [Square.ts](https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/Square.ts) example file.
    
    \[if !supportLists\]2.      \[endif\]Copy the entire contents of the file into your smart contract in the `src/Square.ts` file.
    
    Now you are ready to review the imports in the smart contract.
    
    ### **Imports**[**​**](https://docs.minaprotocol.com/zkapps/tutorials/hello-world#imports)
    
    The `import` statement brings in other packages and dependencies to use in your smart contract.
    
    All functions used inside a smart contract must operate on o1js compatible data types: `Field` types and other types built on top of `Field` types.
    
    Here are the items mentioned, explained in the context of o1js and zkApp smart contracts:
    
    * **Field**: The native number type in o1js. You can think of field elements as unsigned integers. Field elements are the most basic type in o1js, and all other o1js-compatible types are built on top of field elements.
        
    * **SmartContract**: The class used to create zkApp smart contracts. It forms the basis for building the logic and structure of your zkApp.
        
    * **state**: A decorator used in zkApp smart contracts to create references to state stored on-chain in a zkApp account. It makes interacting with and modifying on-chain state easier.
        
    * **State**: A class used in zkApp smart contracts to represent state that is stored on-chain in a zkApp account. It defines the data structure that will be stored and manipulated within the smart contract.
        
    * **method**: A decorator used in zkApp smart contracts to create smart contract methods (functions). These methods are the end-user's entry points to interact with the smart contract.
        
    
    The `Square` smart contract in the `src/Square.ts` file has the following structure:
    
    ```plaintext
    typescript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    export class Square extends SmartContract {
    ```
    
    ```plaintext
      @state(Field) num = State<Field>();
    ```
    
    ```plaintext
    }
    ```
    
    ### Breakdown:
    
    * **Square Class**: This class extends `SmartContract`, meaning it is a zkApp smart contract that can run on the Mina blockchain.
        
    * **num (state)**: The contract has one piece of on-chain state named `num`, which is of type `Field`.
        
        * `@state(Field)`: The `@state` decorator is used to define `num` as a state variable that is stored on-chain.
            
        * `State<Field>()`: This initializes the state variable `num` with the type `Field`, which is the basic number type in o1js.
            
    
    This contract is simple, storing a field element (`num`) on-chain that can be interacted with within the contract's methods.
    
    The updated `Square` smart contract in the `src/Square.ts` file includes an `init` method, which is used to initialize the on-chain state when the contract is deployed:
    
    ```plaintext
    typescript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    export class Square extends SmartContract {
    ```
    
    ```plaintext
      @state(Field) num = State<Field>();
    ```
    
    ```plaintext
      init() {
    ```
    
    ```plaintext
        super.init();
    ```
    
    ```plaintext
        this.num.set(Field(3));
    ```
    
    ```plaintext
      }
    ```
    
    ```plaintext
    }
    ```
    
    ### Breakdown:
    
    * **init Method**:
        
        * `super.init()`: Since the `Square` class extends the `SmartContract` class, it calls the `init` method from the base class using `super.init()`. This ensures that any initialization logic from the base class is executed.
            
        * `this.num.set(Field(3))`: This line sets the initial value of the `num` state to `3` when the smart contract is deployed. The value is stored as a `Field` type, which is a basic number type in o1js.
            
    
    ### Key Points:
    
    * **Initialization**: The `init` method is a special method that runs when the zkApp smart contract is deployed. It is where you can set up the initial state of the contract.
        
    * **State Management**: The `this.num.set(Field(3))` line ensures that the state variable `num` starts with the value `3`.
        
    * **Permissions**: You can specify permissions for state variables, though this is optional. More details on setting permissions can be found in the o1js Reference documentation.
        
    * ### Import Items in `main.ts`:
        
        * `Field`: The fundamental o1js data type, representing unsigned integers.
            
        * `Mina`: A local, simulated Mina blockchain instance used for testing and deploying smart contracts.
            
        * `PrivateKey`: A class that provides functions to create and manipulate private keys.
            
        * `AccountUpdate`: A class responsible for generating data structures used to update zkApp accounts on the Mina blockchain.
            
        
        These imports allow developers to interact with the Mina blockchain, deploy smart contracts, and simulate real blockchain operations locally.
        
        ### Simulated Local Blockchain
        
        A **simulated local blockchain** provides a fast and efficient way to develop and test zkApps without interacting with a live network. It allows developers to:
        
        * **Deploy smart contracts locally** without incurring transaction fees.
            
        * **Test contract behavior** in a controlled environment.
            
        * **Debug efficiently** before moving to a public testnet or mainnet.
            
        
        Later tutorials will introduce **Lightnet**, a lightweight Mina network that serves as an intermediate testing environment before deploying to live networks.
        
        The **simulated local blockchain** is the initial testing environment for zkApps, providing a fast and efficient way to test smart contracts locally.
        
        **Lightnet** is a lightweight version of the Mina network, offering a more accurate representation of the live blockchain. It serves as an intermediate testing step before deploying to public testnets or mainnet.
        
        For more details, refer to **Testing zkApps with Lightnet**.
        
        To initialize your simulated local blockchain, add the following code from the [main.ts](https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/main.ts) [example](https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/main.ts) file to `src/main.ts`:
        
        4 const useProof = false;  
        5  
        6 const Local = await Mina.LocalBlockchain({ proofsEnabled: useProof });  
        7 Mina.setActiveInstance(Local);  
        8  
        9 const deployerAccount = Local.testAccounts\[0\];  
        10 const deployerKey = deployerAccount.key;  
        11 const senderAccount = Local.testAccounts\[1\];  
        12 const senderKey = senderAccount.key;
        
        To ensure line numbers remain consistent in your **main.ts** file, insert blank lines as necessary when copying code snippets.
        
        The **simulated local blockchain** includes **pre-funded test accounts**. Add the following lines to create **local test accounts** with **test MINA (tMINA)** for this tutorial:
        
        16 // ----------------------------------------------------  
        17  
        18 // Create a public/private key pair. The public key is your address and where you deploy the zkApp to  
        19 const zkAppPrivateKey = PrivateKey.random();  
        20 const zkAppAddress = zkAppPrivateKey.toPublicKey();
        
        To execute the compiled JavaScript code, use the following command:
        
        ```plaintext
        shCopyEdit$ node build/main.js
        ```
        
        This will deploy the **Square** smart contract to the **simulated local blockchain** and execute your interaction script. Let me know if you need help troubleshooting any issues!
        
        That's correct! Running the command:
        
        ```plaintext
        shCopyEditnpm run build && node build/src/main.js
        ```
        
        ensures that your **Square** smart contract is compiled and executed in the **simulated local blockchain** in a single step. Let me know if you run into any issues or need further clarification!
        
        To initialize your smart contract, follow these steps and add the corresponding code to `src/main.ts`:
        
        ### **1\. Create a Public/Private Key Pair**
        
        This generates an address (`zkAppAddress`) on the Mina network where the zkApp will be deployed.
        
        ### **2\. Deploy the Smart Contract**
        
        Create an instance of the `Square` smart contract and deploy it to `zkAppAddress`.
        
        ### **3\. Get the Initial State**
        
        Retrieve the initial state (`num`) stored on-chain and log it to confirm deployment.
        
        ### **Example Code:**
        
        ```plaintext
        typescriptCopyEdit// Import required classes
        import { Mina, PrivateKey, AccountUpdate } from 'o1js';
        import { Square } from './Square';
        
        // Initialize a local Mina blockchain
        const localBlockchain = Mina.LocalBlockchain();
        Mina.setActiveInstance(localBlockchain);
        
        // Generate deployer and zkApp keys
        const deployerKey = localBlockchain.testAccounts[0].privateKey;
        const zkAppPrivateKey = PrivateKey.random();
        const zkAppAddress = zkAppPrivateKey.toPublicKey();
        
        // Create an instance of Square and deploy it
        const zkAppInstance = new Square(zkAppAddress);
        const deployTxn = await Mina.transaction(deployerKey.toPublicKey(), async () => {
          AccountUpdate.fundNewAccount(deployerKey.toPublicKey());
          await zkAppInstance.deploy();
        });
        await deployTxn.sign([deployerKey, zkAppPrivateKey]).send();
        
        // Retrieve and log the initial state
        const num0 = zkAppInstance.num.get();
        console.log('State after init:', num0.toString());
        ```
        
        ### **Expected Output:**
        
        ```plaintext
        shCopyEditState after init: 3
        ```
        
        ### **Smart Contract Initialization Summary**
        
        To initialize your smart contract, add more code from the `main.ts` example file to `src/main.ts`.
        
        #### **Steps:**
        
        1. **Generate Keys:** Create a public/private key pair; the public key is an address on the Mina network where the zkApp is deployed.
            
        2. **Deploy Smart Contract:** Create an instance of `Square` and deploy it to `zkAppAddress`.
            
        3. **Retrieve Initial State:** Get the initial state of `Square` after deployment.
            
        
        #### **Code Breakdown:**
        
        ```plaintext
        typescriptCopyEdit// create an instance of Square - and deploy it to zkAppAddress
        const zkAppInstance = new Square(zkAppAddress);
        const deployTxn = await Mina.transaction(deployerAccount, async () => {
          AccountUpdate.fundNewAccount(deployerAccount);
          await zkAppInstance.deploy();
        });
        await deployTxn.sign([deployerKey, zkAppPrivateKey]).send();
        
        // get the initial state of Square after deployment
        const num0 = zkAppInstance.num.get();
        console.log('state after init:', num0.toString());
        ```
        
        This code initializes and deploys the `Square` smart contract while retrieving its initial on-chain state.
        
        ### **Updating zkApp Account with a Transaction**
        
        To update your local zkApp account with a transaction, add the following code to `src/main.ts`:
        
        #### **Code Implementation:**
        
        ```plaintext
        typescriptCopyEdit// ----------------------------------------------------
        
        const txn1 = await Mina.transaction(senderAccount, async () => {
          await zkAppInstance.update(Field(9));
        });
        await txn1.prove();
        await txn1.sign([senderKey]).send();
        
        const num1 = zkAppInstance.num.get();
        console.log('state after txn1:', num1.toString());
        ```
        
        #### **Execution & Expected Output:**
        
        Run the following command:
        
        ```plaintext
        shCopyEdit$ npm run build && node build/src/main.js
        ```
        
        Expected output:
        
        ```plaintext
        perlCopyEdit> 01-hello-world@0.1.0 build
        > tsc
        
        state after init: 3  
        state after txn1: 9
        ```
        
        This confirms that the zkApp's state was successfully updated from 3 to 9 based on the `update()` function’s rules.
        
        Here’s a reconstructed and summarized version without adding or removing any words:
        
        ---
        
        ### Adding a Transaction That Fails
        
        To test a failing transaction, add more code from `main.ts` to `src/main.ts`. The contract logic allows the stored number to be updated only with its square. Since `num` is now `9`, updating is only possible with `81`.
        
        To test failure, modify the state to `75` using:
        
        ```plaintext
        typescriptCopyEdittry {
          const txn2 = await Mina.transaction(senderAccount, async () => {
            await zkAppInstance.update(Field(75));
          });
          await txn2.prove();
          await txn2.sign([senderKey]).send();
        } catch (error: any) {
          console.log(error.message);
        }
        const num2 = zkAppInstance.num.get();
        console.log('state after txn2:', num2.toString());
        ```
        
        Run:
        
        ```plaintext
        shCopyEdit$ npm run build && node build/src/main.js
        ```
        
        **Expected Output:**
        
        ```plaintext
        yamlCopyEditstate after init: 3  
        state after txn1: 9  
        Field.assertEquals(): 75 != 81  
        state after txn2: 9
        ```
        
        Finally, update `main.ts` to correctly change the state to `81` and rerun the command.
        
        **Expected Output:**
        
        ```plaintext
        perlCopyEditstate after init: 3  
        state after txn1: 9  
        state after txn2: 81
        ```
        
        ### **Tutorial 2: Private Inputs and Hash Functions**
        
        In the **Hello World** tutorial, you created a basic zkApp smart contract using **o1js** with a single state variable that could be updated only if you knew its square.
        
        This tutorial introduces **private inputs** and **hash functions**.
        
        In a **zkApp**, a user's device generates zero-knowledge proofs, which the **Mina network** verifies. Each method in an **o1js** smart contract corresponds to constructing a proof.
        
        By default, **all inputs to a smart contract are private**. Inputs are only visible on the blockchain if they are explicitly stored as on-chain state in the **zkApp account**.
        
        In this tutorial, you will build a smart contract with **private state** that can be modified only if the user knows its value.
        
        ### **Prerequisites**
        
        This tutorial has been tested with **zkApp CLI version 0.20.1**. Ensure your environment meets the **Prerequisites for zkApp Developer Tutorials**.
        
        ---
        
        ### **Create a Project**
        
        1. Navigate to a directory where you have write privileges.
            
        2. Run the following command to create a new zkApp project:
            
            ```plaintext
            shCopyEdit$ zk project 02-private-inputs-and-hash-functions
            ```
            
        3. When prompted, select **none** for the accompanying UI project:
            
            ```plaintext
            sqlCopyEdit? Create an accompanying UI project too? …
              next
              svelte
              nuxt
              empty
            > none
            ```
            
        4. **Expected Output:**
            
            ```plaintext
            sqlCopyEdit✔ Create an accompanying UI project too? · none
            ✔ UI: Set up project
            ✔ Initialize Git repo
            ✔ Set up project
            ✔ NPM install
            ✔ NPM build contract
            ✔ Set project name
            ✔ Git init commit
            
            Success!
            
            Next steps:
              cd 02-private-inputs-and-hash-functions
              git remote add origin <your-repo-url>
              git push -u origin main
            ```
            
        
        ---
        
        ### **Project Structure**
        
        The `zk project` command creates the `02-private-inputs-and-hash-functions` directory, which includes:
        
        * **Prettier** (code formatting)
            
        * **ESLint** (static code analysis)
            
        * **Jest** (JavaScript testing framework)
            
        
        To explore the project, change into the directory and list its contents:
        
        ```plaintext
        shCopyEdit$ cd 02-private-inputs-and-hash-functions
        $ ls
        ```
        
        **Expected Output:**
        
        ```plaintext
        luaCopyEditLICENSE
        README.md
        babel.config.cjs
        build
        config.json
        jest-resolver.cjs
        jest.config.js
        keys
        node_modules
        package-lock.json
        package.json
        src
        tsconfig.json
        ```
        
        You will run commands from the **root** of this directory while working on **TypeScript** code inside the `src` folder.
        
        Each time you update, build, or deploy, the **TypeScript code** is compiled into **JavaScript** in the `build` directory.
        
    * ### **Prepare the Project**
        
        #### **1\. Remove Default Files**
        
        Delete the default generated files:
        
        ```plaintext
        shCopyEdit$ rm src/Add.ts
        $ rm src/Add.test.ts
        $ rm src/interact.ts
        ```
        
        ---
        
        #### **2\. Create New Files**
        
        Run the following commands to set up new files for the project:
        
        ```plaintext
        shCopyEdit$ zk file src/IncrementSecret
        $ touch src/main.ts
        ```
        
        * The `zk file` command creates:
            
            * `src/IncrementSecret.ts` (smart contract file)
                
            * `src/IncrementSecret.test.ts` (test file, but not used in this tutorial)
                
        * `main.ts` will be used as a script to interact with the smart contract.
            
        
        ---
        
        #### **3\. Modify** `src/index.ts`
        
        Open `src/index.ts` in a text editor and modify it to:
        
        ```plaintext
        typescriptCopyEditimport { IncrementSecret } from './IncrementSecret.js';
        
        export { IncrementSecret };
        ```
        
        This file manages exports for external consumption, such as UI components interacting with the smart contract.
        
        ### **Copy the Example Files**
        
        This tutorial requires using the example files from `02-private-inputs-and-hash-functions/src/`.
        
        #### **1\. Copy** `IncrementSecret.ts`
        
        * Open the **example** `IncrementSecret.ts` file.
            
        * Copy its entire contents into **your** `src/IncrementSecret.ts` file.
            
        
        #### **2\. Copy** `main.ts`
        
        * Open the **example** `main.ts` file.
            
        * Copy its entire contents into **your** `src/main.ts` file.
            
        
        ---
        
        Now, you are ready to **review the imports** in the smart contract.
        
        ### **Write the Smart Contract**
        
        Now, let's build the smart contract for our application.
        
        ---
        
        ### **Imports**
        
        The import statement in `IncrementSecret.ts` brings in required packages:
        
        ```plaintext
        typescriptCopyEditimport { Field, SmartContract, state, State, method, Poseidon } from 'o1js';
        ```
        
        ⚡ **Note:**  
        All functions inside a smart contract must operate on **o1js-compatible data types**, such as `Field` and types built on top of `Field`.
        
        ---
        
        ### **Exports**
        
        The smart contract **IncrementSecret** has an **on-chain state** named `x` of type `Field`:
        
        ```plaintext
        typescriptCopyEditexport class IncrementSecret extends SmartContract {
          @state(Field) x = State<Field>();
        }
        ```
        
        This defines the basic structure of the smart contract. If you completed **Tutorial 01: Hello World**, you should recognize the import and export structure.
        
        ---
        
        ### **Initial State**
        
        The `initState()` method runs **once** to set up the initial state in the zkApp account:
        
        ```plaintext
        typescriptCopyEdit@method async initState(salt: Field, firstSecret: Field) {
          this.x.set(Poseidon.hash([salt, firstSecret]));
        }
        ```
        
        * The method accepts two inputs:
            
            * `salt` → A random value for added security
                
            * `firstSecret` → The initial private state
                
        
        These **inputs are private** to whoever initializes the contract. The **zkApp account does not reveal** the actual values of `firstSecret` or `salt`.
        
        ### **Update the State**
        
        The `incrementSecret()` method updates the on-chain state:
        
        ```plaintext
        typescriptCopyEdit@method async incrementSecret(salt: Field, secret: Field) {
          const x = this.x.get();
          this.x.requireEquals(x);
        
          Poseidon.hash([salt, secret]).assertEquals(x);
          this.x.set(Poseidon.hash([salt, secret.add(1)]));
        }
        ```
        
        ---
        
        ### **How It Works**
        
        1. **Retrieves** the current state `x`.
            
        2. **Ensures** that `x` matches the expected value.
            
        3. **Verifies** that the provided `salt` and `secret` hash to `x`.
            
        4. **Increments** the secret (`secret + 1`).
            
        5. **Updates** `x` with the hash of `salt` and the new secret.
            
        
        ---
        
        ### **Why Poseidon Hash?**
        
        * **Optimized** for zero-knowledge proof systems.
            
        * **Takes an array of** `Field`s and outputs a single `Field`.
            
        
        This ensures that:
        
        ✅ The **secret and salt remain private** (not stored on-chain).  
        ✅ The **only revealed value** is `x = hash([salt, secret + 1])`.  
        ✅ The **transaction updates** the zkApp account securely.
        
        Since **hash functions are one-way**, **salt and secret cannot be deduced** from their hash, ensuring privacy.
        
        ### **About the** `salt` Argument
        
        Cryptographic **salt** adds an extra layer of security to a smart contract.
        
        Without `salt`, an attacker could:
        
        1. **Guess likely secrets**, hash them, and compare with the stored hash.
            
        2. **Discover the secret** if it falls within a small range (e.g., 1–10,000).
            
        
        **Example Attack Without Salt:**
        
        * The attacker hashes numbers from **1 to 10,000**.
            
        * If a match is found, the secret is exposed.
            
        
        ---
        
        ### **How** `salt` Enhances Security
        
        By including `salt` in the hash:  
        ✅ **The same secret produces a different hash each time.**  
        ✅ **Attackers can’t precompute hashes** without knowing `salt`.  
        ✅ **Reverse-engineering the secret becomes impractical.**
        
        For **maximum security**:
        
        * **Keep** `salt` private (only you should know it).
            
        * **Use a random value** to prevent predictable patterns.
            
        
        This makes the **contract more secure** and protects on-chain data from brute-force attacks.
        
        ### **Main**
        
        The `src/main.ts` file is similar to the **Hello World** tutorial but with modifications for using the **Poseidon hash** and smart contract initialization.
        
        ---
        
        ### **Smart Contract Initialization**
        
        The smart contract is initialized with a **random salt** and a **secret** value. The `initState()` method takes both:
        
        ```plaintext
        typescriptCopyEditconst salt = Field.random();
        
        const deployTxn = await Mina.transaction(deployerAccount, async () => {
          AccountUpdate.fundNewAccount(deployerAccount);
          await zkAppInstance.deploy();
          await zkAppInstance.initState(salt, Field(750));  // Initializing with salt and secret 750
        });
        await deployTxn.prove();
        ```
        
        * **salt** is randomly generated using `Field.random()`.
            
        * **secret** is `750` in this case.
            
        * `initState()` sets the initial state for the smart contract, using the salt and secret to create the **Poseidon hash**.
            
        
        ---
        
        ### **User Transaction**
        
        The user transaction is used to update the on-chain state, calling the `incrementSecret()` method:
        
        ```plaintext
        typescriptCopyEditconst txn1 = await Mina.transaction(senderAccount, async () => {
          await zkAppInstance.incrementSecret(salt, Field(750));  // Sending salt and secret 750
        });
        ```
        
        This call does not include the salt or secret in the transaction itself. Instead, it includes the **proof** that the update was valid and that the state was updated.
        
        ---
        
        ### **What Happens in the Transaction?**
        
        The transaction proves that the update to the on-chain state **passed all assertions**. The state `x` is updated to:
        
        ```plaintext
        plaintextCopyEditPoseidon.hash([salt, Field(750).add(1)])
        ```
        
        * The **salt** and **secret** are not included in the transaction.
            
        * Only the **updated state** is stored on-chain.
            
        
        Once the transaction is processed by the **Mina network**, the new value of `x` becomes:
        
        ```plaintext
        plaintextCopyEditPoseidon.hash([salt, 751])
        ```
        
        ---
        
        ### **Run the Script**
        
        To run the script, use:
        
        ```plaintext
        shCopyEdit$ npm run build && node build/src/main.js
        ```
        
        ---
        
        ### **Expected Output**
        
        The output will look like this:
        
        ```plaintext
        perlCopyEditstate after init: 3116464240601550031577632290308565252747064306168758166756574536757280262269
        state after txn1: 15333363135506653312218020664441564145350761288169575380089681962972642150348
        ```
        
        The state strings will differ because `Field.random()` generates a unique salt each time, ensuring different state values.
        
        ### **Tutorial 3: Deploy to a Live Network**
        
        In previous tutorials, you learned how to deploy and execute transactions on a local network. In this tutorial, you will use the **zk config** command to create the deploy alias, request **tMINA** funds to pay for transaction fees, and deploy **zkApp** to a live network.
        
        This tutorial reuses the **Square contract** that was created in **Tutorial 1: Hello World**.
        
        ### **Prerequisites**
        
        This tutorial has been tested with:
        
        * **zkApp CLI version 0.20.1**
            
        * **o1js version 1.1.0**
            
        
        Ensure your environment meets the prerequisites for zkApp Developer Tutorials.
        
        If you have earlier versions of **zkApp CLI** and **o1js**, be sure to update them to the latest version with the command:
        
        ```plaintext
        shCopyEditnpm update -g zkapp-cli
        ```
        
        ---
        
        ### **Create a Project**
        
        1. **Create or change to a directory** where you have write privileges.
            
        2. Use the **zk project** command to create the project:
            
            ```plaintext
            shCopyEdit$ zk project 03-deploying-to-a-live-network
            ```
            
            The **zk project** command has the ability to scaffold the UI for your project. For this tutorial, select **none** when prompted:
            
            ```plaintext
            sqlCopyEdit? Create an accompanying UI project too? …
            > none
            ```
            
            **Expected Output:**
            
            ```plaintext
            pgsqlCopyEdit✔ Create an accompanying UI project too? · none
            ✔ UI: Set up project
            ✔ Initialize Git repo
            ✔ Set up project
            ✔ NPM install
            ✔ NPM build contract
            ✔ Set project name
            ✔ Git init commit
            ```
            
        3. After the setup is complete, proceed with the next steps:
            
            ```plaintext
            shCopyEditcd 03-deploying-to-a-live-network
            git remote add origin <your-repo-url>
            git push -u origin main
            ```
            
        4. The **zk project** command creates the **03-deploying-to-a-live-network** directory containing the scaffolding for your project. It includes tools like:
            
            * Prettier (for code formatting)
                
            * ESLint (for static code analysis)
                
            * Jest (for JavaScript testing)
                
        5. Change into the **03-deploying-to-a-live-network** directory:
            
            ```plaintext
            shCopyEditcd 03-deploying-to-a-live-network
            ```
            
        
        ---
        
        ### **Prepare the Project**
        
        1. **Delete Default Files**  
            Start by deleting the default files that come with the new project:
            
            ```plaintext
            shCopyEdit$ rm src/Add.ts
            $ rm src/Add.test.ts
            $ rm src/interact.ts
            ```
            
        2. **Copy Files from the First Tutorial**  
            Copy the `src/Square.ts` and `src/index.ts` files from the **01-hello-world/src** directory of the first tutorial to your local **03-deploying-to-a-live-network/src** directory. If prompted, replace the existing files.
            
        3. **Smart Contract Ready for Deployment**  
            After copying the files, your smart contract is now in place and ready for deployment to **Devnet**.
            
        
        ### **zkApp CLI**
        
        You have already installed the **zkApp CLI** as part of the prerequisites, so you're equipped with the necessary tools to manage deployments.
        
        In certain cases, you might need to:
        
        1. **Create a custom account** for your zkApp.
            
        2. **Programmatically parameterize a zkApp** before initializing it.
            
        3. **Create a smart contract** programmatically for users as part of an application.
            
        
        For more information on these advanced topics, refer to the **Interacting with zkApps server-side** section.
        
        ### **Deploy the Smart Contract**
        
        The **config.json** configuration file contains the necessary settings to deploy your **zkApp**. This file was automatically created when you ran the **zk project** command to scaffold your project.
        
        However, the generated **config.json** file does not yet contain the **deploy alias**.
        
        To proceed with deploying your **zkApp**, you will need to update the **config.json** file with the appropriate **deploy alias** for your target network (such as **Devnet**, **Testnet**, or **Mainnet**).
        
        ### **Deploy Alias Configuration**
        
        The **zk config** command helps you set up a deploy alias in your project’s **config.json** file. You can create one or more deploy aliases, which are essential for deploying your zkApp.
        
        A **deploy alias** consists of:
        
        1. **A self-describing name** that can be anything. It's helpful to use a pattern if you have multiple deploy aliases.
            
        2. **The target network kind** (Testnet, Mainnet, or custom network ID).
            
        3. **The Mina GraphQL API URL**, which defines the network for your deploy transaction (e.g., Testnet, Devnet, Mainnet).
            
        4. **The transaction fee** (in MINA) used for deployment.
            
        5. **Two key pairs**:
            
            * A key pair for the zkApp account (generated automatically in **keys/&lt;deploy-alias-name&gt;.json**).
                
            * A key pair for the fee payer account for updates and deployments (stored locally and reusable across projects).
                
        6. **Fee payer account alias**: You can use an existing account or create a new one to pay for transaction fees.
            
        
        #### Steps to Configure Your Deploy Alias:
        
        Run the **zk config** command and answer the prompts:
        
        ```plaintext
        bashCopyEdit$ zk config
        ```
        
        For this tutorial (using **Devnet**), use the following values:
        
        1. **Deploy alias name**: `devnet`
            
        2. **Target network kind**: `Testnet`
            
        3. **Mina GraphQL API URL**: `https://api.minascan.io/node/devnet/v1/graphql`
            
        4. **Transaction fee**: `0.1 MINA`
            
        5. When prompted for an account to pay transaction fees, select **Use a different account**.
            
        6. Choose to **Create a new fee payer key pair**.
            
            * **Fee payer alias**: `03-deploy`
                
        
        Once your deploy alias is configured, the **zkApp key pair** and **fee payer key pair** are created and stored in **keys/devnet.json** and **${HOME}/.cache/zkapp-cli/keys/03-deploy.json** respectively.
        
        #### Request tMINA from the Faucet:
        
        To fund your fee payer account, request **tMINA** from the faucet:
        
        * Go to the faucet URL: https://faucet.minaprotocol.com
            
        * Choose the network (Devnet in this case) and click **Request**.
            
        
        Wait for the transaction to be included in the next block, so your fee payer account gets funded.
        
        #### Deploy the zkApp:
        
        Once your fee payer account is funded, deploy the zkApp by running:
        
        ```plaintext
        bashCopyEdit$ zk deploy
        ```
        
        * When prompted, select the `devnet` deploy alias.
            
        * A **verification key** for your smart contract is generated (it takes 10-30 seconds).
            
        * Review and confirm the transaction details:
            
            * Deploy alias: `devnet`
                
            * Network: `Testnet`
                
            * URL: `https://api.minascan.io/node/devnet/v1/graphql`
                
            * Fee payer account: `03-deploy`
                
            * zkApp account: `Square`
                
            * Transaction fee: `0.1 Mina`
                
        
        When prompted, type **yes** to confirm and send the transaction to the network.
        
        #### After Deployment:
        
        Your smart contract will be live (or updated) once the transaction is included in a block. You can view the transaction and zkApp details via the **Minascan** explorer:
        
        * **Transaction Link**: `https://minascan.io/devnet/tx/<txn-hash>?type=zk-tx`
            
        
        This link shows the deployed zkApp transaction and involved accounts.
        
        ### **Success: zkApp Deployed!**
        
        Once the transaction is included in a block, your **zkApp** is successfully deployed! Here’s what happens after deployment:
        
        * **Verification Key**: The Mina account used to deploy the zkApp now contains the verification key for the smart contract.
            
        * **Key Pairs**:
            
            * The **fee payer key pair** was created at `${HOME}/.cache/zkapp-cli/keys/03-deploy.json`.
                
            * The **zkApp key pair** was created at `keys/devnet.json`.
                
        * **Funding**: You successfully requested **tMINA** to fund your fee payer account and pay for the deploy transaction fees. The remaining tMINA can be used for building and testing.
            
        * **Deployment Process**:
            
            * You generated a verification key for your smart contract.
                
            * The **zk deploy** command sent the deploy transaction to the Mina network.
                
        
        ### **Next Steps**
        
        * If you want to continue testing, configuring, and deploying your zkApp locally, explore **Testing zkApps with Lightnet**.
            
            ### **Smart Contract Transactions and Proofs**
            
            In this tutorial, the **smart contract** used is from Tutorial 1: Hello World, where permissions are set in a way that **editState** operations require a valid zk proof. Here's how this works:
            
            1. **Proof Creation**:
                
                * When a user interacts with the smart contract, they provide a proof that is generated locally on their device using the **private key** associated with the **zkApp account**.
                    
            2. **Transaction Submission**:
                
                * The generated proof is included in the transaction when it is submitted to the network. The network checks that the proof is correct and that it matches the **on-chain verification key**.
                    
            3. **Proof Verification**:
                
                * Once the transaction is accepted by the network, the proof, along with the transaction, is recursively proven and bundled into Mina's **recursive zero knowledge proof**. This process ensures the integrity and privacy of the transaction.
                    
            4. **Smart Contract Code Changes**:
                
                * If you modify the smart contract code, the associated **verification key** will change. You’ll need to follow the same steps to **redeploy** your zkApp with the updated code and key.
                    
            
            ### **Permissions for Typical Smart Contracts**
            
            For most smart contracts, permissions are configured to **only allow proof-based authorization**. This means that only valid proofs can interact with the smart contract's state, ensuring privacy and security.
            
            In **Tutorial 4: Build a zkApp UI in the Browser with React**, you're building a **browser UI** using **Next.js** that interacts with the smart contract you deployed earlier.
            
            ### **Steps Overview**:
            
            1. **Building on Past Tutorials**:
                
                * In **Tutorial 1: Hello World**, you created the zkApp smart contract using **o1js**.
                    
                * In **Tutorial 3: Deploy to a Live Network**, you deployed the zkApp to a **live network** using **zkApp CLI**.
                    
            2. **Building the UI**:
                
                * Now, in this tutorial, you're going to create a **React-based browser UI** using **Next.js** that will interact with your smart contract. The UI will allow users to interact with your smart contract, such as calling its methods and displaying results on the front-end.
                    
            
            ### **What You'll Learn**:
            
            * How to **integrate** the deployed zkApp smart contract with a **Next.js** app.
                
            * How to create a **front-end interface** that interacts with the **Mina blockchain** through zkApps.
                
            
            By the end of the tutorial, you'll be able to build and deploy a full-stack zkApp with a front-end interface that communicates with your **smart contract on the Mina network**
            
            **Prerequisites:**
            
            * Ensure you have the latest zkApp CLI installed using:
                
                ```plaintext
                rubyCopyEdit$ npm install -g zkapp-cli
                ```
                
            * Ensure your environment meets the prerequisites for zkApp Developer Tutorials.
                
            * Install the Auro Wallet browser extension wallet that supports zkApp interactions and create a MINA account.
                
            
            **Tested Versions:**
            
            * zkApp CLI version: 0.21.6
                
            * o1js version: 1.8.0
                
            * Auro Wallet version: 2.2.15
                
                **High-Level Overview:**
                
                In this tutorial, you will:
                
                * Create a new GitHub repository to deploy the UI to GitHub Pages.
                    
                * Use example code and the zkApp CLI to build an application that:
                    
                    1. Loads a public key from an extension-based wallet.
                        
                    2. Checks if the public key has funds; if not, directs the user to the Faucet.
                        
                    3. Connects to the example zkApp Add smart contract, deployed on Devnet (or another network) at a fixed address.
                        
                    4. Implements a button to send a transaction.
                        
                    5. Implements a button to request the latest state of the smart contract.
                        
                    6. Deploys the zkApp to GitHub Pages.
                        
                
                **Create a project:**
                
                1. Change to a directory with write privileges.
                    
                2. Create a project using the `zk project` command:
                    
                    ```plaintext
                    bashCopyEdit$ zk project 04-zkapp-browser-ui
                    ```
                    
                3. When prompted, select `next` to scaffold the UI using the Next.js React framework:
                    
                    ```plaintext
                    sqlCopyEdit? Create an accompanying UI project too? …
                    > next
                    svelte
                    nuxt
                    empty
                    none
                    ```
                    
                4. If prompted to install the required Next packages, press `y` to proceed.
                    
                5. Select `yes` for the prompt: `Do you want to set up your project for deployment to Github Pages?`
                    
                6. If prompted, press `y` to install the required packages.
                    
                7. For the prompts:
                    
                    * Select `No` for: `Would you like to use ESLint with this project?`
                        
                    * Select `No` for: `Would you like to use Tailwind CSS with this project?`
                        
                8. Your UI is created in the `04-zkapp-browser-ui/ui` directory, with two subdirectories:
                    
                    * `contracts`: Contains the smart contract code.
                        
                    * `ui`: Where you will write the UI code.
                        
                9. For this tutorial, run commands from the root of the `04-zkapp-browser-ui/ui` directory, and work in the `ui/app` directory on TypeScript files for the UI code.
                    
                10. Each time you make updates, the TypeScript code is compiled into JavaScript in the build directory.
                    
                
                **Install the dependencies:**
                
                When you ran the `zk project` command, your UI was created in the `04-zkapp-browser-ui/ui` directory. This project has two subdirectories:
                
                * `contracts`: Contains the smart contract code.
                    
                * `ui`: Contains the UI application code.
                    
                
                The dependencies for both the **contracts** and **ui** subdirectories are automatically installed by the `zkApp CLI`. No additional installation steps are required for dependencies in these subdirectories.
                
                **Create a Repository:**
                
                To interact with a deployed zkApp UI on GitHub Pages, you'll need to create a GitHub repository.
                
                1. Go to [https://github.com/new](https://github.com/new).
                    
                2. For the **Repository name**, enter `04-zkapp-browser-ui`.
                    
                3. Optionally, add a description and a README.
                    
                
                Your project repository is now ready to use!
                
                **Preparing the Project:**
                
                1. In the `04-zkapp-browser-ui/ui` directory, delete the default `page.tsx` file to start with a clean project:
                    
                    ```plaintext
                    bashCopyEdit$ rm app/page.tsx
                    ```
                    
        
        In the `04-zkapp-browser-ui/ui` directory, install the `comlink` package to integrate web workers into the React application. This simplifies communication between the main thread and web workers by abstracting the postMessage API, allowing functions in the worker to be called as if they were local. Install it with:
        
        ```plaintext
        bashCopyEdit$ npm install comlink
        ```
        
        For more information, refer to the documentation.
        
        Download the helper files from the `examples/zkapps/04-zkapp-browser-ui` directory on GitHub:
        
        * `zkappWorker.ts`: Web worker code.
            
        * `zkappWorkerClient.ts`: Client code to interact with the web worker from React.
            
        
        Move these files to your local `04-zkapp-browser-ui/ui/app` directory.
        
        Review the files to understand how they work and how you can extend them for your zkApp. Web workers handle computational tasks to ensure the UI thread is not blocked during long computations like compiling a smart contract or proving a transaction.
        
        ### **Steps to Download and Move** `page.tsx`:
        
        1. **Download the** `page.tsx` example file
            
            * If the file is hosted on a specific URL, download it using:
                
                ```plaintext
                shCopyEditwget <URL_TO_PAGE_TSX>
                ```
                
            * If provided as a ZIP or GitHub repo, clone or extract the file.
                
        2. **Move** `page.tsx` to the correct directory  
            Run the following command in your terminal to place it in your zkApp project:
            
            ```plaintext
            shCopyEditmv path/to/downloaded/page.tsx 04-zkapp-browser-ui/ui/app/
            ```
            
        3. **Verify the file location**  
            Navigate to the directory and confirm the file is there:
            
            Build the default `Add` contract, which is always scaffolded with the `zk project` command.
            
            To make the contract usable with the UI application, run the following command from the `04-zkapp-browser-ui/contracts` directory:
            
            ```plaintext
            arduinoCopyEdit$ npm run build
            ```
            
            Outside this tutorial, the standard workflow involves modifying files in the `contracts` folder, rebuilding the contract, and then integrating it into the UI application code.
            
            ## Implement the UI
            
            The UI application consists of multiple components, including the React page and the code that interacts with `o1js`.
            
        
        ### Setup web workers
        
        The web worker code is located in the `04-zkapp-browser-ui/ui/app/zkappWorker.ts` file, where functions to be executed in the worker thread are defined.
        
        #### Defining State
        
        The `state` object manages references to the zkApp instance, the `Add` contract instance, and transactions:
        
        ```plaintext
        typescriptCopyEditconst state = {
          AddInstance: null as null | typeof Add,
          zkappInstance: null as null | Add,
          transaction: null as null | Transaction,
        };
        ```
        
        # Defining functions that will run in the worker thread
        
        The `api` object defines functions that run in the web worker thread, handling tasks such as network setup, smart contract loading and compiling, account fetching, contract interactions, and transaction management:
        
        ```plaintext
        typescriptCopyEditexport const api = {
          async setActiveInstanceToDevnet() {
            const Network = Mina.Network('https://api.minascan.io/node/devnet/v1/graphql');
            console.log('Devnet network instance configured');
            Mina.setActiveInstance(Network);
          },
          async loadContract() {
            const { Add } = await import('../../contracts/build/src/Add.js');
            state.AddInstance = Add;
          },
          async compileContract() {
            await state.AddInstance!.compile();
          },
          async fetchAccount(publicKey58: string) {
            const publicKey = PublicKey.fromBase58(publicKey58);
            return fetchAccount({ publicKey });
          },
          async initZkappInstance(publicKey58: string) {
            const publicKey = PublicKey.fromBase58(publicKey58);
            state.zkappInstance = new state.AddInstance!(publicKey);
          },
          async getNum() {
            const currentNum = await state.zkappInstance!.num.get();
            return JSON.stringify(currentNum.toJSON());
          },
          async createUpdateTransaction() {
            state.transaction = await Mina.transaction(async () => {
              await state.zkappInstance!.update();
            });
          },
          async proveUpdateTransaction() {
            await state.transaction!.prove();
          },
          async getTransactionJSON() {
            return state.transaction!.toJSON();
          },
        };
        ```
        
        #### Expose functions to the main thread with `comlink`[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#expose-functions-to-the-main-thread-with-comlink)
        
        ```plaintext
        // Expose the API to be used by the main thread
        Comlink.expose(api);
        ```
        
        Creating the worker client[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client)
        
        * The web worker client code r[e](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client)sides in the `04-zkapp-browser-ui/ui/app/zkappWorkerClient.ts` file. Here you create a client in the main thread that interacts with the web worker.
            
        * `worker` is a reference to the web worker instance and `remoteApi` is a reference to a proxy object that provides typesafe access to the worker's API methods.
            
        
        ```plaintext
        export default class ZkappWorkerClient {
          worker: Worker;
          // Proxy to interact with the worker's methods as if they were local
          remoteApi: Comlink.Remote<typeof import('./zkappWorker').api>;
        ```
        
        In the constructor create a [n](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client)ew Worker instance pointing to the `zkappWorker.ts` file.
        
        ```plaintext
        constructor() {
          // Initialize the worker from the zkappWorker module
          const worker = new Worker(new URL('./zkappWorker.ts', import.meta.url), { type: 'module' });
        ```
        
        With `Comlink.wrap`, create a [p](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client)roxy object `remoteApi` that provides typesafe access the worker's API methods.
        
        ```plaintext
          // Wrap the worker with Comlink to enable direct method invocation
          this.remoteApi = Comlink.wrap(this.worker);
        ```
        
        Define methods in the ZkappW[o](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client)rkerClient class that call the corresponding method on `remoteApi`, effectively forwarding the calls to the worker.
        
        ```plaintext
        async setActiveInstanceToDevnet() {
            return this.remoteApi.setActiveInstanceToDevnet();
          }
        
          async loadContract() {
            return this.remoteApi.loadContract();
          }
        
          async compileContract() {
            return this.remoteApi.compileContract();
          }
        
          async fetchAccount(publicKeyBase58: string) {
            return this.remoteApi.fetchAccount(publicKeyBase58);
          }
        
          async initZkappInstance(publicKeyBase58: string) {
            return this.remoteApi.initZkappInstance(publicKeyBase58);
          }
        
          async getNum(): Promise<Field> {
            const result = await this.remoteApi.getNum();
            return Field.fromJSON(JSON.parse(result as string));
          }
        
          async createUpdateTransaction() {
            return this.remoteApi.createUpdateTransaction();
          }
        
          async proveUpdateTransaction() {
            return this.remoteApi.proveUpdateTransaction();
          }
        
          async getTransactionJSON() {
            return this.remoteApi.getTransactionJSON();
          }
        ```
        
        The environment configuration ensures the UI interacts with the correct zkApp deployed on Devnet.
        
        * In `page.tsx`, `ZKAPP_ADDRESS` holds the public key of the deployed smart contract. Users can deploy their own contract and update this variable if needed.
            
        * In `zkappWorker.ts`, `setActiveInstanceToDevnet()` configures the network instance using Mina’s Devnet GraphQL endpoint. If switching networks, update the endpoint accordingly while ensuring compatibility with Auro Wallet.
            
        
        In this example, the o1js code runs on the client side within a client component after the page loads. If integrating o1js into a server component, Next.js's caching could lead to outdated data being returned. To prevent this, you can disable caching by adding `export const revalidate = 0;` to your component. For further details, check the Next.js caching documentation.
        
        ### Add state[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#add-state)
        
        The following statements in `04-zkapp-browser-ui/ui/app/page.tsx` create mutable state to track various aspects of the UI, which updates as the application runs:
        
        ```plaintext
        tsxCopyEditconst [zkappWorkerClient, setZkappWorkerClient] = useState<null | ZkappWorkerClient>(null);
        const [hasWallet, setHasWallet] = useState<null | boolean>(null);
        const [hasBeenSetup, setHasBeenSetup] = useState(false);
        const [accountExists, setAccountExists] = useState(false);
        const [currentNum, setCurrentNum] = useState<null | Field>(null);
        const [publicKeyBase58, setPublicKeyBase58] = useState('');
        const [creatingTransaction, setCreatingTransaction] = useState(false);
        const [displayText, setDisplayText] = useState('');
        const [transactionlink, setTransactionLink] = useState('');
        ```
        
        These hooks track the state values, which can be referenced and updated as the application runs.
        
        For more information on `useState`, refer to the React API reference documentation on built-in hooks.
        
        ### zkApp setting up[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#zkapp-setting-up)
        
        This `04-zkapp-brow`[`s`](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance)`er-ui/ui/app/page.tsx` code adds a functions to set up zkApp:
        
        * The Boolean `hasBee`[`n`](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance)`Setup` ensures that the react feature `use`[`Effect` is](https://react.dev/reference/react/useEffect) run only o[nce. To l](https://react.dev/reference/react/useEffect)earn more about `useEffect` hooks, see [useEffect](https://react.dev/reference/react/useEffect) in the React API reference [documenta](https://react.dev/reference/react/useEffect)tion.
            
        * This code also set[s](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance) up your web worker client that interacts with the web worker running o1js code to ensure the computationally heavy o1js code doesn't block the [UI threa](https://react.dev/reference/react/useEffect)d.
            
        
        #### Load web worker an[d](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance) setup Mina active instance[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance)
        
        ```plaintext
        ...
          displayStep('Loading web worker...')
          const zkappWorkerClient = new ZkappWorkerClient();
          setZkappWorkerClient(zkappWorkerClient);
          await new Promise((resolve) => setTimeout(resolve, 5000));
          displayStep('Done loading web worker')
        
          await zkappWorkerClient.setActiveInstanceToDevnet();
        ...
        ```
        
        The code in `04-zkapp-browser-ui/ui/app/page.tsx` connects to Auro Wallet and sets up the fee payer account as follows:
        
        * It checks if the `mina` object is available (from Auro Wallet).
            
        * If not, it sets `hasWallet` to `false` and displays an error message.
            
        * If Auro Wallet is found, it retrieves the public key using `mina.requestAccounts()`.
            
        * The public key is displayed and stored in `publicKeyBase58`.
            
        * It then checks if the fee payer account exists by calling `zkappWorkerClient.fetchAccount(publicKeyBase58)`.
            
        * The result (`accountExists`) is updated based on whether the account exists or not.
            
        
        ```plaintext
        tsxCopyEditconst mina = (window as any).mina;
        if (mina == null) {
          setHasWallet(false);
          displayStep('Wallet not found.');
          return;
        }
        
        const publicKeyBase58: string = (await mina.requestAccounts())[0];
        setPublicKeyBase58(publicKeyBase58);
        displayStep(`Using key:${publicKeyBase58}`);
        
        displayStep('Checking if fee payer account exists...');
        const res = await zkappWorkerClient.fetchAccount(publicKeyBase58);
        const accountExists = res.error === null;
        setAccountExists(accountExists);
        ```
        
        The code in `04-zkapp-browser-ui/ui/app/page.tsx` imports the contract code, instantiates the zkApp instance, compiles the contract, and fetches the zkApp state as follows:
        
        1. It loads the contract using `zkappWorkerClient.loadContract()`.
            
        2. The contract is compiled with `zkappWorkerClient.compileContract()`, and a message is displayed.
            
        3. The zkApp instance is initialized with the deployed `ZKAPP_ADDRESS` using `zkappWorkerClient.initZkappInstance(ZKAPP_ADDRESS)`.
            
        4. It fetches the current state of the zkApp by calling `zkappWorkerClient.fetchAccount(ZKAPP_ADDRESS)` and retrieves the current number from the zkApp with `zkappWorkerClient.getNum()`.
            
        5. The retrieved state (`currentNum`) is stored in `currentNum` and logged to the console.
            
        
        ```plaintext
        tsxCopyEditawait zkappWorkerClient.loadContract();
        
        displayStep('Compiling zkApp...');
        await zkappWorkerClient.compileContract();
        displayStep('zkApp compiled');
        
        await zkappWorkerClient.initZkappInstance(ZKAPP_ADDRESS);
        
        displayStep('Getting zkApp state...');
        await zkappWorkerClient.fetchAccount(ZKAPP_ADDRESS);
        const currentNum = await zkappWorkerClient.getNum();
        setCurrentNum(currentNum);
        console.log(`Current state in zkApp: ${currentNum}`);
        ```
        
        The state of the React application is updated as follows:
        
        The state of the React application is updated as follows:
        
        1. The `hasBeenSetup` state is set to `true` to indicate that the setup process is complete.
            
        2. The `hasWallet` state is set to `true`, confirming that the wallet is found and connected.
            
        3. The `displayText` state is reset to an empty string, likely to clear any previous messages shown during setup.
            
        
        ```plaintext
        tsxCopyEditsetHasBeenSetup(true);
        setHasWallet(true);
        setDisplayText('');
        ```
        
        ### Run the React app
        
        o run the React app, follow these steps:
        
        1. **Start the development server** in the `04-zkapp-browser-ui/ui/` directory:
            
            ```plaintext
            bashCopyEdit$ npm run dev
            ```
            
            This will serve your UI application at [`localhost:3000`](http://localhost:3000).
            
        2. **Change the default port** by specifying the `--port` argument. For example, to run it on port 8001:
            
            ```plaintext
            bashCopyEdit$ npm run dev -- --port 8001
            ```
            
        3. **Interacting with the app**:
            
            * The zkApp UI in the browser will display the current state of the zkApp.
                
            * It includes buttons for sending a transaction and fetching the latest on-chain state of the zkApp.
                
            * The browser will refresh automatically when the source code is updated.
                
        4. **Faucet Request**: If prompted, request funds from the Testnet Faucet service to fund your fee payer account.
            
        5. **Start TypeScript watch mode**: In a second terminal window, run the following command to start the TypeScript compiler in watch mode:
            
            ```plaintext
            bashCopyEdit$ npm run ts-watch
            ```
            
            This allows the TypeScript compiler to react to any changes in the code.
            
        
        ### Wait for the fee payer account to be funded[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#wait-for-the-fee-payer-account-to-be-funded)
        
        Now that the UI setup is finished, a new useE[f](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#wait-for-the-fee-payer-account-to-be-funded)fect waits for the fee payer account to be funded if it didn't before by checking the account presence in ledger.
        
        Don't forget that if the account has been new[l](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#wait-for-the-fee-payer-account-to-be-funded)y created, it must be funded from the Faucet.
        
        ```plaintext
        ...
          useEffect(() => {
            const checkAccountExists = async () => {
              if (hasBeenSetup && !accountExists) {
                try { 
                  for (;;) {
                    displayStep('Checking if fee payer account exists...');
                    
                    const res = await zkappWorkerClient!.fetchAccount(publicKeyBase58);
                    const accountExists = res.error == null;
                    if (accountExists) {
                      break;
                    }
                    await new Promise((resolve) => setTimeout(resolve, 5000));
                  } 
                } catch (error: any) {
                  displayStep(`Error checking account: ${error.message}`);
                }
        
              }
              setAccountExists(true);
            };
        
            checkAccountExists();
          }, [zkappWorkerClient, hasBeenSetup, accountExists]); 
        ...
        ```
        
        ### Let UI buttons do some useful work[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#let-ui-buttons-do-some-useful-work)
        
        These functions will be triggered on buttons press.
        
        ```plaintext
        ...
          const onSendTransaction = async () => {
            setCreatingTransaction(true);
            displayStep('Creating a transaction...');
           
            console.log('publicKeyBase58 sending to worker', publicKeyBase58);
            await zkappWorkerClient!.fetchAccount(publicKeyBase58);
        
            await zkappWorkerClient!.createUpdateTransaction();
        
            displayStep('Creating proof...');
            await zkappWorkerClient!.proveUpdateTransaction();
        
            displayStep('Requesting send transaction...');
            const transactionJSON = await zkappWorkerClient!.getTransactionJSON();
        
            displayStep('Getting transaction JSON...');
            const { hash } = await (window as any).mina.sendTransaction({
              transaction: transactionJSON,
              feePayer: {
                fee: transactionFee,
                memo: '',
              },
            });
        
            const transactionLink = `https://minascan.io/devnet/tx/${hash}`;
            setTransactionLink(transactionLink);
            setDisplayText(transactionLink);
        
            setCreatingTransaction(true);
          };
        
          const onRefreshCurrentNum = async () => {
            try {
              displayStep('Getting zkApp state...');
              await zkappWorkerClient!.fetchAccount(ZKAPP_ADDRESS);
              const currentNum = await zkappWorkerClient!.getNum();
              setCurrentNum(currentNum);
              console.log(`Current state in zkApp: ${currentNum}`);
              setDisplayText('');
            } catch (error: any) {
              displayStep(`Error refreshing state: ${error.message}`);
            }
          };
        ```
        
        ### Take care of the page markup[​](https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#take-care-of-the-page-markup)
        
        ```plaintext
        ...
          let auroLinkElem;
          if (hasWallet === false) {
            const auroLink = 'https://www.aurowallet.com/';
            auroLinkElem = (
              <div>
                Could not find a wallet.{' '}
                <a href="https://www.aurowallet.com/" target="_blank" rel="noreferrer">
                  Install Auro wallet here
                </a>
              </div>
            );
          }
        
          const stepDisplay = transactionlink ? (
            <a
              href={transactionlink}
              target="_blank"
              rel="noreferrer"
              style={{ textDecoration: 'underline' }}
            >
              View transaction
            </a>
          ) : (
            displayText
          );
        
          let setup = (
            <div
              className={styles.start}
              style={{ fontWeight: 'bold', fontSize: '1.5rem', paddingBottom: '5rem' }}
            >
              {stepDisplay}
              {auroLinkElem}
            </div>
          );
        
          let accountDoesNotExist;
          if (hasBeenSetup && !accountExists) {
            const faucetLink =
              `https://faucet.minaprotocol.com/?address='${publicKeyBase58}`;
            accountDoesNotExist = (
              <div>
                <span style={{ paddingRight: '1rem' }}>Account does not exist.</span>
                <a href={faucetLink} target="_blank" rel="noreferrer">
                  Visit the faucet to fund this fee payer account
                </a>
              </div>
            );
          }
        
          let mainContent;
          if (hasBeenSetup && accountExists) {
            mainContent = (
              <div style={{ justifyContent: 'center', alignItems: 'center' }}>
                <div className={styles.center} style={{ padding: 0 }}>
                  Current state in zkApp: {currentNum?.toString()}{' '}
                </div>
                <button
                  className={styles.card}
                  onClick={onSendTransaction}
                  disabled={creatingTransaction}
                >
                  Send Transaction
                </button>
                <button className={styles.card} onClick={onRefreshCurrentNum}>
                  Get Latest State
                </button>
              </div>
            );
          }
        
          return (
            <GradientBG>
              <div className={styles.main} style={{ padding: 0 }}>
                <div className={styles.center} style={{ padding: 0 }}>
                  {setup}
                  {accountDoesNotExist}
                  {mainContent}
                </div>
              </div>
            </GradientBG>
          );
        ```
        
        The UI has three sections:
        
        1. **setup**: Informs the user when the zkApp has finished loading.
            
        2. **accountDoesNotExist**: Provides a link to the Faucet if the user's account hasn't been funded yet.
            
        3. **mainContent**: Displays the current zkApp on-chain state and provides buttons for users to interact with the zkApp. These buttons let users create transactions to update the on-chain zkApp state and refresh the current state.
            
        
        Once the code is set up, you can interact with the UI application at [`localhost:3000`](http://localhost:3000) if you’re running it with `npm run dev`.
        
        To deploy the application to GitHub Pages, follow these steps:
        
        1. **Push the project to GitHub**: First, ensure that your project is pushed to the GitHub repository you created at the beginning of the tutorial. The repository name must match the project name (`04-zkapp-browser-ui`).
            
        2. **Verify project name consistency**: Ensure the GitHub repository name matches your project name. The `zk project` command has already set the project name in the `next.config.js` and `src/pages/reactCOIServiceWorker.ts` files.
            
        
        After confirming the project is correctly set up and pushed to GitHub, you can proceed with deploying it to GitHub Pages.
        
        To deploy your UI to GitHub Pages:
        
        1. **Navigate to the UI directory**: Change to the `04-zkapp-browser-ui/ui/` directory.
            
            ```plaintext
            bashCopyEditcd 04-zkapp-browser-ui/ui/
            ```
            
        2. **Run the deploy script**: Execute the following command to deploy your UI to GitHub Pages.
            
            ```plaintext
            bashCopyEditnpm run deploy
            ```
            
            This script builds your application and automatically publishes it to GitHub Pages.
            
        3. **Access the deployed zkApp UI**: After the deployment is complete, your zkApp UI will be available at the following URL:
            
            ```plaintext
            cppCopyEdithttps://<username>.github.io/04-zkapp-browser-ui/
            ```
            
            Replace `<username>` with your GitHub username.
            
            # Tutorial 5: Common Types and Functions
            
            In previous tutorials, you learned how to deploy smart contracts to the network interact with them from a React UI and NodeJS.
            
            In this tutorial, you learn about types you can use when building with o1js. Earlier tutorials mostly use the `Field` type. o1js provides other higher-order types built from Fields that are useful for zkApp development and expand the possibilities for more applications.
            
            The [example project](https://github.com/o1-labs/docs2/tree/main/examples/zkapps/05-common-types-and-functions/src) includes a [main.ts](https://github.com/o1-labs/docs2/blob/main/examples/zkapps/05-common-types-and-functions/src/main.ts) file that shows all of the concepts presented in this tutorial, along with smart contracts showing more advanced usage of some of the concepts, particularly Merkle Trees.
            
            **Prerequisites**:
            
            * zkApp CLI version 0.20.1
                
            * o1js version 1.1.0
                
            
            Ensure your environment is set up according to the zkApp Developer Tutorials prerequisites.
            
            ## Basic Types
            
            In this section, five basic types are introduced, all derived from Fields. These types are:
            
            * `Bool`
                
            * `UInt32`
                
            * `UInt64`
                
            * `Int64`
                
            * `Character`
                
            
            Each type follows standard programming language semantics. Here's an example with different types:
            
            * **UInt32 and UInt64**:
                
                * `num1` is created as a `UInt32` with the value 40.
                    
                * `num2` is created as a `UInt64` with the same value.
                    
                * A comparison is made between `num1` and `num2`, resulting in `num1EqualsNum2` being `true` as the values are equal after conversion.
                    
            * **Int64**:
                
                * `signedNum1` and `signedNum2` are created with values -3 and 45, respectively.
                    
                * The sum of these two numbers is computed, resulting in 42.
                    
            * **Character**:
                
                * `char1` is created from the string 'c', and `char2` from 'd'.
                    
                * A comparison between `char1` and `char2` returns `false` because they are different characters.
                    
            
            **Output of the code**:
            
            ```plaintext
            yamlCopyEditnum1 === num2: true
            Fields in num1: 1
            signedNum1 + signedNum2: 42
            Fields in signedNum1: 2
            char1: c
            char1 === char2: false
            Fields in char1: 1
            ```
            
        
        ## More Advanced Types
        
        This section introduces four advanced types:
        
        * `CircuitString`
            
        * `PrivateKey`
            
        * `PublicKey`
            
        * `Signature`
            
        
        ### Key Points:
        
        * **CircuitString**:
            
            * The default `CircuitString` has a maximum length of 128 characters, but it can be treated like a dynamic-length string. You can create custom types to modify the length.
                
            * Example:
                
                ```plaintext
                javascriptCopyEditconst str1 = CircuitString.fromString('abc..xyz');
                console.log(`str1: ${str1}`);
                console.log(`Fields in str1: ${CircuitString.toFields(str1).length}`);
                ```
                
        * **PrivateKey and PublicKey**:
            
            * A `PrivateKey` can be generated randomly, and its corresponding `PublicKey` can be derived from it.
                
            * Example:
                
                ```plaintext
                javascriptCopyEditconst zkAppPrivateKey = PrivateKey.random();
                const zkAppPublicKey = zkAppPrivateKey.toPublicKey();
                ```
                
        * **Signature**:
            
            * Signatures are created using the `PrivateKey` and verified against the `PublicKey`.
                
            * Example:
                
                ```plaintext
                javascriptCopyEditconst signature = Signature.create(zkAppPrivateKey, data2);
                const verifiedData1 = signature.verify(zkAppPublicKey, data1).toString();
                const verifiedData2 = signature.verify(zkAppPublicKey, data2).toString();
                ```
                
        
        ### Output:
        
        ```plaintext
        vbnetCopyEditstr1: abc..xyz
        Fields in str1: 128
        private key: EKF714j3wgH3tuuQncL93ruQFbJGnhDzfWossAHUp15PdATKE7Ka
        public key: B62qrhsTdExJDAxQx76V1mc13ibzikpmNaNRShTG3MWedCXESBhQ2Ch
        Fields in private key: 2
        Fields in public key: 2
        signature verified for data1: false
        signature verified for data2: true
        Fields in signature: 3
        ```
        
        ### Notes:
        
        * **Private Key Security**: Never expose private keys in real applications.
            
        * **Field Sizes**: A private key has 255 Fields, and a signature has 256 Fields due to cryptographic reasons related to elliptic curve scalars.
            
        
        ### Struct
        
        You can create custom compound data types using the `Struct` type in o1js. This allows you to define data structures that combine different data types (e.g., `Field`, higher-order types, or other `Struct` types). Additionally, you can define methods for these `Struct` types to operate on their data.
        
        In o1js, data structures need to be fixed-size because programs are compiled into circuits that must handle static-sized data.
        
        ### Example 1: Point Structure and Addition Method
        
        ```plaintext
        javascriptCopyEditclass Point extends Struct({ x: Field, y: Field }) {
          static add(a: Point, b: Point) {
            return { x: a.x.add(b.x), y: a.y.add(b.y) };
          }
        }
        
        const point1 = { x: Field(10), y: Field(4) };
        const point2 = { x: Field(1), y: Field(2) };
        
        const pointSum = Point.add(point1, point2);
        
        console.log(`pointSum Fields: ${Point.toFields(pointSum)}`);
        ```
        
        ### Example 2: Points8 Structure (Array of 8 Points)
        
        ```plaintext
        javascriptCopyEditclass Points8 extends Struct({
          points: [Point, Point, Point, Point, Point, Point, Point, Point],
        }) {}
        
        const points = new Array(8)
          .fill(null)
          .map((_, i) => ({ x: Field(i), y: Field(i * 10) }));
        const points8: Points8 = { points };
        
        console.log(`points8 JSON: ${JSON.stringify(points8)}`);
        ```
        
        ### Console Output:
        
        ```plaintext
        cssCopyEditpointSum Fields: 11,6
        points8 Fields: {"points":[{"x":"0","y":"0"},{"x":"1","y":"10"},{"x":"2","y":"20"},{"x":"3","y":"30"},{"x":"4","y":"40"},{"x":"5","y":"50"},{"x":"6","y":"60"},{"x":"7","y":"70"}]}
        ```
        
        ### Explanation:
        
        * **Point Structure**: A `Point` is defined as a `Struct` with two fields (`x` and `y`), both of which are of type `Field`. The `add` method adds the `x` and `y` values of two `Point` objects.
            
        * **Points8 Structure**: The `Points8` structure is an array of 8 `Point` objects. The `points` array is fixed in size, as required for o1js programs.
            
        
        This demonstrates how to use `Struct` to build more complex data types that are compatible with zkApps.
        
        ### Control Flow in o1js
        
        o1js provides two main functions for control flow in zkApps:
        
        1. **Provable.if**: Similar to a ternary operator in JavaScript. It allows conditional execution based on a test condition.
            
        2. **Provable.switch**: Similar to a switch-case statement in JavaScript. It evaluates multiple conditions and returns the corresponding value.
            
        
        Both functions help manage control flow inside zkApps when building logic that needs conditional execution.
        
        ### Example 1: Using `Provable.if`
        
        ```plaintext
        javascriptCopyEditconst input1 = Int64.from(10);
        const input2 = Int64.from(-15);
        
        const inputSum = input1.add(input2);
        
        const inputSumAbs = Provable.if(
          inputSum.isPositive(),
          inputSum,
          inputSum.mul(Int64.minusOne)
        );
        
        console.log(`inputSum: ${inputSum.toString()}`);
        console.log(`inputSumAbs: ${inputSumAbs.toString()}`);
        ```
        
        ### Example 2: Using `Provable.switch`
        
        ```plaintext
        javascriptCopyEditconst input3 = Int64.from(22);
        
        const input1largest = input1
          .sub(input2)
          .isPositive()
          .and(input1.sub(input3).isPositive());
        const input2largest = input2
          .sub(input1)
          .isPositive()
          .and(input2.sub(input3).isPositive());
        const input3largest = input3
          .sub(input1)
          .isPositive()
          .and(input3.sub(input2).isPositive());
        
        const largest = Provable.switch(
          [input1largest, input2largest, input3largest],
          Int64,
          [input1, input2, input3]
        );
        
        console.log(`largest: ${largest.toString()}`);
        ```
        
        ### Output:
        
        ```plaintext
        makefileCopyEditinputSum: -5
        inputSumAbs: 5
        largest: 22
        ```
        
        ### Explanation:
        
        * **Provable.if**: This acts similarly to a ternary operation. Both branches (the "true" branch and the "false" branch) are evaluated to maintain the logic for zk circuits. Here, `inputSumAbs` returns the absolute value of the sum by checking if the sum is positive.
            
        * **Provable.switch**: This function evaluates a series of boolean conditions (e.g., which input is largest) and switches to the corresponding value based on the conditions. In this example, it checks whether `input3` is the largest number and returns the largest of the three values (`input1`, `input2`, or `input3`).
            
        
        These control flow methods ensure proper conditional logic while building zkApps with o1js.
        
        ### Assertions and Constraints in o1js
        
        In o1js, functions are compiled into zk circuits, which are used to prove that the logic in your program has been correctly executed and that all assertions hold true. The key idea is that when a transaction is proven in o1js, it ensures that the computations follow the program's logic and all assertions are valid.
        
        ### Key Points:
        
        * **Assertions**: These verify that certain conditions hold true during execution. For example, `.assertEquals(a, b)` ensures `a` equals `b`. Similarly, `.assertTrue()` can be used to assert that a boolean condition is true, which is useful for controlling logic flow.
            
        * **Circuit Size Constraints**: o1js operates within fixed-size circuits, and every operation performed in your code counts toward the maximum size of the circuit. The size limits are:
            
            * Approximately **5,200 hashes** for circuits involving two fields.
                
            * About **2,600 hashes** for circuits involving four fields.
                
            * Roughly **2^17 field multiplies**.
                
            * Around **2^17 field additions**.
                
        
        These constraints limit how complex a circuit can be. If the program exceeds these limits, it may need to be broken down into smaller pieces, each of which can be verified in a separate proof. This is where **Recursion** comes into play.
        
        ### Recursion:
        
        If the program is too large for the circuit size limits, **recursion** can be used to break the program into smaller, manageable parts. Each part is verified independently, and the overall correctness of the program can still be proven, while staying within the circuit size constraints.
        
        In summary, assertions ensure correctness, while circuit size constraints limit the complexity. If needed, recursion allows breaking down complex programs into smaller verifiable chunks.
        
        ### Merkle Trees in o1js
        
        Merkle trees are used in o1js to manage large amounts of data efficiently within a zk-SNARK circuit. This is useful when you need to handle data in a way that proves its inclusion in a tree structure without revealing the entire dataset.
        
        The example project for this tutorial demonstrates how to work with Merkle trees using the `BasicMerkleTreeContract.ts` contract and `main.ts` to interact with Merkle trees.
        
        #### Steps to Create a Merkle Tree:
        
        1. **Importing MerkleTree**:  
            Import the `MerkleTree` class from `o1js`:
            
            ```plaintext
            tsCopyEditimport { MerkleTree } from 'o1js';
            ```
            
        2. **Create a Merkle Tree**:  
            Define the height of the tree (which determines how many leaves the tree will have):
            
            ```plaintext
            tsCopyEditconst height = 20; // This creates a tree with 2^(20-1) = 524,288 leaves
            const tree = new MerkleTree(height);
            ```
            
        3. **Store the Merkle Tree in a Smart Contract**:  
            Merkle trees are stored in a smart contract as the hash of the tree's root. You can update the Merkle root by providing a Merkle witness (which represents the Merkle path to a leaf).
            
        4. **Example of a Contract Updating a Merkle Tree**: Here’s a simplified example of how to define a smart contract that updates a Merkle tree by checking conditions:
            
            ```plaintext
            tsCopyEdit@state(Field) treeRoot = State<Field>();
            
            @method async initState(initialRoot: Field) {
              this.treeRoot.set(initialRoot);
            }
            
            @method async update(
              leafWitness: MerkleWitness20,
              numberBefore: Field,
              incrementAmount: Field
            ) {
              const initialRoot = this.treeRoot.get();
              this.treeRoot.requireEquals(initialRoot);
            
              incrementAmount.assertLt(Field(10));
            
              // Check initial state matches expectation
              const rootBefore = leafWitness.calculateRoot(numberBefore);
              rootBefore.assertEquals(initialRoot);
            
              // Compute root after increment
              const rootAfter = leafWitness.calculateRoot(numberBefore.add(incrementAmount));
            
              // Set new root
              this.treeRoot.set(rootAfter);
            }
            ```
            
        5. **Interacting with the Smart Contract**:
            
            * **Initialize the zkApp**:
                
                ```plaintext
                tsCopyEditconst zkApp = new BasicMerkleTreeContract(basicTreeZkAppAddress);
                await BasicMerkleTreeContract.compile();
                ```
                
            * **Create a Merkle Tree**:
                
                ```plaintext
                tsCopyEditconst height = 20;
                const tree = new MerkleTree(height);
                ```
                
            * **Deploy the Smart Contract**: Deploy the contract and initialize the tree state:
                
                ```plaintext
                tsCopyEditconst deployTxn = await Mina.transaction(deployerAccount, async () => {
                  AccountUpdate.fundNewAccount(deployerAccount);
                  await zkApp.deploy();
                  await zkApp.initState(tree.getRoot());
                });
                await deployTxn.prove();
                deployTxn.sign([deployerKey, basicTreeZkAppPrivateKey]);
                ```
                
        6. **Update Tree Data**:
            
            * **Get the Witness for the Tree**:
                
                ```plaintext
                tsCopyEditconst witness = new MerkleWitness20(tree.getWitness(incrementIndex));
                ```
                
            * **Update the Tree Locally**:
                
                ```plaintext
                tsCopyEdittree.setLeaf(incrementIndex, incrementAmount);
                ```
                
            * **Update the Smart Contract**:
                
                ```plaintext
                tsCopyEditconst txn1 = await Mina.transaction(senderPublicKey, async () => {
                  await zkApp.update(witness, Field(0), incrementAmount);
                });
                await txn1.prove();
                const pendingTx = await txn1.sign([senderPrivateKey, basicTreeZkAppPrivateKey]).send();
                await pendingTx.wait();
                ```
                
        7. **Compare Roots**: After the transaction, you can compare the root of the local tree and the root stored in the smart contract:
            
            ```plaintext
            tsCopyEditconsole.log(`BasicMerkleTree: local tree root hash after send1: ${tree.getRoot()}`);
            console.log(`BasicMerkleTree: smart contract root hash after send1: ${zkApp.treeRoot.get()}`);
            ```
            
        
        ### Advanced Example:
        
        A more advanced example uses a **LedgerContract** to implement a basic ledger of tokens, with checks to ensure that the sender has signed their transaction and that the amounts sent match what is received.
        
        #### Benefits of Using Merkle Trees:
        
        * **Efficient Data Proof**: Merkle trees allow for efficient inclusion proofs, enabling you to prove that a piece of data exists in a large dataset without revealing the entire dataset.
            
        * **Secure Updates**: By using Merkle witnesses and hashes, updates to the data can be securely and efficiently verified.
            
        
        ### Merkle Map in o1js
        
        Merkle Maps are similar to Merkle Trees, but instead of using an index to access the data, they use keys (e.g., fields) to store and retrieve values. This is particularly useful for implementing key-value stores within zk-SNARK smart contracts.
        
        #### Basic Example of Using Merkle Map
        
        1. **Create and Populate a Merkle Map**:
            
            ```plaintext
            tsCopyEditconst map = new MerkleMap();
            
            const key = Field(100);
            const value = Field(50);
            
            map.set(key, value);
            console.log('value for key', key.toString() + ':', map.get(key));
            ```
            
            This will output:
            
            ```plaintext
            rustCopyEditvalue for key 100: 50
            ```
            
        2. **Smart Contract Usage**: Similar to Merkle Trees, you can use Merkle Maps in smart contracts. The contract uses a Merkle Map to store the root of the key-value map, and it uses witnesses to prove changes to the map.
            
            * **Smart Contract Definition**:
                
                ```plaintext
                tsCopyEdit@state(Field) mapRoot = State<Field>();
                
                @method async init(initialRoot: Field) {
                  this.mapRoot.set(initialRoot);
                }
                
                @method async update(
                  keyWitness: MerkleMapWitness,
                  keyToChange: Field,
                  valueBefore: Field,
                  incrementAmount: Field,
                ) {
                  const initialRoot = this.mapRoot.get();
                  this.mapRoot.requireEquals(initialRoot);
                
                  incrementAmount.assertLt(Field(10));
                
                  // Check the initial state matches what we expect
                  const [rootBefore, key] = keyWitness.computeRootAndKey(valueBefore);
                  rootBefore.assertEquals(initialRoot);
                
                  key.assertEquals(keyToChange);
                
                  // Compute the root after incrementing
                  const [rootAfter, _] = keyWitness.computeRootAndKey(valueBefore.add(incrementAmount));
                
                  // Set the new root
                  this.mapRoot.set(rootAfter);
                }
                ```
                
        3. **Interacting with the Smart Contract**: Similar to Merkle Trees, you interact with Merkle Maps by getting the witness for the key you want to update, and then sending the update to the smart contract.
            
            * **Example of Interacting with the Map**:
                
                ```plaintext
                tsCopyEditconst map = new MerkleMap();
                
                const rootBefore = map.getRoot();
                
                const key = Field(100);
                
                const witness = map.getWitness(key);
                
                // Update the smart contract with the new value for the key
                const txn1 = await Mina.transaction(deployerAccount, async () => {
                  await zkApp.update(
                    contract.update(
                      witness,
                      key,
                      Field(50),  // Previous value
                      Field(5)    // Increment value
                    )
                  );
                });
                ```
                
        
        #### Use Cases for Merkle Maps:
        
        1. **Key-Value Store**:  
            You can implement a key-value store, such as a mapping of public keys to booleans (for token accounts) or other types of data.
            
        2. **Nullifiers**:  
            Merkle Maps can be used to privately track whether an input has been used (e.g., in voting systems), without revealing the value of the input.
            
        
        for more information:[https://docs.minaprotocol.com/zkapps/tutorials/common-types-and-functions](https://docs.minaprotocol.com/zkapps/tutorials/common-types-and-functions)
