Docs
Network & Transaction APIs

Network & Transaction APIs

Each runtime method has access to the current execution context, which provides access to the following APIs: network and transaction. Both of these allow you to tap into information about the current transaction execution, such as the current block height or the transaction sender.

Network API

The network API provides in-runtime method access to the observed network state. Following APIs are available under this.network within a runtime method:

  • Current block height
  • Previous block's state root hash
balances.ts
import {
  RuntimeModule,
  runtimeModule,
  state,
  runtimeMethod,
} from "@proto-kit/module";
import { StateMap, assert } from "@proto-kit/protocol";
import { MintProof } from './mint-proof'
import { PublicKey } from "o1js";
import { UInt64 } from "@proto-kit/library"
 
interface BalancesConfig {
  totalSupply: UInt64;
}
 
@runtimeModule()
export class Balances extends RuntimeModule<BalancesConfig> {
  @state() public balances = StateMap.from(PublicKey, UInt64);
 
  @runtimeMethod()
  public mint(address: PublicKey, amount: UInt64) {
    assert(
      UInt64.from(this.network.block.height).lessThanOrEqual(UInt64.from(1000)),
      "Minting ended at block height #1000"
    );
    this.balances.set(address, amount);
  }
 
  @runtimeMethod()
  public mintPrivate(proof: MintProof, amount: UInt64) {
    assert(this.network.previous.rootHash.equals(proof.publicOutput.rootHash), "Proof is not valid");
  }
}

Transaction API

The transasction API offers access to the information about the transaction which invoked the current runtime method. You can access the following information about the transaction:

  • sender
  • nonce
  • methodId
  • argsHash

The methodId and argsHash are used by the runtimeMethod decorator to prove that the runtime method execution was authorized by the transaction sender.

balances.ts
import {
  RuntimeModule,
  runtimeModule,
  state,
  runtimeMethod,
} from "@proto-kit/module";
import { assert, StateMap } from "@proto-kit/protocol";
import { PublicKey } from "o1js";
import { UInt64 } from "@proto-kit/library"
 
@runtimeModule()
export class Balances extends RuntimeModule<Record<string, never>> {
  @state() public balances = StateMap.from(PublicKey, UInt64);
 
  @runtimeMethod()
  public mint(address: PublicKey, amount: UInt64) {
    assert(
      this.transaction.sender.value.equals(address),
      "Minting can only be done by the owner of the address"
    );
    this.balances.set(address, amount);
  }
}