All files / tr8-script/validators/rules source-constraints-allocation-policy-in-notif-rule.ts

100% Statements 28/28
100% Branches 14/14
100% Functions 6/6
100% Lines 27/27

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            1x       12x 12x   12x 12x       12x 12x     12x             12x 12x   12x 11x 11x 11x 3x     8x   8x     4x 4x       4x         8x 8x     8x 2x 2x       2x             12x                
import { autoInjectable } from "tsyringe";
 
import { Tr8AST, Tr8ASTType, Tx } from "../../domain/ast.js";
import { SemanticValidationRule, ValidationResult } from "../validator.js";
 
@autoInjectable()
class SourceConstraintsAllocationPolicyInNotifRule
  implements SemanticValidationRule
{
  validate(ast: Tr8AST): ValidationResult {
    let isValid = true;
    const errors: string[] = [];
 
    for (const tx of ast.txs) {
      const { isValid: txIsValid, errors: txErrors } = this.validateTx(
        tx,
        ast.type,
      );
      isValid &&= txIsValid;
      errors.push(...txErrors);
    }
 
    return {
      isValid,
      errors,
    };
  }
 
  validateTx(tx: Tx, astType: Tr8ASTType): ValidationResult {
    let isValid = true;
    const errors: string[] = [];
 
    if (astType === "NOTIF") {
      for (const source of tx.sources) {
        const { constraints, allocationPolicy } = source;
        if (constraints.length === 0 || allocationPolicy.policy === "max") {
          continue;
        }
 
        if (
          constraints.some(
            (c) => c.constraint === "keep" || c.constraint === "limit",
          )
        ) {
          isValid &&= false;
          errors.push(
            `NOTIF cannot have policy ${
              allocationPolicy.policy
            } with constraints ${constraints
              .map((c) => c.constraint)
              .join(",")}.`,
          );
        }
 
        const overdraftConstraint = constraints.find(
          (c) => c.constraint === "overdraft",
        );
 
        if (overdraftConstraint && overdraftConstraint.amount !== "unbounded") {
          isValid &&= false;
          errors.push(
            `NOTIF cannot have policy ${
              allocationPolicy.policy
            } with constraints ${constraints
              .map((c) => c.constraint)
              .join(",")}.`,
          );
        }
      }
    }
 
    return {
      isValid,
      errors,
    };
  }
}
 
export { SourceConstraintsAllocationPolicyInNotifRule };