All files / src rollupnft.ts

67.31% Statements 173/257
46.21% Branches 61/132
82.6% Functions 19/23
68.82% Lines 170/247

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 7481x 1x 1x 1x 1x 1x 1x             1x   1x 1x   1x 1x                       1x 1x               1x                   1x                           1x     3x 3x                                             3x 3x 3x 3x 1x 1x 2x 3x 3x 3x 3x 1x                 1x                       2x                 2x   2x 1x   1x     1x       1x   2x 2x       2x   2x 10x   10x     10x 10x 10x 10x 10x         10x       10x   2x                 2x   4x               4x                         2x                 2x   2x                 2x                           2x 2x 2x   2x   2x                                       2x 2x 2x 2x         2x 2x 2x 2x             2x           2x   2x                           2x       178x                     5x 5x               2x                             1x 1x                               1x 1x                               1x 1x 1x 1x                       1x         1x 1x 1x 1x 1x   1x                                                                                                                               1x 1x                                                             1x   1x 1x 1x 1x 5x 5x     1x 1x 1x 4x       4x     1x               1x   1x 1x     1x   1x   1x           1x 5x         1x       1x   1x                                                       5x 5x                               1x   1x 5x 5x 5x 5x     1x       1x       1x 1x 1x 1x 1x 1x 5x 5x 5x   5x       5x     1x 1x 1x 1x 4x 4x 4x         4x 4x     1x 1x       1x 1x 1x 1x       1x                         1x         1x 1x 1x 1x                         1x                             1x       1x 1x 1x 1x                                                        
import { Field, verify, Struct, VerificationKey, PublicKey } from "o1js";
import axios from "axios";
import { MinaNFT } from "./minanft";
import { BaseMinaNFT } from "./baseminanft";
import { PrivateMetadata } from "./privatemetadata";
import { Metadata, Storage } from "./contract/metadata";
import {
  MinaNFTMetadataUpdate,
  MetadataTransition,
  MetadataUpdate,
  MetadataMap,
  MinaNFTMetadataUpdateProof,
} from "./contract/update";
import { serializeFields, deserializeFields } from "./lib/fields";
 
import { TextData } from "./storage/text";
import { File, FileData } from "./storage/file";
import { MinaNFTMapUpdate } from "./storage/map";
import { IPFS } from "./storage/ipfs";
import { ARWEAVE } from "./storage/arweave";
import {
  MinaNFTStringUpdate,
  MinaNFTFieldUpdate,
  MinaNFTImageUpdate,
  MinaNFTTextUpdate,
  MinaNFTFileUpdate,
  MinaNFTCommit,
  MinaNFTPrepareCommit,
  RollupNFTCommit,
  RollupNFTCommitData,
} from "./update";
import { MapData } from "./storage/map";
import { sleep } from "./mina";
 
/**
 * RollupUpdate is the data for the update of the metadata to be written to the NFT state
 * @property oldRoot The old root of the Merkle Map of the metadata
 * @property newRoot The new root of the Merkle Map of the metadata
 * @property storage The storage of the NFT - IPFS (i:...) or Arweave (a:...) hash string
 */
export class RollupUpdate extends Struct({
  oldRoot: Metadata,
  newRoot: Metadata,
  storage: Storage,
}) {
  constructor(value: {
    oldRoot: Metadata;
    newRoot: Metadata;
    storage: Storage;
  }) {
    super(value);
  }
}
/**
 * RollupNFT are the NFT used in the Rollup
 * TODO: change parameters
 * @property name Name of the NFT
 * @property storage Storage of the NFT - IPFS (i:...) or Arweave (a:...) hash string
 * @property address Public key of the NFT
 * @property updates Array of the metadata updates
 * @property metadataRoot Root of the Merkle Map of the metadata
 * @property isSomeMetadata Boolean if there is some metadata
 * @property external_url External URL of the NFT
 */
export class RollupNFT extends BaseMinaNFT {
  storage: Storage | undefined;
  metadataRoot: Metadata;
  isSomeMetadata: boolean = false;
  private updates: MetadataUpdate[] = [];
  name?: string;
  address?: PublicKey;
  external_url?: string;
 
  /**
   * Create MinaNFT object
   * @param params arguments
   * @param params.name Name of NFT
   * @param params.address Public key of the NFT
   * @param params.root Root of the Merkle Map of the metadata
   * @param params.storage Storage of the NFT - IPFS (i:...) or Arweave (a:...) hash string
   * @param params.external_url External URL of the NFT
   */
  constructor(
    params: {
      storage?: Storage;
      root?: Metadata;
      name?: string;
      address?: PublicKey | string;
      external_url?: string;
    } = {}
  ) {
    const { storage, root, name, address, external_url } = params;
    super();
    const metadataMap = new MetadataMap();
    if (root !== undefined) {
      this.metadataRoot = root;
      this.isSomeMetadata = true;
    } else this.metadataRoot = metadataMap.getRoot();
    this.storage = storage;
    this.name = name;
    this.external_url = external_url;
    if (address !== undefined)
      this.address =
        typeof address === "string" ? PublicKey.fromBase58(address) : address;
  }
 
  /**
   * Compiles RollupNFT MetadataUpdate contract
   * @returns verification key
   */
  public static async compile(): Promise<VerificationKey> {
    return BaseMinaNFT.compile(true);
  }
 
  /**
   * Load metadata from blockchain and IPFS/Arweave
   * @param metadataURI URI of the metadata. Obligatorily in case there is private metadata as private metadata cannot be fetched from IPFS/Arweave
   * @param skipCalculatingMetadataRoot Skip calculating metadata root in case metadataURI is not provided and NFT contains private data
   */
  public async loadMetadata(
    metadataURI: string | undefined = undefined,
    skipCalculatingMetadataRoot: boolean = false
  ): Promise<void> {
    const uri = metadataURI
      ? JSON.parse(metadataURI)
      : this.storage
      ? (
          await axios.get(
            "https://gateway.pinata.cloud/ipfs/" + this.storage.toIpfsHash()
          )
        ).data
      : undefined;
    Iif (uri === undefined) throw new Error("uri: NFT metadata not found");
 
    if (this.isSomeMetadata) {
      Iif (uri.metadata.data !== this.metadataRoot.data.toJSON())
        throw new Error("uri: NFT metadata data mismatch");
      Iif (uri.metadata.kind !== this.metadataRoot.kind.toJSON())
        throw new Error("uri: NFT metadata kind mismatch");
    } else {
      this.metadataRoot = new Metadata({
        data: Field.fromJSON(uri.metadata.data),
        kind: Field.fromJSON(uri.metadata.kind),
      });
      this.isSomeMetadata = true;
    }
    this.name = uri.name;
    this.address =
      uri.address && typeof uri.address === "string"
        ? PublicKey.fromBase58(uri.address)
        : undefined;
    this.external_url = uri.external_url;
 
    Object.entries(uri.properties).forEach(([key, value]) => {
      Iif (typeof key !== "string")
        throw new Error("uri: NFT metadata key mismatch - should be string");
      Iif (typeof value !== "object")
        throw new Error("uri: NFT metadata value mismatch - should be object");
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const obj = value as any;
      const data = obj.data;
      const kind = obj.kind;
      const isPrivate: boolean = obj.isPrivate ?? false;
      Iif (data === undefined)
        throw new Error(
          `uri: NFT metadata: data should present: ${key} : ${value} kind: ${kind} daya: ${data} isPrivate: ${isPrivate}`
        );
 
      Iif (kind === undefined || typeof kind !== "string")
        throw new Error(
          `uri: NFT metadata: kind mismatch - should be string: ${key} : ${value}`
        );
      switch (kind) {
        case "text":
          this.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: TextData.fromJSON(obj),
            })
          );
          break;
        case "string":
          this.metadata.set(
            key,
            new PrivateMetadata({
              data: MinaNFT.stringToField(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
            })
          );
          break;
        case "file":
          this.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: FileData.fromJSON(obj),
            })
          );
          break;
        case "image":
          this.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: FileData.fromJSON(obj),
            })
          );
          break;
        case "map":
          this.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: MapData.fromJSON(obj, skipCalculatingMetadataRoot),
            })
          );
          break;
        default:
          this.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
            })
          );
          break;
      }
    });
 
    if (skipCalculatingMetadataRoot === false) {
      const { root } = this.getMetadataRootAndMap();
      Iif (root.data.toJSON() !== this.metadataRoot.data.toJSON())
        throw new Error("Metadata root data mismatch");
      Iif (root.kind.toJSON() !== this.metadataRoot.kind.toJSON())
        throw new Error("Metadata root kind mismatch");
      this.isSomeMetadata = true;
    }
  }
 
  /**
   * Creates a Map from JSON
   * @param json json with map data
   * @returns map as JSON object
   */
  public static mapFromJSON(json: object): Map<string, string> {
    const map: Map<string, string> = new Map<string, string>();
    Object.entries(json).forEach(([key, value]) => map.set(key, value));
    return map;
  }
 
  /**
   * Converts to JSON
   * @returns JSON object
   */
  public toJSON(params: { includePrivateData?: boolean } = {}): object {
    const includePrivateData = params.includePrivateData ?? false;
    let description: string | undefined = undefined;
    const descriptionObject = this.getMetadata("description");
    if (
      descriptionObject !== undefined &&
      descriptionObject.linkedObject !== undefined &&
      descriptionObject.linkedObject instanceof TextData
    )
      description = descriptionObject.linkedObject.text;
    let image: string | undefined = undefined;
    const imageObject = this.getMetadata("image");
    if (
      imageObject !== undefined &&
      imageObject.linkedObject !== undefined &&
      imageObject.linkedObject instanceof FileData &&
      imageObject.linkedObject.storage !== undefined &&
      imageObject.linkedObject.storage.length > 2
    )
      image =
        imageObject.linkedObject.storage[0] === "i"
          ? "https://gateway.pinata.cloud/ipfs/" +
            imageObject.linkedObject.storage.slice(2)
          : "https://arweave.net/" + imageObject.linkedObject.storage.slice(2);
 
    const { root } = this.getMetadataRootAndMap();
 
    const json = {
      name: this.name,
      address: this.address?.toBase58(),
      description: description,
      image,
      external_url: this.external_url ?? this.getURL(),
      uri: this.storage
        ? "https://gateway.pinata.cloud/ipfs/" + this.storage.toIpfsHash()
        : undefined,
      storage: this.storage?.toString(),
      time: Date.now(),
      metadata: { data: root.data.toJSON(), kind: root.kind.toJSON() },
      properties: Object.fromEntries(this.metadata),
    };
    return includePrivateData
      ? JSON.parse(JSON.stringify(json))
      : JSON.parse(
          JSON.stringify(json, (_, value) =>
            value?.isPrivate === true ? undefined : value
          )
        );
  }
 
  /**
   * updates Metadata
   * @param key key to update
   * @param value value to update
   */
  public updateMetadata(key: string, value: PrivateMetadata): void {
    const update: MetadataUpdate = this.updateMetadataMap(key, value);
    this.updates.push(update);
  }
 
  /**
   * updates PrivateMetadata
   * @param data {@link MinaNFTStringUpdate} update data
   */
  public update(data: MinaNFTStringUpdate): void {
    this.updateMetadata(
      data.key,
      new PrivateMetadata({
        data: MinaNFT.stringToField(data.value),
        kind: MinaNFT.stringToField(data.kind ?? "string"),
        isPrivate: data.isPrivate ?? false,
      })
    );
  }
 
  /**
   * updates PrivateMetadata
   * @param data {@link MinaNFTTextUpdate} update data
   */
  public updateText(data: MinaNFTTextUpdate): void {
    const text = new TextData(data.text);
    this.updateMetadata(
      data.key,
      new PrivateMetadata({
        data: text.root,
        kind: MinaNFT.stringToField("text"),
        isPrivate: data.isPrivate ?? false,
        linkedObject: text,
      })
    );
  }
 
  /**
   * updates PrivateMetadata
   * @param data {@link MinaNFTTextUpdate} update data
   */
  public updateMap(data: MinaNFTMapUpdate): void {
    data.map.setRoot();
    this.updateMetadata(
      data.key,
      new PrivateMetadata({
        data: data.map.root,
        kind: MinaNFT.stringToField("map"),
        isPrivate: data.isPrivate ?? false,
        linkedObject: data.map,
      })
    );
  }
 
  /**
   * updates PrivateMetadata
   * @param data {@link MinaNFTImageUpdate} update data
   */
  public async updateImage(data: MinaNFTImageUpdate): Promise<void> {
    const file = new File(data.filename, data.fileType, data.fileMetadata);
    if (data.IPFSHash === undefined && data.ArweaveHash === undefined) {
      console.log("Pinning image...");
      await file.pin({
        pinataJWT: data.pinataJWT,
        arweaveKey: data.arweaveKey,
        keyvalues: { project: "MinaNFT", type: "image", nftType: "RollupNFT" },
      });
    } else Eif (data.IPFSHash !== undefined) {
      file.storage = "i:" + data.IPFSHash;
      await file.setMetadata();
    } else Iif (data.ArweaveHash !== undefined) {
      file.storage = "a:" + data.ArweaveHash;
      await file.setMetadata();
    }
    Iif (data.calculateRoot !== false) {
      console.log("Calculating image Merkle tree root...");
      console.time("Image Merkle tree root calculated");
      await file.treeData(data.calculateRoot ?? true);
      console.timeEnd("Image Merkle tree root calculated");
    } else await file.treeData(false);
    console.time("Calculated SHA-3 512");
    await file.sha3_512();
    console.timeEnd("Calculated SHA-3 512");
    const fileData: FileData = await file.data();
    //console.log("Image data:", fileData);
    this.updateFileData({
      key: "image",
      type: "image",
      data: fileData,
      isPrivate: false,
    });
  }
 
  /**
   * updates PrivateMetadata
   * @param data {@link MinaNFTFileUpdate} update data
   */
  public async updateFile(data: MinaNFTFileUpdate): Promise<void> {
    const file = new File(data.filename, data.fileType, data.fileMetadata);
 
    if (data.IPFSHash === undefined && data.ArweaveHash === undefined) {
      Iif (data.isPrivate !== true) {
        console.log("Pinning file...");
        await file.pin({
          pinataJWT: data.pinataJWT,
          arweaveKey: data.arweaveKey,
          keyvalues: { project: "MinaNFT", type: "file", nftType: "RollupNFT" },
        });
      }
    } else if (data.IPFSHash !== undefined) {
      file.storage = "i:" + data.IPFSHash;
      await file.setMetadata();
    } else Iif (data.ArweaveHash !== undefined) {
      file.storage = "a:" + data.ArweaveHash;
      await file.setMetadata();
    }
    if (data.calculateRoot !== false) {
      console.log("Calculating file Merkle tree root...");
      console.time("File Merkle tree root calculated");
      await file.treeData(data.calculateRoot ?? true);
      console.timeEnd("File Merkle tree root calculated");
    } else await file.treeData(false);
 
    console.time("Calculated SHA-3 512");
    await file.sha3_512();
    console.timeEnd("Calculated SHA-3 512");
    const fileData: FileData = await file.data();
    this.updateFileData({
      key: data.key,
      type: "file",
      data: fileData,
      isPrivate: data.isPrivate ?? false,
    });
  }
 
  /**
   * updates PrivateMetadata
   * @param params arguments
   * @param params.key key to update
   * @param params.type type of metadata ('file' or 'image' for example)
   * @param params.data {@link FileData} file data
   * @param params.isPrivate is metadata private
   */
  public updateFileData(params: {
    key: string;
    type?: string;
    data: FileData;
    isPrivate?: boolean;
  }): void {
    const { key, type, data, isPrivate } = params;
    this.updateMetadata(
      key,
      new PrivateMetadata({
        data: data.root,
        kind: MinaNFT.stringToField(type ?? "file"),
        isPrivate: isPrivate ?? false,
        linkedObject: data,
      })
    );
  }
 
  /**
   * updates PrivateMetadata
   * @param data {@link MinaNFTFieldUpdate} update data
   */
  public updateField(data: MinaNFTFieldUpdate): void {
    this.updateMetadata(data.key, {
      data: data.value,
      kind: MinaNFT.stringToField(data.kind ?? "string"),
      isPrivate: data.isPrivate ?? false,
    } as PrivateMetadata);
  }
 
  /**
   * Prepare commit updates of the MinaNFT to blockchain
   *
   * @param commitData {@link MinaNFTPrepareCommit} commit data
   */
  public async prepareCommitData(
    commitData: RollupNFTCommit
  ): Promise<RollupNFTCommitData | undefined> {
    const { pinataJWT, arweaveKey, generateProofData } = commitData;
 
    if (this.updates.length !== 0) {
      const transactions = [];
      console.log("Creating transactions...");
      for (const update of this.updates) {
        const state: MetadataTransition = MetadataTransition.create(update);
        transactions.push({ state, update });
      }
 
      console.log("Merging states...");
      let mergedState = transactions[0].state;
      for (let i = 1; i < transactions.length; i++) {
        const state: MetadataTransition = MetadataTransition.merge(
          mergedState,
          transactions[i].state
        );
        mergedState = state;
      }
 
      Iif (
        this.isSomeMetadata &&
        (this.metadataRoot.data.toJSON() !==
          mergedState.oldRoot.data.toJSON() ||
          this.metadataRoot.kind.toJSON() !== mergedState.oldRoot.kind.toJSON())
      )
        throw new Error("Metadata old root data mismatch");
 
      this.metadataRoot = mergedState.newRoot;
 
      const storage = await this.pinToStorage(pinataJWT, arweaveKey);
      Iif (storage === undefined) {
        throw new Error("Storage error");
      }
      this.storage = storage.hash;
 
      Iif (generateProofData !== true) return undefined;
 
      const update = new RollupUpdate({
        oldRoot: mergedState.oldRoot,
        newRoot: mergedState.newRoot,
        storage: this.storage,
      });
 
      const transactionsStr: string[] = transactions.map((t) =>
        JSON.stringify({
          state: serializeFields(MetadataTransition.toFields(t.state)),
          update: serializeFields(MetadataUpdate.toFields(t.update)),
        })
      );
      const updateStr: string = JSON.stringify({
        update: serializeFields(RollupUpdate.toFields(update)),
      });
 
      this.isSomeMetadata = true;
 
      return {
        update: updateStr,
        transactions: transactionsStr,
      };
    } else E{
      const storage = await this.pinToStorage(pinataJWT, arweaveKey);
      Iif (storage === undefined) {
        throw new Error("Storage error");
      }
      this.storage = storage.hash;
      Iif (generateProofData !== true) return undefined;
 
      const update = new RollupUpdate({
        oldRoot: this.metadataRoot,
        newRoot: this.metadataRoot,
        storage: this.storage,
      });
      const updateStr: string = JSON.stringify({
        update: serializeFields(RollupUpdate.toFields(update)),
      });
      return {
        update: updateStr,
        transactions: [],
      };
    }
  }
 
  public getURL(): string | undefined {
    Iif (this.storage === undefined) return undefined;
    return "https://minanft.io/nft/i" + this.storage.toIpfsHash();
  }
 
  /**
   * Commit updates of the MinaNFT to blockchain using prepared data
   * Generates recursive proofs for all updates,
   * than verify the proof locally and send the transaction to the blockchain
   * @param preparedCommitData {@link RollupNFTCommitData} commit data
   * @param verbose verbose mode
   * @returns proof {@link MinaNFTMetadataUpdateProof}
   */
  public static async generateProof(
    preparedCommitData: RollupNFTCommitData,
    verbose: boolean = false
  ): Promise<MinaNFTMetadataUpdateProof> {
    const { update: updateStr, transactions: transactionsStr } =
      preparedCommitData;
 
    const transactions = transactionsStr.map((t) => {
      const obj = JSON.parse(t);
      const state = MetadataTransition.fromFields(deserializeFields(obj.state));
      const update = MetadataUpdate.fromFields(deserializeFields(obj.update));
      return { state, update };
    });
 
    const update = RollupUpdate.fromFields(
      deserializeFields(JSON.parse(updateStr).update)
    );
 
    Iif (MinaNFT.updateVerificationKey === undefined) {
      throw new Error("generateProof: Update verification key is undefined");
    }
 
    console.log("Creating proofs...");
    const logMsg = `Update proofs created`;
    console.time(logMsg);
    let proofs: MinaNFTMetadataUpdateProof[] = [];
    let count = 1;
    for (const transaction of transactions) {
      if (verbose)
        console.log(`Creating proof ${count++}/${transactions.length}`);
      await sleep(100); // alow GC to run
      const proof: MinaNFTMetadataUpdateProof =
        await MinaNFTMetadataUpdate.update(
          transaction.state,
          transaction.update
        );
      proofs.push(proof);
    }
 
    console.log("Merging proofs...");
    let proof: MinaNFTMetadataUpdateProof = proofs[0];
    count = 1;
    for (let i = 1; i < proofs.length; i++) {
      if (verbose) console.log(`Merging proof ${count++}/${proofs.length - 1}`);
      await sleep(100); // alow GC to run
      const state: MetadataTransition = MetadataTransition.merge(
        proof.publicInput,
        proofs[i].publicInput
      );
      const mergedProof: MinaNFTMetadataUpdateProof =
        await MinaNFTMetadataUpdate.merge(state, proof, proofs[i]);
      proof = mergedProof;
    }
 
    console.time("Update proof verified");
    const verificationResult: boolean = await verify(
      proof.toJSON(),
      MinaNFT.updateVerificationKey
    );
    console.timeEnd("Update proof verified");
    console.timeEnd(logMsg);
    console.log("Proof verification result:", verificationResult);
    Iif (verificationResult === false) {
      throw new Error("Proof verification error");
    }
 
    return proof;
  }
 
  /**
   * Pins NFT to IPFS or Arweave
   * @param pinataJWT Pinata JWT
   * @param arweaveKey Arweave key
   * @returns NFT's storage hash and hash string
   */
  private async pinToStorage(
    pinataJWT: string | undefined,
    arweaveKey: string | undefined
  ): Promise<{ hash: Storage; hashStr: string } | undefined> {
    Iif (pinataJWT === undefined && arweaveKey === undefined) {
      throw new Error(
        "No storage service key provided. Provide pinateJWT or arweaveKey"
      );
    }
    if (pinataJWT !== undefined) {
      console.log("Pinning to IPFS...");
      const ipfs = new IPFS(pinataJWT);
      let hash = await ipfs.pinJSON({
        data: this.toJSON({
          includePrivateData: false,
        }),
        name: (this.name ? this.name + "-" : "") + "rollup-nft.json",
        keyvalues: {
          name: this.name,
          address: this.address?.toBase58(),
          project: "MinaNFT",
          type: "metadata",
          nftType: "RollupNFT",
        },
      });
      Iif (hash === undefined) {
        console.error("Pinning to IPFS failed. Retrying...");
        await sleep(10000);
        hash = await ipfs.pinJSON({
          data: this.toJSON({
            includePrivateData: false,
          }),
          name: "rollup-nft.json",
          keyvalues: {
            project: "MinaNFT",
            type: "metadata",
            nftType: "RollupNFT",
          },
        });
      }
      Iif (hash === undefined) {
        console.error("Pinning to IPFS failed");
        return undefined;
      }
      const hashStr = "i:" + hash;
      const ipfs_fields = MinaNFT.stringToFields(hashStr);
      Iif (ipfs_fields.length !== 2) throw new Error("IPFS hash encoding error");
      return {
        hash: new Storage({ hashString: ipfs_fields as [Field, Field] }),
        hashStr,
      };
    } else Eif (arweaveKey !== undefined) {
      console.log("Pinning to Arweave...");
      const arweave = new ARWEAVE(arweaveKey);
      const hash = await arweave.pinString(
        JSON.stringify(
          this.toJSON({
            includePrivateData: false,
          }),
          null,
          2
        )
      );
      Iif (hash === undefined) return undefined;
      const hashStr = "a:" + hash;
      const arweave_fields = MinaNFT.stringToFields(hashStr);
      Iif (arweave_fields.length !== 2)
        throw new Error("Arweave hash encoding error");
      return {
        hash: new Storage({ hashString: arweave_fields as [Field, Field] }),
        hashStr,
      };
    } else return undefined;
  }
}