Save & Load State on Blockchain

For most blockchain gaming usages, we can think of the blockchain as a secure and permanent database.

This database is expensive to write, but relatively cheap to read.

We have seen we can generate proves, wether in OPZK or Zk only implementation of zkSpin. When writing the states to the blockchain, we'll need to provide those proves.

Reading Game State from the Chain

We are using WalletConnect's Web3Modal. The frontend wallet library does not matter. The example here is just trying to show what contracts and functions of the smart contracts are called.

import {
    SpinOPZKGameContractABI,
    getOnchainStatesWagmi
} from "@zkspin/lib";
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
import { getAccount, readContract } from "wagmi/actions";

export const config = createConfig({
  chains: [mainnet, sepolia],
  transports: {
    [mainnet.id]: http(),
    [sepolia.id]: http(),
  },
})

const GAME_CONTRACT_ADDRESS = <>;
const OPZK_GAME_ID = <>;
const STORAGE_STATE_SIZE = 2; // number of u64 in your GameState

export const getOnchainGameState = async () => {
    return getOnchainStatesWagmi(
        getAccount(config).address!,
        GAME_CONTRACT_ADDRESS,
        OPZK_GAME_ID,
        STORAGE_STATE_SIZE,
        readContract,
        config
    );
};

Writing Game State to the Chain

import {
    SpinOPZKProverOutput,
} from "@zkspin/lib";

async function submit_to_operator(
    submissionData: SpinOPZKProverOutput
): Promise<any> {

    const response = await fetch(`${OPZK_OPERATOR_URL}/submitTransaction`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(submission.data, (_, v) =>
            typeof v === "bigint" ? v.toString() : v
        ),
    })
    
    const data = await response.json();
    return data;
}

Gameplays are submitted to operators, operators will handle on-chain interactions.

Last updated