SmartContract

In the ZkFibonacci 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 SmartContract class.

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

Example from: AdvenTRUE

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 project.

Last updated