# All files / lib/messages ContractInfo.ts

83.76% Statements 98/117
50.91% Branches 28/55
80% Functions 16/20
83.62% Lines 97/116

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
    4401x

    1x
    1x

    1x
    1x

    1x

    54x
    54x

    54x

    42x

    12x

    30x

    30x
    22x

    8x
    8x

    77x

    1x
    1x
    1x

    22x

    22x

    22x

    22x

    22x

    22x

    42x
    42x

    42x
    42x

    42x

    42x
    42x

    42x
    42x

    21x

    21x

    21x

    42x

    113x

    113x

    9x

    9x

    17x

    105x

    105x
    105x
    105x

    105x
    55x
    55x

    50x
    50x

    105x

    1x
    1x
    1x

    8x

    8x

    8x
    8x

    16x

    8x

    12x
    12x

    12x
    12x

    12x

    12x

    24x

    24x
    24x

    24x

    24x

    24x

    24x

    24x
    24x

    24x

    12x

    20x

    20x

    20x

    4x

    8x

    28x

    28x
    28x
    28x

    28x
    56x

    56x

    56x
    56x

    28x

    1x
    1x

     import { BufferReader, BufferWriter } from '@node-dlc/bufio';

    import { ContractInfoType, MessageType } from '../MessageType';
    import {
      ContractDescriptor,
      ContractDescriptorV0JSON,
      ContractDescriptorV1JSON,
    } from './ContractDescriptor';
    import { DlcMessage, IDlcMessage } from './DlcMessage';
    import {
      MultiOracleInfo,
      MultiOracleInfoJSON,
      OracleInfo,
      SingleOracleInfo,
      SingleOracleInfoJSON,
    } from './OracleInfo';

    export abstract class ContractInfo extends DlcMessage {
      public static deserialize(
        buf: Buffer,
      ): SingleContractInfo | DisjointContractInfo {
        const reader = new BufferReader(buf);
        const typeId = Number(reader.readBigSize());

        switch (typeId) {
          case ContractInfoType.Single:
            return SingleContractInfo.deserialize(buf);
          case ContractInfoType.Disjoint:
            return DisjointContractInfo.deserialize(buf);
          default:
            throw new Error(
              `Contract info type must be Single (0) or Disjoint (1), got ${typeId}`,
            );
        }
      }

      /**
       * Creates a ContractInfo from JSON data (e.g., from test vectors)
       * @param json JSON object representing contract info
       */
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
      public static fromJSON(json: any): ContractInfo {
        Iif (!json) {
          throw new Error('contractInfo is required');
        }

        // Check if it's a single contract info or disjoint contract info
        if (json.singleContractInfo || json.single_contract_info) {
          return SingleContractInfo.fromJSON(
            json.singleContractInfo || json.single_contract_info,
          );
        } else Eif (json.disjointContractInfo || json.disjoint_contract_info) {
          return DisjointContractInfo.fromJSON(
            json.disjointContractInfo || json.disjoint_contract_info,
          );
        } else {
          throw new Error(
            'contractInfo must have either singleContractInfo or disjointContractInfo',
          );
        }
      }

      public abstract contractInfoType: ContractInfoType;
      public abstract totalCollateral: bigint;
      public abstract validate(): void;
      public abstract toJSON(): ISingleContractInfoJSON | IDisjointContractInfoJSON;
      public abstract serialize(): Buffer;

      // Method to get total collateral (for compatibility)
      public getTotalCollateral(): bigint {
        return this.totalCollateral;
      }
    }

    /**
     * SingleContractInfo contains information about a contract's outcomes,
     * their corresponding payouts, and the oracles to be used.
     * This corresponds to the previous ContractInfoV0.
     */
    export class SingleContractInfo extends ContractInfo implements IDlcMessage {
      public static contractInfoType = ContractInfoType.Single;
      public static type = MessageType.SingleContractInfo;

      /**
       * Creates a SingleContractInfo from JSON data
       * @param json JSON object representing single contract info
       */
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
      public static fromJSON(json: any): SingleContractInfo {
        const instance = new SingleContractInfo();

        instance.totalCollateral = BigInt(
          json.totalCollateral || json.total_collateral || 0,
        );

        // Handle nested contractInfo structure (test vectors have double nesting)
        const contractInfoData = json.contractInfo || json.contract_info || json;

        // Parse contract descriptor using proper fromJSON method
        instance.contractDescriptor = ContractDescriptor.fromJSON(
          contractInfoData.contractDescriptor ||
            contractInfoData.contract_descriptor,
        );

        // Parse oracle info using proper fromJSON method
        instance.oracleInfo = OracleInfo.fromJSON(
          contractInfoData.oracleInfo || contractInfoData.oracle_info,
        );

        return instance;
      }

      /**
       * Deserializes a single_contract_info message
       * @param buf
       */
      public static deserialize(buf: Buffer): SingleContractInfo {
        const instance = new SingleContractInfo();
        const reader = new BufferReader(buf);

        reader.readBigSize(); // read type (0)
        instance.totalCollateral = reader.readUInt64BE();

        // Read contract descriptor as sibling type (starts with its own type prefix)
        instance.contractDescriptor = ContractDescriptor.deserialize(
          reader.buffer.subarray(reader.position),
        );
        // Skip past the contract descriptor we just read
        const descLength = instance.contractDescriptor.serialize().length;
        reader.position += descLength;

        // Read oracle info with rust-dlc format - discriminator + body
        const oracleType = Number(reader.readBigSize());
        if (oracleType === 0) {
          // Single oracle
          instance.oracleInfo = SingleOracleInfo.deserializeBody(
            reader.buffer.subarray(reader.position),
          );
        } else Eif (oracleType === 1) {
          // Multi oracle
          instance.oracleInfo = MultiOracleInfo.deserializeBody(
            reader.buffer.subarray(reader.position),
          );
        } else {
          throw new Error(`Unknown oracle info type: ${oracleType}`);
        }

        return instance;
      }

      /**
       * The type for single_contract_info message - using MessageType for IDlcMessage compatibility
       */
      public type = MessageType.SingleContractInfo;

      /**
       * The contract info type for new format
       */
      public contractInfoType = ContractInfoType.Single;

      public totalCollateral: bigint;

      public contractDescriptor: ContractDescriptor;

      public oracleInfo: OracleInfo;

      // Compatibility property
      public get length(): bigint {
        return BigInt(this.serialize().length);
      }

      /**
       * Validates correctness of all fields in the message
       * @throws Will throw an error if validation fails
       */
      public validate(): void {
        Iif (this.totalCollateral <= 0) {
          throw new Error('totalCollateral must be greater than 0');
        }

        this.oracleInfo.validate();

        // TODO: Add contract descriptor validation once available
        // this.contractDescriptor.validate();
      }

      /**
       * Converts single_contract_info to JSON
       */
      public toJSON(): ISingleContractInfoJSON {
        // Return enum variant format for Rust compatibility
        return {
          singleContractInfo: {
            totalCollateral: Number(this.totalCollateral),
            contractInfo: {
              contractDescriptor: this.contractDescriptor.toJSON(),
              oracleInfo: this.oracleInfo.toJSON(),
            },
          },
        };
      }

      /**
       * Serializes the single_contract_info message into a Buffer
       */
      public serialize(): Buffer {
        const writer = new BufferWriter();

        writer.writeBigSize(this.contractInfoType);
        writer.writeUInt64BE(this.totalCollateral);
        writer.writeBytes(this.contractDescriptor.serialize());

        // Use serializeBody() to match rust-dlc behavior - don't add extra TLV wrapper
        if (this.oracleInfo instanceof SingleOracleInfo) {
          writer.writeBigSize(0); // Single oracle discriminator
          writer.writeBytes(this.oracleInfo.serializeBody());
        } else {
          writer.writeBigSize(1); // Multi oracle discriminator
          writer.writeBytes(this.oracleInfo.serializeBody());
        }

        return writer.toBuffer();
      }
    }

    /**
     * DisjointContractInfo contains information about multiple disjoint contract events.
     * This corresponds to the previous ContractInfoV1.
     */
    export class DisjointContractInfo extends ContractInfo implements IDlcMessage {
      public static contractInfoType = ContractInfoType.Disjoint;
      public static type = MessageType.DisjointContractInfo;

      /**
       * Creates a DisjointContractInfo from JSON data
       * @param json JSON object representing disjoint contract info
       */
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
      public static fromJSON(json: any): DisjointContractInfo {
        const instance = new DisjointContractInfo();

        instance.totalCollateral = BigInt(
          json.totalCollateral || json.total_collateral || 0,
        );

        // Parse contract infos array
        const contractInfosData = json.contractInfos || json.contract_infos || [];
        instance.contractOraclePairs = contractInfosData.map(
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (contractInfoData: any) => ({
            contractDescriptor: ContractDescriptor.fromJSON(
              contractInfoData.contractDescriptor ||
                contractInfoData.contract_descriptor,
            ),
            oracleInfo: OracleInfo.fromJSON(
              contractInfoData.oracleInfo || contractInfoData.oracle_info,
            ),
          }),
        );

        return instance;
      }

      /**
       * Deserializes a disjoint_contract_info message
       * @param buf
       */
      public static deserialize(buf: Buffer): DisjointContractInfo {
        const instance = new DisjointContractInfo();
        const reader = new BufferReader(buf);

        reader.readBigSize(); // read type (1)
        instance.totalCollateral = reader.readUInt64BE();

        const numDisjointEvents = Number(reader.readBigSize());

        for (let i = 0; i < numDisjointEvents; i++) {
          // Read contract descriptor as sibling type (starts with its own type prefix)
          const contractDescriptor = ContractDescriptor.deserialize(
            reader.buffer.subarray(reader.position),
          );
          // Skip past the contract descriptor we just read
          const descLength = contractDescriptor.serialize().length;
          reader.position += descLength;

          // Read oracle info with rust-dlc format - discriminator + body (same as SingleContractInfo)
          const oracleType = Number(reader.readBigSize());
          let oracleInfo: OracleInfo;

          Iif (oracleType === 0) {
            // Single oracle
            oracleInfo = SingleOracleInfo.deserializeBody(
              reader.buffer.subarray(reader.position),
            );
          } else Eif (oracleType === 1) {
            // Multi oracle
            oracleInfo = MultiOracleInfo.deserializeBody(
              reader.buffer.subarray(reader.position),
            );
          } else {
            throw new Error(`Unknown oracle info type: ${oracleType}`);
          }

          // Skip past the oracle info we just read
          const oracleInfoLength = oracleInfo.serializeBody().length;
          reader.position += oracleInfoLength;

          instance.contractOraclePairs.push({ contractDescriptor, oracleInfo });
        }

        return instance;
      }

      /**
       * The type for disjoint_contract_info message - using MessageType for IDlcMessage compatibility
       */
      public type = MessageType.DisjointContractInfo;

      /**
       * The contract info type for new format
       */
      public contractInfoType = ContractInfoType.Disjoint;

      public totalCollateral: bigint;

      public contractOraclePairs: IContractOraclePair[] = [];

      // Compatibility property
      public get length(): bigint {
        return BigInt(this.serialize().length);
      }

      /**
       * Validates correctness of all fields in the message
       * @throws Will throw an error if validation fails
       */
      public validate(): void {
        if (this.totalCollateral <= 0) {
          throw new Error('totalCollateral must be greater than 0');
        }

        if (this.contractOraclePairs.length === 0) {
          throw new Error('contractOraclePairs cannot be empty');
        }

        this.contractOraclePairs.forEach((pair, index) => {
          try {
            pair.oracleInfo.validate();
            // TODO: Add contract descriptor validation once available
            // pair.contractDescriptor.validate();
          } catch (error) {
            throw new Error(
              `Validation failed for contract oracle pair ${index}: ${error.message}`,
            );
          }
        });
      }

      /**
       * Converts disjoint_contract_info to JSON
       */
      public toJSON(): IDisjointContractInfoJSON {
        // Return enum variant format for Rust compatibility
        return {
          disjointContractInfo: {
            totalCollateral: Number(this.totalCollateral),
            contractInfos: this.contractOraclePairs.map((pair) => ({
              contractDescriptor: pair.contractDescriptor.toJSON(),
              oracleInfo: pair.oracleInfo.toJSON(),
            })),
          },
        };
      }

      /**
       * Serializes the disjoint_contract_info message into a Buffer
       */
      public serialize(): Buffer {
        const writer = new BufferWriter();

        writer.writeBigSize(this.contractInfoType);
        writer.writeUInt64BE(this.totalCollateral);
        writer.writeBigSize(this.contractOraclePairs.length);

        for (const pair of this.contractOraclePairs) {
          writer.writeBytes(pair.contractDescriptor.serialize());

          // Write oracle info with discriminator like SingleContractInfo does
          Iif (pair.oracleInfo instanceof SingleOracleInfo) {
            writer.writeBigSize(0); // Single oracle discriminator
            writer.writeBytes(pair.oracleInfo.serializeBody());
          } else {
            writer.writeBigSize(1); // Multi oracle discriminator
            writer.writeBytes(pair.oracleInfo.serializeBody());
          }
        }

        return writer.toBuffer();
      }
    }

    // Legacy support - keeping old class names as aliases (both value and type exports)
    export const ContractInfoV0 = SingleContractInfo;
    export const ContractInfoV1 = DisjointContractInfo;
    export type ContractInfoV0 = SingleContractInfo;
    export type ContractInfoV1 = DisjointContractInfo;

    interface IContractOraclePair {
      contractDescriptor: ContractDescriptor;
      oracleInfo: OracleInfo;
    }

    interface IContractOraclePairJSON {
      contractDescriptor: ContractDescriptorV0JSON | ContractDescriptorV1JSON;
      oracleInfo: SingleOracleInfoJSON | MultiOracleInfoJSON;
    }

    // Rust-dlc enum variant format for SingleContractInfo
    export interface ISingleContractInfoJSON {
      singleContractInfo: {
        totalCollateral: number;
        contractInfo: {
          contractDescriptor: ContractDescriptorV0JSON | ContractDescriptorV1JSON;
          oracleInfo: SingleOracleInfoJSON | MultiOracleInfoJSON;
        };
      };
    }

    // Rust-dlc enum variant format for DisjointContractInfo
    export interface IDisjointContractInfoJSON {
      disjointContractInfo: {
        totalCollateral: number;
        contractInfos: IContractOraclePairJSON[];
      };
    }

    // Legacy type aliases for backward compatibility (same as the new interfaces)
    export type IContractInfoV0JSON = ISingleContractInfoJSON;
    export type IContractInfoV1JSON = IDisjointContractInfoJSON;