# O1js: TypeScript library for zkApp development

# **Introduction to o1js**

ZKP Labs Vietnam hosted a workshop on o1js, a powerful TypeScript library for zk-SNARKs and zkApps designed by O(1) Labs. Led by Chiro8x, founder of Orochi Network, and David from Mina Foundation, the workshop delved deep into the functionalities and applications of o1js in the Mina ecosystem.

# What are zkApps?

  
zkApps (zero knowledge apps) are Mina Protocol smart contracts that utilize zero knowledge proofs, specifically zk-SNARKs.

zkApps operate using an off-chain execution and mostly off-chain state model. This design enables private computation and allows the state to be either private or public.

zkApps can carry out arbitrarily complex computations off-chain, requiring only a flat fee to send the resulting zero knowledge proof to the chain for verification. This approach offers cost savings compared to other blockchains, which execute computations on-chain and rely on a variable gas-fee model.

# What is TypeScript?

JavaScript and More

TypeScript adds additional syntax to JavaScript to support a **tighter integration with your editor**. Catch errors early in your editor.

A Result You Can Trust

TypeScript code converts to JavaScript, which **runs anywhere JavaScript runs**: In a browser, on Node.js, Deno, Bun and in your apps.

Safety at Scale

TypeScript understands JavaScript and uses **type inference to give you great tooling** without additional code.

# **TypeScript**

  
zkApps are written in TypeScript.

TypeScript offers an accessible and familiar language (JavaScript) while incorporating type safety, making it straightforward to begin developing zkApps. If you're new to TypeScript, you can explore this helpful 12-minute introductory video: *TypeScript - The Basics*.

# **How zkApps Work**

  
zkApps run in the latest versions of Chrome, Firefox, Edge, and Brave web browsers.

They are written in TypeScript using the zkApp CLI.

A zkApp is made up of two components:

1. A **smart contract**
    
2. A **user interface (UI)** for users to interact with the zkApp.:
    

# **Zero knowledge-based smart contracts**

  
zkApps are based on zero knowledge proofs (zk-SNARKs). As a zkApp developer, you use the zkApp CLI to scaffold and deploy your project.

\[if !supportLists\]3.      \[endif\]Provable code is written using o1js and generates a prover function and a corresponding verifier function that are derived during the build process.

\[if !supportLists\]4.      \[endif\]The prover function is the function that executes a smart contract's custom logic and runs in an end user's web browser as part of the zkApp. The prover function generates a proof of the executed code.

\[if !supportLists\]5.      \[endif\]When interacting with a zkApp UI, users enter any data (for example, buy ABC for y price) that is required as input to the prover function, which then generates a zero knowledge proof.

# **Private and Public Inputs**

  
Private and public inputs represent data that must be provided to the prover function when it runs in the end user's web browser.

* **Private inputs** are not required again.
    
* **Public inputs** must also be provided to the verifier function when it runs on the Mina network. Public inputs should not be used for data that needs to remain private.
    

The **verifier function** validates whether a zero knowledge proof successfully passes all the constraints defined in the prover function. The verifier function always runs quickly and efficiently, irrespective of the prover function's complexity.

Within the **Mina network**, Mina acts as the verifier and runs the verifier function.

# **Prover Function and Verification Key**

  
After you write a smart contract, build it by running the npm run build command. The build process compiles the TypeScript code into JavaScript and outputs the smart\_contract.js file.

From this file, you can:

* Run a prover function to execute your smart contract.
    
* Generate a verification key to deploy your smart contract.
    

While the prover function runs in an end user's web browser, the verification key lives on-chain for a given zkApp account and is used by the Mina network to verify that a zero knowledge proof has met all constraints defined in the prover. A verification key is required to create a zkApp account.

You can also use the verifier function or verification key to verify proofs off-chain.

# **Deploy a smart contract**

  
zkApp developers use the zkApp CLI to deploy smart contracts to the Mina network. The deployment process sends a transaction that contains the verification key, which is an output of the verifier function, to an address on the Mina blockchain.

# **Deploy a zkApp UI**

  
A zkApp consists of a smart contract and a UI to interact with it.

To enable users to interact with your smart contract in a web browser, you build a website UI and then deploy this interactive UI as a static website. Choosing a host that offers a global content delivery network (CDN) ensures the best experience for all users.

# **How users interact with a zkApp**

  
To use a zkApp, end users must install a wallet that supports interactions with zkApps.

After a zkApp is deployed to a host (for example, [mycoolzkapp.com](http://mycoolzkapp.com)), end users can interact with it:

1. The user visits [*mycoolzkapp.com*](http://mycoolzkapp.com).
    
2. The user interacts with the zkApp and enters the required data. For example, if this were an automated market maker, the user might specify to buy x amount of ABC at y price.
    
3. The prover function in the zkApp generates a zero knowledge proof locally using the data entered by the user. This data can be either:
    
    * **Private**: The data is never seen by the blockchain.
        
    * **Public**: The data is stored on-chain or off-chain, depending on what the zkApp specified as required for a given use case.
        
4. A list of state updates (called account updates) to be created by the transaction is generated. The account updates are associated with this proof.
    
5. The user selects *Submit to chain* in the zkApp UI.
    
6. The user confirms the transaction on their wallet.
    
7. The wallet signs the transaction containing the proof and the associated description of the state to update.
    
8. The wallet sends the transaction to the Mina network.
    
9. The Mina network receives this transaction and verifies that the proof successfully passes the verifier method listed on the zkApp account. If the network accepts this transaction, the proof and the requested state changes are valid and allowed to update the zkApp state.
    

The end user's privacy is maintained because their interaction occurs locally in a web browser using JavaScript on the client.

# **How state is updated on-chain**

  
The zkApp account gets updated on-chain.

When the prover function runs in a web browser, the smart contract outputs a proof and some associated data called "account updates" that are sent to a zkApp address as part of the transaction. The account updates are a JSON plain text description that describes how to update the state on a zkApp account.

The integrity of these account updates is ensured by passing a hash of the account updates as a public input to the smart contract. The account updates must be present and unmodified for the verification function to pass successfully when it runs on Mina. In this way, the Mina network can confirm the integrity of both the proof and the associated account updates that describe how to update the zkApp account state.

# **zkApp state**

* **On-chain state** describes state that lives on the Mina blockchain.
    
* **Off-chain state** describes state stored anywhere else.
    

---

# **On-chain state**

  
Each zkApp account provides 8 fields of 32 bytes each of arbitrary storage. You may store anything here as long as it fits in the size provided.

If you anticipate your state to be larger, or if the state accumulates per user with your zkApp, then use off-chain state instead.

---

# **Off-chain state**

  
For larger data, you might want to consider storing the root of a Merkle tree or a similar data structure within your zkApp's on-chain storage that references self-hosted off-chain state stored elsewhere. Mina doesn't offer an out-of-the-box solution for off-chain storage.

When the zkApp runs in a user's web browser, it can insert state to an external storage, such as IPFS. When the transaction is sent to the Mina network, if the network accepts this zkApp transaction and confirms the proof and state are valid, the zkApp transaction can update the root of the Merkle tree that is stored on-chain.

# **On-Chain Values**

  
In a zkApp, you can access the current on-chain state and many other on-chain values of the account.

The zkApp account's on-chain state can be updated by account updates included in a transaction (see Tutorial 10: Account Updates). On the Mina blockchain, each zkApp account provides eight fields of ~32 bytes each of arbitrary storage for the on-chain state.

---

**Two possible use cases**:

1. **Voting**: You want to let users vote on a proposal, but only within a specific timespan. To restrict the dates, your zkApp can require that the current timestamp lies in a certain range.
    
2. **DeFi**: You want to compute amounts relative to a balance. For example, paying a yield of 0.001 times the account balance requires the current on-chain balance.
    

---

There are two categories of on-chain values:

1. **Network**: Includes the current timestamp, block height, total Mina in circulation, and other network state.
    
2. **Account**: Includes fields and properties of the zkApp account, such as balance, nonce, and delegate.
    

In a smart contract, the subfields are accessible via [this.network](http://this.network) and this.account. For example, the timestamp on [this.network](http://this.network).timestamp has four methods:

# **The familiar on-chain state**

  
On-chain state values in zkApps provide the same familiar methods, such as get() and requireEquals().

Additionally, the requireBetween() method offers enhanced functionality, allowing you to assert that a timestamp lies between a specified lower and upper bound (inclusive).

---

**Example: Restricting timestamps**  
To use the requireBetween() method in a voting scenario, you can restrict voting to occur only during September 2024. Timestamps are represented as a UInt64 in milliseconds since the UNIX epoch. The JavaScript Date object can be used to easily convert human-readable dates into this representation.

In the simplest case, a zkApp can hard-code the dates:

**A more refined example**  
A more refined approach could store the current start date in an on-chain state variable. This start date can then be updated by a process encoded within the zkApp, allowing for more dynamic behavior based on use cases.

---

# **Network reference**

  
For completeness, here is a list of network states you can access and make assertions about in your zkApp.

All of these fields provide:

* **get()**: To retrieve the current value.
    
* **requireEquals()**: To assert that the value matches an expected value.
    

Additionally, fields that represent **ordered values** (such as those stored as UInt32 or UInt64) also support the requireBetween() method for range-based assertions.

# **Account reference**

  
Here is the complete list of values accessible on the zkApp account.

Like network states, these account values provide:

* **get()**: To retrieve the current value.
    
* **Require Equals()**: To assert that the value matches an expected value.
    

Additionally, **balance** and **nonce** support the **require Between()** method, enabling range-based assertions.

**Bailing out**  
In rare cases, you might want to retrieve an on-chain value using **get()** without placing any constraints on it. By default, o1js will throw a helpful error reminding you to use **require Equals()** or **require Between()** for constraint validation.

However, as an escape hatch, if you're absolutely certain you do not want to apply any constraints to the on-chain value, you can use **require**

**Nothing()** on all of these fields (including on-chain state).

---

**Danger**  
**require Nothing()** should be used sparingly, as it can introduce security risks through unexpected behavior if misused. It effectively bypasses the normal checks, which could lead to unintended consequences. Be absolutely certain of your intentions before using this method.

**Setting account fields**  
Just like on-chain state, some account fields can be written to. The API for setting these values is consistent with how you handle state: this.account.&lt;field&gt;.set(newValue).

For example, to change permissions on an account, you would use this method to set the desired new value:

javascript

CopyEdit

this.account.permissions.set(newPermissions);

This allows for modification of specific account properties, such as permissions or other fields, directly within the zkApp.

The fields that you can set are not the same as the fields that you can make assertions about.

Here is the full list of fields that have a .set():

* **delegate**: Sets the delegate public key for staking purposes.
    
* **permissions**: Sets the permissions for the account.
    
* **balance**: Sets the account balance (in some cases).
    
* **nonce**: Sets the nonce for the account.
    

Note: The specific fields that can be set might depend on the implementation of the zkApp and what permissions or changes are allowed for each account.

# **Accessing accounts other than the zkApp's account**

  
The API described in this section (e.g., get(), set(), assertEquals(), etc.) can be used not only to access the zkApp's own account but also any other account. Account updates are a flexible and powerful data structure that can express a variety of updates, events, and preconditions used in smart contract development. For more details, refer to **Tutorial 10: Account Updates**.

To create an account update to interact with the same account and network fields, you can:

javascript

CopyEdit

const accountUpdate = this.account.update();

accountUpdate.setField('fieldName', newValue);

This allows you to access and modify fields in other accounts, provided you have the necessary permissions and context to do so.

Account updates enable dynamic and complex interactions across accounts within the Mina ecosystem.

# **Offchain Storage**

  
One of Mina's unique features is its succinctness, both in computation and storage. To prevent state bloat and maintain Mina's efficiency and verifiability, offchain storage solutions are used to handle large volumes of data.

In a previous section, we introduced the concept of **on-chain values**. Since Mina currently supports a total of only 8 on-chain field elements, leveraging offchain storage is necessary to extend that capacity. This approach allows for efficient storage without compromising on security.

Offchain storage maintains a **provably secure connection** between the on-chain smart contract and the offchain data, such as that stored in an archive node. By storing larger datasets offchain, Mina ensures that the blockchain remains lightweight and efficient while still being able to reference and validate extensive data securely when needed.

# **Design**

  
Currently, offchain storage in Mina supports two types of state:

1. **OffchainState.Field**: Represents a single field of state.
    
2. [**OffchainState.Map**](http://OffchainState.Map): Similar to key-value maps found in JavaScript, like let myMap = new Map&lt;string, number&gt;();.
    

All offchain state resides within a single **Merkle Map**, which is essentially a wrapper around a Merkle Tree. Practically speaking, there are no limits on the number of state fields and maps that a developer can store in a smart contract using offchain storage.

**Utilizing Offchain Storage**  
**Prerequisites**  
The **OffchainState** API is accessible within the **Experimental** namespace. To use OffchainState, import **Experimental** from **o1js** version 1.9.1 or higher.

**Setting up Offchain Storage**  
To integrate Offchain storage, developers must first define an **Offchain state configuration** and a **state proof type**, and then prepare the smart contract.

* The **OffchainState configuration** allows the specification of the desired Offchain state type, including key-value pairs in a map and any additional required state.
    
* The **StateProof type** will then be used to finalize published state changes using a recursive reducer.
    
* The **OffchainStateInstance** stores internal data, such as the associated contract instance and the Merkle trees of data.
    

Developers also need to set the **smart contract instance** and assign it to the offchain storage. This process compiles the recursive **Offchain zkProgram** in the background and assigns the Offchain state to the smart contract instance property.

---

# **Framework for State Management**

  
Under this framework, **Actions** and **Reducers** are used to manage state changes:

* **Actions** dispatch state updates.
    
* **Reducers** settle these updates and finalize changes.
    

A **Merkle Tree** is employed to maintain a **provably secure commitment** to the data, with the root stored on-chain. This ensures that the integrity of offchain data is verifiable.

---

# **State Settlement**

  
Before users can access published state, it must first undergo **settlement**. Thanks to the design of offchain storage, all state is recoverable from actions alone, removing the need for additional events or external data storage. This makes state management both efficient and secure, with the guarantee that the state can be reconstructed and validated without relying on external systems.

# **Permissions**

  
Permissions are crucial in zkApp development as they define who has the authority to interact with and modify specific parts of a smart contract.

Proper permissions are essential to prevent attacks or security vulnerabilities. Permissions are stored on-chain, making them part of the account's representation on the network. They are verified every time an account update attempts to interact with an account.

**Types of Permissions**

There are 13 permissions that define and guard interactions with a zkApp account:

1. **editState**: Controls how the zkApp account's eight on-chain state fields can be manipulated.
    
2. **send**: Governs the ability to send transactions from the account, such as transferring MINA.
    
3. **receive**: Determines whether the account can receive transactions, such as deposits of MINA.
    
4. **setDelegate**: Manages the ability to set the delegate field, specifying another account to delegate the account’s MINA for staking.
    
5. **setPermissions**: Defines who can change the permissions of the account.
    
6. **setVerificationKey**: Regulates the ability to change the verification key used to verify off-chain proofs, essentially defining smart contract "upgradeability."
    
7. **setZkappUri**: Controls the ability to update the zkApp URI field, which stores metadata about the smart contract, like a source code link.
    
8. **editActionsState**: Allows changes to the actions state of the account, which commits dispatched actions on-chain.
    
9. **setTokenSymbol**: Governs the ability to set the token symbol associated with the account.
    
10. **incrementNonce**: Determines whether the nonce can be incremented via an account update and specifies who can perform this action.
    
11. **setVotingFor**: Controls the ability to set the chain hash for voting on a hard fork via the account's votingFor field.
    
12. **access**: Restricts any account updates for the account, including no-op updates. Typically, access requires no authorization, but for token manager contracts, it demands proof authorization.
    
13. **setTiming**: Manages the vesting schedule for time-locked accounts.
    

# **Authorization**

Authorization specifies what resources can be accessed, while permissions define who has the ability to perform actions.

A transaction is composed of multiple **account updates** (instructions to the network), each of which must be authorized. In o1js or a blockchain explorer, the **authorization field** of an account update indicates how it is authorized:

1. **Proof**: If the authorization field contains a proof, the transaction is authorized by a proof verified against the account's verification key.
    
2. **Signature**: If the authorization field contains a signature, the transaction is authorized by a signature.
    

**Types of Authorizations**

1. **none**: Fields with this permission can be accessed and manipulated by anyone without restriction.
    
2. **impossible**: Fields with this permission cannot be changed under any circumstances.
    
3. **signature**: Only account updates authorized by a valid signature can manipulate these fields.
    
4. **proof**: Only account updates authorized by a valid proof, generated by executing a smart contract method, can manipulate these fields. The proof is checked against the account's verification key to ensure correctness.
    
5. **proofOrSignature**: These permissions accept either a valid signature or a valid proof for authorization.
    

This example account update is authorized by a **signature**, and it attempts to update the app state of the smart contract.

However, if a smart contract's **editState** permission is set to **none**, anyone can change the state of the smart contract freely, which is highly insecure.

To restrict state changes, you should set the authorization to **proof**. This ensures that a valid proof accompanies any account update attempting to modify the state. The proof is checked against the account's verification key, guaranteeing that state changes occur only if the user has executed a smart contract method correctly and generated a valid proof.

When a smart contract is deployed, it begins with the following **default permissions**:

* **editState**: proof
    
* **send**: proof
    
* **receive**: none
    
* **setDelegate**: signature
    
* **setPermissions**: signature
    
* **setVerificationKey**: signature
    
* **setZkappUri**: signature
    
* **editActionsState**: proof
    
* **setTokenSymbol**: signature
    

To enhance the security of your smart contract, refer to examples illustrating how to configure and utilize permissions effectively.

An **UnsecureContract** example demonstrates how smart contracts managing state and tokens, such as the native MINA token, might inadvertently allow vulnerabilities. Without proper permission configurations, malicious actors could exploit the contract to withdraw all funds.

This type of example is often provided as a starting point to emphasize the importance of securing contracts through permissions. A similar example, **simple-zkapp-payment.ts**, can typically be found in the provided examples folder. It highlights the need to enforce secure configurations to protect against unauthorized access and fund manipulation.

The **UnsecureContract** example defines a withdraw() method that allows funds to be withdrawn from the smart contract account. However, the contract's init() method sets the send permission to Permissions.none(). This configuration is highly insecure because Permissions.none() allows anyone to interact with the contract without any form of authorization.

**Exploit Scenario**

With Permissions.none() for the send action, a malicious actor could construct and execute a transaction that drains all funds from the smart contract account. This happens because no signature or proof is required to authorize the transaction.

The following malicious transaction demonstrates how this vulnerability can be exploited:

* A malicious actor initiates a transaction to withdraw all funds.
    
* The network does not enforce any checks for authorization due to the Permissions.none() configuration.
    
* As a result, the attacker successfully drains the contract account.
    

**Lesson**

This example illustrates why setting Permissions.none() for critical actions like send or editState is a poor security practice. Instead, permissions should be configured more securely, such as using Permissions.proof() or Permissions.signature() to require proper authorization mechanisms for sensitive operations.

By changing the send permission to Permissions.signature() in the **UnsecureContract**, the vulnerability allowing unauthorized transactions is mitigated. Here's what happens after this change:

# **Updated Permission**

The send permission in the init() method is updated as follows:

javascript

CopyEdit

this.account.permissions.set({

  ...Permissions.default(),

  send: Permissions.signature(),

});

**Effects of the Change**

1. **Authorization Required:** The Permissions.signature() setting requires that any transaction attempting to send funds from the smart contract be signed by the private key of the smart contract account.
    
2. **Malicious Transaction Blocked:** The previous exploit, where a fee payer's private key authorized the transaction, will no longer work because the malicious transaction lacks the required signature from the smart contract account.
    
3. **Security Enhancement:** This ensures that only the entity in possession of the smart contract's private key can authorize transactions involving the send permission.
    

**Best Practices**

1. Use **appropriate permissions** to secure critical actions in your zkApp.
    
2. Regularly review permissions during development and testing to identify and address potential vulnerabilities.
    
3. Consider requiring **proof-based authorizations** (using Permissions.proof()) for complex or sensitive operations that need to enforce specific rules defined in the zkApp logic.
    

\[if !supportLists\]4.      \[endif\]The upgradeability of a smart contract on the Mina blockchain is directly tied to the `setVerificationKey` permission. The verification key, generated from the contract's source code, is stored on-chain and used for verifying proofs. To control whether the smart contract can be upgraded after deployment, you adjust the `setVerificationKey` permission.

#  **Allowing Upgradeability**

To allow a smart contract to be upgraded (i.e., the verification key can be changed), you set the `setVerificationKey` permission to `Permissions.signature()` or `Permissions.proof()` depending on how you want the upgrade process to be authorized. This means that after the contract is deployed, the contract's verification key can be modified by submitting a valid signature or proof.

### **Upgrading After an Update to the Mina Protocol**

When Mina Protocol undergoes a non-backwards compatible update, zkApps that were previously deployed might need to upgrade their verification key to stay compatible with the new protocol version. If a zkApp fails to upgrade its verification key, it won't be able to verify proofs, and as a result, it will no longer be able to interact with the network, essentially becoming non-functional.

To address this, Mina has special rules regarding the permissions for modifying the verification key (specifically the **Impossible** and **Proof** permissions) that allow zkApps to update their verification key even after a protocol update.

### **Permissions for Verification Key: Impossible and Proof**

\[if !supportLists\]·         \[endif\]**Impossible Permission**: Normally, if the **Impossible** permission is set for the verification key, it means the verification key cannot be changed under any circumstances. This is designed to lock the verification key for security reasons. However, in the case of a protocol update, the Impossible permission is automatically treated as **Signature** when the zkApp's transaction version is lower than the current protocol version. This allows the zkApp to update its verification key to remain compatible with the new protocol.

\[if !supportLists\]·         \[endif\]**Proof Permission**: If the **Proof** permission is set, it means that only a valid proof can change the verification key. Similarly, when a protocol update occurs and the zkApp's transaction version is outdated, the Proof permission is automatically treated as **Signature** to allow for the necessary verification key upgrade.

### **Verification Key Permissions Representation**

The permissions for the verification key are internally represented as a **tuple** consisting of two fields:

1. **Mechanism**: Defines how the verification key can be modified (e.g., Impossible, Signature, Proof).
    
2. **Transaction Version**: Specifies the version of the Mina Protocol that was in use when the zkApp's verification key was deployed. This version field ensures that the zkApp is properly aligned with the protocol version and can be upgraded when needed.
    
3. ZkApp Upgradability                                                                                                                  ZkApp Upgradability on Mina Protocol is unique because upgrades are essentially restricted to changes in the verification key, ensuring that the underlying logic of the smart contract does not change unexpectedly. This is a crucial distinction compared to other blockchains, where a contract upgrade could lead to unexpected behavior. On Mina, the contract logic remains consistent, and only the verification key is upgraded on-chain, allowing for a secure and predictable upgrade process.
    
    ### Key points:
    
    \[if !supportLists\]1.      \[endif\]**Permissions for Upgrades**: To upgrade a ZkApp, specific permissions related to the verification key must be configured. The `setVerificationKey` permission governs whether the verification key can be modified.
    
    \[if !supportLists\]2.      \[endif\]**Execution Model on Mina**: Mina's execution model ensures that users always interact with the same program, even after an upgrade. Unlike other blockchains, where upgrades may change the contract's behavior, Mina's upgrades only involve changes to the verification key, ensuring that users interact with the same program (but the newer, upgraded version) after the upgrade.
    
    \[if !supportLists\]3.      \[endif\]**Proof Compatibility**: When the verification key is changed, proofs generated with the previous key will no longer be valid. Users must download the new prover function (the program used to generate valid proofs) to continue interacting with the updated ZkApp.
    
    By adhering to this execution model and ensuring that only the verification key changes on-chain, Mina ensures that contract upgrades remain predictable, secure, and transparent for all users.
    
    ## Baseline ZkApp[​](https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#baseline-zkapp)
    
    For example, let's use our standard `Add` example smart contract as the baseline ZkApp.
    
    This contract has a verification key of `"27729068461170601362912907281403262888852363473424470267835507636847418791713"`
    
    ## Upgraded ZkApp[​](https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#upgraded-zkapp)
    
    For our upgraded contract, let's use this updated example which adds by 4 instead of by 2.
    
    This contract has a verification key of `"18150279532259194644722165513074833862035641840431153413486908511595437348455"`
    
    ## Upgrading a ZkApp[​](https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#upgrading-a-zkapp)
    
    Upgrading a ZkApp by signature can be done if you control the private key of a ZkApp. To do this, you need to sign a transaction that upgrades the ZkApp with that key.
    
    Imagine we have already deployed the `Add` contract, and we have the private key available as `zkAppKey`
    
    And just like that, when the transaction is applied to the blockchain, the verification key at the ZkApp address will be updated from `"27729068461170601362912907281403262888852363473424470267835507636847418791713"` to `"18150279532259194644722165513074833862035641840431153413486908511595437348455"`!
    
    ## Upgrades with More Surface Area[​](https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#upgrades-with-more-surface-area)
    
    In the previous example, we changed one small variable in the smart contract but kept the state and methods the same. However, there is no limit to what you can change via upgrade. Let's go through one more example where more things have changed.
    
    This new contract is more of a departure from our original design. It has an extra piece of state that tracks how many times it has been called, and it allows for different operands to be used in the addition. It is a valid upgrade path to go from `AddV1` to `AddV3`.
    
      
    When upgrading a ZkApp on Mina, it's important to remember the following:
    
    1. **State Order Consistency**: If you change the order of state variables in your upgraded contract, the upgrade will fail because the contract's state will no longer match the expected order. Mina depends on the exact layout of state variables to maintain consistency, so reordering them will break the upgrade process.
        
    2. **No State Reset**: The state of your deployed contract will **not be reset** upon upgrade. This means that the data stored in the contract's state will persist across upgrades, and the contract will continue from its previous state.
        
    3. **No Re-initialization**: The init function will **not be called** again during an upgrade. This is important because it means you cannot use the upgrade process to modify or reinitialize the state, except for updating the verification key.
        
    4. **Only Verification Key Changes**: The only aspect of the smart contract that will be directly
        
    
    # **Events**
    
    To use events in a ZkApp, you need to declare an `events` field in the smart contract. This field contains the names and types of the events that the contract can emit. Below is an example of how to define events in a smart contract:
    
    ```plaintext
    javascript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    // Declare an events field at the top level of the contract
    ```
    
    ```plaintext
    const events = {
    ```
    
    ```plaintext
      MessagePublished: Event({
    ```
    
    ```plaintext
        message: Field,
    ```
    
    ```plaintext
      }),
    ```
    
    ```plaintext
      StateUpdated: Event({
    ```
    
    ```plaintext
        stateRoot: Field,
    ```
    
    ```plaintext
      }),
    ```
    
    ```plaintext
    }
    ```
    
    In this example:
    
    \[if !supportLists\]1.      \[endif\]**Publishing Events**: Once events are declared in the contract, you can emit them using the `emit` keyword within the smart contract's methods. This attaches arbitrary information to the transaction that observers can use.
    
    \[if !supportLists\]2.      \[endif\]**Event Types**: Events can include various types like `Field`, which represents a basic data type, or more complex structures like a Merkle tree root.
    
    \[if !supportLists\]3.      \[endif\]**Off-Chain State**: If your contract only stores a commitment (such as the root of a Merkle tree) on-chain, you can use events to communicate the changes in full to off-chain participants. This helps keep the full state updated off-chain by sending the relevant changes (like Merkle leaf changes) as events.
    
    In essence, events serve as a way to carry additional information that is not stored directly on-chain but can still be observed and used by external parties, enhancing the interactivity and functionality of ZkApps.
    
    \[if !supportLists\]1.      \[endif\]**Event Types**: While `Field` is simple for basic data, you can also use custom types like `Struct` to create more complex event data. For example, for Merkle tree leaves, it would be better to define a custom `Struct` to hold all the relevant information.
    
    \[if !supportLists\]2.      \[endif\]**Custom Struct Example**:
    
    ```plaintext
    javascript
    ```
    
    ```plaintext
    CopyEdit
    ```
    
    ```plaintext
    const MerkleLeaf = Struct({
    ```
    
    ```plaintext
      leafData: Field,
    ```
    
    ```plaintext
      proof: Field,
    ```
    
    ```plaintext
    });
    ```
    
    ```plaintext
    // Use this in events
    ```
    
    ```plaintext
    const events = {
    ```
    
    ```plaintext
      "add-merkle-leaf": Event({
    ```
    
    ```plaintext
        leaf: MerkleLeaf,
    ```
    
    ```plaintext
      }),
    ```
    
    ```plaintext
      "update-merkle-leaf": Event({
    ```
    
    ```plaintext
        leaf: MerkleLeaf,
    ```
    
    ```plaintext
      }),
    ```
    
    ```plaintext
    };
    ```
    
    In this scenario, each event would now carry a `MerkleLeaf` struct containing the relevant data for each leaf, making the event much more useful for tracking changes to the Merkle tree.
    
    ### Conclusion:
    
    Events are a powerful tool for allowing off-chain observers to track changes in the smart contract's state. By using events like `add-merkle-leaf` and `update-merkle-leaf`, you can pass along valuable information with each transaction, ensuring that changes to things like a Merkle tree can be followed off-chain without needing to store all the tree data on-chain.
    
    Some important facts about events:
    
    * Events are not stored on-chain. Only events from the most recent couple of transactions are retained by consensus nodes. After that, the events are discarded, but are still accessible on archive nodes.
        
    * You can't refer to previously emitted events in a smart contract, because there is no way of proving that the events you refer to are actually the events emitted by that contract.
        
    
    # **Actions & Reducer**
    
    In zkApps, **actions** provide a powerful mechanism for handling state changes and interactions between users, going beyond what is possible with events. Here are some key concepts about actions and their use in zkApps:
    
    1. **Actions vs. Events**:
        
        * **Events** are used to emit information without interacting with the contract's internal state. They are not stored on-chain and cannot be referred to within a contract.
            
        * **Actions**, on the other hand, are used to change the state and can be processed in the smart contract. Unlike events, actions are tied to the contract’s state history and can be proven to have been dispatched, making them more powerful and versatile.
            
    2. **ActionState**:
        
        * Each account in a zkApp has an **actionState** that stores a history of actions dispatched to it. This enables the smart contract to process past actions, giving it the ability to work with a history of state changes.
            
        
        for more info: [https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/fetch-events-and-actions#events](https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/fetch-events-and-actions#events), [https://docs.minaprotocol.com/zkapps/writing-a-zkapp](https://docs.minaprotocol.com/zkapps/writing-a-zkapp)
