All files / approval-engine-2/domain ledger-event.handler.ts

61.24% Statements 177/289
57.47% Branches 100/174
52% Functions 13/25
60.97% Lines 175/287

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 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952                                                                              1x       8x 8x 8x 8x 8x   8x 8x 8x 8x 8x   8x       8x                           9x 9x 9x     9x 9x           9x         9x   9x                       9x 9x 6x   6x 1x           5x     8x         8x   8x         8x 16x   8x             8x 8x         8x                                                                                                                     8x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       8x 8x   8x             8x       8x   1x 1x 1x           1x         1x       1x                         1x   1x       1x               1x 1x     7x     7x 7x 7x 7x 16x 16x     7x 8x 8x       7x 7x 2x 2x 3x 3x   2x 2x 2x         7x 7x           7x 7x 15x           7x 7x 3x             7x 7x 8x     8x   8x                                                     7x           15x                                                         7x   7x       7x                 7x 8x 7x   1x                         1x   1x     1x                     7x   7x                   7x                   7x 7x   2x 5x   2x         2x 3x     3x       3x 3x   3x           1x         7x 7x 26x   7x                         7x   7x                   6x 6x 6x                                     8x 8x 10x 10x                       8x       8x 8x 8x 1x 1x       8x 8x 1x       8x 9x 1x         8x               3x 6x       3x   3x   4x       3x 3x     3x                 3x         3x   3x   6x       3x 3x   3x 3x     3x 3x             3x                     3x   6x           3x 3x 2x 1x       3x 2x 2x     2x                 1x   1x       1x   1x 1x 1x         1x             3x          
import { Repository } from "typeorm";
import { IabSnapshotEntity } from "../../approval-engine-2/entity/iab.snapshot.entity.js";
import { AppDataSourceService } from "../../approval-engine-2/domain/data-source.js";
import { autoInjectable, inject, singleton } from "tsyringe";
 
import { AmountMapper } from "../../commons/mappers/amount.mapper.js";
import { tokens } from "../../registry/tokens.js";
import { SyncSignalEvent } from "../../sync-engine/domain/sync-events.js";
import {
  AssetState,
  AssetStateChangeLog,
  LedgerEventEvaluator,
  MarkedStateChangeLog,
  MetricStateChangeLog,
} from "../../tr8-script/domain/eval.js";
import type { Amount } from "../../tr8-script/domain/value.js";
import {
  extractAccountsFromLedgerEvent,
  getSourceBookForTx,
  isRelativeTx,
  LedgerEvent,
} from "../../tr8-script/domain/ledger-event.js";
import { zero } from "../../tr8-script/domain/utils/math-low-level.js";
import { minus, plus } from "../../tr8-script/domain/utils/math.js";
import { AssetStateChangeLogsEventProducer } from "../asset-state-change-log-events.producer.js";
import { AssetStateChangeLogsEvent } from "../dtos/asset-state-change-logs-event.dto.js";
 
import type { KafkaProducer } from "../../commons/interfaces/kafka-producer.base.js";
import type { Logger } from "pino";
import { AmountDto } from "../../commons/dtos/values.dto.js";
import { RedisRequestStore } from "../store/redis-request.store.js";
import { RedisMarkedStateStore } from "../store/redis-marked.store.js";
import { RedisIABAssetStore } from "../store/redis-iab-asset.store.js";
import { RedisProcessedEventStateStore } from "../store/redis-processed-event.store.js";
import { Result } from "../../tr8-script/domain/utils/types.js";
import { MarginService } from "./margin.service.js";
 
@singleton()
@autoInjectable()
class LedgerEventHandler {
  private readonly iabSnapshotRepository: Repository<IabSnapshotEntity>;
 
  constructor(
    private readonly IABAssetRepository: RedisIABAssetStore,
    private readonly markedStateRepository: RedisMarkedStateStore,
    private readonly requestRepository: RedisRequestStore,
    private readonly processedEventRepository: RedisProcessedEventStateStore,
    private readonly evaluator: LedgerEventEvaluator,
    @inject(tokens.SyncSignalEventProducer)
    private readonly syncSignalEventProducer: KafkaProducer<SyncSignalEvent>,
    private readonly changelogsEventProducer: AssetStateChangeLogsEventProducer,
    @inject(tokens.Logger) private readonly logger: Logger,
    private appDataSourceService: AppDataSourceService,
    private readonly marginService: MarginService,
  ) {
    this.iabSnapshotRepository =
      this.appDataSourceService.AppDataSource.getRepository(IabSnapshotEntity);
  }
 
  handle = async (
    event: LedgerEvent,
    commit: () => void,
    partition: number,
    offset: string,
    transaction_time: string,
  ): Promise<Result<
    { bookId: string; iabAsset: AssetState },
    Error
  > | null> => {
    // Find the first transaction with a normal (user) book as source
    // This ensures we process the event in the context of the user book,
    // even if world book transactions appear first in the txs array
    let bookId: string;
    const normalBookTx = event.txs.find((tx) => {
      const sourceBook = getSourceBookForTx(tx);
      return sourceBook.type === "normal";
    });
 
    if (normalBookTx) {
      bookId = getSourceBookForTx(normalBookTx).book;
    } else E{
      // Fallback to first transaction if no normal book found
      bookId = getSourceBookForTx(event.txs[0]!).book;
    }
 
    const eventId = `${partition}#${offset}#${event.scriptId}`;
 
    // TODO: if request, check for suspension
 
    // TODO: if event is already processed, skip
    const redisState = await this.processedEventRepository.get(eventId);
 
    Iif (redisState.ok) {
      const existingOffset = redisState.value.offset;
 
      if (existingOffset === offset) {
        this.logger.info(
          `Offset ${offset} for bookId=${bookId} already processed, skipping`,
        );
        return null;
      }
    }
 
    // get current iab, marked state, txlogs
    let prevAssetTxLogs: AssetStateChangeLog[][] = [];
    if (event.type === "NOTIF" || event.type === "PARTIAL_NOTIF") {
      const requestResult = await this.requestRepository.get(event.scriptId);
 
      if (!requestResult.ok) {
        return {
          ok: false,
          error: requestResult.error,
        };
      }
 
      prevAssetTxLogs = requestResult.value;
    }
 
    const accounts = this.extractAccountsForBook(
      bookId,
      event,
      prevAssetTxLogs,
    );
    const markedAccounts = this.extractMarkedState(bookId, event);
 
    const results = await Promise.all([
      this.IABAssetRepository.get(bookId, accounts),
      this.markedStateRepository.get(bookId, markedAccounts),
    ]);
 
    const failedResult = results.find(
      (r): r is { ok: false; error: Error } => r !== null && r?.ok === false,
    );
    Iif (failedResult) {
      return {
        ok: false,
        error: failedResult.error,
      };
    }
 
    const iabAsset = (results[0] as { ok: true; value: AssetState }).value;
    const markedState = (results[1] as { ok: true; value: AssetState }).value;
 
    // this.logger.info({ iabAsset, markedState });
 
    // Options margin checking
    Iif (this.marginService.isOptionsShortingTrade(event)) {
      // Options trades are split into multiple sub-events:
      // - SubId 1: USD transactions (premium + fee)
      // - SubId 2: Option contract transactions
      // We need to perform margin check for ALL sub-events to ensure consistency.
      // If margin is insufficient, all sub-events should be rejected.
      this.logger.info(
        "Options shorting trade detected, checking margin requirements",
      );
 
      const marginCheckResult = await this.marginService.checkMargin(
        event,
        iabAsset,
        bookId,
      );
 
      if (!marginCheckResult.ok) {
        this.logger.error(
          { err: marginCheckResult.error },
          "Margin check failed",
        );
 
        const syncSignalEvent: SyncSignalEvent = {
          scriptId: event.scriptId,
          scriptType: event.type,
          bookId: bookId,
          semaphore: Object.values(event.semaphore).map((v) => [
            event.scriptId,
            event.subId,
            v,
          ]),
          status: "REJECTED",
          txLogs: [],
          metricLogs: [],
          vars: {},
          message: `Margin check failed: ${marginCheckResult.error.message}`,
          partial_notif_id: event.partial_notif_id ?? null,
        };
 
        this.logger.info({ syncSignalEvent }, "REJECTED - Margin check failed");
 
        const sendReject = await this.syncSignalEventProducer.send(
          syncSignalEvent,
        );
 
        if (!sendReject.ok) {
          this.logger.error("❌ Sync signal event failed to send reject.");
          return {
            ok: false,
            error: sendReject.error,
          };
        }
 
        commit();
        return null;
      }
 
      // If we reach here, margin check passed - REQ txs will handle reservations
      this.logger.info("Margin check passed for options shorting");
    I} else if (this.marginService.isBuyToCloseTrade(event)) {
      // Skip position validation for NOTIF/PARTIAL_NOTIF - REQ already validated position
      if (event.type === "NOTIF" || event.type === "PARTIAL_NOTIF") {
        this.logger.info(
          { eventType: event.type, scriptId: event.scriptId },
          "Buy-to-close: Skipping position validation for NOTIF/PARTIAL_NOTIF - REQ already validated",
        );
        // Skip validation - REQ already confirmed position exists
      } else {
        // Only validate for user book (normal book), skip validation for global/world book
        const isUserBook = event.txs.some(
          (tx) =>
            tx.destinations.some(
              (dest) =>
                dest.account.includes("OP-OWN") &&
                dest.book.type === "normal" &&
                dest.book.book === bookId,
            ) ||
            tx.sources.some(
              (src) =>
                src.account.includes("S-RES-OP") &&
                src.book.type === "normal" &&
                src.book.book === bookId,
            ),
        );
 
        if (!isUserBook) {
          this.logger.info(
            `Buy-to-close: Skipping validation for non-user book ${bookId}`,
          );
          // Skip validation for global/world books
        } else {
          this.logger.info(
            "Buy-to-close trade detected, validating position and reservation release",
          );
 
          // For buy-to-close, we need to load IAB from user book (where position exists)
          // Extract user book from event destinations (where OP-OWN account is)
          let userBookId = bookId;
          let userIabAsset = iabAsset;
 
          // Find the transaction with OP-OWN destination to get user book
          const metadata = JSON.parse(event.metadata);
          for (const tx of event.txs) {
            for (const dest of tx.destinations) {
              if (
                dest.account.includes("OP-OWN") &&
                dest.book.type === "normal"
              ) {
                userBookId = dest.book.book;
                this.logger.info(
                  `Buy-to-close: Loading IAB from user book ${userBookId} for position validation`,
                );
 
                // Load IAB from user book if different from current bookId
                if (userBookId !== bookId) {
                  const userAccounts = [`OP-OWN-${metadata.ticker}`];
                  const userIabResult = await this.IABAssetRepository.get(
                    userBookId,
                    userAccounts,
                  );
 
                  if (!userIabResult.ok) {
                    this.logger.error(
                      { err: userIabResult.error },
                      "Failed to load user IAB for position validation",
                    );
                    return {
                      ok: false,
                      error: userIabResult.error,
                    };
                  }
 
                  userIabAsset = userIabResult.value;
                  this.logger.info(
                    { userIabAsset },
                    "User IAB loaded successfully",
                  );
                }
                break;
              }
            }
          }
 
          // Step 1: Validate position exists (using user book IAB)
          const positionValidationResult =
            await this.marginService.validatePosition(event, userIabAsset);
 
          if (!positionValidationResult.ok) {
            this.logger.error(
              { err: positionValidationResult.error },
              "Position validation failed",
            );
 
            const syncSignalEvent: SyncSignalEvent = {
              scriptId: event.scriptId,
              scriptType: event.type,
              bookId: bookId,
              semaphore: Object.values(event.semaphore).map((v) => [
                event.scriptId,
                event.subId,
                v,
              ]),
              status: "REJECTED",
              txLogs: [],
              metricLogs: [],
              vars: {},
              message: `Position validation failed: ${positionValidationResult.error.message}`,
              partial_notif_id: event.partial_notif_id ?? null,
            };
 
            this.logger.info(
              { syncSignalEvent },
              "REJECTED - Position validation failed",
            );
 
            const sendReject = await this.syncSignalEventProducer.send(
              syncSignalEvent,
            );
 
            if (!sendReject.ok) {
              this.logger.error("❌ Sync signal event failed to send reject.");
              return {
                ok: false,
                error: sendReject.error,
              };
            }
 
            commit();
            return null;
          }
 
          this.logger.info(
            { positionInfo: positionValidationResult.value },
            "Position validation passed for buy-to-close",
          );
 
          // Step 2: Validate reservation release (using user book IAB for reserves check)
          // For buy-to-close, reserves are in user book, not global book
          let reserveIabAsset = iabAsset;
          if (userBookId !== bookId) {
            // Need to load reserve accounts from user book
            const metadata = JSON.parse(event.metadata);
            const reserveAccounts = [
              metadata.option_type === "call"
                ? `S-RES-OP-${metadata.ticker}`
                : `C-RES-OP-${metadata.ticker}`,
            ];
            const reserveIabResult = await this.IABAssetRepository.get(
              userBookId,
              reserveAccounts,
            );
 
            if (!reserveIabResult.ok) {
              this.logger.error(
                { err: reserveIabResult.error },
                "Failed to load user IAB for reservation validation",
              );
              return {
                ok: false,
                error: reserveIabResult.error,
              };
            }
 
            reserveIabAsset = reserveIabResult.value;
            this.logger.info(
              { reserveIabAsset },
              "Reserve IAB loaded successfully",
            );
          }
 
          const reservationValidationResult =
            await this.marginService.validateReservationRelease(
              event,
              reserveIabAsset,
            );
 
          if (!reservationValidationResult.ok) {
            this.logger.error(
              { err: reservationValidationResult.error },
              "Reservation release validation failed",
            );
 
            const syncSignalEvent: SyncSignalEvent = {
              scriptId: event.scriptId,
              scriptType: event.type,
              bookId: bookId,
              semaphore: Object.values(event.semaphore).map((v) => [
                event.scriptId,
                event.subId,
                v,
              ]),
              status: "REJECTED",
              txLogs: [],
              metricLogs: [],
              vars: {},
              message: `Reservation release validation failed: ${reservationValidationResult.error.message}`,
              partial_notif_id: event.partial_notif_id ?? null,
            };
 
            this.logger.info(
              { syncSignalEvent },
              "REJECTED - Reservation release validation failed",
            );
 
            const sendReject = await this.syncSignalEventProducer.send(
              syncSignalEvent,
            );
 
            if (!sendReject.ok) {
              this.logger.error("❌ Sync signal event failed to send reject.");
              return {
                ok: false,
                error: sendReject.error,
              };
            }
 
            commit();
            return null;
          }
 
          // If we reach here, both validations passed
          this.logger.info(
            {
              positionInfo: positionValidationResult.value,
              releaseInfo: reservationValidationResult.value.releaseInfo,
            },
            "All validations passed for buy-to-close",
          );
        }
      }
    }
 
    // eval
    // For options sell_to_open NOTIF, don't pass prevAssetTxLogs to prevent auto-rollback/release
    const isOptionsSellToOpen =
      event.type === "NOTIF" && this.isOptionsSellToOpen(event);
    const txLogsForEval = isOptionsSellToOpen ? [] : prevAssetTxLogs;
 
    const evalResult = this.evaluator.eval(
      event,
      iabAsset,
      markedState,
      txLogsForEval,
    );
 
    const metricResult = this.evaluator.evalMetric(event.metrics, iabAsset);
 
    // printDebug({ evalResult });
 
    if (!evalResult.ok || !metricResult.ok) {
      // If evaluation fails, we send a sync signal event to all semaphores with status REJECTED
      let errorMessage = "";
      if (!evalResult.ok) {
        errorMessage = evalResult.error.message;
      E} else if (!metricResult.ok) {
        errorMessage = metricResult.error.message;
      }
 
      // Fallback to ensure errorMessage is never empty
      Iif (!errorMessage) {
        errorMessage =
          "Evaluation failed - no specific error message available";
      }
 
      const syncSignalEvent: SyncSignalEvent = {
        scriptId: event.scriptId,
        scriptType: event.type,
        bookId: bookId,
        semaphore: Object.values(event.semaphore).map((v) => [
          event.scriptId,
          event.subId,
          v,
        ]),
        status: "REJECTED",
        txLogs: [],
        metricLogs: [],
        vars: {},
        message: errorMessage,
        partial_notif_id: event.partial_notif_id ?? null,
      };
 
      this.logger.info({ syncSignalEvent }, "REJECTED");
 
      const sendReject = await this.syncSignalEventProducer.send(
        syncSignalEvent,
      );
 
      Iif (!sendReject.ok) {
        this.logger.error("❌ Sync signal event failed to send reject.");
        return {
          ok: false,
          error: sendReject.error,
        };
      }
 
      commit();
      return null;
    }
 
    const { assetTxLogs, markedTxLogs, vars } = evalResult.value;
 
    // filter relevant tx logs
    const assetTxLogsByBookId: Record<string, AssetStateChangeLog[][]> = {};
    for (const txLogs of assetTxLogs) {
      const txLogsByBookId: Record<string, AssetStateChangeLog[]> = {};
      for (const txLog of txLogs) {
        txLogsByBookId[txLog.book.book] ??= [];
        txLogsByBookId[txLog.book.book]!.push(txLog);
      }
 
      for (const [bookId, logs] of Object.entries(txLogsByBookId)) {
        assetTxLogsByBookId[bookId] ??= [];
        assetTxLogsByBookId[bookId]!.push(logs);
      }
    }
 
    const markedTxLogsByBookId: Record<string, MarkedStateChangeLog[][]> = {};
    for (const txLogs of markedTxLogs) {
      const txLogsByBookId: Record<string, MarkedStateChangeLog[]> = {};
      for (const txLog of txLogs) {
        txLogsByBookId[txLog.book.book] ??= [];
        txLogsByBookId[txLog.book.book]!.push(txLog);
      }
      for (const [bookId, logs] of Object.entries(txLogsByBookId)) {
        markedTxLogsByBookId[bookId] ??= [];
        markedTxLogsByBookId[bookId]!.push(logs);
      }
    }
 
    // filter relevant metric logs
    const metricLogsByBookId: Record<string, MetricStateChangeLog[]> = {};
    for (const metricLog of metricResult.value) {
      metricLogsByBookId[metricLog.book.book] ??= [];
      metricLogsByBookId[metricLog.book.book]!.push(metricLog);
    }
 
    // reduce to new iab, marked state
    const assetTxLogsForThisBook = assetTxLogsByBookId[bookId] ?? [];
    for (const txLog of assetTxLogsForThisBook.flat()) {
      iabAsset[txLog.account] = plus(
        iabAsset[txLog.account] ?? zero,
        txLog.change,
      );
    }
 
    const markedTxLogsForThisBook = markedTxLogsByBookId[bookId] ?? [];
    for (const txLog of markedTxLogsForThisBook.flat()) {
      markedState[txLog.account] = plus(
        markedState[txLog.account] ?? zero,
        txLog.change,
      );
    }
 
    // TODO: if request, check for suspension
    const allBookIds = Object.keys(assetTxLogsByBookId);
    for (const bId of allBookIds) {
      const bookRecord = await this.iabSnapshotRepository.findOne({
        where: { book_id: bId },
      });
      this.logger.info({ bookRecord }, "bookRecord");
 
      Iif (bookRecord?.status === "SUSPEND") {
        this.logger.info(`Book ${bId} is suspended, rejecting event.`);
 
        const syncSignalEvent: SyncSignalEvent = {
          scriptId: event.scriptId,
          scriptType: event.type,
          bookId: bId,
          semaphore: Object.values(event.semaphore).map((v) => [
            event.scriptId,
            event.subId,
            v,
          ]),
          status: "REJECTED",
          txLogs: [],
          metricLogs: [],
          vars: {},
          message: "USER SUSPENDED",
          partial_notif_id: event.partial_notif_id ?? null,
        };
 
        await this.syncSignalEventProducer.send(syncSignalEvent);
        commit();
        return null;
      }
    }
 
    // signal to sync
    const syncSignalEvent: SyncSignalEvent = {
      scriptId: event.scriptId,
      scriptType: event.type,
      bookId: bookId,
      semaphore: [[event.scriptId, event.subId, event.semaphore[bookId]!]],
      status: "APPROVED",
      txLogs: assetTxLogsForThisBook.flat().map((x) => ({
        ...x,
        change: AmountMapper.toDTO(x.change),
        subId: event.subId,
      })),
      metricLogs: metricResult.value
        .filter((x) => x.book.book === bookId)
        .map((x) => ({
          ...x,
          change: AmountMapper.toDTO(x.change),
        })),
      vars: Object.keys(vars).reduce(
        (acc, k) => {
          acc[k] = AmountMapper.toDTO(vars[k]!);
          return acc;
        },
        {} as Record<string, AmountDto>,
      ),
      message:
        event.type === "NOTIF"
          ? "NOTIF event successfully processed"
          : event.type === "PARTIAL_NOTIF"
          ? "PARTIAL_NOTIF event successfully processed"
          : event.type === "REQ"
          ? "REQ event successfully processed"
          : "Event successfully processed",
      partial_notif_id: event.partial_notif_id ?? null,
    };
 
    this.logger.info({ syncSignalEvent }, "approve ledger event");
 
    const sendSignalApprove = await this.syncSignalEventProducer.send(
      syncSignalEvent,
    );
 
    Iif (!sendSignalApprove.ok) {
      this.logger.error("❌ Sync signal event failed to send approve.");
      return {
        ok: false,
        error: sendSignalApprove.error,
      };
    }
 
    // send other tx logs for processing
    for (const [bId, assetTxLogs] of Object.entries(assetTxLogsByBookId)) {
      if (bId === bookId) {
        continue;
      }
      const changelogsEvent: AssetStateChangeLogsEvent = {
        bookId: bId,
        scriptId: event.scriptId,
        subId: event.subId,
        type: event.type,
        semaphore: event.semaphore,
        assetTxLogs: assetTxLogs.flat(),
        markedTxLogs: (markedTxLogsByBookId[bId] ?? []).flat(),
        metricLogs: metricLogsByBookId[bId] ?? [],
        transaction_time: transaction_time,
        partial_notif_id: event.partial_notif_id ?? null,
      };
 
      this.logger.info({ changelogsEvent }, "send changelogsEvent");
 
      const sendChangeLog = await this.changelogsEventProducer.send(
        changelogsEvent,
      );
      Iif (!sendChangeLog.ok) {
        this.logger.error("❌ Change Log event failed to send.");
        return {
          ok: false,
          error: sendChangeLog.error,
        };
      }
    }
 
    // commit
    // TODO: Rollback logic
    const promises = [];
    // rollback: get original iab asset and set it back to that
    promises.push(
      this.IABAssetRepository.set(
        bookId,
        iabAsset,
        partition,
        offset,
        transaction_time,
      ),
    );
 
    promises.push(
      this.processedEventRepository.set(
        eventId,
        event.scriptId,
        partition,
        offset,
      ),
    );
 
    // rollback: get original marked state and set it back to that
    promises.push(this.markedStateRepository.set(bookId, markedState));
    if (event.type === "REQ") {
      // Store the complete transaction logs from evaluation
      promises.push(this.requestRepository.set(event.scriptId, assetTxLogs));
    } else if (event.type === "PARTIAL_NOTIF") {
      // Update stored REQ logs to reflect reduced reservation after PARTIAL_NOTIF consumption
      const updatedReqLogs = this.updateReservationLogs(
        prevAssetTxLogs,
        assetTxLogs,
      );
      // Overwrite REQ logs with updated data
      promises.push(this.requestRepository.set(event.scriptId, updatedReqLogs));
    E} else if (event.type === "NOTIF") {
      // rollback: insert tx logs
      // Skip deleting REQ logs for options sell_to_open (keep reserve until buy_to_close)
      const isOptionsSellToOpen = this.isOptionsSellToOpen(event);
 
      // Only delete REQ snapshot when user book semaphore reaches 0
      // This ensures all NOTIF events for this scriptId can access prevAssetTxLogs
      const userBookSemaphore = event.semaphore[bookId];
      const isLastNotifForUserBook = userBookSemaphore === 0;
 
      if (
        prevAssetTxLogs.length > 0 &&
        !isOptionsSellToOpen &&
        isLastNotifForUserBook
      ) {
        // Delete REQ snapshot for this scriptId
        promises.push(this.requestRepository.del(event.scriptId));
      }
    }
    // PARTIAL_NOTIF now updates the stored REQ logs with reduced reservations for accurate NOTIF excess calculation
 
    const resultPromise = await Promise.all(promises);
    const errors = resultPromise
      .filter((r): r is { ok: false; error: Error } => !r.ok)
      .map((r) => r.error);
    Iif (errors.length > 0) {
      this.logger.error("❌ Multiple Redis operations failed:");
      for (const err of errors) {
        this.logger.error(err.message);
      }
 
      return {
        ok: false,
        error: new Error(
          `Multiple failures: ${errors.map((e) => e.message).join("; ")}`,
        ),
      };
    }
    commit();
 
    return {
      ok: true,
      value: {
        bookId,
        iabAsset,
      },
    };
  };
 
  private isOptionsSellToOpen(event: LedgerEvent): boolean {
    try {
      const metadata = JSON.parse(event.metadata);
      return (
        metadata.trade_type === "options" &&
        metadata.order_side === "sell" &&
        metadata.position_intent === "sell_to_open"
      );
    } catch (error) {
      this.logger.error(
        { err: error },
        "Error checking if options sell_to_open",
      );
      return false;
    }
  }
 
  extractAccountsForBook(
    bookId: string,
    event: LedgerEvent,
    txLogs: AssetStateChangeLog[][],
  ): string[] {
    const accounts = new Set(extractAccountsFromLedgerEvent(event, bookId));
    for (const txLog of txLogs.flat()) {
      Eif (txLog.book.book === bookId) {
        accounts.add(txLog.account);
      }
    }
 
    // Remove metrics accounts from being loaded into iab asset state
    // Metrics will still be processed and sent to sync signal, but not stored in iab asset
    // for (const metric of event.metrics ?? []) {
    //   if (metric.book.book === bookId) {
    //     accounts.add(metric.account);
    //   }
    // }
 
    return [...accounts];
  }
 
  extractMarkedState(bookId: string, event: LedgerEvent): string[] {
    const markedState = new Set<string>();
    for (const tx of event.txs) {
      if (isRelativeTx(tx)) {
        Eif (tx.use) {
          markedState.add(tx.use);
        }
      }
 
      for (const source of tx.sources) {
        if (source.book.book === bookId && source.mark) {
          markedState.add(source.mark);
        }
      }
 
      for (const dest of tx.destinations) {
        if (dest.book.book === bookId && dest.mark) {
          markedState.add(dest.mark);
        }
      }
    }
 
    return [...markedState];
  }
 
  updateReservationLogs(
    prevAssetTxLogs: AssetStateChangeLog[][],
    assetTxLogs: AssetStateChangeLog[][],
  ): AssetStateChangeLog[][] {
    // Clone the original REQ logs to avoid modifying the original
    const updatedReqLogs: AssetStateChangeLog[][] = prevAssetTxLogs.map(
      (txLogs) => txLogs.map((log) => ({ ...log })),
    );
 
    // Calculate consumption amounts from PARTIAL_NOTIF
    const consumptionByAccount: Record<string, Amount> = {};
 
    for (const txLog of assetTxLogs.flat()) {
      // Look for negative changes (consumption from reserve accounts)
      if (
        (txLog.change.amount < 0n && txLog.account.includes("C-RES")) ||
        txLog.account.includes("S-RES")
      ) {
        const key = `${txLog.book.book}#${txLog.account}`;
        const consumption = consumptionByAccount[key] ?? zero;
 
        // Use minus() to properly handle scale conversion
        consumptionByAccount[key] = minus(consumption, txLog.change);
      }
    }
 
    // Update the reservation amounts in the stored REQ logs
    // We need to update BOTH:
    // 1. Reserve account (C-RES-B positive) - reduce by consumption
    // 2. Source account (C-FC negative) - reduce proportionally
    // This ensures handleExcessReservation() calculates correct excess
    for (const txLogs of updatedReqLogs) {
      // First pass: find reserve accounts and their consumption ratios
      const reserveUpdates: Map<
        string,
        { originalAmount: Amount; newAmount: Amount; ratio: Amount }
      > = new Map();
 
      for (const log of txLogs) {
        // Look for positive changes to reserve accounts (original reservations)
        if (
          (log.change.amount > 0n && log.account.includes("C-RES")) ||
          log.account.includes("S-RES")
        ) {
          const key = `${log.book.book}#${log.account}`;
          const consumption = consumptionByAccount[key];
 
          Eif (consumption) {
            const originalAmount = { ...log.change };
            // Reduce the reservation by the amount consumed in PARTIAL_NOTIF
            // Use minus() to properly handle scale conversion
            const newAmount = minus(log.change, consumption);
            log.change = {
              amount: newAmount.amount > 0n ? newAmount.amount : 0n,
              scale: newAmount.scale,
            };
 
            // Calculate ratio for updating source account
            // ratio = newAmount / originalAmount
            reserveUpdates.set(log.account, {
              originalAmount,
              newAmount: log.change,
              ratio: log.change, // We'll use newAmount directly for source update
            });
          }
        }
      }
 
      // Second pass: update source accounts proportionally
      // Source accounts are negative entries that correspond to positive reserve entries
      for (const log of txLogs) {
        // Look for negative changes (source accounts)
        if (log.change.amount < 0n) {
          // Find the corresponding reserve account update
          // Try multiple matching strategies:
          // 1. C-FC corresponds to C-RES-B
          // 2. C-OWN corresponds to S-RES
          // 3. Any negative entry with matching book gets updated if there's a reserve update
          let reserveAccount: string | null = null;
          if (log.account.includes("C-FC")) {
            reserveAccount = log.account.replace("C-FC", "C-RES-B");
          I} else if (log.account.includes("C-OWN")) {
            reserveAccount = log.account.replace("C-OWN", "S-RES");
          }
 
          if (reserveAccount) {
            const update = reserveUpdates.get(reserveAccount);
            Eif (update) {
              // Update source account proportionally
              // source.newAmount = -reserve.newAmount (negated because source is negative)
              log.change = {
                amount: -update.newAmount.amount,
                scale: update.newAmount.scale,
              };
            }
          } else {
            // Fallback: if no explicit mapping, find matching reserve in same txLogs
            // This handles generic cases where source is not C-FC/C-OWN
            // Look for any reserve update in this transaction
            for (const [, update] of reserveUpdates) {
              // Use the reserve update to scale down the source proportionally
              Eif (update.originalAmount.amount !== 0n) {
                // Calculate ratio: newAmount / originalAmount
                // Apply same ratio to source: source.new = source.original * (reserve.new / reserve.original)
                const ratio =
                  (update.newAmount.amount * BigInt(10 ** 18)) /
                  update.originalAmount.amount;
                const originalSource = -log.change.amount; // Make positive for calculation
                const newSource = (originalSource * ratio) / BigInt(10 ** 18);
                log.change = {
                  amount: -newSource, // Make negative again
                  scale: log.change.scale,
                };
              }
              break; // Only apply first matching reserve update
            }
          }
        }
      }
    }
 
    return updatedReqLogs;
  }
}
 
export { LedgerEventHandler };