All files / src minanft.ts

71.4% Statements 487/682
44.35% Branches 106/239
86.36% Functions 38/44
71.98% Lines 483/671

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 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835  27x   27x                         27x 27x 27x 27x 27x 27x         27x 27x                 27x 27x 27x   27x 27x                           27x 27x   27x 27x 27x       27x                                                                                                                         30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 10x   30x 30x                       19x       19x     19x 19x 19x 19x 19x         19x 19x 19x 19x 19x 19x                                     19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x     19x             19x       19x           19x 19x 19x   19x   19x     19x 62x   62x     62x 62x 62x 62x 62x         62x       62x   19x                 19x   38x               38x   1x                 1x   1x                 1x   3x                 3x                                   19x   19x 19x 19x   19x                                                                                                                                                                                                                                                                                                                       29x 29x 29x 29x 29x         27x 29x 29x 29x             7x           29x 29x       29x                           29x       1231x                                         52x                 45x 45x 45x                 24x                             10x 10x                               6x 6x                               3x 3x 3x 3x                       3x         3x 3x 3x 3x 3x 3x                                               2x   2x 2x 1x 1x                         2x         2x   2x 2x 2x 2x 2x                                                                 5x 5x                                                           63x     63x     63x 63x 63x 63x 63x       63x 63x   63x   63x         63x 63x       63x 63x       63x 63x             63x               63x 63x     63x       63x 63x       63x   63x                                       3x   3x       3x   3x         3x         3x   3x                     3x           3x     3x 3x 3x 5x 5x   5x 5x 5x 5x       3x 3x 2x 2x         2x 2x 2x 2x   3x     3x         3x   3x       3x 3x     3x   3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x                 3x           3x       6x     3x 3x 3x 3x 3x 3x 3x 3x       3x     3x   3x 3x 3x 3x 3x 3x 3x 3x                                   1x   1x       1x   1x         1x         1x 1x 1x 1x       1x 1x               1x 1x     1x   1x       1x   1x   1x                   1x 1x                       1x 1x 4x 1029x     1x 11x     1x   1x                                                       1x           1x   1x     1x 1x 1x 4x   1x 1029x   1x     1x 1x 1x 1x 11x     1x         1x 1x 1x 1x 1x 1x   1x       1x     1x 1x 1x                   1x   1x 1x       1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x       2x     1x 1x 1x 1x 1x 1x 1x 1x       1x     1x 1x 1x                                                                                                                         15x         15x 14x 14x 14x               14x                       14x       14x 14x 14x 14x       1x 1x 1x 1x                   1x 1x 1x 1x   1x                                                                                                                               50x       50x 50x                                                                   45x   45x 45x 45x 45x                                                       11x   11x       11x 11x 11x   11x   11x 11x   11x   11x 11x 11x 11x     11x     11x 11x       11x   11x                     11x                               11x   11x           11x 11x 11x 11x   11x 11x 11x 11x   11x     22x 22x     11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x                                                                                                             1x 1x       1x 1x         1x   1x     1x 1x           1x 1x     1x 1x 1x 1x 1x 1x 1x 1x   1x     2x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                   1x 1x     1x   1x       1x     1x     1x 1x       1x 1x     1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x     2x     1x 1x 1x 1x 1x 1x 1x 1x 1x                                       1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x     2x     1x 1x 1x 1x 1x 1x      
/* eslint-disable @typescript-eslint/no-inferrable-types */
export { MinaNFT };
 
import {
  Mina,
  PrivateKey,
  PublicKey,
  Field,
  AccountUpdate,
  verify,
  Poseidon,
  Signature,
  UInt64,
  VerificationKey,
  Account,
} from "o1js";
import axios from "axios";
import { fetchMinaAccount } from "./fetch";
import { BaseMinaNFT } from "./baseminanft";
import { PrivateMetadata } from "./privatemetadata";
import { MinaNFTContract } from "./contract/nft";
import {
  MinaNFTNameServiceContract,
  NFTMintData,
  MintData,
} from "./contract/names";
import { Metadata, Update, Storage } from "./contract/metadata";
import {
  MinaNFTMetadataUpdate,
  MetadataTransition,
  MetadataUpdate,
  MetadataMap,
  MinaNFTMetadataUpdateProof,
} from "./contract/update";
 
import { RedactedMinaNFTMapStateProof } from "./plugins/redactedmap";
import { MinaNFTVerifier } from "./plugins/verifier";
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,
  MinaNFTMint,
  MinaNFTTransfer,
  MinaNFTApproval,
  MinaNFTCommit,
  MinaNFTPrepareCommit,
  MinaNFTCommitData,
} from "./update";
import { MapData } from "./storage/map";
import { initBlockchain, MinaNetworkInstance, sleep } from "./mina";
import { blockchain } from "./networks";
import config from "./config";
import { MinaNFTNameService } from "./minanftnames";
import {
  EscrowTransferVerification,
  EscrowTransferApproval,
} from "./contract/transfer";
const { MINAFEE, MINANFT_NAME_SERVICE } = config;
 
/**
 * MinaNFT is the class for the NFT, wrapper around the MinaNFTContract
 * @property name Name of the NFT
 * @property creator Creator of the NFT
 * @property storage Storage of the NFT - IPFS (i:...) or Arweave (a:...) hash string
 * @property owner Owner of the NFT - Poseidon hash of owner's public key
 * @property escrow Escrow of the NFT - Poseidon hash of three escrow's public keys
 * @property version Version of the NFT, increases by one with the changing of the metadata or owner
 * @property isMinted True if the NFT is minted
 * @property address Public key of the deployed NFT zkApp
 * @property tokenId Token ID of the NFT Name Service
 * @property nameService Public key of the NFT Name Service
 * @property updates Array of the metadata updates
 * @property metadataRoot Root of the Merkle Map of the metadata
 */
class MinaNFT extends BaseMinaNFT {
  /*
  @state(Field) name = State<Field>();
  @state(Metadata) metadata = State<Metadata>();
  @state(Field) storage = State<Field>();
  @state(Field) owner = State<Field>();
  @state(Field) escrow = State<Field>();
  @state(UInt64) version = State<UInt64>();
  */
 
  name: string;
  creator: string;
  storage: string;
  owner: Field;
  escrow: Field;
  version: UInt64;
  isMinted: boolean;
  address: PublicKey;
  tokenId: Field | undefined;
  nameService: PublicKey | undefined;
 
  private updates: MetadataUpdate[];
  private metadataRoot: Metadata;
 
  /**
   * Create MinaNFT object
   * @param params arguments
   * @param params.name Name of NFT
   * @param params.address Public key of the deployed NFT zkApp
   * @param params.creator Creator of the NFT
   * @param params.storage Storage of the NFT - IPFS (i:...) or Arweave (a:...) hash string
   * @param params.owner Owner of the NFT - Poseidon hash of owner's public key
   * @param params.escrow Escrow of the NFT - Poseidon hash of three escrow's public keys
   * @param params.nameService Public key of the NFT Name Service
   */
  constructor(params: {
    name: string;
    address: PublicKey;
    creator?: string;
    storage?: string;
    owner?: Field;
    escrow?: Field;
    nameService?: PublicKey;
  }) {
    super();
    this.name = params.name[0] === "@" ? params.name : "@" + params.name;
    this.creator = params.creator ?? "MinaNFT library";
    this.storage = params.storage ?? "";
    this.owner = params.owner ?? Field(0);
    this.escrow = params.escrow ?? Field(0);
    this.version = UInt64.from(0);
    this.isMinted = params.address === undefined ? false : true;
    this.address = params.address;
    this.updates = [];
    const metadataMap = new MetadataMap();
    this.metadataRoot = metadataMap.getRoot();
    this.nameService = params.nameService;
    if (this.nameService === undefined) {
      this.nameService = PublicKey.fromBase58(MINANFT_NAME_SERVICE);
    }
    const nameService = new MinaNFTNameServiceContract(this.nameService);
    this.tokenId = nameService.deriveTokenId();
  }
 
  /**
   * 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> {
    Iif (this.address === undefined) {
      throw new Error("address is undefined");
      return;
    }
    Iif (this.nameService === undefined) {
      this.nameService = PublicKey.fromBase58(MINANFT_NAME_SERVICE);
    }
    const nameService = new MinaNFTNameServiceContract(this.nameService);
    const tokenId = nameService.deriveTokenId();
    const nft = new MinaNFTContract(this.address, tokenId);
    await fetchMinaAccount({ publicKey: this.address, tokenId });
    Iif (!Mina.hasAccount(this.address, tokenId)) {
      throw new Error("NFT is not deployed");
      return;
    }
 
    const name = nft.name.get();
    const storage = nft.storage.get();
    const owner = nft.owner.get();
    const escrow = nft.escrow.get();
    const metadata = nft.metadata.get();
    const version = nft.version.get();
 
    /*
      metadata: Map<string, PrivateMetadata>;
      +name: string;
      creator: string;
      +storage: string;
      +owner: Field;
      +escrow: Field;
      +version: UInt64;
      +isMinted: boolean;
      +address: PublicKey | undefined;
      +tokenId: Field | undefined;
      +nameService: PublicKey | undefined;
 
      +private updates: MetadataUpdate[];
      +private metadataRoot: Metadata;
    */
 
    const nameStr = MinaNFT.stringFromField(name);
    Iif (nameStr !== this.name) throw new Error("NFT name mismatch");
    const storageStr = MinaNFT.stringFromFields(Storage.toFields(storage));
    this.storage = storageStr;
    this.owner = owner;
    this.escrow = escrow;
    this.version = version;
    this.metadataRoot = metadata;
    this.isMinted = true;
    this.tokenId = tokenId;
    this.nameService = nameService.address;
 
    //try {
    Iif (
      storageStr.length < 2 ||
      (storageStr[0] !== "i" && storageStr[0] !== "a")
    ) {
      throw new Error("Invalid storage string");
    }
    const uriURL =
      storageStr[0] === "i"
        ? "https://gateway.pinata.cloud/ipfs/" + storageStr.slice(2)
        : "https://arweave.net/" + storageStr.slice(2);
    const uri =
      metadataURI === undefined
        ? (await axios.get(uriURL)).data
        : JSON.parse(metadataURI);
    //const image = data.data.properties.image;
    //console.log("IPFS uri:", JSON.stringify(uri, null, 2));
    //console.log("IPFS image:", image);
    this.creator = uri.creator ?? "";
    Iif (uri.name !== this.name) throw new Error("uri: NFT name mismatch");
    Iif (uri.version !== this.version.toString())
      throw new Error("uri: NFT version mismatch");
    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");
 
    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;
      }
    });
    /*
    } catch (error) {
      throw new Error(`IPFS uri import error: ${error}`);
    }
    */
    Iif (!(await this.checkState("load metadata")))
      throw new Error("State verification error after loading metadata");
    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");
    }
  }
 
  /**
   * Load metadata from blockchain and IPFS/Arweave
   * @param params arguments
   * @param params.metadataURI URI of the metadata. Obligatorily in case there is private metadata as private metadata cannot be fetched from IPFS/Arweave
   * @param params.nameServiceAddress Public key of the Name Service
   * @param params.skipCalculatingMetadataRoot Skip calculating metadata root
   * @returns MinaNFT object
   */
  public static fromJSON(params: {
    metadataURI: string;
    nameServiceAddress: PublicKey;
    skipCalculatingMetadataRoot?: boolean;
  }): MinaNFT {
    const nameService = new MinaNFTNameServiceContract(
      params.nameServiceAddress
    );
    const tokenId = nameService.deriveTokenId();
    const skipCalculatingMetadataRoot: boolean =
      params.skipCalculatingMetadataRoot ?? false;
 
    const uri = JSON.parse(params.metadataURI);
    const nft = new MinaNFT({
      name: uri.name,
      nameService: params.nameServiceAddress,
      creator: uri.creator,
      owner: Field.fromJSON(uri.owner),
      address: PublicKey.fromBase58(uri.address),
    });
    nft.version = UInt64.from(uri.version);
    nft.metadataRoot = new Metadata({
      data: Field.fromJSON(uri.metadata.data),
      kind: Field.fromJSON(uri.metadata.kind),
    });
    nft.owner = Field.fromJSON(uri.owner);
    nft.escrow = Field.fromJSON(uri.escrow);
    nft.tokenId = tokenId;
 
    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} data: ${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":
          nft.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: TextData.fromJSON(obj),
            })
          );
          break;
        case "string":
          nft.metadata.set(
            key,
            new PrivateMetadata({
              data: MinaNFT.stringToField(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
            })
          );
          break;
        case "file":
          nft.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: FileData.fromJSON(obj),
            })
          );
          break;
        case "image":
          nft.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: FileData.fromJSON(obj),
            })
          );
          break;
        case "map":
          nft.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: MapData.fromJSON(obj, skipCalculatingMetadataRoot),
            })
          );
          break;
        default:
          nft.metadata.set(
            key,
            new PrivateMetadata({
              data: Field.fromJSON(data),
              kind: MinaNFT.stringToField(kind),
              isPrivate: isPrivate,
              linkedObject: FileData.fromJSON(obj),
            })
          );
          break;
      }
    });
    return nft;
  }
 
  /**
   * 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
   * @param params parameters
   * @param params.increaseVersion increase version by one
   * @param params.includePrivateData include private data
   * @returns JSON object
   */
  public toJSON(
    params: {
      increaseVersion?: boolean;
      includePrivateData?: boolean;
    } = {}
  ): object {
    const increaseVersion: boolean = params.increaseVersion ?? false;
    const includePrivateData: boolean = 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 version = increaseVersion
      ? this.version.add(UInt64.from(1)).toJSON()
      : this.version.toJSON();
 
    const json = {
      name: this.name,
      description: description ?? "",
      image,
      external_url: "https://minanft.io/" + this.name,
      version,
      time: Date.now(),
      creator: this.creator,
      address: this.address.toBase58(),
      owner: this.owner.toJSON(),
      escrow: this.escrow.toJSON(),
      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
          )
        );
  }
 
  /**
   * Initialize Mina o1js library
   * @param chain blockchain to initialize
   */
  public static async minaInit(
    chain: blockchain
  ): Promise<MinaNetworkInstance> {
    return await initBlockchain(chain);
  }
 
  /**
   * Get current Mina network fee
   * @returns current Mina network fee
   */
  public static async fee(): Promise<UInt64> {
    //TODO: update after mainnet launch
    return UInt64.fromJSON(MINAFEE);
  }
 
  /**
   * updates Metadata
   * @param key key to update
   * @param value value to update
   */
  public updateMetadata(key: string, value: PrivateMetadata): void {
    if (this.isMinted) {
      const update: MetadataUpdate = this.updateMetadataMap(key, value);
      this.updates.push(update);
    } else Ethis.metadata.set(key, value);
  }
 
  /**
   * 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", nft: this.name },
      });
    } 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();
    this.updateFileData({
      key: "image",
      type: "image",
      data: fileData,
      isPrivate: false,
    });
    /*
    this.updateMetadata(
      "image",
      new PrivateMetadata({
        data: fileData.root,
        kind: MinaNFT.stringToField("image"),
        isPrivate: false,
        linkedObject: fileData,
      })
    );
*/
  }
 
  /**
   * 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) {
      if (data.isPrivate !== true) {
        console.log("Pinning file...");
        await file.pin({
          pinataJWT: data.pinataJWT,
          arweaveKey: data.arweaveKey,
          keyvalues: { project: "MinaNFT", type: "file", nft: this.name },
        });
      }
    } 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 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,
    });
    /*
    this.updateMetadata(
      data.key,
      new PrivateMetadata({
        data: fileData.root,
        kind: MinaNFT.stringToField("file"),
        isPrivate: data.isPrivate ?? false,
        linkedObject: fileData,
      })
    );
*/
  }
 
  /**
   * 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);
  }
 
  /**
   * Checks that on-chain state is equal to off-chain state
   * @param info additional info for logging
   * @returns true if on-chain state is equal to off-chain state
   */
  public async checkState(info: string = ""): Promise<boolean> {
    //console.log("Checking state for", this.name, "at", info);
    Iif (this.address === undefined)
      throw new Error("NFT contract is not deployed");
 
    Iif (this.nameService === undefined)
      throw new Error("Names contract address is undefined");
 
    const address: PublicKey = this.address;
    const nameService = new MinaNFTNameServiceContract(this.nameService);
    const tokenId = nameService.deriveTokenId();
    await fetchMinaAccount({ publicKey: address, tokenId });
    Iif (!Mina.hasAccount(address, tokenId)) {
      console.error("NFT contract is not deployed");
      return false;
    }
    const zkApp = new MinaNFTContract(address, tokenId);
    let result = true;
 
    const version: UInt64 = zkApp.version.get();
    //console.log("Version:", this.name, info, version.toString());
    Iif (version.toBigInt().valueOf() !== this.version.toBigInt().valueOf()) {
      console.error("Version mismatch");
      result = false;
    }
    //console.log("After version:", this.name, info, version.toString());
    const oldEscrow = zkApp.escrow.get();
    Iif (oldEscrow.toBigInt().valueOf() !== this.escrow.toBigInt().valueOf()) {
      console.error("Escrow mismatch");
      result = false;
    }
    const oldOwner = zkApp.owner.get();
    Iif (oldOwner.toBigInt().valueOf() !== this.owner.toBigInt().valueOf()) {
      console.error("Owner mismatch");
      result = false;
    }
    const oldMetadata = zkApp.metadata.get();
    Iif (
      oldMetadata.data.toBigInt().valueOf() !==
      this.metadataRoot.data.toBigInt().valueOf()
    ) {
      console.error("Metadata data mismatch");
      result = false;
    }
    Iif (
      oldMetadata.kind.toBigInt().valueOf() !==
      this.metadataRoot.kind.toBigInt().valueOf()
    ) {
      console.error("Metadata kind mismatch");
      result = false;
    }
 
    const oldStorage = zkApp.storage.get();
    const storage: string = MinaNFT.stringFromFields(
      Storage.toFields(oldStorage)
    );
    Iif (this.storage !== storage) {
      throw new Error("Storage mismatch");
    }
 
    const name = zkApp.name.get();
    Iif (MinaNFT.stringFromField(name) !== this.name) {
      console.error("Name mismatch");
      result = false;
    }
    Iif (result === false)
      console.error("State verification error for", this.name, "at", info);
    return result;
  }
 
  /**
   * Commit updates of the MinaNFT to blockchain
   * Generates recursive proofs for all updates,
   * than verify the proof locally and send the transaction to the blockchain
   *
   * @param commitData {@link MinaNFTCommit} commit data
   */
  public async commit(
    commitData: MinaNFTCommit
  ): Promise<Mina.PendingTransaction | undefined> {
    const {
      deployer,
      ownerPrivateKey,
      pinataJWT,
      arweaveKey,
      nameService,
      nonce: nonceArg,
    } = commitData;
 
    Iif (this.address === undefined) {
      console.error("NFT contract is not deployed");
      return undefined;
    }
    const address: PublicKey = this.address;
 
    Iif (this.updates.length === 0) {
      console.error("No updates to commit");
      return undefined;
    }
 
    Iif (this.isMinted === false) {
      console.error("NFT is not minted");
      return undefined;
    }
 
    Iif (nameService === undefined)
      throw new Error("Names Service is undefined");
    Iif (nameService.address === undefined)
      throw new Error("Names service address is undefined");
 
    /*
    const proof: MinaNFTMetadataUpdateProof | undefined =
      await this.generateProof();
    if (proof === undefined) {
      console.error("Proof generation error");
      return undefined;
    }
    */
    Iif (MinaNFT.updateVerificationKey === undefined) {
      console.error("Update verification key is undefined");
      return undefined;
    }
 
    //console.log("Creating proofs...");
    const logMsg = `Update proofs created for ${
      this.name
    } version ${this.version.toString()}`;
    console.time(logMsg);
    let proofs: MinaNFTMetadataUpdateProof[] = [];
    for (const update of this.updates) {
      await sleep(100); // alow GC to run
      let state: MetadataTransition | null = MetadataTransition.create(update);
      let proof: MinaNFTMetadataUpdateProof | null =
        await MinaNFTMetadataUpdate.update(state, update);
      proofs.push(proof);
      state = null;
      proof = null;
    }
 
    //console.log("Merging proofs...");
    let proof: MinaNFTMetadataUpdateProof | null = proofs[0];
    for (let i = 1; i < proofs.length; i++) {
      await sleep(100); // alow GC to run
      let state: MetadataTransition | null = MetadataTransition.merge(
        proof.publicInput,
        proofs[i].publicInput
      );
      let mergedProof: MinaNFTMetadataUpdateProof | null =
        await MinaNFTMetadataUpdate.merge(state, proof, proofs[i]);
      proof = mergedProof;
      state = null;
      mergedProof = null;
    }
    proofs = [];
 
    //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");
    }
 
    const storage = await this.pinToStorage(pinataJWT, arweaveKey);
    Iif (storage === undefined) {
      throw new Error("IPFS Storage error");
    }
    const storageHash: Storage = storage.hash;
 
    Iif (false === (await this.checkState("commit"))) {
      throw new Error("State verification error");
    }
 
    //console.log("Commiting updates to blockchain...");
    const sender = deployer.toPublicKey();
    const zkApp = new MinaNFTNameServiceContract(nameService.address);
    const tokenId = zkApp.deriveTokenId();
    await fetchMinaAccount({ publicKey: nameService.address, force: true });
    const zkAppNFT = new MinaNFTContract(address, tokenId);
    await fetchMinaAccount({ publicKey: this.address, tokenId });
    await fetchMinaAccount({ publicKey: sender });
    const hasAccount = Mina.hasAccount(this.address, tokenId);
    Iif (!hasAccount) throw new Error("NFT is not deployed, no account");
    const account = Mina.getAccount(sender);
    const nonce: number = nonceArg ?? Number(account.nonce.toBigint());
    const version: UInt64 = zkAppNFT.version.get();
    const newVersion: UInt64 = version.add(UInt64.from(1));
    const oldOwner = zkAppNFT.owner.get();
    const ownerPublicKey = ownerPrivateKey.toPublicKey();
    const owner = Poseidon.hash(ownerPublicKey.toFields());
    Iif (oldOwner.equals(owner).toBoolean() === false) {
      throw new Error("Owner privateKey mismatch");
    }
 
    const update: Update = new Update({
      oldRoot: proof.publicInput.oldRoot,
      newRoot: proof.publicInput.newRoot,
      storage: storageHash,
      verifier: nameService.address,
      version: newVersion,
      name: MinaNFT.stringToField(this.name),
      owner,
    });
    const signature = Signature.create(
      ownerPrivateKey,
      Update.toFields(update)
    );
 
    //console.log("Sending update...");
    const tx = await Mina.transaction(
      { sender, fee: await MinaNFT.fee(), memo: "minanft.io", nonce },
      async () => {
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        await zkApp.update(address, update, signature, ownerPublicKey, proof!);
      }
    );
    let sentTx: Mina.PendingTransaction | undefined = undefined;
    try {
      await sleep(100); // alow GC to run
      await tx.prove();
      tx.sign([deployer]);
      console.time("Update transaction sent");
      sentTx = await tx.send();
      console.timeEnd("Update transaction sent");
    } catch (error) {
      throw new Error("Prooving error");
    }
    Iif (sentTx === undefined) {
      throw new Error("Transaction error");
    }
    await MinaNFT.transactionInfo(sentTx, "update", false);
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    const newRoot = proof!.publicInput.newRoot;
    proof = null;
    if (sentTx.status === "pending") {
      this.metadataRoot = newRoot;
      this.updates = [];
      this.version = newVersion;
      this.storage = storage.hashStr;
      return sentTx;
    } else Ereturn undefined;
  }
 
  /**
   * Prepare commit updates of the MinaNFT to blockchain
   *
   * @param commitData {@link MinaNFTPrepareCommit} commit data
   */
  public async prepareCommitData(
    commitData: MinaNFTPrepareCommit
  ): Promise<MinaNFTCommitData | undefined> {
    const {
      ownerPrivateKey,
      ownerPublicKey,
      nameServiceAddress,
      pinataJWT,
      arweaveKey,
    } = commitData;
 
    Iif (this.address === undefined) {
      console.error("NFT contract is not deployed");
      return undefined;
    }
    const address: PublicKey = this.address;
 
    Iif (this.updates.length === 0) {
      console.error("No updates to commit");
      return undefined;
    }
 
    Iif (this.isMinted === false) {
      console.error("NFT is not minted");
      return undefined;
    }
 
    const 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;
    }
 
    const storage = await this.pinToStorage(pinataJWT, arweaveKey);
    Iif (storage === undefined) {
      throw new Error("Storage error");
    }
    const storageHash: Storage = storage.hash;
 
    Iif (false === (await this.checkState("commit"))) {
      throw new Error("State verification error");
    }
 
    const newVersion: UInt64 = this.version.add(UInt64.from(1));
 
    const owner = Poseidon.hash(ownerPublicKey.toFields());
 
    const update: Update = new Update({
      oldRoot: mergedState.oldRoot,
      newRoot: mergedState.newRoot,
      storage: storageHash,
      verifier: nameServiceAddress,
      version: newVersion,
      name: MinaNFT.stringToField(this.name),
      owner,
    });
 
    let signatureStr: string = "";
    Iif (ownerPrivateKey !== undefined) {
      Iif (
        ownerPrivateKey.toPublicKey().toBase58() !== ownerPublicKey.toBase58()
      )
        throw new Error("Owner privateKey mismatch");
      const signature = Signature.create(
        ownerPrivateKey,
        Update.toFields(update)
      );
      signatureStr = signature.toBase58();
    }
 
    const transactionsStr: string[] = transactions.map((t) =>
      JSON.stringify({
        state: MetadataTransition.toFields(t.state).map((f) => f.toJSON()),
        update: MetadataUpdate.toFields(t.update).map((f) => f.toJSON()),
      })
    );
    const updateStr: string = JSON.stringify({
      update: Update.toFields(update).map((f) => f.toJSON()),
    });
 
    const addressStr: string = address.toBase58();
 
    return {
      signature: signatureStr,
      update: updateStr,
      transactions: transactionsStr,
      address: addressStr,
    };
  }
 
  /**
   * 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 commitData {@link MinaNFTCommit} commit data
   */
  public static async commitPreparedData(commitData: {
    deployer: PrivateKey;
    preparedCommitData: MinaNFTCommitData;
    ownerPublicKey: string;
    nameService: MinaNFTNameService;
    nonce?: number;
  }): Promise<Mina.PendingTransaction | undefined> {
    const {
      deployer,
      preparedCommitData,
      nameService,
      ownerPublicKey: ownerPublicKeyStr,
      nonce: nonceArg,
    } = commitData;
    const {
      address: addressStr,
      signature: signatureStr,
      update: updateStr,
      transactions: transactionsStr,
    } = preparedCommitData;
 
    Iif (nameService.address === undefined)
      throw new Error("Names service address is undefined");
 
    const transactions = transactionsStr.map((t) => {
      const obj = JSON.parse(t);
      const state = MetadataTransition.fromFields(
        obj.state.map((f: string) => Field.fromJSON(f))
      );
      const update = MetadataUpdate.fromFields(
        obj.update.map((f: string) => Field.fromJSON(f))
      );
      return { state, update };
    });
 
    const address = PublicKey.fromBase58(addressStr);
    const ownerPublicKey = PublicKey.fromBase58(ownerPublicKeyStr);
    const signature = Signature.fromBase58(signatureStr);
    const update = Update.fromFields(
      JSON.parse(updateStr).update.map((f: string) => Field.fromJSON(f))
    );
 
    Iif (MinaNFT.updateVerificationKey === undefined) {
      console.error("Update verification key is undefined");
      return undefined;
    }
 
    console.log("Creating proofs...");
    const logMsg = `Update proofs created`;
    console.time(logMsg);
    let proofs: MinaNFTMetadataUpdateProof[] = [];
    for (const transaction of transactions) {
      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];
    for (let i = 1; i < proofs.length; i++) {
      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;
    }
    proofs = [];
 
    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");
    }
 
    console.log("Commiting updates to blockchain...");
    const sender = deployer.toPublicKey();
    const zkApp = new MinaNFTNameServiceContract(nameService.address);
    const tokenId = zkApp.deriveTokenId();
    await fetchMinaAccount({ publicKey: nameService.address, force: true });
    await fetchMinaAccount({ publicKey: address, tokenId });
    await fetchMinaAccount({ publicKey: sender });
    const hasAccount = Mina.hasAccount(address, tokenId);
    Iif (!hasAccount) throw new Error("NFT is not deployed, no account");
    const account = Mina.getAccount(sender);
    const nonce: number = nonceArg ?? Number(account.nonce.toBigint());
 
    //console.log("Sending update...");
    const tx = await Mina.transaction(
      { sender, fee: await MinaNFT.fee(), memo: "minanft.io", nonce },
      async () => {
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        await zkApp.update(address, update, signature, ownerPublicKey, proof!);
      }
    );
    let sentTx: Mina.PendingTransaction | undefined = undefined;
    try {
      await sleep(100); // alow GC to run
      await tx.prove();
      tx.sign([deployer]);
      console.time("Update transaction sent");
      sentTx = await tx.send();
      console.timeEnd("Update transaction sent");
    } catch (error) {
      throw new Error("Prooving error");
    }
    Iif (sentTx === undefined) {
      throw new Error("Transaction error");
    }
    await MinaNFT.transactionInfo(sentTx, "update", false);
    if (sentTx.status === "pending") {
      return sentTx;
    } else Ereturn undefined;
  }
 
  /*
  private async generateProof(): Promise<
    MinaNFTMetadataUpdateProof | undefined
  > {
    if (MinaNFT.updateVerificationKey === undefined) {
      console.error("Update verification key is undefined");
      return undefined;
    }
 
    //console.log("Creating proofs...");
    console.time("Update proofs created");
    const proofs: MinaNFTMetadataUpdateProof[] = [];
    for (const update of this.updates) {
      const state = MetadataTransition.create(update);
      const proof = await MinaNFTMetadataUpdate.update(state, update);
      proofs.push(proof);
    }
 
    //console.log("Merging proofs...");
    let proof: MinaNFTMetadataUpdateProof = proofs[0];
    for (let i = 1; i < proofs.length; i++) {
      const state = MetadataTransition.merge(
        proof.publicInput,
        proofs[i].publicInput
      );
      const mergedProof = await MinaNFTMetadataUpdate.merge(
        state,
        proof,
        proofs[i]
      );
      proof = mergedProof;
    }
 
    const verificationResult: boolean = await verify(
      proof.toJSON(),
      MinaNFT.updateVerificationKey
    );
    console.timeEnd("Update proofs created");
    //console.log("Proof verification result:", verificationResult);
    if (verificationResult === false) {
      throw new Error("Proof verification error");
      return undefined;
    }
    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({
          increaseVersion: true,
          includePrivateData: false,
        }),
        name: this.name + ".json",
        keyvalues: { project: "MinaNFT", type: "metadata", nft: this.name },
      });
      Iif (hash === undefined) {
        console.error("Pinning to IPFS failed. Retrying...");
        await sleep(10000);
        hash = await ipfs.pinJSON({
          data: this.toJSON({
            increaseVersion: true,
            includePrivateData: false,
          }),
          name: this.name + ".json",
          keyvalues: { project: "MinaNFT", type: "metadata", nft: this.name },
        });
      }
      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 if (arweaveKey !== undefined) {
      console.log("Pinning to Arweave...");
      const arweave = new ARWEAVE(arweaveKey);
      const hash = await arweave.pinString(
        JSON.stringify(
          this.toJSON({
            increaseVersion: true,
            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 Ereturn undefined;
  }
 
  /*
 
  public async getPrivateJson(): Promise<Object | undefined> {
    if (!this.publicAttributes.get("name") || !this.publicAttributes.get("image"))
      return undefined;
    const publicAttributes: MerkleMap = new MerkleMap();
    Object.keys(this.publicAttributes).map((key) => {
      const value = this.publicAttributes.get(key);
      if (value)
        publicAttributes.set(
          MinaNFT.stringToField(key),
          MinaNFT.stringToField(value)
        );
      else {
        console.error("Map error");
        return undefined;
      }
    });
    const publicMapRoot: string = publicAttributes.getRoot().toJSON();
 
    const privateAttributes: MerkleMap = new MerkleMap();
    Object.keys(this.privateAttributes).map((key) => {
      const value = this.publicAttributes.get(key);
      if (value)
        privateAttributes.set(
          MinaNFT.stringToField(key),
          MinaNFT.stringToField(value)
        );
      else {
        console.error("Map error");
        return undefined;
      }
    });
    const privateMapRoot: string = privateAttributes.getRoot().toJSON();
 
    return {
      publicMapRoot,
      privateMapRoot,
      secret: this.secret ? this.secret.toJSON() : "",
      salt: this.salt ? this.salt.toJSON() : "",
      publicAttributes: MinaNFT.mapToJSON(this.publicAttributes),
      privateAttributes: MinaNFT.mapToJSON(this.privateAttributes),
    };
  }
  */
 
  /**
   * Logs transaction info
   * @param tx transaction
   * @param description description
   * @param wait wait for transaction to be included in the block
   */
  public static async transactionInfo(
    tx: Mina.PendingTransaction,
    description: string = "",
    wait: boolean = true
  ): Promise<void> {
    Iif (tx.status === "rejected") {
      console.error("Transaction failed");
      return;
    }
    try {
      Mina.getNetworkState();
    } catch (error) {
      // We're on Berkeley or TestWorld2
      const hash = tx.hash;
      Iif (hash === undefined) {
        throw new Error("Transaction hash is undefined");
        return;
      }
 
      console.log(`MinaNFT ${description} transaction sent: ${hash}`);
      Iif (wait) {
        try {
          //console.log("Waiting for transaction...");
          console.time("Transaction time");
          await tx.wait({ maxAttempts: 120, interval: 30 * 1000 }); //one hour
          console.timeEnd("Transaction time");
        } catch (error) {
          console.log("Error waiting for transaction", error);
        }
      }
    }
  }
 
  /*
   * Wait for transaction to be included in the block
   * @param tx transaction
   */
  public static async wait(tx: Mina.PendingTransaction): Promise<boolean> {
    /*
    try {
      Mina.getNetworkState();
    } catch (error) {
      // We're on Berkeley
      */
    try {
      //console.log("Waiting for transaction...");
      console.time("Transaction wait time");
      await tx.wait({ maxAttempts: 120, interval: 30 * 1000 }); //one hour
      console.timeEnd("Transaction wait time");
      return true;
    } catch (error) {
      console.log("Error waiting for transaction", error);
      return false;
    }
    //}
    //return true;
  }
 
  /**
   * Mints an NFT. Deploys and compiles the MinaNFT contract if needed.
   * @param minaData {@link MinaNFTMint} mint data
   * @param skipCalculatingMetadataRoot skip calculating metadata root in case the NFT is imported from the JSON that do not contains private metadata and therefore the root cannot be calculated
   */
  public async mint(
    minaData: MinaNFTMint,
    skipCalculatingMetadataRoot: boolean = false
  ): Promise<Mina.PendingTransaction | undefined> {
    const {
      nameService: nameServiceArg,
      deployer,
      owner: ownerArg,
      pinataJWT,
      arweaveKey,
      privateKey,
      escrow: escrowArg,
      nonce: nonceArg,
      signature: signatureArg,
    } = minaData;
    const nameService =
      nameServiceArg ??
      new MinaNFTNameService({
        address: PublicKey.fromBase58(MINANFT_NAME_SERVICE),
      });
    const escrow: Field = escrowArg ?? Field(0);
    const owner: Field = ownerArg ?? this.owner;
    Iif (owner.toJSON() === Field(0).toJSON())
      throw new Error("Owner is not defined");
    Iif (nameService.address === undefined)
      throw new Error("Names service address is undefined");
    await MinaNFT.compile();
    Iif (MinaNFT.verificationKey === undefined)
      throw new Error("Compilation error");
    const verificationKey: VerificationKey = MinaNFT.verificationKey;
    //console.log("Minting NFT...");
    const sender = deployer.toPublicKey();
    const zkAppPrivateKey = privateKey ?? PrivateKey.random();
    this.address = zkAppPrivateKey.toPublicKey();
    console.log("Deploying NFT to address", this.address.toBase58());
    //const zkApp = new MinaNFTContract(this.address);
 
    const root = skipCalculatingMetadataRoot
      ? this.metadataRoot
      : this.getMetadataRootAndMap().root;
    const storage = await this.pinToStorage(pinataJWT, arweaveKey);
    Iif (storage === undefined) {
      console.error("IPFS/Arweave Storage error");
      return undefined;
    }
    const storageHash: Storage = storage.hash;
    //const url = "https://minanft.io/" + this.name;
    const name = MinaNFT.stringToField(this.name);
    /*
        class MinaNFTContract extends SmartContract {
              @state(Field) name = State<Field>();
              @state(Metadata) metadata = State<Metadata>();
              @state(Storage) storage = State<Storage>();
              @state(Field) owner = State<Field>();
              @state(Field) escrow = State<Field>();
              @state(UInt64) version = State<UInt64>();
    */
 
    const nft = new NFTMintData({
      name,
      address: this.address,
      initialState: [
        name,
        root.data, // metadata.data,
        root.kind, // metadata.kind,
        storageHash.hashString[0],
        storageHash.hashString[1],
        owner,
        escrow,
        Field.from(1), //version
      ],
      verifier: nameService.address,
    });
    const signature =
      signatureArg ??
      (await nameService.issueNameSignature(nft, verificationKey.hash));
    const mintData: MintData = new MintData({
      nft,
      verificationKey,
      signature,
    });
 
    const zkApp = new MinaNFTNameServiceContract(nameService.address);
    const tokenId = zkApp.deriveTokenId();
    this.tokenId = tokenId;
    await fetchMinaAccount({ publicKey: nameService.address, force: true });
    //await fetchMinaAccount({ publicKey: this.address, tokenId });
    await fetchMinaAccount({ publicKey: sender, force: true });
    const account = Mina.getAccount(sender);
    const nonce: number = nonceArg ?? Number(account.nonce.toBigint());
    const hasAccount = Mina.hasAccount(this.address, tokenId);
 
    const transaction = await Mina.transaction(
      { sender, fee: await MinaNFT.fee(), memo: "minanft.io", nonce },
      async () => {
        if (!hasAccount) AccountUpdate.fundNewAccount(sender);
        await zkApp.mint(mintData);
      }
    );
    await sleep(100); // alow GC to run
    await transaction.prove();
    transaction.sign([deployer, zkAppPrivateKey]);
    const sentTx = await transaction.send();
    await MinaNFT.transactionInfo(sentTx, "mint", false);
    if (sentTx.status === "pending") {
      this.isMinted = true;
      this.metadataRoot = root;
      this.storage = storage.hashStr;
      this.owner = owner;
      this.escrow = escrow;
      this.version = UInt64.from(1);
      this.nameService = nameService.address;
      return sentTx;
    } else Ereturn undefined;
 
    /*
    await sleep(10 * 1000);
 
    // Check that the contract is deployed correctly
    await fetchMinaAccount({ publicKey: this.address });
 
    const newName = zkApp.name.get();
    if (newName.toJSON() !== MinaNFT.stringToField(this.name).toJSON())
      throw new Error("Wrong name");
 
    const newMetadataRoot = zkApp.metadata.get();
    if (
      newMetadataRoot.data.toJSON() !== root.data.toJSON() ||
      newMetadataRoot.kind.toJSON() !== root.kind.toJSON()
    )
      throw new Error("Wrong metadata");
 
    const newStorage = zkApp.storage.get();
    if (newStorage.toJSON() !== storageHash.toJSON())
      throw new Error("Wrong storage");
 
    const newOwner = zkApp.owner.get();
    if (newOwner.toJSON() !== owner.toJSON()) throw new Error("Wrong owner");
 
    const newVersion = zkApp.version.get();
    if (newVersion.toJSON() !== UInt64.from(0).toJSON())
      throw new Error("Wrong version");
 
    const newEscrow = zkApp.escrow.get();
    if (newEscrow.toJSON() !== Field(0).toJSON())
      throw new Error("Wrong escrow");
   */
  }
 
  /**
   * Transfer the NFT. Compiles the contract if needed.
   * @param transferData {@link MinaNFTTransfer} transfer data
   */
  public async transfer(
    transferData: MinaNFTTransfer
  ): Promise<Mina.PendingTransaction | undefined> {
    const {
      deployer,
      data,
      signature1,
      signature2,
      signature3,
      escrow1,
      escrow2,
      escrow3,
      nameService,
      nonce: nonceArg,
    } = transferData;
    Iif (this.address === undefined) {
      throw new Error("NFT contract is not deployed");
      return;
    }
    const address: PublicKey = this.address;
    Iif (this.isMinted === false) {
      throw new Error("NFT is not minted");
      return undefined;
    }
 
    Iif (nameService === undefined)
      throw new Error("Names service is undefined");
    Iif (nameService.address === undefined)
      throw new Error("Names service address is undefined");
 
    await MinaNFT.compile();
    Iif (MinaNFT.verificationKey === undefined) {
      throw new Error("Compilation error");
      return undefined;
    }
 
    //console.log("Transferring NFT...");
    this.nameService = nameService.address;
    Iif (false === (await this.checkState("transfer"))) {
      throw new Error("State verification error");
    }
    const sender = deployer.toPublicKey();
    const zkApp = new MinaNFTNameServiceContract(nameService.address);
    const tokenId = zkApp.deriveTokenId();
    await fetchMinaAccount({ publicKey: sender });
    await fetchMinaAccount({ publicKey: address, tokenId });
    const account = Mina.getAccount(sender);
    const nonce: number = nonceArg ?? Number(account.nonce.toBigint());
    Iif (!Mina.hasAccount(address, tokenId))
      throw new Error("NFT is not deployed, no account exists");
    const tx = await Mina.transaction(
      { sender, fee: await MinaNFT.fee(), memo: "minanft.io", nonce },
      async () => {
        await zkApp.escrowTransfer(
          address,
          data,
          signature1,
          signature2,
          signature3,
          escrow1,
          escrow2,
          escrow3
        );
      }
    );
    await sleep(100); // alow GC to run
    await tx.prove();
    tx.sign([deployer]);
    const txSent = await tx.send();
    await MinaNFT.transactionInfo(txSent, "transfer", false);
    if (txSent.status === "pending") {
      this.owner = data.newOwner;
      this.escrow = Field(0);
      this.version = this.version.add(UInt64.from(1));
      return txSent;
    } else Ereturn undefined;
  }
 
  /**
   * Approve the escrow for the NFT. Compiles the contract if needed.
   * @param approvalData {@link MinaNFTApproval} approval data
   */
  public async approve(
    approvalData: MinaNFTApproval
  ): Promise<Mina.PendingTransaction | undefined> {
    const {
      deployer,
      data,
      signature,
      ownerPublicKey,
      nameService,
      nonce: nonceArg,
    } = approvalData;
    Iif (this.address === undefined) {
      throw new Error("NFT contract is not deployed");
    }
    const address: PublicKey = this.address;
 
    Iif (this.isMinted === false) {
      throw new Error("NFT is not minted");
    }
 
    Iif (nameService === undefined)
      throw new Error("Names service is undefined");
 
    Iif (nameService.address === undefined)
      throw new Error("Names service address is undefined");
 
    await MinaNFT.compile();
    Iif (MinaNFT.verificationKey === undefined) {
      throw new Error("Compilation error");
    }
 
    this.nameService = nameService.address;
    Iif (false === (await this.checkState("approve"))) {
      throw new Error("State verification error");
    }
    const sender = deployer.toPublicKey();
    const zkApp = new MinaNFTNameServiceContract(nameService.address);
    const tokenId = zkApp.deriveTokenId();
    console.time("Calculated approval proof");
    const proof = await EscrowTransferVerification.check(
      new EscrowTransferApproval({
        approval: data,
        owner: Poseidon.hash(ownerPublicKey.toFields()),
      }),
      signature,
      ownerPublicKey
    );
    console.timeEnd("Calculated approval proof");
    await fetchMinaAccount({ publicKey: nameService.address, force: true });
    await fetchMinaAccount({ publicKey: address, tokenId });
    await fetchMinaAccount({ publicKey: sender });
    const account = Mina.getAccount(sender);
    const nonce: number = nonceArg ?? Number(account.nonce.toBigint());
    const tx = await Mina.transaction(
      { sender, fee: await MinaNFT.fee(), memo: "minanft.io", nonce },
      async () => {
        await zkApp.approveEscrow(address, proof);
      }
    );
    await sleep(100); // alow GC to run
    await tx.prove();
    tx.sign([deployer]);
    const txSent = await tx.send();
    await MinaNFT.transactionInfo(txSent, "approve", false);
    if (txSent.status === "pending") {
      this.escrow = data.escrow;
      this.version = this.version.add(UInt64.from(1));
      return txSent;
    } else Ereturn undefined;
  }
 
  /**
   * Verify Redacted MinaNFT proof
   * @param params arguments
   * @param params.deployer Private key of the account that will commit the updates
   * @param params.verifier Public key of the Verifier contract that will verify the proof
   * @param params.nft Public key of the NFT contract
   * @param params.nameServiceAddress Public key of the Name Service contract
   * @param params.proof Redacted MinaNFT proof
   */
  public static async verify(params: {
    deployer: PrivateKey;
    verifier: PublicKey;
    nft: PublicKey;
    nameServiceAddress: PublicKey;
    proof: RedactedMinaNFTMapStateProof;
  }): Promise<Mina.PendingTransaction> {
    const { deployer, verifier, nft, nameServiceAddress, proof } = params;
    const address = nft;
    await MinaNFT.compileVerifier();
 
    console.log("Verifying the proof...");
    const sender = deployer.toPublicKey();
    await fetchMinaAccount({ publicKey: sender });
    await fetchMinaAccount({ publicKey: address });
    const zkApp = new MinaNFTVerifier(verifier);
    const zkAppNFT = new MinaNFTNameServiceContract(nameServiceAddress);
    const tokenId = zkAppNFT.deriveTokenId();
 
    const tx = await Mina.transaction(
      { sender, fee: await MinaNFT.fee(), memo: "minanft.io" },
      async () => {
        await zkApp.verifyRedactedMetadata(address, tokenId, proof);
      }
    );
    await sleep(100); // alow GC to run
    await tx.prove();
    tx.sign([deployer]);
    const res = await tx.send();
    await MinaNFT.transactionInfo(res, "verify", false);
    return res;
  }
}