All files / lib/messages PayoutCurvePiece.ts

83.33% Statements 105/126
62.24% Branches 61/98
100% Functions 15/15
84.43% Lines 103/122

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 4551x   1x 1x 1x     1x       74x 74x   74x   62x   12x                           44x         44x 42x     2x 2x                                                   1x     1x               42x   42x   42x           42x               62x 62x   62x 62x   62x 33x 33x 33x   33x             62x           106x         106x   106x           22x     11x                           324x   324x 324x   324x 164x 164x 164x     324x                 1x     1x                 30x       30x 30x   3x 3x               27x   27x     27x                                         5x       5x     5x         5x     5x   5x   5x     5x         5x         5x 5x 5x 5x     5x       5x                                     12x 12x   12x 12x     12x 12x 12x 12x 12x 12x       12x           12x           12x           32x   32x                                           32x 32x     32x         32x         32x         32x         32x         32x                       4x                                 31x   31x 31x     31x 31x 31x 31x 31x 31x   31x                                                                              
import { BufferReader, BufferWriter } from '@node-dlc/bufio';
 
import { MessageType, PayoutCurvePieceType } from '../MessageType';
import { F64 } from '../serialize/F64';
import { bigIntToNumber, toBigInt } from '../util';
import { IDlcMessage } from './DlcMessage';
 
export abstract class PayoutCurvePiece {
  public static deserialize(
    buf: Buffer,
  ): PolynomialPayoutCurvePiece | HyperbolaPayoutCurvePiece {
    const reader = new BufferReader(buf);
    const typeId = Number(reader.readBigSize());
 
    switch (typeId) {
      case PayoutCurvePieceType.Polynomial:
        return PolynomialPayoutCurvePiece.deserialize(buf);
      case PayoutCurvePieceType.Hyperbola:
        return HyperbolaPayoutCurvePiece.deserialize(buf);
      default:
        throw new Error(
          `Payout curve piece type must be Polynomial (0) or Hyperbola (1), got ${typeId}`,
        );
    }
  }
 
  /**
   * Creates a PayoutCurvePiece from JSON data
   * @param json JSON object representing a payout curve piece
   */
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
  public static fromJSON(json: any): PayoutCurvePiece {
    Iif (!json) {
      throw new Error('payoutCurvePiece is required');
    }
 
    // Handle test vector format with nested types
    if (json.polynomialPayoutCurvePiece) {
      return PolynomialPayoutCurvePiece.fromJSON(
        json.polynomialPayoutCurvePiece,
      );
    } else Eif (json.hyperbolaPayoutCurvePiece) {
      return HyperbolaPayoutCurvePiece.fromJSON(json.hyperbolaPayoutCurvePiece);
    }
    // Handle direct format
    else if (json.points !== undefined || json.payoutPoints !== undefined) {
      return PolynomialPayoutCurvePiece.fromJSON(json);
    } else if (json.usePositivePiece !== undefined) {
      return HyperbolaPayoutCurvePiece.fromJSON(json);
    } else {
      throw new Error(
        'payoutCurvePiece must be either polynomial (with points) or hyperbola (with usePositivePiece)',
      );
    }
  }
 
  public abstract payoutCurvePieceType: PayoutCurvePieceType;
  public abstract type: number; // For backward compatibility
  public abstract toJSON():
    | PolynomialPayoutCurvePieceJSON
    | HyperbolaPayoutCurvePieceJSON;
  public abstract serialize(): Buffer;
}
 
/**
 * PolynomialPayoutCurvePiece defines a polynomial curve piece for payout functions.
 * This corresponds to type 0 in the sibling sub-type format.
 */
export class PolynomialPayoutCurvePiece
  extends PayoutCurvePiece
  implements IDlcMessage {
  public static payoutCurvePieceType = PayoutCurvePieceType.Polynomial;
 
  /**
   * Creates a PolynomialPayoutCurvePiece from JSON data
   * @param json JSON object representing a polynomial payout curve piece
   */
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
  public static fromJSON(json: any): PolynomialPayoutCurvePiece {
    const instance = new PolynomialPayoutCurvePiece();
 
    const points = json.payoutPoints || json.points || [];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    instance.points = points.map((point: any) => ({
      eventOutcome: toBigInt(point.eventOutcome || point.event_outcome),
      outcomePayout: toBigInt(point.outcomePayout || point.outcome_payout),
      extraPrecision: point.extraPrecision || point.extra_precision || 0,
    }));
 
    return instance;
  }
 
  /**
   * Deserializes a polynomial_payout_curve_piece message
   * @param buf
   */
  public static deserialize(buf: Buffer): PolynomialPayoutCurvePiece {
    const instance = new PolynomialPayoutCurvePiece();
    const reader = new BufferReader(buf);
 
    reader.readBigSize(); // read type (0)
    const numPts = Number(reader.readBigSize());
 
    for (let i = 0; i < numPts; i++) {
      const eventOutcome = reader.readUInt64BE();
      const outcomePayout = reader.readUInt64BE();
      const extraPrecision = reader.readUInt16BE();
 
      instance.points.push({
        eventOutcome,
        outcomePayout,
        extraPrecision,
      });
    }
 
    return instance;
  }
 
  /**
   * The type for polynomial_payout_curve_piece message - Note: this is a sub-component, not a standalone wire message
   */
  public type = MessageType.PolynomialPayoutCurvePiece;
 
  /**
   * The payout curve piece type for new format
   */
  public payoutCurvePieceType = PayoutCurvePieceType.Polynomial;
 
  public points: IPoint[] = [];
 
  /**
   * Converts polynomial_payout_curve_piece to JSON
   */
  public toJSON(): PolynomialPayoutCurvePieceJSON {
    return {
      polynomialPayoutCurvePiece: {
        payoutPoints: this.points.map((point) => {
          return {
            eventOutcome: bigIntToNumber(point.eventOutcome),
            outcomePayout: bigIntToNumber(point.outcomePayout),
            extraPrecision: Number(point.extraPrecision),
          };
        }),
      },
    };
  }
 
  /**
   * Serializes the polynomial_payout_curve_piece message into a Buffer
   */
  public serialize(): Buffer {
    const writer = new BufferWriter();
 
    writer.writeBigSize(this.payoutCurvePieceType);
    writer.writeBigSize(this.points.length);
 
    for (const point of this.points) {
      writer.writeUInt64BE(point.eventOutcome);
      writer.writeUInt64BE(point.outcomePayout);
      writer.writeUInt16BE(point.extraPrecision);
    }
 
    return writer.toBuffer();
  }
}
 
/**
 * HyperbolaPayoutCurvePiece defines a hyperbola curve piece for payout functions.
 * This corresponds to type 1 in the sibling sub-type format.
 * Updated to use F64 for precise f64 parameter handling.
 */
export class HyperbolaPayoutCurvePiece
  extends PayoutCurvePiece
  implements IDlcMessage {
  public static payoutCurvePieceType = PayoutCurvePieceType.Hyperbola;
 
  /**
   * Helper function to safely parse F64 values from JSON
   * Handles both number and string inputs for maximum precision
   */
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
  private static parseF64Value(value: any): F64 | null {
    // Check for basic null/undefined
    Iif (value === null || value === undefined) {
      return null;
    }
 
    try {
      if (typeof value === 'string') {
        // Parse string directly to preserve precision
        try {
          return F64.fromString(value);
        } catch (error) {
          // If fromString fails, try parsing as number
          const numValue = parseFloat(value);
          if (!isNaN(numValue) && isFinite(numValue)) {
            return F64.fromNumber(numValue);
          }
        }
      } else Eif (typeof value === 'number') {
        // Parse number - handle special cases
        Iif (!isFinite(value)) {
          return null; // Reject NaN, Infinity, -Infinity
        }
        return F64.fromNumber(value);
      }
 
      // Try to convert other types to number as fallback
      const numValue = Number(value);
      if (!isNaN(numValue) && isFinite(numValue)) {
        return F64.fromNumber(numValue);
      }
 
      return null;
    } catch (error) {
      return null;
    }
  }
 
  /**
   * Creates a HyperbolaPayoutCurvePiece from JSON data
   * @param json JSON object representing a hyperbola payout curve piece
   */
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
  public static fromJSON(json: any): HyperbolaPayoutCurvePiece | null {
    Iif (!json || typeof json !== 'object') return null;
 
    // Handle both wrapped format and direct format
    let data =
      json.hyperbolaPayoutCurvePiece || json.hyperbola_payout_curve_piece;
 
    // If no wrapper found, assume direct format if it has the expected properties
    Eif (
      !data &&
      (json.usePositivePiece !== undefined ||
        json.use_positive_piece !== undefined)
    ) {
      data = json;
    }
 
    Iif (!data) return null;
 
    try {
      const usePositivePiece =
        data.usePositivePiece || data.use_positive_piece || false;
 
      // Parse each F64 value with null check
      const translateOutcome = this.parseF64Value(
        data.translateOutcome !== undefined
          ? data.translateOutcome
          : data.translate_outcome,
      );
      const translatePayout = this.parseF64Value(
        data.translatePayout !== undefined
          ? data.translatePayout
          : data.translate_payout,
      );
      const a = this.parseF64Value(data.a);
      const b = this.parseF64Value(data.b);
      const c = this.parseF64Value(data.c);
      const d = this.parseF64Value(data.d);
 
      // Check that all required values were parsed successfully
      Iif (!translateOutcome || !translatePayout || !a || !b || !c || !d) {
        throw new Error('Failed to parse one or more F64 values');
      }
 
      return new HyperbolaPayoutCurvePiece(
        usePositivePiece,
        translateOutcome,
        translatePayout,
        a,
        b,
        c,
        d,
      );
    } catch (error) {
      return null;
    }
  }
 
  /**
   * Deserializes a hyperbola_payout_curve_piece message
   * @param buf
   */
  public static deserialize(buf: Buffer): HyperbolaPayoutCurvePiece {
    const instance = new HyperbolaPayoutCurvePiece();
    const reader = new BufferReader(buf);
 
    reader.readBigSize(); // read type (1)
    instance.usePositivePiece = reader.readUInt8() === 1;
 
    // Read f64 values using F64 for precise handling - read raw 8-byte buffers
    instance.translateOutcome = F64.deserialize(reader.readBytes(8));
    instance.translatePayout = F64.deserialize(reader.readBytes(8));
    instance.a = F64.deserialize(reader.readBytes(8));
    instance.b = F64.deserialize(reader.readBytes(8));
    instance.c = F64.deserialize(reader.readBytes(8));
    instance.d = F64.deserialize(reader.readBytes(8));
 
    // Note: leftEndPoint and rightEndPoint are not part of the serialization
    // They will be set by PayoutFunction when creating from JSON
    instance.leftEndPoint = {
      eventOutcome: BigInt(0),
      outcomePayout: BigInt(0),
      extraPrecision: 0,
    };
 
    instance.rightEndPoint = {
      eventOutcome: BigInt(0),
      outcomePayout: BigInt(0),
      extraPrecision: 0,
    };
 
    return instance;
  }
 
  /**
   * The type for hyperbola_payout_curve_piece message - Note: this is a sub-component, not a standalone wire message
   */
  public type = MessageType.HyperbolaPayoutCurvePiece;
 
  public payoutCurvePieceType = HyperbolaPayoutCurvePiece.payoutCurvePieceType;
 
  // Use F64 for precise f64 parameter handling to avoid JavaScript precision issues
  public leftEndPoint: IPayoutPoint;
  public rightEndPoint: IPayoutPoint;
  public usePositivePiece: boolean;
  public translateOutcome: F64; // f64 - precise handling with F64
  public translatePayout: F64; // f64 - precise handling with F64
  public a: F64; // f64 - precise handling with F64
  public b: F64; // f64 - precise handling with F64
  public c: F64; // f64 - precise handling with F64
  public d: F64; // f64 - precise handling with F64
 
  constructor(
    usePositivePiece = false,
    translateOutcome?: string | F64,
    translatePayout?: string | F64,
    a?: string | F64,
    b?: string | F64,
    c?: string | F64,
    d?: string | F64,
  ) {
    super();
    this.usePositivePiece = usePositivePiece;
 
    // Convert string inputs to F64 objects, or use existing F64 objects
    this.translateOutcome = translateOutcome
      ? typeof translateOutcome === 'string'
        ? F64.fromString(translateOutcome)
        : translateOutcome
      : F64.fromNumber(0);
    this.translatePayout = translatePayout
      ? typeof translatePayout === 'string'
        ? F64.fromString(translatePayout)
        : translatePayout
      : F64.fromNumber(0);
    this.a = a
      ? typeof a === 'string'
        ? F64.fromString(a)
        : a
      : F64.fromNumber(0);
    this.b = b
      ? typeof b === 'string'
        ? F64.fromString(b)
        : b
      : F64.fromNumber(0);
    this.c = c
      ? typeof c === 'string'
        ? F64.fromString(c)
        : c
      : F64.fromNumber(0);
    this.d = d
      ? typeof d === 'string'
        ? F64.fromString(d)
        : d
      : F64.fromNumber(0);
  }
 
  /**
   * Converts hyperbola_payout_curve_piece to JSON
   * Uses F64.toJSONValue() which preserves precision by using strings for very large numbers
   */
  public toJSON(): HyperbolaPayoutCurvePieceJSON {
    return {
      hyperbolaPayoutCurvePiece: {
        usePositivePiece: this.usePositivePiece,
        translateOutcome: this.translateOutcome.toJSONValue(), // Smart conversion: number if safe, string if large
        translatePayout: this.translatePayout.toJSONValue(), // Preserves precision automatically
        a: this.a.toJSONValue(),
        b: this.b.toJSONValue(),
        c: this.c.toJSONValue(),
        d: this.d.toJSONValue(),
      },
    };
  }
 
  /**
   * Serializes the hyperbola_payout_curve_piece message into a Buffer
   */
  public serialize(): Buffer {
    const writer = new BufferWriter();
 
    writer.writeBigSize(this.payoutCurvePieceType);
    writer.writeUInt8(this.usePositivePiece ? 1 : 0);
 
    // Write f64 values using F64 for precise handling - write raw 8-byte buffers
    writer.writeBytes(this.translateOutcome.serialize());
    writer.writeBytes(this.translatePayout.serialize());
    writer.writeBytes(this.a.serialize());
    writer.writeBytes(this.b.serialize());
    writer.writeBytes(this.c.serialize());
    writer.writeBytes(this.d.serialize());
 
    return writer.toBuffer();
  }
}
 
interface IPoint {
  eventOutcome: bigint;
  outcomePayout: bigint;
  extraPrecision: number;
}
 
interface IPointJSON {
  eventOutcome: number;
  outcomePayout: number;
  extraPrecision: number;
}
 
interface IPayoutPoint {
  eventOutcome: bigint;
  outcomePayout: bigint;
  extraPrecision: number;
}
 
export interface PolynomialPayoutCurvePieceJSON {
  polynomialPayoutCurvePiece: {
    payoutPoints: IPointJSON[];
  };
}
 
export interface HyperbolaPayoutCurvePieceJSON {
  hyperbolaPayoutCurvePiece: {
    usePositivePiece: boolean;
    translateOutcome: number | string;
    translatePayout: number | string;
    a: number | string;
    b: number | string;
    c: number | string;
    d: number | string;
  };
}