Tutorial 5: Common Types and Functions
In previous tutorials, you learned how to deploy smart contracts to the network and 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 includes a 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.
Open the example project in GitHub Codespaces. GitHub starts a container with Node.js 22 in the examples/zkapps/05-common-types-and-functions folder, installs the dependencies and builds the project. This takes some minutes. Then, in the terminal, run npm test. Some tests make proofs, and these tests take several minutes.
You must have a GitHub account. The codespace uses the free monthly quota of your account. Stop or delete the codespace when you are done.
Prerequisites
This tutorial has been tested with o1js version 3.0.0. o1js 3.0.0 requires Node.js 22.19.5 or later.
Ensure your environment meets the Prerequisites for zkApp Developer Tutorials.
Basic Types
Five basic types are derived from Fields:
Each type has the usual programming language semantics.
For example, the following code:
const num1 = UInt32.from(40);
const num2 = UInt64.from(40);
const num1EqualsNum2: Bool = num1.toUInt64().equals(num2);
console.log(`num1 === num2: ${num1EqualsNum2.toString()}`);
console.log(`Fields in num1: ${num1.toFields().length}`);
// --------------------------------------
const signedNum1 = Int64.from(-3);
const signedNum2 = Int64.from(45);
const signedNumSum = signedNum1.add(signedNum2);
console.log(`signedNum1 + signedNum2: ${signedNumSum}`);
console.log(`Fields in signedNum1: ${signedNum1.toFields().length}`);
// --------------------------------------
const char1 = Character.fromString('c');
const char2 = Character.fromString('d');
const char1EqualsChar2: Bool = char1.toField().equals(char2.toField());
console.log(`char1: ${char1}`);
console.log(`char1 === char2: ${char1EqualsChar2.toString()}`);
console.log(`Fields in char1: ${Character.toFields(char1).length}`);
This result prints to the console when the code is run:
num1 === 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
Four advanced types are:
All arguments passed into smart contracts must be arguments o1js can consume. You cannot pass normal strings. Instead, you must pass in strings that are wrapped to be compatible with circuits. This is accomplished with Struct.
The default CircuitString has a maximum length of 128 characters because o1js types must be fixed length. However, the CircuitString API abstracts this restriction away and can be used like a dynamic length string with the maximum length caveat.
You can create custom types to build your own strings, modified to whatever length you want.
A brief example of custom types:
const str1 = CircuitString.fromString('abc..xyz');
console.log(`str1: ${str1}`);
console.log(`Fields in str1: ${CircuitString.toFields(str1).length}`);
// --------------------------------------
const zkAppPrivateKey = PrivateKey.random();
const zkAppPublicKey = zkAppPrivateKey.toPublicKey();
const data1 = Character.toFields(char2).concat(signedNumSum.toFields());
const data2 = Character.toFields(char1).concat(CircuitString.toFields(str1));
const signature = Signature.create(zkAppPrivateKey, data2);
const verifiedData1 = signature.verify(zkAppPublicKey, data1).toString();
const verifiedData2 = signature.verify(zkAppPublicKey, data2).toString();
console.log(`private key: ${zkAppPrivateKey.toBase58()}`);
console.log(`public key: ${zkAppPublicKey.toBase58()}`);
console.log(`Fields in private key: ${zkAppPrivateKey.toFields().length}`);
console.log(`Fields in public key: ${zkAppPublicKey.toFields().length}`);
console.log(`signature verified for data1: ${verifiedData1}`);
console.log(`signature verified for data2: ${verifiedData2}`);
console.log(`Fields in signature: ${signature.toFields().length}`);
And the console output:
str1: abc..xyz
Fields in str1: 128
private key: EKEkySvJhQexHr2NEb3iKHe5czTMDnMwzRbTwp2MAuCJKuCGoy3B
public key: B62qpkeBN4rCyP5wCj4FDh7AHuDLn2gnaxFUXGZNteRgWSBrqrfiqpX
Fields in private key: 2
Fields in public key: 2
signature verified for data1: false
signature verified for data2: true
Fields in signature: 3
Observe and follow best practices for your key security. Make sure that you never use the private key in this example output, or any private key that's publicly accessible, in a real application.
toFields() gives 2 Fields for a private key and 3 Fields for a signature, as the output shows. Inside a circuit, the elliptic curve scalars in a private key and a signature are most efficiently represented as an array of bits, and the bit length of these scalars is 255.
Struct
You can create your own compound data types with the special Struct type. For more about structs, see Structs in the o1js documentation.
Define a Struct as one or more data types that o1js understands. For example, Field, higher-order types built into o1js based on Field, or other Struct types defined by you. You can also define methods on your Struct to act upon this data type.
The following example demonstrates how to use Struct to implement a Point structure and an array of points of length 8 structure.
In o1js, programs are compiled into fixed-sized circuits. This means that data structures it consumes must also be a fixed size.
To meet the fixed-size requirement, this code declares the array in Points8 structure to be a static size of 8.
class 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)}`);
class 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)}`);
The console output:
pointSum Fields: 11,6
points8 JSON: {"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"}]}
Control Flow
Two functions help do control flow in o1js:
-
Provable.if Similar to a ternary in JavaScript
-
Provable.switch Similar to a switch case statement in JavaScript
You can write conditionals inside o1js with these functions.
For example:
const 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}`);
console.log(`inputSumAbs: ${inputSumAbs}`);
const 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}`);
With output:
inputSum: -5
inputSumAbs: 5
largest: 22
Both branches are executed when using Provable.if, like in a JavaScript ternary. Because o1js is creating a zk circuit, there is no primitive for if statements where only one branch is executed.
Assertions and Constraints
o1js functions are compiled to generate circuits.
When a transaction is proven in o1js, the proof is that the program logic is computed according to the written program, and all assertions are holding true.
In previous tutorials, you learned a.assertEquals(b). The .assertTrue() is available on the Bool class.
Circuits in o1js have a fixed maximum size. Each operation performed in a function counts towards this maximum size. This maximum size is equivalent to:
- about 5,200 hashes on two fields
- about 2,600 hashes on four fields
- about
2^17field multiplies - about
2^17field additions
If a program is too large to fit into these constraints, it can be broken up into multiple recursive proof verifications. See Recursion.
Merkle Trees
You can use Merkle trees to manage large amounts of data within a circuit. The power of Merkle trees is demonstrated in the 05-common-types-and-functions/src reference project for this tutorial. See the BasicMerkleTreeContract.ts contract and main.ts that demonstrates how contracts interact with Merkle trees and how to construct them.
The first step is to import MerkleTree:
import {
...
MerkleTree,
...
} from 'o1js'
To create Merkle trees in your application:
const height = 20;
const tree = new MerkleTree(height);
The height variable determines how many leaves are available to the application. For example, a height of 20 leads to a tree with 2^(20-1), or 524,288 leaves.
Merkle trees in smart contracts are stored as the hash of the Merkle tree's root. Smart contract methods that update the Merkle root can take a witness of the change as an argument. A witness represents the Merkle path to the data for which inclusion is being proved. For a Merkle tree, the MerkleWitness function creates a witness class for a tree height, such as MerkleWitness20 in the contract below. For more about Merkle trees in o1js, see Merkle Trees in the o1js documentation.
A contract stores the root of a Merkle tree, where each leaf stores a number, and the smart contract has an update function that adds a number to the leaf.
For example, to put a condition on a leaf update, the update function checks that the number added was less than 10:
class MerkleWitness20 extends MerkleWitness(20) {}
export class BasicMerkleTreeContract extends SmartContract {
@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.assertLessThan(Field(10));
// check the initial state matches what we expect
const rootBefore = leafWitness.calculateRoot(numberBefore);
rootBefore.assertEquals(initialRoot);
// compute the root after incrementing
const rootAfter = leafWitness.calculateRoot(
numberBefore.add(incrementAmount)
);
// set the new root
this.treeRoot.set(rootAfter);
}
}
The code to interact with the smart contract:
// initialize the zkapp
const zkApp = new BasicMerkleTreeContract(basicTreeZkAppAddress);
await BasicMerkleTreeContract.compile();
// create a new tree
const height = 20;
const tree = new MerkleTree(height);
class MerkleWitness20 extends MerkleWitness(height) {}
// deploy the smart contract
const deployTxn = await Mina.transaction(deployerAccount, async () => {
// 1 Mina fee is required to create a new account for the zkApp
// This line means the deployer account will pay the fee for any account created in this transaction
AccountUpdate.fundNewAccount(deployerAccount);
await zkApp.deploy();
// get the root of the new tree to use as the initial tree root
await zkApp.initState(tree.getRoot());
});
await deployTxn.prove();
deployTxn.sign([deployerKey, basicTreeZkAppPrivateKey]);
const pendingDeployTx = await deployTxn.send();
/**
* `txn.send()` returns a pending transaction with two methods - `.wait()` and `.hash`
* `.hash` returns the transaction hash
* `.wait()` automatically resolves once the transaction has been included in a block. this is redundant for the LocalBlockchain, but very helpful for live testnets
*/
await pendingDeployTx.wait();
const incrementIndex = 522n;
const incrementAmount = Field(9);
// get the witness for the current tree
const witness = new MerkleWitness20(tree.getWitness(incrementIndex));
// update the leaf locally
tree.setLeaf(incrementIndex, incrementAmount);
// update the smart contract
const txn1 = await Mina.transaction(senderPublicKey, async () => {
await zkApp.update(
witness,
Field(0), // leafs in new trees start at a state of 0
incrementAmount
);
});
await txn1.prove();
const pendingTx = await txn1
.sign([senderPrivateKey])
.send();
await pendingTx.wait();
// compare the root of the smart contract tree to our local tree
console.log(
`BasicMerkleTree: local tree root hash after send1: ${tree.getRoot()}`
);
console.log(
`BasicMerkleTree: smart contract root hash after send1: ${zkApp.treeRoot.get()}`
);
In this example, leaves are fields. However, you can put more variables in a leaf by hashing an array of fields and setting a leaf to that hash.
This complete example is in the project directory.
A more advanced example LedgerContract implements a basic ledger of tokens, including checks that the sender has signed their transaction and that the amount the sender has sent matches the amount the receiver receives.
Merkle Map
See the API reference documentation for the MerkleMap class you can use to implement key-value stores.
The API for Merkle Maps is similar to Merkle Trees, just instead of using an index to set a leaf, one uses a key:
const map = new MerkleMap();
const key = Field(100);
const value = Field(50);
map.set(key, value);
console.log(`value for key ${key}: ${map.get(key)}`);
Which prints:
value for key 100: 50
It can be used inside smart contracts with a witness, similar to Merkle trees:
export class BasicMerkleMapContract extends SmartContract {
@state(Field) mapRoot = State<Field>();
@method async initState(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.assertLessThan(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);
}
}
The code to interact with it is similar to the Merkle tree example above:
const map = new MerkleMap();
const rootBefore = map.getRoot();
const key = Field(100);
// deploy the smart contract with the root of the empty map
const deployTxn = await Mina.transaction(deployerAccount, async () => {
AccountUpdate.fundNewAccount(deployerAccount);
await zkapp.deploy();
await zkapp.initState(rootBefore);
});
await deployTxn.prove();
await deployTxn.sign([deployerKey, basicMapZkAppPrivateKey]).send();
// get the witness for the key, then update the value locally
const witness = map.getWitness(key);
map.set(key, Field(5));
// update the smart contract
const txn1 = await Mina.transaction(deployerAccount, async () => {
await zkapp.update(
witness,
key,
Field(0), // keys in a new map start at a value of 0
Field(5)
);
});
await txn1.prove();
await txn1.sign([deployerKey]).send();
// compare the root of the smart contract map to our local map
console.log(`BasicMerkleMap: local map root after update: ${map.getRoot()}`);
console.log(
`BasicMerkleMap: smart contract root after update: ${zkapp.mapRoot.get()}`
);
The witness proves both the old value and the key. The contract rejects a witness for a different key, so a caller cannot change the value of one key with a witness for another key.
You use MerkleMaps to implement many useful patterns. For example:
- A key-value store from public keys to booleans, for example to record whether each account has voted yet.
- A nullifier that privately tracks if an input was used, without revealing it.
In o1js 3.0.0, MerkleMap is still exported and is not marked as deprecated. But IndexedMerkleMap does the same job with fewer constraints, and it can prove that a key is not in the map. Use MerkleMap only when existing code or an existing root on chain depends on it.
Provable data structures
A circuit has a fixed size. Thus, a smart contract method cannot take a JavaScript array or a JavaScript Map of any length. A method can take only a provable type: a type that o1js can convert to a fixed number of field elements. o1js 3.0.0 has these provable data structures:
- A fixed-size array, made with
Provable.Array(type, length)or with aStruct, such asPoints8in Struct. DynamicArray: an array with a fixed capacity and a length that can change.MerkleList: a list of any length, which the circuit sees as one hash.MerkleTreeandMerkleWitness: values at index positions. See Merkle Trees.MerkleMapandMerkleMapWitness: values by key. See Merkle Map.IndexedMerkleMap: values by key, with fewer constraints thanMerkleMap.
A commitment is one field element, such as a hash or a Merkle root, that identifies all of the data. Usually, a smart contract stores only the commitment in its on-chain state. The caller keeps the full data off chain and gives it to the method as an argument. The method makes sure that the data agrees with the commitment on chain, changes the data, and stores the new commitment.
Which structure for which job
The rows column shows the size of the circuit of each method in the example project. It is the number that analyzeMethods() reports in o1js 3.0.0. A method that only sets one state field, such as initState, takes 614 rows. Thus, most of the rows of a small method do not come from the data structure.
| Structure | Use it when | Size limit | What the method gets | What goes on chain | Rows in the example |
|---|---|---|---|---|---|
Provable.Array, Struct | You always have exactly n values. | n, fixed | all n values | the values, or their hash | not measured |
DynamicArray | You have from 0 to capacity values, and the method reads all of them or reads by index. | capacity less than 216 | all capacity slots and the length | nothing, or a hash that you calculate | addAll: 742, pick: 707 (capacity 8) |
MerkleList | You have a list of unknown length that a method reads in order, for example a queue of tasks. | no limit on the list; forEach(n) reads at most n elements | 1 field: the hash | the hash | push: 628, pop: 628, sum: 686 (4 steps) |
MerkleTree | You have values at index positions. | 2(height-1) leaves | a witness of height - 1 hashes | the root | update: 1,307 (height 20) |
MerkleMap | Existing code uses it. | height fixed at 256 | a witness | the root | update: 10,591 |
IndexedMerkleMap | You need values by key, or you must prove that a key is not in the map. | 2(height-1) leaves, height at most 52 | 2 fields, plus the map data as an unconstrained value | the root | insert: 2,621, update: 1,613 (height 33) |
An unconstrained value is data that the prover gives to the circuit without a proof. The method must check it against a constrained value, for example against the root on chain.
IndexedMerkleMap
An IndexedMerkleMap is a key-value map in a Merkle tree. Each leaf holds a key, a value, and the next larger key in the map. Thus, the leaves make a sorted linked list. Because of this list, the map can prove that a key is not in the map: it shows the leaf with the next smaller key, and that leaf points to a larger key.
In o1js 3.0.0, import IndexedMerkleMap directly from o1js. It is not in the Experimental namespace. Make a class for one height:
const indexedMap = new Map33();
indexedMap.insert(100n, 50n);
console.log(`value for key 100: ${indexedMap.get(100n)}`);
console.log(`key 101 is in the map: ${indexedMap.getOption(101n).isSome}`);
console.log(`Fields in Map33: ${Map33.provable.sizeInFields()}`);
try {
indexedMap.insert(100n, 51n);
} catch {
console.log('second insert of key 100: rejected');
}
The output:
value for key 100: 50
key 101 is in the map: false
Fields in Map33: 2
second insert of key 100: rejected
These are the rules of the map:
- A new map contains the key
0with the value0. This entry uses one of the 2(height-1) leaves. insert(key, value)fails if the key is already in the map.update(key, value)fails if the key is not in the map. It returns the old value.set(key, value)does an insert or an update. It costs more constraints thaninsert()orupdate().get(key)fails if the key is not in the map.getOption(key)returns anOption: a provable type with anisSomeBool and avalue.isSomeis false if the key is not in the map. Thenvalueis unconstrained, so read it withorElse(default). The o1js API reference says thatgetOption()takes about two times the constraints ofget().map.rootis the hash of the internal Merkle root and the number of entries. Storemap.rooton chain.
The map goes into a smart contract method as an argument. The contract stores only the root:
// A map with 2^(33-1) leaves. The initial key 0 uses one leaf.
export class Map33 extends IndexedMerkleMap(33) {}
export class IndexedMerkleMapContract extends SmartContract {
// Only the root goes on chain. The map data stays with the caller.
@state(Field) mapRoot = State<Field>();
init() {
super.init();
this.mapRoot.set(new Map33().root);
}
// Add a new key. Fails if the key is already in the map.
@method async insert(map: Map33, key: Field, value: Field) {
// Change a copy. The method body can run more than one time for
// each transaction, and a change to `map` itself also changes the
// map of the caller.
const copy = map.clone();
this.mapRoot.requireEquals(copy.root);
copy.insert(key, value);
this.mapRoot.set(copy.root);
}
// Change the value of a key. Fails if the key is not in the map.
@method async update(map: Map33, key: Field, value: Field) {
const copy = map.clone();
this.mapRoot.requireEquals(copy.root);
copy.update(key, value);
this.mapRoot.set(copy.root);
}
}
The method changes a clone() of the map, not the argument. In o1js 3.0.0, Mina.transaction() can run the method body more than one time, and the argument shares its unconstrained data with the map of the caller. If the method changes the argument, the first run adds the key to the data of the caller but not to its root. The second run then fails with Invalid low node (root). The tests of the example project find this error.
The caller sends the transaction, and then makes the same change to its own map:
// init() sets the root of an empty map on chain
const deployTxn = await Mina.transaction(deployerAccount, async () => {
AccountUpdate.fundNewAccount(deployerAccount);
await zkApp.deploy();
});
await deployTxn.prove();
await deployTxn.sign([deployerKey, zkAppPrivateKey]).send();
// the caller keeps the full map
const map = new Map33();
// insert on chain, then make the same change to the local map
const txn1 = await Mina.transaction(deployerAccount, async () => {
await zkApp.insert(map, Field(100), Field(50));
});
await txn1.prove();
await txn1.sign([deployerKey]).send();
map.insert(100n, 50n);
// update on chain, then locally
const txn2 = await Mina.transaction(deployerAccount, async () => {
await zkApp.update(map, Field(100), Field(51));
});
await txn2.prove();
await txn2.sign([deployerKey]).send();
map.update(100n, 51n);
console.log(
`IndexedMerkleMap: local root equals contract root: ${map.root.equals(
zkApp.mapRoot.get()
)}`
);
The output:
IndexedMerkleMap: local root equals contract root: true
MerkleList
A MerkleList is a list that the circuit sees as one hash. Each push() hashes the old hash with the new element. popExn() removes the element that was pushed last, so the list is a stack. Because the method gets only the hash, the list can have any length.
Use a MerkleList when:
- The length of the data is not known when you write the contract.
- The method reads the elements in order, not by index.
forEach(n, callback) always takes n steps, so its cost is n times the cost of one step. It fails if the list has more than n elements. After the last element, the callback gets dummy elements with isDummy set to true.
const list = FieldList.empty();
list.push(Field(1));
list.push(Field(2));
list.push(Field(3));
console.log(`list elements: ${list.toArrayUnconstrained().get()}`);
console.log(`Fields in the list: ${FieldList.provable.sizeInFields()}`);
console.log(`popExn: ${list.popExn()}`);
The output:
list elements: 1,2,3
Fields in the list: 1
popExn: 3
popExn() fails on an empty list. pop() does not fail on an empty list: it returns a dummy element. popOption() returns an Option.
A contract that keeps the hash of a list on chain:
export class FieldList extends MerkleList.create(Field) {}
// The number of steps that `sum` takes. A longer list fails.
export const MAX_SUM_LENGTH = 4;
export class MerkleListContract extends SmartContract {
// Only the hash of the list goes on chain. The elements stay with the caller.
@state(Field) listHash = State<Field>();
@state(Field) lastPopped = State<Field>();
@state(Field) total = State<Field>();
init() {
super.init();
this.listHash.set(FieldList.empty().hash);
}
@method async push(list: FieldList, element: Field) {
// Change a copy, for the same reason as in IndexedMerkleMapContract.
const copy = list.clone();
this.listHash.requireEquals(copy.hash);
copy.push(element);
this.listHash.set(copy.hash);
}
// Remove the element that was pushed last. Fails if the list is empty.
@method async pop(list: FieldList) {
const copy = list.clone();
this.listHash.requireEquals(copy.hash);
this.lastPopped.set(copy.popExn());
this.listHash.set(copy.hash);
}
// Add up all elements in MAX_SUM_LENGTH steps.
@method async sum(list: FieldList) {
this.listHash.requireEquals(list.hash);
let total = Field(0);
list.clone().forEach(MAX_SUM_LENGTH, (element, isDummy) => {
total = total.add(Provable.if(isDummy, Field(0), element));
});
this.total.set(total);
}
}
Each method changes a clone() of the list for the same reason as in the IndexedMerkleMap contract. Without the clone, the hash of the list of the caller stays the same, but its elements change.
const deployTxn = await Mina.transaction(deployerAccount, async () => {
AccountUpdate.fundNewAccount(deployerAccount);
await zkApp.deploy();
});
await deployTxn.prove();
await deployTxn.sign([deployerKey, zkAppPrivateKey]).send();
const list = FieldList.empty();
for (const element of [Field(5), Field(7)]) {
const txn = await Mina.transaction(deployerAccount, async () => {
await zkApp.push(list, element);
});
await txn.prove();
await txn.sign([deployerKey]).send();
list.push(element);
}
const sumTxn = await Mina.transaction(deployerAccount, async () => {
await zkApp.sum(list);
});
await sumTxn.prove();
await sumTxn.sign([deployerKey]).send();
console.log(`MerkleList: contract total: ${zkApp.total.get()}`);
The output:
MerkleList: contract total: 12
DynamicArray
A DynamicArray has a fixed capacity and a length from 0 to the capacity. The circuit always holds all capacity slots plus one field for the length. The slots after the length can hold any value that the prover gives.
Use a DynamicArray when:
- The data is short and its length changes, for example from 0 to 8 scores.
- The method must read elements by index, or must read all elements.
A read at a variable index adds one constraint for each slot, so the cost grows with the capacity. For long data, use a MerkleList or a Merkle tree.
const scores = Scores.from([UInt32.from(3), UInt32.from(4), UInt32.from(5)]);
console.log(`length: ${scores.length}, capacity: ${scores.capacity}`);
console.log(`Fields in Scores: ${Scores.provable.sizeInFields()}`);
console.log(`element at index 2: ${scores.get(Field(2))}`);
The output:
length: 3, capacity: 8
Fields in Scores: 9
element at index 2: 5
get(i) fails if i is not less than the length. Scores.from() fails for more elements than the capacity.
A contract that takes a DynamicArray as an argument:
// Between 0 and 8 scores. The circuit always holds 8 slots.
export class Scores extends DynamicArray(UInt32, { capacity: 8 }) {}
// When o1js 3.0.0 builds the circuit (compile(), analyzeMethods(), prove()),
// it copies each SmartContract method argument. The copy of a DynamicArray
// loses its private fields, and forEach() and get() then throw "Cannot read
// private member". Make a new array from the copy before you use it.
function rebuild(scores: Scores) {
return new Scores(scores.array, scores.length);
}
export class DynamicArrayContract extends SmartContract {
@state(UInt32) total = State<UInt32>();
@state(UInt32) picked = State<UInt32>();
// Add up the real elements. The callback also sees the empty slots,
// with isDummy set to true.
@method async addAll(scores: Scores) {
let total = UInt32.zero;
rebuild(scores).forEach((score, isDummy) => {
total = total.add(Provable.if(isDummy, UInt32.zero, score));
});
this.total.set(total);
}
// Store the element at `index`. Fails if `index` is not less than the length.
@method async pick(scores: Scores, index: Field) {
this.picked.set(rebuild(scores).get(index));
}
}
forEach() gives each slot with an isDummy flag. addAll adds 0 for a dummy slot. Without this check, a prover can put any value in a slot after the length, and that value goes into the total.
const txn = await Mina.transaction(deployerAccount, async () => {
await zkApp.addAll(scores);
});
await txn.prove();
await txn.sign([deployerKey]).send();
console.log(`DynamicArray: contract total: ${zkApp.total.get()}`);
The output:
DynamicArray: contract total: 12
Not on this page
o1js 3.0.0 has more provable types that hold data. This tutorial does not show them:
BytesandUInt8: fixed-size byte arrays for hash functions such as SHA-256 and Keccak.Experimental.OffchainStateandExperimental.BatchReducer: APIs that keep a map or a list off chain and settle it with actions. See Tutorial 6 for off-chain storage.
Test it
The example project in this repository carries two test suites for the code on this page:
cd examples/zkapps/05-common-types-and-functions
npm install
npm test
CommonTypes.test.ts asserts each value that the console-output blocks on this
page print, from num1 === num2: true to value for key 100: 50. It also runs
three contracts on a local blockchain:
BasicMerkleTreeContractaccepts an increment of9and rejects an increment of10. After an update, the contract root and the local tree root are equal.BasicMerkleMapContractadds5to key100and rejects an increment of10and a witness for a different key. After an update, the contract root and the local map root are equal.LedgerContractmoves12to an existing recipient and to a new recipient. It rejects a transfer signed by a different key, a transfer of the full balance, and a new recipient that claims a balance that is not0.
DataStructures.test.ts covers the provable data structures:
IndexedMerkleMaprejects a second insert of the same key, an update of a missing key,get()of a missing key, more keys than 2(height-1) leaves, and a height of 53.IndexedMerkleMapContractkeeps the same root as the local map, does not change the map of the caller, and rejects a map that does not match the root on chain. Its methods take at least 4 times fewer rows than theMerkleMapupdate.MerkleListContractpops the element that was pushed last, adds up a list of 3 elements, and rejects a pop from an empty list, a sum of a list longer thanMAX_SUM_LENGTH, and a list that does not match the hash on chain.DynamicArrayContractadds up only the real elements, also when the empty slots hold other values, and rejects an index that is not less than the length.Scores.from()rejects more elements than the capacity.
main.ts compiles all six contracts and creates real proofs, so it takes
several minutes. The test suites turn proofs off and are much faster.
Conclusion
Congratulations! You have finished reviewing more common types and functions in o1js. With this, you should now be capable of writing many advanced smart contracts and zkApps.
To use more data from your zkApp, check out Tutorial 6 to learn how to use off-chain storage.