All files / lib/dlc CETCalculator.ts

93.98% Statements 156/166
86.96% Branches 60/69
100% Functions 28/28
93.63% Lines 147/157

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 4511x   1x       1x 80x     1x 18x 31x 16x     2x     1x         29x 29x 29x 141x 141x 141x   29x     1x                   12x 12x   12x 12x 24x 13x 11x     12x             1x 9x 9x   14x     9x 1x   8x 34x   26x 26x   26x 26x 58x   26x     34x     1x 9x 9x   17x     9x 1x     8x 31x   23x 23x   23x 23x 21x     23x     31x     1x       9x 9x 17x   9x     1x           12x             12x   15x 4x     2x 10x 1x 1x 1x       8x     1x   9x 9x 9x   9x   114x                                                                       1x                 18x       18x   18x 21x 34x     21x               18x 4999x   18x 18x 21x   18x     18x             18x 4x           4x           4x     14x     14x 21x       21x     21x             21x   21x         21x 21x   21x   4985x                     4985x       4985x   4985x       4985x         4985x         4985x               2472x   2472x         4985x   4985x 6x           6x 6x     4979x           14x             14x                           14x 14x     4965x             4965x       4965x     4965x     4965x 4965x   4965x                 14x             14x     1x 20x 5075x 5075x 5055x         39x 39x       5036x       1x 9909x 9909x       9909x       9909x    
import BigNumber from 'bignumber.js';
 
import { BigIntMath, toBigInt } from '../utils/BigIntUtils';
import { HyperbolaPayoutCurve } from './HyperbolaPayoutCurve';
import { PolynomialPayoutCurve } from './PolynomialPayoutCurve';
 
export function zipWithIndex<T>(arr: T[]): [T, number][] {
  return arr.map((a, i) => [a, i]);
}
 
export function dropUntil<T>(data: T[], check: (_: T) => boolean): T[] {
  for (let i = 0; i < data.length; i++) {
    if (check(data[i])) {
      return data.slice(i);
    }
  }
  return [];
}
 
export function decompose(
  num: bigint,
  base: number,
  numDigits: number,
): number[] {
  let currentNumber = num;
  const digits = [];
  while (numDigits > 0) {
    digits.push(Number(currentNumber % BigInt(base)));
    currentNumber = currentNumber / BigInt(base);
    numDigits--;
  }
  return digits.reverse();
}
 
export function separatePrefix(
  start: bigint,
  end: bigint,
  base: number,
  numDigits: number,
): {
  prefixDigits: number[];
  startDigits: number[];
  endDigits: number[];
} {
  const startDigits = decompose(start, base, numDigits);
  const endDigits = decompose(end, base, numDigits);
 
  const prefixDigits: number[] = [];
  for (let i = 0; i < startDigits.length; i++) {
    if (startDigits[i] === endDigits[i]) {
      prefixDigits.push(startDigits[i]);
    } else break;
  }
 
  return {
    prefixDigits,
    startDigits: startDigits.splice(prefixDigits.length),
    endDigits: endDigits.splice(prefixDigits.length),
  };
}
 
export function frontGroupings(digits: number[], base: number): number[][] {
  const digitsReversed = Array.from(digits).reverse();
  const nonZeroDigits = dropUntil(
    zipWithIndex(digitsReversed),
    (a) => a[0] !== 0,
  );
 
  if (nonZeroDigits.length === 0) {
    return [[0]];
  }
  const fromFront = nonZeroDigits
    .filter((_, i) => i !== nonZeroDigits.length - 1)
    .flatMap(([d, i]) => {
      const fixedDigits = Array.from(digits);
      fixedDigits.length = fixedDigits.length - (i + 1);
 
      const result: number[][] = [];
      for (let n = d + 1; n < base; n++) {
        result.push([...Array.from(fixedDigits), n]);
      }
      return result;
    });
 
  return [nonZeroDigits.map((a) => a[0]).reverse(), ...fromFront];
}
 
export function backGroupings(digits: number[], base: number): number[][] {
  const digitsReversed = Array.from(digits).reverse();
  const nonMaxDigits = dropUntil(
    zipWithIndex(digitsReversed),
    (a) => a[0] !== base - 1,
  );
 
  if (nonMaxDigits.length === 0) {
    return [[base - 1]];
  }
 
  const fromBack = nonMaxDigits
    .filter((_, i) => i !== nonMaxDigits.length - 1)
    .flatMap(([d, i]) => {
      const fixedDigits = Array.from(digits);
      fixedDigits.length = fixedDigits.length - (i + 1);
 
      const result: number[][] = [];
      for (let n = d - 1; n >= 0; n--) {
        result.push([...Array.from(fixedDigits), n]);
      }
 
      return result;
    });
 
  return [...fromBack.reverse(), nonMaxDigits.map((a) => a[0]).reverse()];
}
 
export function middleGroupings(
  firstDigitStart: number,
  firstDigitEnd: number,
): number[][] {
  const result = [];
  while (++firstDigitStart < firstDigitEnd) {
    result.push([firstDigitStart]);
  }
  return result;
}
 
export function groupByIgnoringDigits(
  start: bigint,
  end: bigint,
  base: number,
  numDigits: number,
): number[][] {
  const { prefixDigits, startDigits, endDigits } = separatePrefix(
    start,
    end,
    base,
    numDigits,
  );
 
  if (
    start === end ||
    (startDigits.every((n) => n === 0) &&
      endDigits.every((n) => n === base - 1) &&
      prefixDigits.length !== 0)
  ) {
    return [prefixDigits];
  } else if (prefixDigits.length === numDigits - 1) {
    const result = [];
    for (
      let i = startDigits[startDigits.length - 1];
      i <= endDigits[endDigits.length - 1];
      i++
    ) {
      result.push([...prefixDigits, i]);
    }
 
    return result;
  } else {
    const front = frontGroupings(startDigits, base);
    const middle = middleGroupings(startDigits[0], endDigits[0]);
    const back = backGroupings(endDigits, base);
 
    const groupings = [...front, ...middle, ...back];
 
    return groupings.map((g) => [...prefixDigits, ...g]);
  }
}
 
export interface RoundingInterval {
  beginInterval: bigint;
  roundingMod: bigint;
}
 
export type CETPayout = {
  indexFrom: bigint;
  indexTo: bigint;
  payout: bigint;
};
 
/**
 * Performs optimized evaluation and rounding for strictly monotonic hyperbolas on intervals (from, to)
 * e.g. hyperbolas with the form b = c = 0
 *
 * The next start of a payout range is determined by finding the outcome at the next mid-rounding payout.
 * Uses an inverse function of the hyperbola to find the outcome.
 *
 * Optimizes rounding from O(to - from) to O(totalCollateral / rounding)
 *
 *
 * Evaluates and rounds a payout_function equivalent to:
 *
 *   payout_function_v0
 *    num_pieces: 1
 *    endpoint_0: from
 *    endpoint_payout_0: fromPayout
 *    extra_precision_0: 0
 *    payout_curve_piece: HyperbolaPayoutCurve
 *    endpoint_1: to
 *    endpoint_payout_1: toPayout
 */
export function splitIntoRanges(
  from: bigint,
  to: bigint,
  fromPayout: bigint, // endpoint_payout
  toPayout: bigint, // endpoint_payout
  totalCollateral: bigint,
  curve: HyperbolaPayoutCurve | PolynomialPayoutCurve,
  roundingIntervals: RoundingInterval[],
): CETPayout[] {
  Iif (to - from <= 0) {
    throw new Error('`to` must be strictly greater than `from`');
  }
 
  const reversedIntervals = [...roundingIntervals].reverse();
 
  const getRoundingForOutcome = (outcome: bigint): [bigint, number] => {
    const roundingIndex = reversedIntervals.findIndex(
      (interval) => interval.beginInterval <= outcome,
    );
 
    return [
      roundingIndex !== -1
        ? reversedIntervals[roundingIndex].roundingMod
        : BigInt(1),
      roundingIndex,
    ];
  };
 
  const clamp = (val: bigint) =>
    BigIntMath.clamp(BigInt(0), val, totalCollateral);
 
  const totalCollateralBN = new BigNumber(totalCollateral.toString());
  const clampBN = (val: BigNumber) =>
    BigNumber.max(0, BigNumber.min(val, totalCollateralBN));
 
  const result: CETPayout[] = [];
 
  // outcome = endpoint_0
  result.push({
    payout: fromPayout,
    indexFrom: from,
    indexTo: from,
  });
 
  // In the case of a constant payout curve (fromPayout === toPayout), we can skip the range evaluation
  if (fromPayout === toPayout) {
    result.push({
      payout: toPayout,
      indexFrom: from,
      indexTo: to,
    });
    // outcome = endpoint_1
    result.push({
      payout: toPayout,
      indexFrom: to,
      indexTo: to,
    });
    // merge neighbouring ranges with same payout
    return mergePayouts(result);
  }
 
  let currentOutcome = from + BigInt(1);
 
  // iterate over entire range of outcomes from [from, to]
  while (currentOutcome < to) {
    const [rounding, roundingIndex] = getRoundingForOutcome(currentOutcome);
 
    // either the next rounding interval, or the end of the range
    const nextFirstRoundingOutcome =
      reversedIntervals[roundingIndex - 1]?.beginInterval || to;
 
    // temporary variable to hold the current payout
    let currentPayout = new BigNumber(
      roundPayout(
        clampBN(curve.getPayout(currentOutcome)),
        rounding,
      ).toString(),
    );
 
    let currentMidRoundedOutcome = currentOutcome;
 
    const isAscending = curve
      .getPayout(nextFirstRoundingOutcome)
      .gt(currentPayout);
 
    // Add loop counter to prevent infinite loops
    let loopCounter = 0;
    const maxIterations = Number(to - from) + 1000; // Allow some extra iterations
 
    while (currentMidRoundedOutcome < nextFirstRoundingOutcome) {
      // Prevent infinite loops
      Iif (++loopCounter > maxIterations) {
        // Breaking out of potential infinite loop - add remaining range and exit
        result.push({
          payout: clamp(toBigInt(currentPayout)),
          indexFrom: currentMidRoundedOutcome,
          indexTo: to - BigInt(1),
        });
        currentOutcome = to;
        break;
      }
 
      const nextRoundedPayout = currentPayout
        .integerValue()
        .plus(isAscending ? Number(rounding) : -Number(rounding));
 
      const nextRoundedPayoutBigInt = toBigInt(nextRoundedPayout);
 
      const nextMidRoundedPayout = currentPayout.plus(
        isAscending ? Number(rounding) / 2 : -Number(rounding) / 2,
      );
 
      let nextMidRoundedOutcome = curve.getOutcomeForPayout(
        nextMidRoundedPayout,
      );
 
      // Handle invalid outcomes from getOutcomeForPayout
      Iif (nextMidRoundedOutcome < 0) {
        // If getOutcomeForPayout returns invalid value, advance manually
        nextMidRoundedOutcome = currentMidRoundedOutcome + BigInt(1);
      }
 
      if (
        (!isAscending &&
          nextMidRoundedOutcome >= 0 &&
          curve.getPayout(nextMidRoundedOutcome).lt(nextMidRoundedPayout)) ||
        (isAscending &&
          nextMidRoundedOutcome >= 0 &&
          curve.getPayout(nextMidRoundedOutcome).gte(nextMidRoundedPayout))
      ) {
        nextMidRoundedOutcome = nextMidRoundedOutcome - BigInt(1);
        // Ensure we don't go negative
        Iif (nextMidRoundedOutcome < 0) {
          nextMidRoundedOutcome = currentMidRoundedOutcome;
        }
      }
 
      const nextOutcome = curve.getOutcomeForPayout(nextRoundedPayout);
 
      if (nextMidRoundedOutcome >= nextFirstRoundingOutcome) {
        result.push({
          payout: clamp(toBigInt(currentPayout)),
          indexFrom: currentMidRoundedOutcome,
          indexTo: nextFirstRoundingOutcome - BigInt(1),
        });
 
        currentOutcome = nextFirstRoundingOutcome;
        break;
      }
 
      if (
        nextRoundedPayoutBigInt > totalCollateral ||
        nextRoundedPayoutBigInt < 0 ||
        nextOutcome >= to ||
        nextOutcome < 0 // undefined on curve
      ) {
        Iif (nextMidRoundedOutcome < from || nextMidRoundedOutcome > to) {
          result.push({
            payout: clamp(toBigInt(currentPayout)),
            indexFrom: currentMidRoundedOutcome,
            indexTo: to,
          });
        } else {
          result.push(
            {
              payout: clamp(toBigInt(currentPayout)),
              indexFrom: currentMidRoundedOutcome,
              indexTo: nextMidRoundedOutcome,
            },
            {
              payout: clamp(nextRoundedPayoutBigInt),
              indexFrom: nextMidRoundedOutcome + BigInt(1),
              indexTo: to - BigInt(1),
            },
          );
        }
 
        currentOutcome = to;
        break;
      }
 
      result.push({
        payout: clamp(toBigInt(currentPayout)),
        indexFrom: currentMidRoundedOutcome,
        indexTo: nextMidRoundedOutcome,
      });
 
      // Handle case where nextOutcome is invalid
      Iif (nextOutcome < 0) {
        // Advance manually if getOutcomeForPayout returns invalid value
        currentOutcome = currentMidRoundedOutcome + BigInt(1);
      } else {
        currentOutcome = nextOutcome + BigInt(1);
      }
 
      currentPayout = nextRoundedPayout;
 
      // Additional safety check: ensure we're making progress
      const previousMidRoundedOutcome = currentMidRoundedOutcome;
      currentMidRoundedOutcome = nextMidRoundedOutcome + BigInt(1);
 
      Iif (currentMidRoundedOutcome <= previousMidRoundedOutcome) {
        // No progress detected in splitIntoRanges loop, breaking
        currentOutcome = nextFirstRoundingOutcome;
        break;
      }
    }
  }
 
  // outcome = endpoint_1
  result.push({
    payout: toPayout,
    indexFrom: to,
    indexTo: to,
  });
 
  // merge neighbouring ranges with same payout
  return mergePayouts(result);
}
 
export const mergePayouts = (payouts: CETPayout[]): CETPayout[] => {
  return payouts.reduce((acc: CETPayout[], range) => {
    const prev = acc[acc.length - 1];
    if (prev) {
      if (
        (prev.indexTo === range.indexFrom ||
          prev.indexTo + BigInt(1) === range.indexFrom) &&
        prev.payout === range.payout
      ) {
        prev.indexTo = range.indexTo;
        return acc;
      }
    }
 
    return [...acc, range];
  }, []);
};
 
export function roundPayout(payout: BigNumber, rounding: bigint): bigint {
  const roundingBN = new BigNumber(rounding.toString());
  const mod = payout.gte(0)
    ? payout.mod(roundingBN)
    : payout.mod(roundingBN).plus(roundingBN);
 
  const roundedPayout = mod.gte(roundingBN.dividedBy(2))
    ? payout.plus(roundingBN).minus(mod)
    : payout.minus(mod);
 
  return toBigInt(roundedPayout);
}