All files / tr8-script/frontend parser.ts

100% Statements 114/114
73.41% Branches 58/79
100% Functions 26/26
100% Lines 104/104

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                                                                    87x       68x   68x         78x   70x   151x 175x     70x 70x                   81x 31x 8x     23x 23x 23x 23x           50x 26x   26x 15x 15x               11x       24x 21x 21x 21x 21x 21x             3x         554x 554x 554x 303x 303x                   251x 129x 129x         122x         151x 141x 63x 63x         78x             175x 113x             151x   284x 284x 151x 520x 260x 4x         256x 256x   214x                     42x                       326x   658x 658x   326x   326x   326x 308x 308x 308x 308x   326x     456x   72x 72x         384x               151x 151x 151x   151x 151x 151x 151x   151x     151x   151x             151x 151x 151x       175x 175x 175x 175x 175x   175x   175x         175x 175x 175x         78x 78x           78x 78x                 1x       68x 68x   68x   68x 68x              
import { parse } from "yaml";
 
import {
  Book,
  DestinationAllocationPolicy,
  Metric,
  SourceAllocationPolicy,
  SourceConstraint,
  Tr8AST,
  Tx,
  TxDestination,
  TxSource,
} from "../domain/ast.js";
import { fastHash } from "../domain/utils/hasher.js";
import { decimalStringToAmount } from "../domain/utils/math-low-level.js";
import { AbsoluteFixedValue, Amount, RelativeValue } from "../domain/value.js";
import {
  absRefValueRegex,
  destRegex,
  metricsRegex,
  num,
  relRefValueRegex,
  sourceRegex,
} from "./regex.js";
import { scriptParser, Tr8Script } from "./tr8Script.js";
 
interface Tr8ScriptParser {
  parse(script: string): Tr8AST;
}
 
class HashRegexParser {
  readonly #hash: number;
 
  constructor(hash: number) {
    this.#hash = hash;
  }
 
  parse(script: Tr8Script): Tr8AST {
    const { type, callbackUrl, id, txs, metrics, metadata } = script;
 
    return {
      id,
      type,
      metadata,
      callbackUrl,
      metrics: metrics.map((x) => this.parseMetric(x)),
      txs: txs.map((x) => {
        const r: Tx = {
          asset: x.asset,
          sources: x.sources.map((s) => this.parseSource(s)),
          destinations: x.destinations.map((d) => this.parseDestination(d)),
          refValue: this.parseReferenceValue(x.ref, x.use),
        };
        if (x.use) r.use = x.use;
        return r;
      }),
    } satisfies Tr8AST;
  }
 
  parseReferenceValue(
    s: string,
    use?: string,
  ): AbsoluteFixedValue | RelativeValue {
    // if mark, must be absolute, but use reference value
    if (use) {
      if (!absRefValueRegex.test(s))
        throw new Error(
          "Invalid reference value, use reference value must be absolute",
        );
      const book = "abs";
      const account = s;
      const fraction = "1/1";
      return {
        type: "relative",
        amount: this.parseValue(fraction) as [Amount, Amount],
        book: this.parseBook(book),
        account,
      };
    } else if (absRefValueRegex.test(s)) {
      const a = decimalStringToAmount(s);
      // ensure 4 scale, always
      if (a.scale < 4) {
        const diff = 4n - a.scale;
        return {
          type: "absolute",
          amount: {
            amount: a.amount * 10n ** diff,
            scale: 4n,
          },
        };
      }
      return {
        type: "absolute",
        amount: a,
      };
    } else if (relRefValueRegex.test(s)) {
      const m = relRefValueRegex.exec(s)!.slice();
      const book = m[5]!.trim();
      const account = m[6]!.trim();
      const fraction = m[1]!.trim();
      return {
        type: "relative",
        amount: this.parseValue(fraction) as [Amount, Amount],
        book: this.parseBook(book),
        account,
      };
    } else {
      throw new Error("Invalid reference value");
    }
  }
 
  parseValue(val: string): Amount | [Amount, Amount] {
    const perc = new RegExp(`^${num}%$`);
    const frac = new RegExp(`^${num}/${num}$`);
    if (perc.test(val)) {
      const v = decimalStringToAmount(val.split("%")[0] ?? "0");
      return [
        {
          amount: v.amount,
          scale: v.scale + 2n,
        },
        {
          amount: BigInt(100),
          scale: 2n,
        },
      ];
    } else if (frac.test(val)) {
      const [numerator, denominator] = val.split("/");
      return [
        decimalStringToAmount(numerator ?? "0"),
        decimalStringToAmount(denominator ?? "0"),
      ];
    } else {
      return decimalStringToAmount(val);
    }
  }
 
  parseSourceAllocationPolicy(s: string): SourceAllocationPolicy {
    if (s === "remaining") return { policy: "remaining" };
    if (s.includes("max")) {
      const [, amt] = s.split(" ");
      return {
        policy: "max",
        amount: this.parseValue(amt ?? "0"),
      };
    }
    return {
      policy: "split",
      amount: this.parseValue(s),
    };
  }
 
  parseDestinationAllocationPolicy(s: string): DestinationAllocationPolicy {
    if (s === "remaining") return { policy: "remaining" };
    return {
      policy: "split",
      amount: this.parseValue(s),
    };
  }
 
  parseConstraints(s: string, book: Book, account: string): SourceConstraint[] {
    const constraints = s
      .split(",")
      .map((x) => x.trim())
      .filter((x) => x.length > 0);
    return constraints.map((c) => {
      const [constraint, quantifier] = c.split(" ").map((x) => x.trim());
      if (quantifier === "unbounded") {
        return {
          constraint: constraint as "overdraft" | "limit" | "keep",
          amount: "unbounded",
        } satisfies SourceConstraint;
      }
      const amount = this.parseValue(quantifier ?? "0");
      if (Array.isArray(amount)) {
        // fractional
        return {
          constraint: constraint as "overdraft" | "limit" | "keep",
          amount: {
            type: "relative",
            amount: amount,
            account,
            book,
          } as AbsoluteFixedValue | RelativeValue,
        } satisfies SourceConstraint;
      } else {
        // absolute
        return {
          constraint: constraint as "overdraft" | "limit" | "keep",
          amount: {
            type: "absolute",
            amount: amount,
          } as AbsoluteFixedValue | RelativeValue,
        } satisfies SourceConstraint;
      }
    });
  }
 
  parseModifiers(s: string): { mark?: string; as?: string } {
    const tokens = s
      .split(" ")
      .map((x) => x.trim())
      .filter((x) => x.length > 0);
 
    let count = 0;
 
    const ret: { mark?: string; as?: string } = {};
 
    while (count < tokens.length) {
      const curr = tokens[count];
      if (curr === "as") ret.as = tokens[count + 1];
      if (curr === "mark") ret.mark = tokens[count + 1];
      count += 2;
    }
    return ret;
  }
  parseBook(s: string): Book {
    if (s.startsWith("#")) {
      // world sharding
      const prefix = s.slice(1);
      return {
        book: `${prefix}#${this.#hash}`,
        type: "world",
      };
    } else {
      return {
        book: s,
        type: "normal",
      };
    }
  }
 
  parseSource(s: string): TxSource {
    const m = sourceRegex.exec(s)?.slice() ?? [];
    const allocation = m[1]?.trim() ?? "";
    const constraints = m[9]?.trim() ?? "";
 
    const extern = m[25] === "ext";
    const b = m[26]?.trim() ?? "";
    const account = m[27]?.trim() ?? "";
    const modifiers = m[28]?.trim() ?? "";
 
    const mod = this.parseModifiers(modifiers);
 
    // parse book
    const book = this.parseBook(b);
 
    const ret: TxSource = {
      account,
      book,
      extern,
      allocationPolicy: this.parseSourceAllocationPolicy(allocation),
      constraints: this.parseConstraints(constraints, book, account),
    };
    if (mod.as) ret.as = mod.as;
    if (mod.mark) ret.mark = mod.mark;
    return ret;
  }
 
  parseDestination(s: string): TxDestination {
    const m = destRegex.exec(s)?.slice() ?? [];
    const allocation = m[1]?.trim() ?? "";
    const book = m[6]?.trim() ?? "";
    const account = m[7]?.trim() ?? "";
    const modifiers = m[8]?.trim() ?? "";
 
    const mods = this.parseModifiers(modifiers);
 
    const ret: TxDestination = {
      account,
      book: this.parseBook(book),
      allocationPolicy: this.parseDestinationAllocationPolicy(allocation),
    };
    if (mods.as) ret.as = mods.as;
    if (mods.mark) ret.mark = mods.mark;
    return ret;
  }
 
  parseMetric(s: string): Metric {
    const [, book = "", account = "", ops = "", args = ""] =
      metricsRegex.exec(s)?.slice() ?? [];
    return {
      book: this.parseBook(book),
      account,
      op: ops as "add" | "sub" | "replace",
      args: args
        .split(" ")
        .map((x) => x.trim())
        .filter((x) => x.length > 0),
    };
  }
}
 
class RegexTr8ScriptParser implements Tr8ScriptParser {
  readonly #partitions: number;
 
  constructor(partitions: number = 1) {
    this.#partitions = partitions;
  }
 
  parse(s: string): Tr8AST {
    const u: unknown = parse(s);
    const ts = scriptParser.parse(u) as Tr8Script;
 
    const hash = fastHash(ts.id, this.#partitions);
 
    const parser = new HashRegexParser(hash);
    return parser.parse(ts);
  }
}
 
export { RegexTr8ScriptParser, HashRegexParser };
 
export type { Tr8ScriptParser };