Skip to main content

SmartContract Basics

The SmartContract class is the foundation for building zkApps. It provides the framework for defining state, methods, and behavior of your zero-knowledge smart contracts.

Basic Structure

Every zkApp extends the SmartContract class and follows this basic pattern:

export class SimpleCounter extends SmartContract {
@state(Field) counter = State<Field>();

@method async increment() {
const currentCounter = this.counter.getAndRequireEquals();
this.counter.set(currentCounter.add(1));
}
}

Key components include state variables declared with @state(Type), an init() method for setup, and public methods marked with @method.

State Management

zkApps can have multiple state variables of different types:

export class MultiStateContract extends SmartContract {
@state(Field) counter = State<Field>();
@state(Bool) isActive = State<Bool>();
@state(UInt32) lastUpdate = State<UInt32>();

@method async updateState(newCounter: Field) {
// Check that contract is active
const active = this.isActive.getAndRequireEquals();
active.assertTrue();

// Update counter
this.counter.set(newCounter);

// Update timestamp
this.lastUpdate.set(UInt32.from(Date.now()));
}
}

State operations include get(), getAndRequireEquals(), set(), and requireEquals().

API Reference

For detailed information about the SmartContract class, see: