This way it works:
import {
Struct,
PublicKey,
CircuitString,
Field,
Poseidon,
PrivateKey,
} from "o1js";
import fs from "fs/promises";
export class PostState extends Struct({
posterAddress: PublicKey,
postContentID: CircuitString,
allPostsCounter: Field,
userPostsCounter: Field,
postBlockHeight: Field,
deletionBlockHeight: Field,
}) {
hash(): Field {
return Poseidon.hash(
this.posterAddress
.toFields()
.concat([
this.postContentID.hash(),
this.allPostsCounter,
this.userPostsCounter,
this.postBlockHeight,
this.deletionBlockHeight,
])
);
}
toJSON(): any {
return {
posterAddress: this.posterAddress.toBase58(),
postContentID: this.postContentID.toString(),
allPostsCounter: this.allPostsCounter.toJSON(),
userPostsCounter: this.userPostsCounter.toJSON(),
postBlockHeight: this.postBlockHeight.toJSON(),
deletionBlockHeight: this.deletionBlockHeight.toJSON(),
};
}
static fromJSON(data: any): PostState {
return new PostState({
posterAddress: PublicKey.fromBase58(data.posterAddress),
postContentID: CircuitString.fromString(data.postContentID),
allPostsCounter: Field.fromJSON(data.allPostsCounter),
userPostsCounter: Field.fromJSON(data.userPostsCounter),
postBlockHeight: Field.fromJSON(data.postBlockHeight),
deletionBlockHeight: Field.fromJSON(data.deletionBlockHeight),
});
}
}
async function main() {
const key = PrivateKey.random();
const address = key.toPublicKey();
const post = new PostState({
posterAddress: address,
postContentID: CircuitString.fromString(
"bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"
),
allPostsCounter: Field(1),
userPostsCounter: Field(1),
postBlockHeight: Field(777),
deletionBlockHeight: Field(0),
});
const writeData = JSON.stringify(post.toJSON(), (_, v) =>
typeof v === "bigint" ? v.toString() : v
)
.replaceAll("},", "},\n")
.replaceAll("[", "[\n")
.replaceAll("]", "\n]");
await fs.writeFile("post.json", writeData);
}
main();
import { PostState } from "./struct";
import { Field } from "o1js";
import json from "../post.json";
const post: PostState = PostState.fromJSON(json);
console.log(post.allPostsCounter.toJSON());
post.allPostsCounter.assertEquals(1);
Field(post.allPostsCounter).assertEquals(1);
However, if you use fs.readFile instead of import, it throws an error.