Skip to main content

Basic Tutorials for Developers: Step by Step

Published 27 min readMarkdown

The zkApp developer tutorials make available a hands-on walk-through of use cases to guide you in achieving a defined goal.

o1js, earlier known as SnarkyJS, is a TypeScript (TS) library for writing general-purpose zk programs and zk smart contracts for Mina.

To connect with other developers working on zkApps with o1js, join the #zkapps-developers channel on the Mina Protocol Discord.

Prerequisites​

Each tutorial has been tested with the latest versions:

[if !supportLists]· [endif]zkApp CLI

[if !supportLists]· [endif]o1js

o1js is automatically included when you create a project using the zkApp CLI.

[if !supportLists]· [endif]Other dependencies as noted.

Install the zkApp CLI​

To install the zkApp CLI:

$ npm install -g zkapp-cli

To confirm successful installation:

$ zk --version

Dependencies​

To use the zkApp CLI and o1js, your environment requires:

  • NodeJS v18 and later

  • NPM v10 and later

  • git v2 and late

    Tutorial 1: Hello World

    This Hello World tutorial guides you through getting started with o1js, zkApps, and programming using zero-knowledge proofs.

    In this step-by-step tutorial, you will learn to develop a zkApp from start to finish.

    You will:

    • Write a basic smart contract that maintains a number as on-chain state.

    • Implement contract logic that allows this number to be updated only by squaring it (e.g., 3 → 9 → 81, etc.).

    • Create a project using the zkApp CLI.

    • Write your smart contract code.

    • Utilize a simulated local Mina blockchain to interact with your smart contract.

Later tutorials present additional concepts and patterns.

The complete source code for this tutorial can be found in the examples/zkapps/01-hello-world directory on GitHub. While you're there, consider starring the /docs2 repository to help other zk developers discover how to build a zkApp!

Prerequisites​

Ensure your environment meets the Prerequisites for zkApp Developer Tutorials.

In particular, make sure you have the zkApp CLI installed:

    $ npm install -g zkapp-cliI've reconstructed your instructions while maintaining the original meaning. Let me know if you need any refinements!

Create a new project

Now that you have the tooling installed, you can start building your application.

  1. Create or change to a directory where you have write privileges.

  2. Now, create a project using the zk project command:

    The output shows these results:

     $ zk project 01-hello-world
    

The zk project command has the ability to scaffold the UI for your project. For this tutorial, select none:

    ? Create an accompanying UI project too? …
      next
      svelte
      nuxt
      empty
    > none

The expected output is:

    ✔ 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 01-hello-world
      git remote add origin <your-repo-url>
      git push -u origin main

The zk project command generates the 01-hello-world directory, which includes the foundational structure for your project, along with tools like the Prettier code formatting tool, the ESLint static code analysis tool, and the Jest JavaScript testing framework.

  • Change into the 01-hello-world directory and list the contents:

      $ cd 01-hello-world
      $ ls
    

    The output shows these results:

      LICENSE
      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
    

    For this tutorial, you run commands from the root of the 01-hello-world directory as you work in the src directory on files that contain the TypeScript code for the smart contract. Each time you make updates, then build or deploy, the TypeScript code is compiled into JavaScript in the build directory.

    Prepare the project​

    Start by deleting the default files that come with the new project.

    1. To delete the old files:

       $ rm src/Add.ts
       $ rm src/Add.test.ts
       $ rm src/interact.ts
      
    2. Now, create the new files for your project:

       $ zk file src/Square
       $ touch src/main.ts
      

The zk file command created the src/Square.ts and src/Square.test.ts test files.

This tutorial does not include writing tests, so you just use the main.ts file as a script to interact with the smart contract and observe how it works.

In later tutorials, you learn how to interact with a smart contract from the browser, like a typical end user.

  1. Now, open src/index.ts in a text editor and change it to look like:
    1 import { Square } from './Square.js';

    2 export { Square };

The src/index.ts file contains all of the exports you want to make available for consumption from outside your smart contract project, such as from a UI.

Write the zkApp Smart Contract
Now, the fun part! Write your smart contract in the src/Square.ts file.

Line numbers are provided for convenience. A final version of the smart contract is provided in the Square.ts example file.

This part of the tutorial walks you through the Square smart contract code already completed in the src/Square.ts example file.

Copy the example
This tutorial describes each part of the completed code in the Square.ts example file.

First, open the Square.ts example file.

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​

The import statement brings in other packages and dependencies to use in your smart contract.

    1 import {
    2   Field,
    3   SmartContract,
    4   state,
    5   State,
    6   method,
    7 } from 'o1js';

These items are:

  • 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. All other o1js-compatible types are built on top of field elements.

  • SmartContract: The class that creates zkApp smart contracts.

  • State: A convenience decorator used in zkApp smart contracts to create references to state stored on-chain in a zkApp account.

  • State: A class used in zkApp smart contracts to create state stored on-chain in a zkApp account.

  • method: A convenience decorator used in zkApp smart contracts to create smart contract methods like functions. Methods that use this decorator are the end user's entry points to interacting with a smart contract.

    Smart Contract Class​

    Now, review the smart contract in the src/Square.ts file.

    The smart contract called Square has one element of on-chain state named num of type Field as defined by following code:

      8
      9 export class Square extends SmartContract {
      10   @state(Field) num = State<Field>();
      11
      12 }
    

zkApps can have up to eight fields of on-chain state. Each field stores up to 32 bytes (technically, 31.875 bytes or 255 bits) of arbitrary data. A later tutorial covers options for off-chain state.

Now, this code adds the init method to set up the initial state of the smart contract on deployment:

    8
    9 export class Square extends SmartContract {
    10   @state(Field) num = State<Field>();
    11
    12   init() {
    13     super.init();
    14     this.num.set(Field(3));
    15   }

Since this code extends SmartContract, which has its own initialization to perform, calling super.init() invokes this function on the base class.

Then, this.num.set(Field(3)) initializes the on-chain state num to a value of 3.

You can optionally specify permissions. See setPermissions in the o1js Reference documentation.

Finally, this code adds the update() function:

    14     this.num.set(Field(3));
    15   }
    16
    17   @method async update(square: Field) {
    18     const currentState = this.num.get();
    19     this.num.requireEquals(currentState);
    20     square.assertEquals(currentState.mul(currentState));
    21     this.num.set(square);
    22   }
    23 }

The function name update is arbitrary, but it makes sense for this example. Notice how the @method decorator is used because it is intended to be invoked by end users using a zkApp UI, or as in this case, the main.ts script.

This method contains the logic by which end users are allowed to update the zkApp's account state on-chain.

A zkApp account is an account on the Mina blockchain where a zkApp smart contract is deployed. A zkApp account has a verification key associated with it.

In this example, the code specifies:

  • If the user provides a number (for example, 9) to the update() method that is the square of the existing on-chain state referred to as num (for example, 3), then update the num value that is stored on-chain to the provided value (in this case, 9).

  • If the user provides a number that does not meet these conditions, they are unable to generate a proof or update the on-chain state.

These update conditions are accomplished by using assertions within the method. When a user invokes a method on a smart contract, all assertions must be true to generate the zero-knowledge proof from that smart contract. The Mina network accepts the transaction and updates the on-chain state only if the attached proof is valid. This assertion is how you can achieve predictable behavior in an off-chain execution model.

  • A smart contract retrieves the on-chain account state when it is first invoked if at least one get() exists within it.

  • Similarly, using set() changes the transaction to indicate that changes to this particular on-chain state are updated only when the transaction is received by the Mina network if it contains a valid authorization (usually, a valid authorization is a proof).

    The logic also uses the .mul() method for multiplication of the values stored in Field types. You can view all available methods in the o1js Reference documentation.

    You remember that functions in your smart contract must operate on o1js-compatible data types: Field types and other types built on top of Field types. Because a smart contract is really a zero-knowledge circuit, functions from random npm packages work inside a smart contract only if the functions the contract provides operate on o1js-compatible data types.

    Importantly, data passed as an input to a smart contract method in o1js is private and never seen by the network.

    You can also store data publicly on-chain when needed, like num in this example. A later tutorial covers an example that leverages privacy.

    Congratulations, you have reviewed the complete smart contract code.

    Interact with a smart contract​

    Next, write a script that interacts with your smart contract. As before, the complete main.ts example file is provided. Follow these steps to build the main.ts file so you can interact with the smart contract.

    Imports​

    For this tutorial, the import statement brings in items from o1js that you use to interact with your smart contract.

    1. Copy the following lines from main.ts example file into the src/main.ts file:

       1 import { Square } from './Square.js';
       2 import { Field, Mina, PrivateKey, AccountUpdate } from 'o1
      
      • Field: The same o1js unsigned integer type that you learned earlier.

      • Mina: A simulated local Mina blockchain to deploy the smart contract to so you can interact with it as a user would.

      • PrivateKey: A class with functions for manipulating private keys.

      • Account Update: A class that generates a data structure that can update zkApp accounts.

Simulated Local Blockchain

Using a simulated local blockchain speeds up development and tests the behavior of your smart contract locally. Later tutorials cover how to use a lightweight Mina network (Lightnet) to test your zkApp before you deploy to live networks.

To initialize your simulated local blockchain, add the following code from the main.ts example 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;

Tip: To preserve line numbers in your local main.ts file, add blank lines as needed after you copy the code snippets.

This simulated local blockchain provides pre-funded accounts. Add these lines to create local test accounts with test MINA (tMINA) to use 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();

Build and run the smart contract
Now that the Square smart contract is complete, these commands run your project as a simulated local blockchain.To compile the TypeScript code into JavaScript:

            $ npm run build

To run the JavaScript code:

            $ node build/src/main.js

You have the option to combine these commands into one line:

            npm run build && node build/src/main.js
  • The npm run build command creates JavaScript code in the build directory.

  • The && operator links two commands together. The second command runs only if the first command is successful.

  • The node build/src/main.js command runs the code in src/main.ts.

    Initialize your smart contract

    To initialize your smart contract, add more code from the main.ts example file to the src/main.ts file.

    All smart contracts that you create with the zkApp CLI use similar code:

    • Create a public/private key pair; the public key is an address on the Mina network where you deploy the zkApp to.

    • Create an instance of your smart contract Square and deploy it to zkAppAddress.

    • Get the initial state of Square after deployment.

      Comments break down each stage:

        21
        22 // create an instance of Square - and deploy it to zkAppAddress
        23 const zkAppInstance = new Square(zkAppAddress);
        24 const deployTxn = await Mina.transaction(deployerAccount, async () => {
        25   AccountUpdate.fundNewAccount(deployerAccount);
        26   await zkAppInstance.deploy();
        27 });
        28 await deployTxn.sign([deployerKey, zkAppPrivateKey]).send();
        29
        30 // get the initial state of Square after deployment
        31 const num0 = zkAppInstance.num.get();
        32 console.log('state after init:', num0.toString());
      

      Try running this command again:

        $ npm run build && node build/src/main.js
      

      The expected output is:

        > 01-hello-world@0.1.0 build
        > tsc
      
        state after init: 3
      

      Update your zkApp account with a transaction​

      To update your local zkApp account with a transaction, add the following code to the src/main.ts file:

        33
        34 // ----------------------------------------------------
        35
        36 const txn1 = await Mina.transaction(senderAccount, async () => {
        37   await zkAppInstance.update(Field(9));
        38 });
        39 await txn1.prove();
        40 await txn1.sign([senderKey]).send();
        41
        42 const num1 = zkAppInstance.num.get();
        43 console.log('state after txn1:', num1.toString());
      

      This code creates a new transaction that attempts to update the field to the value 9. Because of the rules in the update() function that is called on the smart contract, this command succeeds when you run it again:

        $ npm run build && node build/src/main.js
      

      The expected output is:

        > 01-hello-world@0.1.0 build
        > tsc
      
        state after init: 3
        state after txn1: 9
      

      Add a transaction that fails
      It's time to do some testing. To add a transaction that fails, add more code from the main.ts example file to the src/main.ts file.

      The contract logic allows the number that is stored as on-chain state to be replaced only by its square. Now that num is in state 9, updating is possible only with 81.

      ​To test a failure, add these next lines of code from the src/main.ts file and change the state to 75 in zkAppInstance.update(Field(75)):

        44
        45 // ----------------------------------------------------
        46
        47 try {
        48   const txn2 = await Mina.transaction(senderAccount, async () => {
        49     await zkAppInstance.update(Field(75));
        50   });
        51   await txn2.prove();
        52   await txn2.sign([senderKey]).send();
        53 } catch (error: any) {
        54   console.log(error.message);
        55 }
        56 const num2 = zkAppInstance.num.get();
        57 console.log('state after txn2:', num2.toString());
      

Try running this command again:

            $ npm run build && node build/src/main.js

The expected output is:

            > 01-hello-world@0.1.0 build
            > tsc

            state after init: 3
            state after txn1: 9
            Field.assertEquals(): 75 != 81
            state after txn2: 9

And finally, be sure to change your main.ts file to include the correct update to change the state to 81 in zkAppInstance.update(Field(81)).

Run this command again:

            $ npm run build && node build/src/main.js

The expected output is:

            > 01-hello-world@0.1.0 build
            > tsc

            state after init: 3
            state after txn1: 9
            state after txn2: 81

Follow along​

You can follow along in this video as cryptographer, David Wong, learns how to code a Hello World project.

The video is provided for educational purposes and uses earlier versions of the zkApp CLI and o1js, so there are some differences. The Hello World tutorial always uses the most recent version of the zkApp CLI and o1js.

https://youtu.be/prx2oNpy0vo

Tutorial 2: Private Inputs and Hash Functions

In the Hello World tutorial, you built a basic zkApp smart contract with o1js with a single state variable that could be updated if you knew the square of that number.

In this tutorial, you learn about private inputs and hash functions.

With a zkApp, a smart contract user's local device generates one or more zero knowledge proofs, which are then verified by the Mina network. Each method in an o1js smart contract corresponds to constructing a proof.

All inputs to a smart contract are private by default. Inputs are never seen by the blockchain unless you store those values as on-chain state in the zkApp account.

In this tutorial, you build a smart contract with a piece of private state that can be modified if a user knows the private state.

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. Create or change to a directory where you have write privileges.

  2. Create a project by using the zk project command:

            $ zk project 02-private-inputs-and-hash-functions

The zk project command has the ability to scaffold the UI for your project. For this tutorial, select none:

            ? Create an accompanying UI project too? …
              next
              svelte
              nuxt
              empty
            > none

The expected output is:

            ✔ 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

The zk project command creates the 02-private-inputs-and-hash-functions directory that contains the scaffolding for your project, including tools such as the Prettier code formatting tool, the ESLint static code analysis tool, and the Jest Javascript testing framework.

  1. Change into the 02-private-inputs-and-hash-functions directory and list the contents:

     $ cd 02-private-inputs-and-hash-functions
     $ ls
    

    The output shows these results:

     LICENSE
     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
    

For this tutorial, you run commands from the root of the 02-private-inputs-and-hash-functions directory as you work in the src directory on files that contain the TypeScript code for the smart contract.

Each time you make updates, then build or deploy, the TypeScript code is compiled into JavaScript in the build directory.

Prepare the project​

Start by deleting the default files that come with the new project.

  1. To delete the default generated files:

     $ rm src/Add.ts
     $ rm src/Add.test.ts
     $ rm src/interact.ts
    
  2. Now, create the new files for your project:

     $ zk file src/IncrementSecret
     $ touch src/main.ts
    

    The zk file command created the src/IncrementSecret.ts file and the src/IncrementSecret.test.ts test file.
    However, this tutorial does not include writing tests, so you just use the main.ts file as a script to interact with the smart contract and observe how it works.

  3. Now, open src/index.ts in a text editor and change it to look like:

     import { IncrementSecret } from './IncrementSecret.js';
    
     export { IncrementSecret };
    

    The src/index.ts file contains all of the exports you want to make available for consumption from outside your smart contract project, such as from a UI.

Copy the example files

This tutorial relies on the completed code in the 02-private-inputs-and-hash-functions/src/ example files.

  1. First, open the IncrementSecret.ts example file.

  2. Copy the entire contents of the file into your smart contract in the IncrementSecret.ts file.

  3. Next, open the main.ts example file.

  4. the entire contents of the file into your smart contract in the main.ts file.

Now you are ready to review the imports in the smart contract.

Write the smart contract

Now we'll build the smart contract for our application.

Imports
The import statement in the IncrementSecret.ts file brings in other packages and dependencies to use in your smart contract.

            1 import { Field, SmartContract, state, State, method, Poseidon } from 'o1js';

Exports​

The smart contract called IncrementSecret has one element of on-chain state named x of type Field as defined by following code:

            ...
              3 export class IncrementSecret extends SmartContract {
              4  @state(Field) x = State<Field>();
              5 }

This code adds the basic structure for the smart contract. You are familiar with the import and export code from Tutorial 01: Hello World.

Initial State​

The initState() method is intended to run once to set up the initial state on the zkApp account.

            ...
              5
              6   @method async initState(salt: Field, firstSecret: Field) {
              7     this.x.set(Poseidon.hash([ salt, firstSecret ]));
              8   }

The initState() method accepts your secret and adds a salt value.

These inputs to the initState() method are private to whoever initializes the contract. The zkApp account on the chain does not reveal what the values firstSecret or salt actually are.

Update the State​

This method updates the state:

            ...
              9
             10   @method async incrementSecret(salt: Field, secret: Field) {
             11     const x = this.x.get();
             12     this.x.requireEquals(x);
             13
             14     Poseidon.hash([ salt, secret ]).assertEquals(x);
             15     this.x.set(Poseidon.hash([ salt, secret.add(1) ]));
             16   }
             17 }

Mina uses the Poseidon hash function that is optimized for fast performance inside zero knowledge proof systems. The Poseidon hash function takes in an array of Fields and returns a single Field as output.

This smart contract uses a secret number and the second Field, salt.

The incrementSecret() method checks that the hash of the salt and the secret is equal to the current state x:

  • If this is the case, add 1 to the secret and set x to the hash of the salt and this new secret.

  • o1js creates a proof of this fact and a JSON description of the state updates to be made on the zkApp account, such as to store the new hash value.

Together, this forms a transaction that can be sent to the Mina network to update the zkApp account.

Because zkApp smart contracts are run off-chain, your salt and secret remain private and are never transmitted anywhere.

Only the result, updating x on-chain state to hash([salt, secret + 1]), is revealed. Because the salt and secret can't be deduced from their hash, they remain private.

About the salt argument

Cryptographic salt adds an additional layer of security to a smart contract. The extra salt argument prevents a possible attack on the smart contract. If you just use the secret, the contract is vulnerable to discovery by an attacker. An attacker could try hashing likely secrets and then check if the hash matches the hash stored in the smart contract. If the hash were to match, then the attacker knows they have discovered the secret. This scenario is particularly concerning if the secret is likely to be within a particular subset of possible values, say between 1 and 10,000. In that case, with just 10,000 hashes, the attacker could discover the secret.

Adding salt as a second input to the contract code makes it harder for an attacker to reverse engineer the code and gain access to the contract. Salt makes the contract more secure and helps protect the data stored within it. For optimal security, the salt is known only to you and is typically random.

Main​

The src/main.ts file is similar to the Hello World tutorial. For a full version, see main.ts.

For this tutorial, the key parts to discuss are initializing our contract and using the poseidon hash.

The smart contract initialization this time is:

            ...
             24 const salt = Field.random();
            ...
             28 const deployTxn = await Mina.transaction(deployerAccount, async () => {
             29   AccountUpdate.fundNewAccount(deployerAccount);
             30   await zkAppInstance.deploy();
             31   await zkAppInstance.initState(salt, Field(750));
             32 });
             33 await deployTxn.prove();
            ...

Note that the initState() method accepts the salt and the secret. In this case, the secret is the number 750.

This code creates a user transaction to update the on-chain state:

            ...
             42 const txn1 = await Mina.transaction(senderAccount, async () => {
             43   await zkAppInstance.incrementSecret(salt, Field(750));
             44 });
            ...

Call the zkApp smart contract using both the salt and the secret, which is the number 750.

Since zkApp smart contracts execute locally, neither the secret nor the salt are included in the transaction.

Instead, the transaction contains only the proof that the update was executed correctly, ensuring all assertions passed and the on-chain state xx was updated where the hash value is stored. Once processed by the Mina network, xx becomes the value of Poseidon.hash([salt,Field(750).add(1)])\text{Poseidon.hash}([ \text{salt}, \text{Field}(750).add(1) ]). The underlying salt and secret remain undisclosed.

Try running main:

            $ npm run build && node build/src/main.js

The output looks something like this:

            state after init: 3116464240601550031577632290308565252747064306168758166756574536757280262269
            state after txn1: 15333363135506653312218020664441564145350761288169575380089681962972642150348

The state strings are different because Field.random() generates the salt.

Conclusion​

Congratulations! You built a smart contract that uses privacy and hash functions.

To deploy zkApps to a live network, see Tutorial 3: Deploy to a Live Network.

Tutorial 3: Deploy to a Live Network

In the 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 cover transaction fees, and deploy the zkApp to a live network.

This tutorial builds upon the Square contract you created in Tutorial 1: Hello World.

Prerequisites​

This tutorial has been tested with:

Ensure your environment meets the Prerequisites for zkApp Developer Tutorials.

If you have earlier versions of the zkApp CLI and o1js installed, be sure to Update the zkApp CLI to the latest version:

            npm update -g zkapp-cli

Create a project​

  1. Create or change to a directory where you have write privileges.

  2. Create a project by using the zk project command:

     $ 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:

     ? Create an accompanying UI project too? …
       next
       svelte
       nuxt
       empty
     > none
    

    The expected output is:

     ✔ 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 03-deploying-to-a-live-network
       git remote add origin <your-repo-url>
       git push -u origin main
    

The zk project command generates the 03-deploying-to-a-live-network directory, which provides the foundational structure for your project. This directory includes essential development tools such as Prettier for code formatting, ESLint for static code analysis, and Jest for JavaScript testing.

  1. Navigate to the 03-deploying-to-a-live-network directory.

For this tutorial, run commands from the root of the 03-deploying-to-a-live-network directory while working on TypeScript files in the src directory, which contain the smart contract code.

Each time you make updates and then build or deploy, the TypeScript code is compiled into JavaScript in the build directory.

Prepare the project​

Start by deleting the default files that come with the new project.

  1. Delete the default generated files:

     $ rm src/Add.ts
     $ rm src/Add.test.ts
     $ rm src/interact.ts
    
  2. Copy the src/Square.ts and src/index.ts files from the files of the first tutorial 01-hello-world/src to your local 03-deploying-to-a-live-network/src directory. If prompted, replace existing files.

Now that your smart contract is in place, you are ready to deploy your zkApp to Devnet.

zkApp CLI

You installed the zkApp CLI as part of the prerequisites, so you already have the necessary tools to manage deployments.

In some cases, you may need to:

  • Create a custom account for your zkApp.

  • Programmatically parameterize a zkApp before initializing it.

  • Generate a smart contract programmatically for users as part of an application.

For more details, refer to Interacting with zkApps server-side.

Deploy the Smart Contract

The config.json file contains the configuration required to deploy your zkApp. This file was automatically created when scaffolding the project using the zk project command.

However, the generated configuration file does not initially include a deploy alias.

Deploy Alias

The zk config command provides interactive prompts to help you create a deploy alias in your project's config.json file.

You can have one or more deploy aliases for your project. Each deploy alias consists of:

  • A self-descriptive name – Helps differentiate multiple deploy aliases.

  • The target network kind – Specifies whether it's for Testnet, Mainnet, or a custom network.

  • The Mina GraphQL API URL – Defines the network receiving your deploy transaction and broadcasting it to the appropriate Mina network (Testnet, Devnet, Mainnet, etc.).

  • The transaction fee (in MINA) – The amount used when deploying.

  • Two key pairs:

    • zkApp account key pair – Public and private keys stored in keys/<deploy-alias-name>.json, used for the zkApp.

    • Fee payer account key pair – Public and private keys stored locally, which can be reused across multiple projects.

Fee Payer Account Alias

A fee payer account is required for deployments and updates. You can either:

  • Use an existing fee payer account.

  • Create a new fee payer account during setup.

  1. To configure your deploy alias, run the zk config command and respond to the prompts:
            $ zk config

For this tutorial on Devnet, use:

  • Deploy alias name: devnet

    This tutorial uses devnet, but the deploy alias name can be anything and does not have to match the network name.

  • Target network kind: Testnet

  • Mina GraphQL API URL: https://api.minascan.io/node/devnet/v1/graphql

  • Transaction fee to use when deploying (in MINA): 0.1

    1. When prompted to choose an account to pay transaction fees, select:
                Use a different account (select to see options)

If this is the first time you are running the zk config command, you see these options:

                > Recover fee payer account from an existing base58 private key
                Create a new fee payer key pair

A third option to choose another saved fee payer account is shown only if you have multiple cached fee payer accounts.

  1. Select to create a new fee payer key pair:
                Create a new fee payer key pair
                NOTE: the private key will be stored in plain text on this computer.

Please mind the note above and do not use the fee payer account that holds a substantial amount of MINA.

  1. When prompted, give an alias to your new fee payer key pair. For this tutorial, use 03-deploy:
                ✔ Create an alias for this account · 03-deploy

Your key pairs and deploy alias are created:

            ✔ Create fee payer key pair at ${HOME}/.cache/zkapp-cli/keys/03-deploy.json
            ✔ Create zkApp key pair at keys/devnet.json
            ✔ Add deploy alias to config.json

            Success!

            Next steps:
              - If this is the testnet, request tMINA at:
                https://faucet.minaprotocol.com/?address=<FEE-PAYER-ACCOUNT>
              - To deploy zkApp, run: `zk deploy devnet`
  1. Request funds from the Testnet Faucet to fund your fee payer account.

    Follow the prompts to request tMINA. To get funds on the Devnet, use the URL that was shown in the zkApp CLI output:

Before proceeding to the next step, wait a few minutes for the next block to include your transaction, so that tMINA becomes available for the fee payer account.

  1. To deploy your project execute the following command:
                $ zk deploy
  1. At the interactive prompt, select the devnet deploy alias:
                ? Which deploy alias would you like to deploy to? …
                > devnet

A verification key for your smart contract is generated (takes 10-30 seconds).

The deploy process is output:

                ✔ Build project
                ✔ Generate build.json
                ✔ Choose smart contract
                  Only one smart contract exists in the project: Square
                  Your config.json was updated to always use this
                  smart contract when deploying to this deploy alias.
                ✔ Generate verification key (takes 10-30 sec)
                ✔ Build transaction
  1. Review and confirm the details of the transaction:
                ✔ Confirm to send transaction

                  |-----------------|-------------------------------------------------|
                  | Deploy alias    | devnet                                          |
                  |-----------------|-------------------------------------------------|
                  | Network kind    | testnet                                         |
                  |-----------------|-------------------------------------------------|
                  | URL             | https://api.minascan.io/node/devnet/v1/graphql  |
                  |-----------------|-------------------------------------------------|
                  | Fee payer       | Alias         : 03-deploy                       |
                  |                 | Account       : B62...                          |
                  |-----------------|-------------------------------------------------|
                  | zkApp           | Smart contract: Square                          |
                  |                 | Account       : B62...                          |
                  |-----------------|-------------------------------------------------|
                  | Transaction fee | 0.1 Mina                                        |
                  |-----------------|-------------------------------------------------|

When prompted, type yes to confirm and send the transaction to the network.

                ✔ Send to network

                Success! Deploy transaction sent.

                Next step:
                  Your smart contract will be live (or updated)
                  at B62...
                  as soon as the transaction is included in a block:
                  https://minascan.io/devnet/tx/<txn-hash>?type=zk-tx
  1. You can follow the transaction link provided in the zkApp CLI output to see the zkApp transaction and navigate the accounts involved. Alternatively, use the Minascan explorer to search for the account with the deployed zkApp."

    The meaning remains unchanged, but the structure is slightly refined for clarity. Let me know if you prefer a more exact reconstruction!

Success

After the transaction is included in a block, your smart contract is deployed!

The Mina account used to deploy the zkApp now contains the verification key associated with this smart contract.
You ran the zk config command to:

  • Create a deploy alias

  • Create a fee payer key pair at ${HOME}/.cache/zkapp-cli/keys/03-deploy.json

  • Create a zkApp key pair at keys/devnet.json"

"You requested tMINA to fund your fee payer account and pay your deploy transaction fees. Use the remaining tMINA to keep building and testing.

You ran the zk deploy command to:

  • Generate a verification key for your smart contract

  • Add and send the deploy transaction to the network"

Congratulations!

To test, configure, and deploy your zkApp on a local representation of the Mina blockchain, see Testing zkApps with Lightnet.

About the Smart Contract Transactions

Because this tutorial used the smart contract from Tutorial 1: Hello World, the smart contract's editState permissions require that the transaction must contain a valid zk proof created by the private key associated with this zkApp account.

When a user interacts with this smart contract by providing a proof, the proof is generated locally on the user's device and included in a transaction.
When the transaction is submitted to the network, the proof is checked to ensure it is correct and matches the on-chain verification key.
After the transaction is accepted, the proof and transaction are recursively proved and bundled into Mina's recursive zero-knowledge proof.
When you change the smart contract code, the associated verification key also changes. Use the same steps to redeploy your zkApp.

For a typical smart contract, permissions are set to only allow proof authorization. You will learn more about setting permissions in the later tutorials."

Video​

Watch this tutorial for a step-by-step guide and extra explanations on how to deploy a zkApp.

https://youtu.be/Sj9lTmgjDXY

For more information: https://docs.minaprotocol.com/zkapps/tutorials

No comments yet. Be the first to comment.

More from this blog