All files / src/metadata metadata.ts

80.41% Statements 156/194
64.54% Branches 71/110
100% Functions 16/16
84.69% Lines 155/183

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 6042x 2x 2x 2x   2x 2x   2x 2x 2x           2x 2x                                                                           559x   559x 559x 559x   168x 168x 168x       327x 327x 327x 327x 327x   23x 23x 23x   25x 25x 25x 25x 25x   16x   16x 16x 16x 16x         559x                       572x                                                                                                       3x               21x           1x                 1x 20x 19x 1x 1x   1x                                         9x 9x 9x                                 6x               6x 6x                                                                     91x                                     91x 91x 91x 91x         91x         91x 69x           91x 1x           91x 91x 91x 91x                                 568x 568x   568x   568x   559x   168x   168x 168x       327x   327x 327x   23x   23x 23x   25x   25x 25x   16x   16x 16x       559x   9x 9x 9x 9x 9x 9x 9x       568x 568x 568x                                         65x             303x     282x         234x   234x 234x   14x   14x 14x   18x   18x 18x   10x   10x 10x   6x 6x   6x 6x   282x                                                               59x 59x 59x 59x 59x   59x   59x   59x   59x   59x 255x 255x   255x   255x     59x             59x   255x         211x   211x 211x   12x   12x 12x   16x   16x                             16x   10x   10x             10x   6x 6x   6x 6x   255x             59x                             59x             2x                  
import { Experimental, Field, Poseidon, Struct, UInt64 } from "o1js";
import { fieldFromString } from "../contracts";
import { Text } from "./text";
import { MetadataTree } from "./tree";
export {
  Metadata,
  MetadataMap,
  MetadataFieldType,
  MetadataFieldTypeValues,
  MetadataValue,
  ColorPlugin,
};
 
/**
 * The height of the metadata Merkle tree.
 */
const METADATA_HEIGHT = 20;
const IndexedMerkleMap = Experimental.IndexedMerkleMap;
type IndexedMerkleMap = Experimental.IndexedMerkleMap;
 
/**
 * A specialized IndexedMerkleMap for storing metadata.
 */
class MetadataMap extends IndexedMerkleMap(METADATA_HEIGHT) {}
 
/**
 * The possible types for metadata fields.
 */
type MetadataFieldType =
  | "string"
  | "text"
  | "image"
  | "url"
  | "field"
  | "map"
  | "tree";
 
/**
 * Represents a metadata value with its type and associated data.
 */
class MetadataValue extends Struct({
  value: Field,
  type: Field,
  length: Field,
  height: Field,
}) {
  /**
   * Creates a new MetadataValue instance.
   * @param params - The parameters including value and type.
   * @returns A new MetadataValue.
   */
  static new(params: {
    value: Field | Text | Metadata | MetadataTree;
    type: MetadataFieldType;
  }) {
    const { value, type } = params;
    let valueField: Field;
    let length = Field(0);
    let height = Field(0);
    switch (type) {
      case "string":
        Iif (!(value instanceof Field)) throw new Error(`Invalid value type`);
        valueField = value;
        break;
      case "text":
      case "image":
      case "url":
        Iif (!(value instanceof Text)) throw new Error(`Invalid value type`);
        valueField = value.root;
        length = Field(value.size);
        height = Field(value.height);
        break;
      case "field":
        Iif (!(value instanceof Field)) throw new Error(`Invalid value type`);
        valueField = value;
        break;
      case "map":
        Iif (!(value instanceof Metadata)) throw new Error(`Invalid value type`);
        valueField = value.map.root;
        length = Field(value.map.length);
        height = Field(value.map.height);
        break;
      case "tree":
        Iif (!(value instanceof MetadataTree))
          throw new Error(`Invalid value type`);
        valueField = value.root;
        length = Field(value.values.length);
        height = Field(value.height);
        break;
      default:
        throw new Error(`Unknown value type`);
    }
 
    return new MetadataValue({
      value: valueField,
      type: Field(MetadataFieldTypeValues[type].code),
      length,
      height,
    });
  }
  /**
   * Computes the Poseidon hash of the metadata value.
   * @returns The hash as a Field.
   */
  hash(): Field {
    return Poseidon.hash(MetadataValue.toFields(this));
  }
}
 
/**
 * Abstract class for creating custom metadata plugins.
 */
abstract class MetadataPlugin {
  /**
   * The name of the plugin.
   */
  readonly name: string;
  /**
   * Retrieves the trait representation of the metadata value.
   * @param params - The parameters including key, type, value, and isPrivate.
   * @returns An object containing the key, value, and canonical representation.
   */
  abstract getTrait(params: {
    key: string;
    type: string;
    value: unknown;
    isPrivate?: boolean;
  }): {
    key: Field;
    value: MetadataValue;
    canonicalRepresentation: unknown;
  };
  /**
   * Converts the value to JSON.
   * @param value - The value to convert.
   * @returns The JSON representation.
   */
  abstract toJSON(value: unknown): string | object;
  /**
   * Parses the value from JSON.
   * @param value - The JSON value to parse.
   * @returns The parsed value.
   */
  abstract fromJSON(value: string | object): unknown;
}
 
/**
 * Type representing color values.
 */
type Color = "blue" | "red" | "green" | "yellow" | "purple" | "orange" | "pink";
/**
 * A plugin for handling color metadata.
 */
class ColorPlugin extends MetadataPlugin {
  /**
   * The name of the plugin.
   */
  readonly name = "color";
 
  /**
   * Converts a color name or value into its numeric representation.
   * @param value - The color value (name, string, or number).
   * @returns The numeric representation of the color.
   */
  getColor(value: Color | string | number): number {
    if (
      typeof value === "string" &&
      ["blue", "red", "green", "yellow", "purple", "orange", "pink"].includes(
        value
      )
    ) {
      const colors: { [key in Color]: number } = {
        blue: 0x0000ff,
        red: 0xff0000,
        green: 0x00ff00,
        yellow: 0xffff00,
        purple: 0x800080,
        orange: 0xffa500,
        pink: 0xffc0cb,
      };
      return colors[value as Color];
    } else if (typeof value === "number") {
      return value;
    } else if (typeof value === "string") {
      try {
        // parse hex color like #0000ff
        return parseInt(value.slice(1), 16);
      } catch (e) {
        throw new Error("Invalid color value");
      }
    }
    throw new Error("Invalid color value");
  }
  /**
   * Retrieves the trait representation of the color value.
   * @param params - The parameters including key, type, and value.
   * @returns An object containing the key, value, and canonical representation.
   */
  getTrait(params: {
    key: string;
    type: string;
    value: Color | string | number;
  }): {
    key: Field;
    value: MetadataValue;
    canonicalRepresentation: number;
  } {
    const { key, value } = params;
    const color = this.getColor(value);
    return {
      key: fieldFromString(key),
      value: new MetadataValue({
        value: Field(color),
        type: Field(10),
        length: Field(0),
        height: Field(0),
      }),
      canonicalRepresentation: color,
    };
  }
  /**
   * Converts the color value to a JSON string.
   * @param value - The color value.
   * @returns The JSON string representation.
   */
  toJSON(value: Color | string | number): string {
    return this.getColor(value).toString(16);
  }
  /**
   * Parses the color value from a JSON string or object.
   * @param value - The JSON value.
   * @returns The numeric representation of the color.
   */
  fromJSON(value: string | object): number {
    Iif (typeof value !== "string") throw new Error("Invalid color value");
    return this.getColor(parseInt(value, 16));
  }
}
 
/**
 * Represents the metadata for an NFT, including traits and associated data.
 */
class Metadata {
  /**
   * The underlying map storing the metadata key-value pairs.
   */
  readonly map: MetadataMap;
  /**
   * The name of the NFT.
   */
  readonly name: string;
  /**
   * The image associated with the NFT.
   */
  image: string;
  /**
   * Optional banner image for the NFT.
   */
  banner?: string;
  /**
   * Optional description of the NFT.
   */
  description?: string;
  /**
   * Array of metadata plugins used for custom traits.
   */
  plugins: MetadataPlugin[];
  /**
   * Object containing the traits of the NFT.
   */
  traits: {
    [key: string]: {
      type: string;
      value: string | Field | Metadata | MetadataTree | unknown;
      isPrivate: boolean;
    };
  } = {};
 
  /**
   * Creates a new Metadata instance.
   * @param params - The parameters for the metadata, including name, image, description, banner, and plugins.
   */
  constructor(params: {
    name: string;
    image: string;
    description?: string;
    banner?: string;
    plugins?: MetadataPlugin[];
  }) {
    const { name, description, image, banner, plugins } = params;
    this.plugins = plugins ?? [];
    this.map = new MetadataMap();
    this.addTrait({
      key: "name",
      type: "string",
      value: name,
    });
    this.addTrait({
      key: "image",
      type: "image",
      value: image,
    });
    if (description) {
      this.addTrait({
        key: "description",
        type: "text",
        value: description,
      });
    }
    if (banner) {
      this.addTrait({
        key: "banner",
        type: "image",
        value: banner,
      });
    }
    this.name = name;
    this.image = image;
    this.banner = banner;
    this.description = description;
  }
 
  /**
   * Adds a trait to the metadata.
   * @param params - The parameters including key, type, value, and isPrivate.
   * @returns An object containing the key and the metadata value.
   */
  addTrait(params: {
    key: string;
    type: string;
    value: string | Field | Metadata | MetadataTree | unknown;
    isPrivate?: boolean;
  }): {
    key: Field;
    value: MetadataValue;
  } {
    const { key, type, value, isPrivate = false } = params;
    let keyField = fieldFromString(key);
    let metadataValue: MetadataValue;
    let canonicalRepresentation: unknown = value;
 
    if (type in MetadataFieldTypeValues) {
      let valueObject: Field | Text | Metadata | MetadataTree;
      switch (type) {
        case "string":
          Iif (typeof value !== "string")
            throw new Error(`Invalid trait value type`);
          valueObject = fieldFromString(value);
          break;
        case "text":
        case "image":
        case "url":
          Iif (typeof value !== "string")
            throw new Error(`Invalid trait value type`);
          valueObject = new Text(value);
          break;
        case "field":
          Iif (!(value instanceof Field))
            throw new Error(`Invalid trait value type`);
          valueObject = value;
          break;
        case "map":
          Iif (!(value instanceof Metadata))
            throw new Error(`Invalid trait value type`);
          valueObject = value;
          break;
        case "tree":
          Iif (!(value instanceof MetadataTree))
            throw new Error(`Invalid trait value type`);
          valueObject = value;
          break;
        default:
          throw new Error(`Unknown trait value type - internal error`);
      }
      metadataValue = MetadataValue.new({ value: valueObject, type });
    } else {
      const index = this.plugins.findIndex((plugin) => plugin.name === type);
      if (index !== -1) {
        const plugin = this.plugins[index];
        const pluginTrait = plugin.getTrait({ key, type, value, isPrivate });
        metadataValue = pluginTrait.value;
        keyField = pluginTrait.key;
        canonicalRepresentation = pluginTrait.canonicalRepresentation;
      } else Ethrow new Error(`Unknown trait type`);
    }
 
    this.map.set(keyField, metadataValue.hash());
    this.traits[key] = { type, value: canonicalRepresentation, isPrivate };
    return { key: keyField, value: metadataValue };
  }
 
  /**
   * Converts the metadata to a JSON representation.
   * @param includePrivateTraits - Whether to include private traits.
   * @returns The JSON representation of the metadata.
   */
  toJSON(includePrivateTraits = false): {
    name: string;
    image: string;
    description?: string;
    banner?: string;
    metadataRoot: string;
    traits: {
      key: string;
      type: string;
      value: string | object;
      isPrivate?: boolean;
    }[];
  } {
    return {
      name: this.name,
      description: this.description,
      image: this.image,
      banner: this.banner,
      metadataRoot: this.map.root.toJSON(),
      traits: Object.entries(this.traits)
        .filter(([_, { isPrivate }]) => includePrivateTraits || !isPrivate)
        .map(([key, { type, value, isPrivate }]) => {
          let jsonValue: string | object;
          switch (type) {
            case "string":
            case "text":
            case "image":
            case "url":
              Iif (typeof value !== "string")
                throw new Error(`Invalid trait value type`);
              jsonValue = value;
              break;
            case "field":
              Iif (!(value instanceof Field))
                throw new Error(`Invalid trait value type`);
              jsonValue = value.toJSON();
              break;
            case "map":
              Iif (!(value instanceof Metadata))
                throw new Error(`Invalid trait value type`);
              jsonValue = value.toJSON(includePrivateTraits);
              break;
            case "tree":
              Iif (!(value instanceof MetadataTree))
                throw new Error(`Invalid trait value type`);
              jsonValue = value.toJSON();
              break;
            default:
              const plugin = this.plugins.find(
                (plugin) => plugin.name === type
              );
              Iif (!plugin) throw new Error(`Unknown trait type`);
              jsonValue = plugin.toJSON(value);
          }
          return {
            key,
            type,
            ...(isPrivate ? { isPrivate } : {}),
            value: jsonValue,
          };
        }),
    };
  }
 
  /**
   * Constructs a Metadata instance from JSON data.
   * @param params - The parameters including json data, checkRoot flag, and plugins.
   * @returns A new Metadata instance.
   */
  static fromJSON(params: {
    json: {
      name: string;
      image: string;
      description?: string;
      banner?: string;
      metadataRoot: string;
      traits: {
        key: string;
        type: string;
        value: string | object;
        isPrivate?: boolean;
      }[];
    };
    checkRoot?: boolean;
    plugins?: MetadataPlugin[];
  }): Metadata {
    const { json, checkRoot = false, plugins } = params;
    const { name, description, image, banner, metadataRoot, traits } = json;
    Iif (!name) throw new Error(`Metadata name is required`);
    Iif (typeof name !== "string") throw new Error(`Invalid metadata name`);
    Iif (!image || typeof image !== "string")
      throw new Error(`Invalid metadata image`);
    Iif (description && typeof description !== "string")
      throw new Error(`Invalid metadata description`);
    Iif (banner && typeof banner !== "string")
      throw new Error(`Invalid metadata banner`);
    Iif (!metadataRoot || typeof metadataRoot !== "string")
      throw new Error(`Invalid metadata root`);
    Iif (!traits || !Array.isArray(traits))
      throw new Error(`Metadata traits are required`);
    for (const { key, type, value, isPrivate } of traits) {
      Iif (!key || typeof key !== "string") throw new Error(`Invalid trait key`);
      Iif (!type || typeof type !== "string")
        throw new Error(`Invalid trait type`);
      Iif (!value || (typeof value !== "string" && typeof value !== "object"))
        throw new Error(`Invalid trait value`);
      Iif (isPrivate && typeof isPrivate !== "boolean")
        throw new Error(`Invalid trait isPrivate`);
    }
    const metadata = new Metadata({
      name,
      description,
      image,
      banner,
      plugins,
    });
    for (const { key, type, value, isPrivate } of traits) {
      let valueField: string | Field | Metadata | MetadataTree | unknown;
      switch (type) {
        case "string":
        case "text":
        case "image":
        case "url":
          Iif (typeof value !== "string")
            throw new Error(`Invalid trait value type`);
          valueField = value;
          break;
        case "field":
          Iif (typeof value !== "string")
            throw new Error(`Invalid trait value type`);
          valueField = Field.fromJSON(value);
          break;
        case "map":
          Iif (typeof value !== "object")
            throw new Error(`Invalid trait value type`);
          valueField = Metadata.fromJSON({
            json: value as unknown as {
              name: string;
              image: string;
              description?: string;
              metadataRoot: string;
              traits: {
                key: string;
                type: string;
                value: string | object;
                isPrivate?: boolean;
              }[];
            },
            checkRoot,
          });
          break;
        case "tree":
          Iif (typeof value !== "object")
            throw new Error(`Invalid trait value type`);
          valueField = MetadataTree.fromJSON(
            value as unknown as {
              height: number;
              root: string;
              values: { key: string; value: string }[];
            }
          );
          break;
        default:
          const plugin = metadata.plugins.find(
            (plugin) => plugin.name === type
          );
          Iif (!plugin) throw new Error(`Unknown trait type`);
          valueField = plugin.fromJSON(value);
      }
      metadata.addTrait({
        key,
        type,
        value: valueField,
        isPrivate: isPrivate ?? false,
      });
    }
    Iif (checkRoot === true && metadata.map.root.toJSON() !== metadataRoot) {
      throw new Error(
        `Invalid metadata root:${JSON.stringify(
          {
            params,
            root: metadata.map.root.toJSON(),
            checkRoot,
            metadata: metadata.toJSON(true),
          },
          null,
          2
        )}`
      );
    }
 
    return metadata;
  }
}
 
/**
 * Mapping of metadata field types to their code values and associated types.
 */
const MetadataFieldTypeValues = {
  string: { code: 1n, inputType: "string", storedType: Field }, // Field
  text: { code: 2n, inputType: "string", storedType: Text }, // Text
  image: { code: 3n, inputType: "string", storedType: Text }, // Text
  url: { code: 4n, inputType: "string", storedType: Text }, // Text
  field: { code: 5n, inputType: Field, storedType: Field }, // Field
  map: { code: 6n, inputType: Metadata, storedType: Metadata }, // Metadata
  tree: { code: 7n, inputType: MetadataTree, storedType: MetadataTree }, // MetadataTree
} as const;