All files / src minanftbadge.ts

80.41% Statements 115/143
36.66% Branches 11/30
85.71% Functions 6/7
82.96% Lines 112/135

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 3224x 4x                   4x 4x 4x         4x       4x 4x 4x 4x                                                                     7x   7x 7x   7x 7x       7x 7x       7x 7x 7x 7x   7x                                                               7x 7x 7x 7x 7x     7x 7x   7x 7x   7x 7x               14x 14x 14x 14x 14x 14x 14x 14x 14x     7x 7x 7x 7x 7x 7x                   2x     2x     2x 2x 2x 2x   2x     2x 2x 2x 2x                     2x 2x 2x       2x                                   2x 2x 2x 2x   2x                       2x           2x           2x 2x       2x         2x 2x   2x 2x   2x 2x 2x 2x 2x   2x   2x 2x 2x 2x 2x   2x               4x 4x                   2x 2x 2x 2x 2x 2x 2x         16x     16x     16x 16x 16x 16x 16x 16x 16x 16x 16x 8x 8x 8x      
export { MinaNFTBadge, MinaNFTBadgeConstructor };
import {
  Mina,
  PrivateKey,
  PublicKey,
  AccountUpdate,
  MerkleMap,
  Signature,
  Account,
  Field,
} from "o1js";
import { MinaNFT } from "./minanft";
import { Metadata, MetadataWitness } from "./contract/metadata";
import {
  MinaNFTBadgeCalculation,
  BadgeData,
  BadgeDataWitness,
} from "./plugins/badgeproof";
import {
  MinaNFTVerifierBadgeEvent,
  MinaNFTVerifierBadge,
} from "./plugins/badge";
import { RedactedMinaNFT } from "./redactedminanft";
import { MinaNFTContract } from "./contract/nft";
import { sleep } from "./mina";
import { fetchMinaAccount } from "./fetch";
 
/**
 * interface for MinaNFTBadge constructor
 * @param name Name of the Badge issuer
 * @param owner Name of the Badge owner
 * @param verifiedKey Key of the Badge that is verified (like "twitter")
 * @param verifiedKind Kind of the Badge that is verified (like "string")
 * @param oracle Oracle public key that verifies the Badge
 *
 */
interface MinaNFTBadgeConstructor {
  name: string;
  owner: string;
  tokenSymbol: string;
  verifiedKey: string;
  verifiedKind: string;
  oracle: PublicKey;
  address?: PublicKey;
}
 
class MinaNFTBadge {
  name: string;
  owner: string;
  tokenSymbol: string;
  verifiedKey: string;
  verifiedKind: string;
  oracle: PublicKey;
  address?: PublicKey;
 
  /**
   * Create MinaNFT object
   * @param args {@link MinaNFTBadgeConstructor}
   */
  constructor(args: MinaNFTBadgeConstructor) {
    Iif (args.name.length > 30)
      throw new Error("Badge name too long, must be maximum 30 character");
    this.name = args.name;
    Iif (args.owner.length > 30)
      throw new Error("Badge owner too long, must be maximum 30 character");
    this.owner = args.owner;
    Iif (args.verifiedKey.length > 30)
      throw new Error(
        "Badge verifiedKey too long, must be maximum 30 character"
      );
    this.verifiedKey = args.verifiedKey;
    Iif (args.verifiedKind.length > 30)
      throw new Error(
        "Badge verifiedKind too long, must be maximum 30 character"
      );
    this.verifiedKind = args.verifiedKind;
    this.oracle = args.oracle;
    this.address = args.address;
    Iif (args.tokenSymbol.length > 6)
      throw new Error("Token symbol too long, must be maximum 6 characters");
    this.tokenSymbol = args.tokenSymbol;
  }
 
  public static async fromPublicKey(
    badgePublicKey: PublicKey
  ): Promise<MinaNFTBadge | undefined> {
    const zkApp = new MinaNFTVerifierBadge(badgePublicKey);
    await fetchMinaAccount({ publicKey: badgePublicKey });
    Iif (!Mina.hasAccount(badgePublicKey)) return undefined;
    const name = zkApp.name.get();
    const owner = zkApp.owner.get();
    const verifiedKey = zkApp.verifiedKey.get();
    const verifiedKind = zkApp.verifiedKind.get();
    const oracle = zkApp.oracle.get();
    // eslint-disable-next-line @typescript-eslint/no-inferrable-types
    const tokenSymbol: string = "BADGE";
    return new MinaNFTBadge({
      name: MinaNFT.stringFromField(name),
      owner: MinaNFT.stringFromField(owner),
      verifiedKey: MinaNFT.stringFromField(verifiedKey),
      verifiedKind: MinaNFT.stringFromField(verifiedKind),
      oracle,
      address: badgePublicKey,
      tokenSymbol,
    });
  }
 
  public async deploy(
    deployer: PrivateKey,
    privateKey: PrivateKey | undefined = undefined,
    nonce?: number
  ): Promise<Mina.PendingTransaction | undefined> {
    const sender = deployer.toPublicKey();
    const zkAppPrivateKey = privateKey ?? PrivateKey.random();
    const zkAppPublicKey = zkAppPrivateKey.toPublicKey();
    await MinaNFT.compileBadge();
    console.log(
      `deploying the MinaNFTVerifierBadge contract to an address ${zkAppPublicKey.toBase58()} using the deployer with public key ${sender.toBase58()}...`
    );
    await fetchMinaAccount({ publicKey: sender });
    await fetchMinaAccount({ publicKey: zkAppPublicKey });
    const deployNonce =
      nonce ?? Number(Mina.getAccount(sender).nonce.toBigint());
    const hasAccount = Mina.hasAccount(zkAppPublicKey);
 
    const zkApp = new MinaNFTVerifierBadge(zkAppPublicKey);
    const transaction = await Mina.transaction(
      {
        sender,
        fee: await MinaNFT.fee(),
        memo: "minanft.io",
        nonce: deployNonce,
      },
      async () => {
        if (!hasAccount) AccountUpdate.fundNewAccount(sender);
        await zkApp.deploy({});
        zkApp.name.set(MinaNFT.stringToField(this.name));
        zkApp.owner.set(MinaNFT.stringToField(this.owner));
        zkApp.verifiedKey.set(MinaNFT.stringToField(this.verifiedKey));
        zkApp.verifiedKind.set(MinaNFT.stringToField(this.verifiedKind));
        zkApp.oracle.set(this.oracle);
        zkApp.account.tokenSymbol.set(this.tokenSymbol);
        zkApp.account.zkappUri.set("https://minanft.io/" + this.name);
      }
    );
    transaction.sign([deployer, zkAppPrivateKey]);
    const tx = await transaction.send();
    await MinaNFT.transactionInfo(tx, "badge deploy", false);
    if (tx.status === "pending") {
      this.address = zkAppPublicKey;
      return tx;
    } else Ereturn undefined;
  }
 
  public async issue(
    deployer: PrivateKey,
    nft: MinaNFT,
    oraclePrivateKey: PrivateKey,
    nonce?: number
  ): Promise<Mina.PendingTransaction | undefined> {
    Iif (this.address === undefined) {
      throw new Error("Badge not deployed");
    }
    Iif (nft.address === undefined) {
      throw new Error("NFT not deployed");
    }
    Iif (nft.tokenId === undefined) throw new Error("NFT tokenId not set");
    const nftTokenId: Field = nft.tokenId;
    const nftAddress: PublicKey = nft.address;
    await MinaNFT.compileBadge();
    //console.log("Creating proofs for", verifiedKey);
    const logStr = `Badge proofs created for ${
      nft.name
    } ${nft.version.toJSON()}`;
    console.time(logStr);
    const disclosure = new RedactedMinaNFT(nft);
    disclosure.copyMetadata(this.verifiedKey);
    const redactedProof = await disclosure.proof();
    /*
        class MinaNFTVerifierBadgeEvent extends Struct({
          address: PublicKey,
          owner: Field,
          name: Field,
          version: UInt64,
          data: Metadata,
          key: Field,
        })
    */
    const privateData = nft.getMetadata(this.verifiedKey);
    Iif (privateData === undefined) throw new Error("Metadata not found");
    const nftdata: Metadata = new Metadata({
      data: privateData.data,
      kind: privateData.kind,
    });
    const badgeEvent: MinaNFTVerifierBadgeEvent = new MinaNFTVerifierBadgeEvent(
      {
        address: nftAddress,
        owner: nft.owner,
        name: MinaNFT.stringToField(nft.name),
        version: nft.version,
        data: nftdata,
        key: MinaNFT.stringToField(this.verifiedKey),
      }
    );
    /*
          class BadgeDataWitness extends Struct({
            root: Metadata,
            value: Metadata,
            key: Field,
            witness: MetadataWitness,
          }) {}
    */
    const data: MerkleMap = new MerkleMap();
    const kind: MerkleMap = new MerkleMap();
    data.set(badgeEvent.key, badgeEvent.data.data);
    kind.set(badgeEvent.key, badgeEvent.data.kind);
 
    const badgeDataWitness: BadgeDataWitness = {
      root: {
        data: data.getRoot(),
        kind: kind.getRoot(),
      } as Metadata,
      value: badgeEvent.data,
      key: badgeEvent.key,
      witness: {
        data: data.getWitness(badgeEvent.key),
        kind: kind.getWitness(badgeEvent.key),
      } as MetadataWitness,
    };
    Iif (
      badgeDataWitness.root.data.toJSON() !==
      redactedProof.publicInput.redactedRoot.data.toJSON()
    ) {
      throw new Error("Data root mismatch");
    }
    Iif (
      badgeDataWitness.root.kind.toJSON() !==
      redactedProof.publicInput.redactedRoot.kind.toJSON()
    ) {
      throw new Error("Kind root mismatch");
    }
    const badgeState = BadgeData.create(badgeDataWitness);
    const badgeStateProof = await MinaNFTBadgeCalculation.create(
      badgeState,
      badgeDataWitness
    );
    const signature = Signature.create(
      oraclePrivateKey,
      MinaNFTVerifierBadgeEvent.toFields(badgeEvent)
    );
 
    const issuer = new MinaNFTVerifierBadge(this.address);
    const tokenId = issuer.deriveTokenId();
 
    console.timeEnd(logStr);
    const sender = deployer.toPublicKey();
 
    await fetchMinaAccount({ publicKey: sender });
    await fetchMinaAccount({ publicKey: nftAddress, tokenId: nftTokenId });
    await fetchMinaAccount({ publicKey: this.address });
    await fetchMinaAccount({ publicKey: nftAddress, tokenId });
    const hasAccount = Mina.hasAccount(nftAddress, tokenId);
    const deployNonce =
      nonce ?? Number(Mina.getAccount(sender).nonce.toBigint());
 
    const hasNftAccount = Mina.hasAccount(nftAddress, nftTokenId);
    Iif (!hasNftAccount) throw new Error("NFT account not found");
    const zkAppNFT = new MinaNFTContract(nftAddress, nftTokenId);
    const version = zkAppNFT.version.get();
    console.log("Issuing badge for", nft.name, "version", version.toJSON());
 
    const transaction = await Mina.transaction(
      {
        sender,
        fee: await MinaNFT.fee(),
        memo: "minanft.io",
        nonce: deployNonce,
      },
      async () => {
        if (!hasAccount) AccountUpdate.fundNewAccount(sender);
        await issuer.issueBadge(
          nftAddress,
          nftTokenId,
          badgeEvent,
          signature,
          redactedProof,
          badgeStateProof
        );
      }
    );
    await sleep(100); // alow GC to run
    await transaction.prove();
    transaction.sign([deployer]);
    const tx = await transaction.send();
    await MinaNFT.transactionInfo(tx, "issue badge", false);
    if (tx.status === "pending") {
      return tx;
    } else Ereturn undefined;
  }
 
  public async verify(nft: MinaNFT): Promise<boolean> {
    Iif (this.address === undefined) {
      throw new Error("Badge not deployed");
    }
    Iif (nft.address === undefined) {
      throw new Error("NFT not deployed");
    }
    Iif (nft.tokenId === undefined) throw new Error("NFT tokenId not set");
    const nftAddress: PublicKey = nft.address;
    const issuer = new MinaNFTVerifierBadge(this.address);
    const tokenId = issuer.deriveTokenId();
    const zkNFT = new MinaNFTContract(nftAddress, nft.tokenId);
    await fetchMinaAccount({ publicKey: nftAddress, tokenId });
    await fetchMinaAccount({ publicKey: nftAddress, tokenId: nft.tokenId });
    const hasAccount = Mina.hasAccount(nftAddress, tokenId);
    if (!hasAccount) return false;
    const version = zkNFT.version.get();
    const balance = Mina.getBalance(nftAddress, tokenId);
    return version.equals(balance).toBoolean();
  }
}