Mina Developer Book
  • What is this book about?
  • Module 1
    • Introduction
    • Why ZK?
    • Mathematics of Zero-Knowledge Proofs
    • OPTIONAL: Advanced Resources
  • Module 2
    • zkFibonacci
    • Mina Protocol
    • o1js
      • SmartContract
      • ZkProgram
      • AccountUpdate
      • Merkle Tree
    • End-to-End zkApp development
      • Mastermind introduction
      • Building the zkApp
      • Testing environment
  • Next steps
  • New to blockchain pack
Powered by GitBook
On this page
  1. Module 2
  2. o1js

SmartContract

Previouso1jsNextZkProgram

Last updated 11 months ago

In the part, you've seen the use of smart contaacts and how to settle some proof to the chain.

class MyContract extends SmartContract

Any contract you'll write is an extension of the class.

Properties of smart contracts are explained pretty well in the , hence we don't need to write them all again.

Example from:

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

export class Quest extends SmartContract {
  @state(Field) commitment = State<Field>();

  @method async init() {
    super.init();
    this.commitment.set(Field(0));
  }

  @method async initialize(commitment: Field) {
    // ensure commitment is not yet set
    this.commitment.requireEquals(Field(0));

    // set the commitment
    this.commitment.set(commitment);
  }

  @method async solve(solution: Field, prize_receiver: PublicKey) {
    this.account.balance.requireEquals(this.account.balance.get());
    const currentState = this.commitment.getAndRequireEquals();

    // check if user knows the solution
    currentState.equals(Poseidon.hash([solution])).assertTrue();

    // proceed with the withdrawal
    this.send({ to: prize_receiver, amount: this.self.account.balance.get() });
  }
}

Example above is simple: There is an on-chain state that has Field type. After initialization of contract with init, it is 'initialized' with the value user feeds.

Solve function give checks if the on-chain value of the balance of the zkApp account is same with the environment. Also, current state of the commitment is ensured to be same with the environment. Later, solution is given as a hash and prize is sent to the receiver.

Do you remember that SmartContract based classes are compiled to zkCircuits? This requireEquals , getAndRequireEquals functions and functions like that are converted to some constraints that form zk Circuits.

You can see other parts of the .

ZkFibonacci
SmartContract
Mina Docs
AdvenTRUE
project