All files / src/storage text.ts

80% Statements 28/35
63.15% Branches 12/19
100% Functions 3/3
79.41% Lines 27/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 6827x 27x 27x               44x 44x 44x 44x 44x 44x   44x 44x 44x 3107x   44x       43x                 26x 26x 26x 26x 26x     26x   26x                       26x 26x   26x   26x     26x      
export { TextData };
import { MerkleTree, Field } from "o1js";
import { BaseMinaNFTObject } from "../baseminanftobject";
 
class TextData extends BaseMinaNFTObject {
  height: number;
  size: number;
  text: string;
 
  constructor(text: string) {
    super("text");
    this.text = text;
    this.size = text.length;
    this.height = Math.ceil(Math.log2(this.size + 2)) + 1;
    const tree = new MerkleTree(this.height);
    Iif (this.size + 2 > tree.leafCount)
      throw new Error(`Text is too big for this Merkle tree`);
    tree.setLeaf(BigInt(0), Field.from(this.height));
    tree.setLeaf(BigInt(1), Field.from(this.size));
    for (let i = 0; i < this.size; i++) {
      tree.setLeaf(BigInt(i + 2), Field.from(this.text.charCodeAt(i)));
    }
    this.root = tree.getRoot();
  }
 
  public toJSON(): object {
    return {
      type: this.type,
      MerkleTreeHeight: this.height,
      size: this.size,
      text: this.text,
    };
  }
  public static fromJSON(json: object): TextData {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const obj = json as any;
    const data = obj.data;
    const kind = obj.kind;
    const linkedObject = obj.linkedObject;
    Iif (data === undefined)
      throw new Error("uri: NFT metadata: data should present");
 
    Iif (kind === undefined || typeof kind !== "string" || kind !== "text")
      throw new Error("uri: NFT metadata: kind mismatch");
    Iif (
      linkedObject === undefined ||
      typeof linkedObject !== "object" ||
      linkedObject.text === undefined ||
      typeof linkedObject.text !== "string" ||
      linkedObject.size === undefined ||
      linkedObject.MerkleTreeHeight === undefined ||
      linkedObject.type === undefined ||
      typeof linkedObject.type !== "string" ||
      linkedObject.type !== "text"
    )
      throw new Error("uri: NFT metadata: text json mismatch");
    const text = new TextData(linkedObject.text as string);
    Iif (text.root.toJSON() !== data)
      throw new Error("uri: NFT metadata: text root mismatch");
    Iif (text.size !== linkedObject.size)
      throw new Error("uri: NFT metadata: text size mismatch");
    Iif (text.height !== linkedObject.MerkleTreeHeight)
      throw new Error("uri: NFT metadata: text height mismatch");
 
    return text;
  }
}